qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
12,709,276 |
I am interested in knowing why static destructors are not allowed in C#. Note that I am not supposing that they exist in any other language.
I could have a class like this one.
```
class A
{
static A()
{
// here I can load a resource that will be avaliable for all instances
// of this class.
}
}
```
When the application ends I may need to release the resource.
So, the semantic of a static destructor could be the following: called when the application ends, for classes that contain it and were initialized in the app.
|
2012/10/03
|
[
"https://Stackoverflow.com/questions/12709276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1499972/"
] |
I just wrote a tutorial on how You can use the FDT 5.6 AIR for iOS Project Template. Hope is detailed enough to set You on the right path.
Here is the link:
[.SWFGEEK - Using FDT 5.6 AIR for iOS Project Template](http://www.swfgeek.net/2012/10/17/using-fdt-5-6-air-for-ios-project-template/)
|
686,889 |
I open firefox and browse through sites. Sometimes, automatically, the cursor stops moving, I can't use the keyboard too and system is hung. It doesn't go to the command line either. I found out that this may mostly be due to a adobe flash plugin. I don't know which one or which one to remove.
Every time this happens I have to manually force shutdown the computer and switch it on again.
I know I've been pretty vague in giving details but I don't know how exactly this problem occurs.
I'm using Ubuntu 14.04.
|
2015/10/18
|
[
"https://askubuntu.com/questions/686889",
"https://askubuntu.com",
"https://askubuntu.com/users/73204/"
] |
>
> 2. `#!/bin/bash` & zsh emulate: The first line declare that this script is running in bash. So, why there is a emulate, which is from zsh?
>
>
>
The first line, the shebang, only indicates that if the script is executed directly, it would be run using bash. Nothing prevents you from running it using zsh:
```
zsh admin.sh
```
I don't know why the author thought to test for zsh, but they did. This section of code is for zsh, and won't run in bash:
```
emulate sh
NULLCMD=:
# Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
# is contrary to our usage. Disable this feature.
alias -g '${1+"$@"}'='"$@"'
setopt NO_GLOB_SUBST
```
>
> 3. `alias -g '${1+"$@"}'='"$@"'`: I just input this on another bash and get the error: `-g :invalid option`, I'm confused about the difference of zsh & bash, and how they work together. Could you explain it to me, please?
>
>
>
That's a very broad question. I won't explain all the differences of zsh and bash - go read the documentation of both for that. For the specific point of `alias -g`, zsh has *global* aliases. In bash, aliases are only substituted at the start of the line. In zsh, `alias -g` defines global aliases which are substituted everywhere in the line.
So, in zsh, if I do:
```
alias -g foo=bar
```
And then run:
```
echo foo
```
The output will be:
```
bar
```
|
29,675,159 |
says it all really in the title I have this javascript
```
<script>
$(".tile").click(function(e){
$(this).toggleClass("flipOutX") ;
})
</script>
```
I have some html dfined boxes called "tile" and the problem here is that when i click an individual tile the flipoutx function works but only the tile I have clicked....
How can I make this work for all my tiles that are all called "tile" and not just the one tile I have clicked ?
|
2015/04/16
|
[
"https://Stackoverflow.com/questions/29675159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3504751/"
] |
You need to size the vectors accordingly before accessing elements. You can do that on construction, or using `resize`.
`vector<int>values(5/*pre-size for 5 elements*/);` and similar for `values2` would fix your problem.
Currently your program behaviour is undefined.
If you want to subtract *adjacent* elements, then shouldn't you have `values2[i]=values[i+1]-values[i];`?
|
352,522 |
I'm working on a Bash script that makes an SSH connection via git at a given point during the script's actions. I'm trying to gracefully handle some errors that can occur, stopping the script before it ends up failing part of the way through.
At one point it runs a command like `git push` which initiates a push over SSH. There's a chance that this will connect to a new host for the first time, which leads to an interactive prompt verifying the validity of the host.
```
RSA key fingerprint is 96:a9:23:5c:cc:d1:0a:d4:70:22:93:e9:9e:1e:74:2f.
Are you sure you want to continue connecting (yes/no)? yes
```
I'm looking for ideas on how to either avoid the SSH prompt or fail the script early if the SSH host hasn't been approved by the user before.
I took a look at [this question](https://unix.stackexchange.com/q/33271/53923). The argument could be made that this question is a duplicate of that, but the solutions listed there don't apply to my situation. I'd prefer to detect that the SSH connection can't be made without the prompt and fail in that case.
|
2017/03/20
|
[
"https://unix.stackexchange.com/questions/352522",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/53923/"
] |
So, instead of adding the host to `known_hosts` automatically, you want to fail the connection if it doesn't already exist there. `StrictHostKeyChecking` is still the option to do this (as in the linked question), but instead of setting it to `no`, set it to `yes`. This will cause the connection to fail if the host key isn't known.
```
$ ssh -oStrictHostKeyChecking=yes [email protected]
No ECDSA host key is known for somehost.somewhere and you have requested strict checking.
Host key verification failed.
```
`ssh` exits with status 255 if an error happens, including this case, so you can test for that in the script with something like
```
if [ "$?" = 255 ] ; then
echo "there was an error"
fi
```
Of course it could be some other error too, you'd need to check the output from `ssh` to make sure.
|
38,250,261 |
I have a table of Appointments made by patients. I want to fetch those new patients who came to our medical facility in the current month, but that they were never here before, so we can send a welcome letter to new patients.
I am not sure how to select. I want to use NOT IN, but not sure how to hold the ones in the current month, and recheck for past appointments. In this table, I would want only patient\_id 004.
```
Patient_ID Appt_Date time
001 2016-01-01
001 2015-05-09
002 2016-06-01
003 2016-07-01
003 2014-09-03
004 2016-07-02
```
|
2016/07/07
|
[
"https://Stackoverflow.com/questions/38250261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556651/"
] |
I would use aggregation for this:
```
select patient_id
from t
group by patient_id
having min(appt_date_time) > cast(dateadd(day, - day(getdate()), getdate()) as date)
```
|
17,104 |
From *My Face for the World to See* (1958) by Alfred Hayes:
>
> Ah! she said, triumphantly: the little boy hurts, doesn't it? I said, stonily, it might be a good idea if, instead of a psychiatrist, she stopped off one afternoon at **a delousing station**.
>
>
> Did I (with her eyes widely open) really think so?
>
>
> Yes: I thought so. A delousing station might, after all, be ever so much more helpful than some poor doctor trying, in a scheduled hour, to disentangle that **soul** of hers.
>
>
> **How nice to say she had one.**
>
>
> She had one. Oh stained a little and dirtied a little and cheap a little. But she had one.
>
>
> White and fluttery?
>
>
> White and fluttery and from the hand of God.
>
>
> She was delighted. A **soul**: an actual **soul**. No one, in years, had used the word. Were souls coming back, like **mahjong**? But it was such a waste, wasn't it, to have bothered giving her **one**. so superfluous. It was one of the least necessary things. A **soul**, how silly. Of what possible use could it be, except to get in the way and trip her, at critical moments, like a nightgown that was a bit too long?
>
>
> She was smiling, with her head somewhat to one side, tracing the rim of the martini glass with her finger.
>
>
> That was the trouble: **they** kept giving you things you didn't need. They never gave you quite what you really needed. Enough guts, for example.
>
>
> **Didn't she have her share?**
>
>
> Sadly, no. No she didn't. she didn't have nearly enough. **she could use more and more**. she could use scads of it for what she wanted to do. she'd trade it in: one **soul**, slightly damaged, for its equivalent in **guts**. Did I know a buyer? someone interested in second-hand **souls**? someone who'd care to exchange? Really: she was serious. She was perfectly serious. She'd love to get rid of the damn thing; it was such a nuisance having one, and being expected to take care of it, when really there wasn't time, and there were so many other more important things which needed her constant attention.
>
>
> Was I still brooding about the little boy?
>
>
>
I don't get the meaning of the whole context clearly and I think it is because the meaning of the "soul" is unclear to me. Does "soul" in this context mean "one person" or does it mean "her spirits"? it is somehow unclear to me. I think it means "person", but in the phrase: "to disentangle that soul of hers", I thought it means "spirits".
The meaning of some other words or phrase in this context that I wrote in bold is also unclear to me and maybe because the meaning of the word "soul" is unclear to me. Does "delousing station" mean "somewhere without bad people"? Does "guts" means "courage" and the writer is saying "some man who the girl become friend with give her courage"? The meaning of "did she have her shire?" is really unclear to me. Does it mean "some courage that she get"? I don't know whom "they" refers to.
Could you interpret this for me?
(I asked this question in ell.stackexchange with another title and they guide me to ask my question in this forum)
|
2021/01/09
|
[
"https://literature.stackexchange.com/questions/17104",
"https://literature.stackexchange.com",
"https://literature.stackexchange.com/users/11834/"
] |
A delousing station would generally be a place that gets rid of your [lice](https://www.lexico.com/en/definition/louse) (small insects that live in your hair). However, in this extract, it seems to means a place that will stop you from being a louse (a contemptible or unpleasant person) yourself.
So *delousing station* is wordplay on the meaning of the word *louse.* The same thing is true for [*soul*](https://www.lexico.com/definition/soul) — the various usages of the word *soul* mean different things.
One meaning of *soul* is the part of a person that lives on after death, as opposed to their body (and either goes to heaven or to hell). This is often represented as a "white and fluttery thing." In folklore, people sometimes "sell their soul to the devil"; this is a deal where they go to Hell after they die in exchange for getting something they want in this life.
Another meaning is a person's emotional nature — this is presumably what the psychiatrist is treating.
For a third meaning, if you are [soulless](https://www.lexico.com/definition/soulless), you lack compassion or other human feelings. This is implicit when she talks about getting rid of her soul.
And guts means courage here.
Mahjongg means the game ... it presumably went out of fashion, and then was coming back into fashion around the time this was written.
For some of your other questions, "how nice to say she had one" refers to her soul; "didn't she have her share" refers to guts.
|
58,121,048 |
I know this issue exists already and people have posted before but I can't get this working so sorry for asking this.
I am using Heroku to build and deploy, this is not being done locally.
I am trying to get MetaMask to get recognized in my Dapp and I am using the code generated by MetaMask to fix their privacy mode breaking change but I cannot get past 'web3' 'Web3' and 'ethereum' undefined compile error. I don't understand where it needs to go within my app. Any assistance would be greatly appreciated. Beyond appreciated.
Here is my app.js:
```
import React, { Component } from 'react'
import './App.css'
import Navbar from './Navbar'
import Content from './Content'
import { connect } from 'react-redux'
import {
loadWeb3,
loadAccount,
loadToken,
loadExchange
} from '../store/interactions'
import { contractsLoadedSelector } from '../store/selectors'
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */});
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */});
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
class App extends Component {
componentWillMount() {
this.loadBlockchainData(this.props.dispatch)
}
async loadBlockchainData(dispatch) {
const web3 = loadWeb3(dispatch)
await web3.eth.net.getNetworkType()
const networkId = await web3.eth.net.getId()
await loadAccount(web3, dispatch)
const token = await loadToken(web3, networkId, dispatch)
if(!token) {
window.alert('Token smart contract not detected on the current network. Please select another network with Metamask.')
return
}
const exchange = await loadExchange(web3, networkId, dispatch)
if(!exchange) {
window.alert('Exchange smart contract not detected on the current network. Please select another network with Metamask.')
return
}
}
render() {
return (
<div>
<Navbar />
{ this.props.contractsLoaded ? <Content /> : <div className="content"></div> }
</div>
);
}
}
export default connect(mapStateToProps)(App)
});
```
|
2019/09/26
|
[
"https://Stackoverflow.com/questions/58121048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11588783/"
] |
As of January 2021, Metmask has removed their injected `window.web3`
If you want to connect your dApp to Metamask, I'd try the following
```
export const connectWallet = async () => {
if (window.ethereum) { //check if Metamask is installed
try {
const address = await window.ethereum.enable(); //connect Metamask
const obj = {
connectedStatus: true,
status: "",
address: address
}
return obj;
} catch (error) {
return {
connectedStatus: false,
status: " Connect to Metamask using the button on the top right."
}
}
} else {
return {
connectedStatus: false,
status: " You must install Metamask into your browser: https://metamask.io/download.html"
}
}
};
```
If you'd like to learn how to also sign transactions with Metamask, I'd recommend you check out this super [beginner-friendly NFT Minter tutorial](https://docs.alchemyapi.io/alchemy/tutorials/nft-minter). You got this!
|
29,196,447 |
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5.
```
App::after(function($request, $response)
{
if($response instanceof Illuminate\Http\Response)
{
$buffer = $response->getContent();
if(strpos($buffer,'<pre>') !== false)
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
);
}
else
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
"/ +/" => ' ',
);
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
}
});
```
Please how do i make this work in Laravel 5.
OR
Please provide a better way of compressing HTML in laravel 5 if any.
Thanks in advance.
NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
|
2015/03/22
|
[
"https://Stackoverflow.com/questions/29196447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2772319/"
] |
Complete code is this (with custom GZip enabled) :
```
<?php
namespace App\Http\Middleware;
use Closure;
class OptimizeMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$buffer = $response->getContent();
if(strpos($buffer,'<pre>') !== false)
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
);
}
else
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
"/ +/" => ' ',
);
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
ini_set('zlib.output_compression', 'On'); // If you like to enable GZip, too!
return $response;
}
}
```
Please check your browser network inspector for `Content-Length` header before/after implement this code.
enjoy it ... :).. .
|
39,156,762 |
```
<li class ="block" ng-repeat="i in items | searchFor:searchString" id={{i.title}}>
<a><img class="gallery" id={{i.title}} ng-src="{{i.image}}" title="{{i.title}}" /></a>
<a href="{{i.image}}" download><button id="eye" title="Preview"></button></a>
<p>{{i.title}}</p>
</li>
```
**Items list**
```
$scope.items = [
{
url: '#',
title: 'Mountain',
image: 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0'
}];
```
This throws an error
>
> jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: <https://images.unsplash.com/photo-1443890923422-7819ed4101c0>
>
>
>
|
2016/08/26
|
[
"https://Stackoverflow.com/questions/39156762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6584514/"
] |
Different fonts have different "aspect values" which is the size difference between a lowercase x and uppercase X for instance. You could try to use something like "font-size adjust" in your css to make all fonts have the same aspect value regardless of the font family.
|
19,202,524 |
I`m trying to create menu which is opening on clicking parent element and closeing on mouseleave from that one which was opened a while ago. It should work from left to right
Here is
```
<ul class="menuFirst">
<li><img src="img/ico1.png"></li>
<ul class="">
<li><img src="img/ico2.png" alt="submoduł1"></li>
<li><img src="img/ico2.png" alt="submoduł2"></li>
<li><img src="img/ico2.png" alt="submoduł3"></li>
</ul>
<li><img src="img/ico1.png"></li>
<ul class="menuSecond">
<li><img src="img/ico2.png" alt="submoduł1"></li>
<li><img src="img/ico2.png" alt="submoduł2"></li>
<li><img src="img/ico2.png" alt="submoduł3"></li>
</ul>
<li><img src="img/ico1.png"></li>
<ul class="menuSecond">
<li><img src="img/ico2.png" alt="submoduł1"></li>
<li><img src="img/ico2.png" alt="submoduł2"></li>
<li><img src="img/ico2.png" alt="submoduł3"></li>
</ul>
</ul>
```
Here is CSS
```
ul.menuFirst{
list-style-type: none;
border-top: #AAA solid 3px;
border-right: #AAA solid 3px;
border-bottom: #AAA solid 2px;
position: absolute;
left: 0px;
top: 70px;}
ul.menuFirst li{
background: #DDD;
border-bottom: #AAA solid 1px;
}
ul.menuFirst li img{
margin:5px;
}
ul.menuFirst ul{
display: none;
}
ul.menuFirst ul.menuSecond {
list-style: none;
display: table;
position: absolute;
left: 30px;
}
ul.menuFirst ul.menuSecond li{
display: table-cell;
}
```
And here is jQuery
```
<script>
$(document).ready(function(){
$("ul.menuFirst li").click(function(){
$(this).next().toggle();
var ypos= $(this).next().position();
alert(ypos.top);
$(this).next().css('top','-=38');
$('ul.menuFirst ul.menuSecond').one('mouseleave',function(){
$(this).css('top', '+=38').toggle();
});
});
});
```
It works for 1st element but it's pretty buggy. When I'm trying to add .animate() It just didn't work. So I`ve decided to take step back and unbug this one but i don't know how. It should looks like this:

|
2013/10/05
|
[
"https://Stackoverflow.com/questions/19202524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2389307/"
] |
Your HTML is not correct use this
```
<ul class="menuFirst">
<li><img src="img/ico1.png">
<ul class="">
<li><img src="img/ico2.png" alt="submodul1"></li>
<li><img src="img/ico2.png" alt="submodul2"></li>
<li><img src="img/ico2.png" alt="submodul3"></li>
</ul>
</li>
<li><img src="img/ico1.png">
<ul class="menuSecond">
<li><img src="img/ico2.png" alt="submodul1"></li>
<li><img src="img/ico2.png" alt="submodul2"></li>
<li><img src="img/ico2.png" alt="submodul3"></li>
</ul>
</li>
<li><img src="img/ico1.png">
<ul class="menuSecond">
<li><img src="img/ico2.png" alt="submodul1"></li>
<li><img src="img/ico2.png" alt="submodul2"></li>
<li><img src="img/ico2.png" alt="submodul3"></li>
</ul>
</li>
</ul>
```
|
9,160 |
I have seen a ticket opened about this on tor bug tracker, but no progress for over a year on the Tor Browser being available on arm processors. I have setup firefox with a proxy to use Tor but that is not safe because the browser itself leaks to much info. So I am asking for help if this is the right place to ask how to compile the Tor Browser on RasPi 2 on Debian/Ubuntu. Just some simple instructions for me to follow so I can compile from source, or is there an easier way?
|
2015/12/03
|
[
"https://tor.stackexchange.com/questions/9160",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/10106/"
] |
Speaking from experience, this is not currently possible.
During the compiling process, the make script will download some binaries that are only built for X86 and not for ARM and therefore the compilation wil fail every time.
The Tor developers plan on releasing a version for Tor Browser for ARM in the future, but there is no ETA.
Your best option at the current time is to download the Tor application and apply it to Firefox/Iceweasel.
|
10,686,209 |
I am trying to attach a PDF file called download.pdf to an email in my Android App. I am copying the file first to the SDCard and then attaching it the email.
I'm not if relevant, but I am testing on a galaxy tab device. The external storage path returns mnt/sdcard/
My code is as follows :
```
public void sendemail() throws IOException {
CopyAssets();
String emailAddress[] = {""};
File externalStorage = Environment.getExternalStorageDirectory();
Uri uri = Uri.fromFile(new File(externalStorage.getAbsolutePath() + "/" + "download.pdf"));
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, emailAddress);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Text");
emailIntent.setType("application/pdf");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send email using:"));
}
public void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
if (filename.equals("download.pdf")) {
try {
System.out.println("Filename is " + filename);
in = assetManager.open(filename);
File externalStorage = Environment.getExternalStorageDirectory();
out = new FileOutputStream(externalStorage.getAbsolutePath() + "/" + filename);
System.out.println("Loacation is" + out);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
```
The problem is that the file that is attached is 0 bytes in size. Can anyone spot what might be wrong ?
**EDIT**
I can see that the file has been saved onto the device if I look in settings, therefore this must be a problem around how I am attaching the file to the email. In the error log I am seeing :
```
gMail Attachment URI: file:///mnt/sdcard/download.pdf
gMail type: application/pdf
gmail name: download.pdf
gmail size: 0
```
**EDIT**
Wondering if this is a bug on the galaxy tab ? If I open the file via a pdf viewer (from my app) then try to attach to a gmail email, the size is again 0. Can anyone verify ?
Thank you.
|
2012/05/21
|
[
"https://Stackoverflow.com/questions/10686209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441717/"
] |
```
String[] mailto = {""};
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CALC/REPORTS/",pdfname ));
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Calc PDF Report");
emailIntent.putExtra(Intent.EXTRA_TEXT, ViewAllAccountFragment.selectac+" PDF Report");
emailIntent.setType("application/pdf");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send email using:"));
```
|
35,271,838 |
Trying to delete `<shipmentIndex Name=\"shipments\">whatever...</shipmentIndex>`
if it appear more then 1 time, keeping only one.
I have surrounded the item i want to delete here with \*\*\*..
The code i am using worked before, but then i added `.Value == "shipments"`
and now it fail.
How can i keep this code and only fix `.Value == "shipments"` to work?
```
class Program
{
static void Main(string[] args)
{
string renderedOutput =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<RootDTO xmlns:json='http://james.newtonking.com/projects/json'>" +
"<destination>" +
"<name>xxx</name>" +
"</destination>" +
"<orderData>" +
"<items json:Array='true'>" +
"<shipmentIndex Name=\"items\" >111</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<items json:Array='true'>" +
"<shipmentIndex Name=\"items\">222</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<items json:Array='true'>" +
"<shipmentIndex Name=\"items\">222</shipmentIndex>" +
"<barcode>12345</barcode>" +
"</items>" +
"<misCode>9876543210</misCode>" +
"<shipments>" +
"<sourceShipmentId></sourceShipmentId>" +
"<shipmentIndex shipments=\"shipments\">111</shipmentIndex>" +
"</shipments>" +
"<shipments>" +
"<sourceShipmentId></sourceShipmentId>" +
"<shipmentIndex Name=\"shipments\">222</shipmentIndex>" +
****
"<shipmentIndex Name=\"shipments\">222</shipmentIndex>" +
****
"</shipments>" +
"</orderData>" +
"</RootDTO>";
var xml = XElement.Parse(renderedOutput);
xml.Element("orderData").Descendants("shipments")
.SelectMany(s => s.Elements("shipmentIndex")
.GroupBy(g => g.Attribute("Name").Value == "shipments")
.SelectMany(m => m.Skip(1))).Remove();
}
}
```
|
2016/02/08
|
[
"https://Stackoverflow.com/questions/35271838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1454961/"
] |
Not sure I understand the question 100% but here goes:
I am thinking you want to filter the results to only include those elements where the name attribute is equal to 'shipments', although not all of the shipmentIndex elements have a 'Name' attribute so you are probably getting a null reference exception. You need to add a check to ensure that the 'Name' attribute exists.
```
xml.Element("orderData").Descendants("shipments")
.SelectMany(s => s.Elements("shipmentIndex")
.GroupBy(g => g.Attribute("Name") != null && g.Attribute("Name").Value == "shipments")
.SelectMany(m => m.Skip(1))).Remove();
```
|
532,590 |
A Windows10 / debian system with a shared ntfs drive:
```
# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 931.5G 0 disk
├─sda1 8:1 0 9.3G 0 part [SWAP]
├─sda2 8:2 0 83.8G 0 part /home
└─sda3 8:3 0 100G 0 part /media/share
nvme0n1 259:0 0 465.8G 0 disk
├─nvme0n1p1 259:1 0 100M 0 part /boot/efi
├─nvme0n1p2 259:2 0 435.7G 0 part
└─nvme0n1p4 259:3 0 27.9G 0 part /
```
The share used to work well up until recently, when it became read-only on the linux part. I think I have the appropriate drivers for write access. The line in fstab:
```
$ cat /etc/fstab | grep share
UUID=2786FC7C74DF871D /media/share ntfs defaults 0 3
```
If I unmount it and then mount again:
```
# mount /dev/sda3 share
The disk contains an unclean file system (0, 0).
Metadata kept in Windows cache, refused to mount.
Falling back to read-only mount because the NTFS partition is in an
unsafe state. Please resume and shutdown Windows fully (no hibernation
or fast restarting.)
Could not mount read-write, trying read-only
```
In windows I checked the disk for errors and defragmented it, then used Shut down. No upgrades started during shutting down.
How to proceed?
|
2019/07/28
|
[
"https://unix.stackexchange.com/questions/532590",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/20506/"
] |
Modern windows has something called fast startup that causes trouble for dual booting.
If you are using a modern windows (8 or 10) and dual booting you should keep it [turned off](https://www.windowscentral.com/how-disable-windows-10-fast-startup)
|
66,629,543 |
I want to create an AWS IAMS account that has various permissions with CloudFormation.
I understand there are policies that would let a user change his password and let him get his account to use MFA [here](https://security.stackexchange.com/questions/124786/aws-cloudformation-enable-mfa?newreg=9d07e7c9d733438b82b483b8a6afe541)
How could I enforce the user to use MFA at first log in time when he needs to change the default password?
This is what I have:
The flow I have so far is:
1. User account is created
2. When user tries to log in for the first time is asked to change the default password.
3. User is logged in the AWS console.
Expected behavior:
1. User account is created
2. When user tries to log in for the first time is asked to change the default password and set MFA using Authenticator app.
3. User is logged in the AWS console and has permissions.
A potential flow is shown [here](https://pomeroy.me/2020/09/solved-first-time-login-problems-when-enforcing-mfa-with-aws/). Is there another way?
Update:
This [blog](https://aws.amazon.com/blogs/security/how-to-delegate-management-of-multi-factor-authentication-to-aws-iam-users/) explains the flow
Again, is there a better way? Like an automatic pop up that would enforce the user straight away?
Update2:
I might have not been explicit enough.
What we have so far it is an ok customer experience.
This flow would be fluid
1. User tries to log in
2. Console asks for password change
3. Colsole asks for scanning the code and introducing the codes
4. User logs in with new password and the code from authenticator
5.User is not able to deactivate MFA
|
2021/03/14
|
[
"https://Stackoverflow.com/questions/66629543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15234088/"
] |
you can use this
<https://pub.dev/packages/auto_direction>
This package changes the direction of a widget from ltr direction into rtl direction and vice versa based on the language of the text provided.
|
23,135 |
1. Go to this website: <http://parts-of-speech.info/>
2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology>
3. Grab the first paragraph and feed it into POS tagger to see the
tags. This is an image of the result:
[](https://i.stack.imgur.com/9cgNz.png)
However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word:
* Evolutionary psychology
* Natural science
* Natural selection
* ...
These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**.
Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
|
2017/06/09
|
[
"https://linguistics.stackexchange.com/questions/23135",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/141/"
] |
There are several terminologies for such words. Here are their definitions found in Wikipedia:
**Multi-word Expressions (MWEs):** *A multiword expression (MWE), also called phraseme, is a lexeme made up of a sequence of two or more lexemes that has properties that are not predictable from the properties of the individual lexemes or their normal mode of combination.* [[URL]](https://en.wikipedia.org/wiki/Multiword_expression)
**Terminology:** *the study of terms and their use. Terms are words and compound words or multi-word expressions that in specific contexts are given specific meanings—these may deviate from the meanings the same words have in other contexts and in everyday language.* [[URL]](https://en.wikipedia.org/wiki/Terminology)
**Collocations:** *In corpus linguistics, a collocation is a sequence of words or terms that co-occur more often than would be expected by chance.* [[URL]](https://en.wikipedia.org/wiki/Collocation)
Note that all of these are similar. Both "collocations" and "terms" are "MWEs". The terms are usually MWEs that are specific for a given topic, while collocations are MWEs which co-occur together in a corpus more frequently than by chance. Collocations and terms often coincide (you can always use a predefined MWE dictionary with terms/collocations).
If you want to discover MWEs in an unsupervised manner by using the corpus statistics - you should use [collocation extraction](https://en.wikipedia.org/wiki/Collocation_extraction) techniques. There have been plenty of work on collocation extraction, so it should be easy for you to find software or some APIs.
Here's a list of tools (feel free to edit the list):
* Software:
+ [Collocation extraction software: Collocate](https://www.athel.com/colloc.html)
+ [Collocation Extract](http://en.freedownloadmanager.org/Windows-PC/Collocation-Extract-FREE.html)
+ [Collocation Extract (other source)](http://pioneer.chula.ac.th/~awirote/resources/collocation-extract.html)
* APIs:
+ [Java] Stanford's CoreNLP [CollocationFinder](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/trees/CollocationFinder.html) (predifined, uses WordNet)
+ [Java] Mahout's [collocation extraction](https://mahout.apache.org/users/basics/collocations.html)
* Resources (all of its MWEs can be seen as collocations/terms)
+ [WordNet](https://wordnet.princeton.edu/)
+ [Wiktionary](https://www.wiktionary.org/)
In my opinion, a nice reading resource is the paper ["50-something years of work on collocations"](http://www.linguistics.ucsb.edu/faculty/stgries/research/2013_STG_DeltaP&H_IJCL.pdf).
|
17,529,012 |
For far too long I've been stumbling around trying to make a simple .click jquery method work in my c# site. I just want it to call to a function in my controller, but I can't seem to get any button click to register. The calls in it are very similar to a .change() function for another control that works just fine.
JQuery method in question:
```
$('#addUserButton').click(function () {
var e = document.getElementById('searchDDL');
var itemText = e.options[e.selectedIndex].text;
var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText);
});
```
HTML of button that is intended to trigger the above function:
```
<button id="addUserButton" type="button" value="addUser">></button>
```
Some things I've researched and tried already:
* Changing from a .click() method to a .live("click", etc) method made no difference.
* I saw that setting the button type="submit" would be a problem, so I changed it to "button."
* I made sure to include it in document.ready() - I was already doing this before researching other problems.
I have created a jsfiddle for the problem [here](http://jsfiddle.net/MQLB4/). I had to remove a lot of sensitive information so the page is not fully fleshed out. It is for an internal application and only has to work with IE.
**EDIT:** Below I am adding the function I am trying to call in my controller; other posters have verified that the jquery is working as expected, so I'm inclined to believe it is something to do with my c#.
```
public ActionResult AddUser(string User)
{
//numUsers = App.NumberUsers + 1;
selectedUsers.Add(User);
return RedirectToAction("ApplicationForm");
}
```
|
2013/07/08
|
[
"https://Stackoverflow.com/questions/17529012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547781/"
] |
Did you try debugging your function or even putting alerts in it to flesh out whats happening.
```
$('#addUserButton').click(function () {
alert("FUNCTION IS GETTING CALLED ON CLICK EVENT");
var e = document.getElementById('searchDDL');
alert(e);
var itemText = e.options[e.selectedIndex].text;
alert(itemText);
var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText);
alert(url);
});
```
Doesn't look like your function makes an AJAX request after getting the URL.
|
60,886,431 |
I have a section of html that needs to be displayed in a certain way but some elements may be optional and I'm not sure if I can do it with `display:grid`.
I need to have 3 columns, but the first and last one are optional and I need to remove the gap when they are not present.
Note that the markup needs to be this one without extra wrapper :
```css
.grid {
display: grid;
grid-template-columns: auto 1fr auto;
grid-gap: 0 20px;
align-items: center;
background-color: lightgrey;
}
.grid > .image {
grid-column: 1;
grid-row: 1 / span 2;
background-color: red;
}
.grid > .title {
grid-column: 2;
background-color: blue;
}
.grid > .description {
grid-column: 2;
background-color: purple;
}
.grid > .button {
grid-column: 3;
grid-row: 1 / span 2;
background-color: green;
}
```
```html
<div class="grid">
<div class="image">image</div>
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<p>Unwanted gap when no image or button :</p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
</div>
```
|
2020/03/27
|
[
"https://Stackoverflow.com/questions/60886431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1458442/"
] |
Rely on implicit column creation and keep only one explicit column
```css
.grid {
display: grid;
grid-template-columns: 1fr; /* one column here */
grid-gap: 0 20px;
align-items: center;
background-color: lightgrey;
}
.grid > .image {
grid-column: -3; /* this will create an implicit column at the start */
grid-row: span 2;
background-color: red;
}
.grid > .title {
background-color: blue;
}
.grid > .description {
background-color: purple;
}
.grid > .button {
grid-column: 2; /* this will create an implicit column at the end */
grid-row:1/ span 2;
background-color: green;
}
```
```html
<div class="grid">
<div class="image">image</div>
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
<div class="button">button</div>
</div>
<p> </p>
<div class="grid">
<div class="image">image</div>
<div class="title">title</div>
<div class="description">description</div>
</div>
<p> </p>
<div class="grid">
<div class="title">title</div>
<div class="description">description</div>
</div>
```
|
35,611,371 |
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file.
Everything works, except I can't get it to remove the middle space. For example:
list1.txt:
```
1
2
```
list2.txt:
```
dog
cat
```
The result I get is:
```
dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat
```
But I need (see spaces):
```
dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat
```
Code:
```
<?php
$array1 = file('list1.txt');
$array2 = file('list2.txt');
$array3 = array();
$array4 = array();
foreach ($array1 as $key1)
{
foreach ($array2 as $key2)
{
$array3[] = $key1 . $key2;
{
$array4[] = $key2 . $key1;
}
}
}
print_r($array3);
print_r($array4);
$fp = fopen('combined.csv', 'w');
fputcsv($fp, $array3);
fputcsv($fp, $array4);
fclose($fp);
?>
```
|
2016/02/24
|
[
"https://Stackoverflow.com/questions/35611371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3526961/"
] |
Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows:
```
$array1 = file('list1.txt'**, FILE\_IGNORE\_NEW\_LINES**);
$array2 = file('list2.txt'**, FILE\_IGNORE\_NEW\_LINES**);
```
The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.
|
4,167,419 |
>
> Let $f(x)=a(x-2)(x-b)$, where $a,b\in R$ and $a\ne0$. Also, $f(f(x))=a^3\left(x^2-(2+b)x+2b-\frac2a\right)\left(x^2-(2+b)x+2b-\frac ba\right)$, $a\ne0$ has exactly one real zeroes $5$. Find the minima and maxima of $f(x)$.
>
>
>
$f(f(x))$ is a quartic equation. So, it would have $4$ roots. Its real root should occur in pair because complex roots occur in pair. So, I failed to understand the meaning of 'exactly one real zero' in the question. Does that mean its real roots are equal and they are equal to $5$?
Since $f(x)$ has a zero at $2$, $f(f(2))=f(0)=2ab$. But even RHS of $f(f(x))$ is coming out to be $2ab$ at $x=2$.
Putting $x=5$ in $f(f(x))$ gives an equation in $a^2$ and $b^2$. Don't know what to do with it.
Also, $f(x)=a(x^2-(2+b)x+2b)$
$f'(x)=a(2x-2-b)=0\implies x=\frac{2+b}2$ is the minima or maxima.
How to proceed next? Do the critical points of $f(x)$ tell us anything about $f(f(x))$?
|
2021/06/08
|
[
"https://math.stackexchange.com/questions/4167419",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/87430/"
] |
Let $q>3$. Then there exists a nonzero element $a\in \Bbb F\_q$ with $a^2-1\neq 0$. Let $A=\begin{pmatrix} 1 & -x \cr 0 & 1 \end{pmatrix}$ and $B=\begin{pmatrix} a & 0 \cr 0 & a^{-1} \end{pmatrix}$ in $SL(2,q)$. Then
\begin{align\*}
[A,B] & = ABA^{-1}B^{-1} \\
& =\begin{pmatrix} 1 & (a^2-1)x \cr 0 & 1 \end{pmatrix}
\end{align\*}
So every element of the corresponding transvection group
is a commutator. Since the transvections generate
$SL(2,q)$, this is enough to show that $SL(2,q)$ is perfect.
|
694,664 |
I am looking for a bash script example which does the following:
I have files being written under `/tmp` folder
I do at the `xterm` prompt, `ls -ltr` which gives me a list of recent files such as:
```
abc_mytest.log
abc_runTimeFailure.scripted.log
myManager.log
```
I want to move (`mv`) the most recent ones that were written today to a new folder which is under /home/project/.
I only want to move the ones that were created in `/tmp` in today's date only to `/home/project/`
Any example that the community can share will save me time before I re-invent the wheel.
Thanks,
Eric
|
2022/03/16
|
[
"https://unix.stackexchange.com/questions/694664",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/518635/"
] |
Read `man find mv` and do something like:
```
find /tmp -maxdepth 1 -type f -daystart -mtime 0 \
-exec mv -t /home/project/ {} +
```
**UNTESTED!** You must test with `echo mv` instead of the potentially dangerous `mv`.
|
73,334,904 |
I've got a .showGuesses block which max-height is set to 100px. When its height goes over its maximum I want a vertical scroll bar to appear. But, unfortunately, for some reason I never get the scroll bar.
**How to make the scrollbar to appear?**
Here's the code and the result: <https://liveweave.com/hyo1ut>
HTML
```
<!DOCTYPE html>
<form class="order-form" method="POST" action="insert_data.php">
<legend>Insert your address</legend>
<div class="input-area-wrap">
<div class="input-area">
<label>street/avenue</label>
<input type="text" name="street" required>
</div>
<div class="showGuesses">
<div class="showGuess">Street 1</div>
<div class="showGuess">Street 2</div>
<div class="showGuess">Street 3</div>
<div class="showGuess">Street 4</div>
</div>
</div>
</form>
```
CSS
```
* {
-webkit-box-sizing: border-box!important;
box-sizing: border-box!important;
}
.order-form {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
width: 80%;
max-width: 800px;
margin: 0 auto;
border: 1px solid #222;
border-radius: 15px;
padding: 20px;
margin-top: 25px;
position: unset!important;
overflow: hidden;
}
legend {
text-align: center;
margin-bottom: 25px!important;
}
.input-area-wrap {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
.input-area {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: baseline;
-ms-flex-align: baseline;
align-items: baseline;
position: relative;
}
.input-area label {
width: 150px;
}
input[type="text"] {
width: 250px!important;
outline: none;
}
input[type="text"]:focus {
border: 2px solid darkred!important;
outline: none;
}
input[type="submit"] {
width: 100px;
margin: 25px auto 0;
border-radius: 25px;
background: rgb(255, 74, 74);
color: #fff;
border: none;
padding: 10px;
font-size: 16px;
}
.showGuesses {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
z-index: 3;
/* top: 25px; */
margin-left: 150px;
font-size: 14px;
width: 100%;
max-height: 100px;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
.showGuess {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
border: 1px solid #222;
padding: 5px;
width: 250px;
min-height: 45px;
text-align: center;
background: #fff;
border-bottom: none;
}
```
**UPD 0:**
Due to help of @EssXTee I now get the scrollbar, but it doesn't disappear if the content of showGuesses block doesn't overflow it. It's just there all the time for some reason.
**How to fix that?**
|
2022/08/12
|
[
"https://Stackoverflow.com/questions/73334904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19712456/"
] |
Pattern matching and regular expressions are two different things. In pattern matching `*` means *any string*. In regular expressions it means *zero or more of what precedes*. In pattern matching `(.+)` means... the literal `(.+)` string. In regular expressions it represents a capture group with at least one character.
For your simple renaming scheme you can try:
```bash
for f in *.fq.gz; do
g="${f/_DKDL220005480-2a-*_HHJ2MCCX2_L8_/_R}"
printf 'mv "%s" "%s"\n' "$f" "${g%.fq.gz}.fastq.gz"
# mv "$f" "${g%.fq.gz}.fastq.gz"
done
```
Once satisfied with the output uncomment the `mv` line.
|
34,190,609 |
```
Page A
Page B
Page C
```
If the user is coming from `page A` do something on `page C` (within the same website)
If the user is coming from `page B` do something else on `page C` (within the same website)
What would be the best approach to do that in JS? (dont use `document.referrer`)
|
2015/12/09
|
[
"https://Stackoverflow.com/questions/34190609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3195927/"
] |
In my opinion, there are two decent solutions:
1. When Page A loads Page C, include a variable in the URL that essentially says "*loaded from page A*". (Same applies to Page B.)
2. When Page A is loaded, set either a cookie, `localStorage`, or `sessionStorage` variable that says "*loaded from page A*". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)
|
1,441,686 |
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded
```
function __autoload($class_name){
include('classes/' . $class_name . '.class.php');
}
```
Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
|
2009/09/17
|
[
"https://Stackoverflow.com/questions/1441686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143030/"
] |
>
> if I were to call the dogs class but
> NOT call the animals class, would the
> animals class file still be loaded?
>
>
>
Yes. When you load an class that extends another class, PHP must load the base class so it knows what it's extending.
re: the idea of storing multiple classes per file: This will not work with the autoload function you provided. One class per file is really the best practice, especially for autoloaded classes.
If you have more than one class in a file, you really shouldn't attempt to autoload any classes from that file.
|
4,628,946 |
I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creating a non-Qt executable (in this case an MFC MDI application with out-of-the-box settings), and a Qt Application (which I changed to a DLL). I added a menu item to the non-Qt executable, and handled the event as follows:
```
void MFCApp::OnFileLaunch()
{
QtApp qtApp;
qtApp.Launch();
}
```
The QtApp class doesn't expose the Qt API at all, and Launch() is implemented as follows:
```
int QtApp::Launch()
{
int argc = 0;
char *argv = 0;
QApplication a(argc, &argv);
MyMainWindow w;
w.show();
return a.exec();
}
```
The non-Qt application remains fully responsive while the Qt application is displayed, apart from the toolbar tooltips (and also keyboard shortcuts such as Ctrl A for Select All).
I suspect this is might be a Qt bug, but just wanted to check anyway in case it's my Launch code that's wrong.
I'm using Qt 4.5.2 by the way.
Thanks
|
2011/01/07
|
[
"https://Stackoverflow.com/questions/4628946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88692/"
] |
You should *always* use 'approximate' comparisons in floating point calculations. E.g., `if (abs(value) < EPS)` instead of `if ( value == 0.00 )`. `EPS` here is a small constant (depends on your requirements and datatype).
I suspect this is what's actually happening. You get to the smallest possible positive value in your datatype, like `1 * 2^(-10000)` (10000 comes from the top of my head) and now `value * 0.98 = value`. E.g., it has to be rounded either to `0` or to `total` and `0.98*total` is obviously closer to `total`.
But that's only speculations, though. With floating point computations, you can never be sure :)
|
12,295,963 |
I've setup an Apache reverse proxy to forward `api.mydomain.com` to `localhost:2000` which works just fine.
However, the real issue i'm having is in regard to sessions - it seems that the req.session's aren't being stored when querying via `api.mydomain.com`. Sessions will work just fine visiting from `localhost:2000`.
I assume this has something to do with the proxied domain...
server.js
```
var express = require('express'),
app = express();
app.enable('trust proxy');
app.configure(function() {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'supersecret'});
app.use(app.router);
});
app.get('/session', function(req, res, next){
console.log(req.session.username)
// this will be undefined when called from api.mydomain.com...
});
app.post('/session', function(req, res, next){
req.session.username = 'my username';
});
```
apache config
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPreserveHost On
ProxyPassReverseCookieDomain api.domain.com localhost:2000
ProxyPassReverseCookiePath / /
</VirtualHost>
```
**EDIT**
Notably, for further testing - adding the below code before `app.use(app.router)` in `app.configure()` ....
```
app.use(function (req, res) {
res.send('<h2>Hello, your session id is ' + req.sessionID + '</h2>');
});
```
will result in the following (each line represents a new GET /session request to the app - node hasn't restarted either).
localhost:2000
```
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
Hello, your session id is sHkkESxJgzOyDhDwyTjwpNzq
```
api.mydomain.com
```
Hello, your session id is uuo4U5ierZAG8LSH1BdwTlVf
Hello, your session id is 8BxL97Bo35SDt4uliuPgnbia
Hello, your session id is 0xkqZZpzQNvTsQpbJtUlXgkR
```
**Setup info**
NodeJS v0.8.8
Apache v2.4.2
ExpressJS v3.0.0rc4
**UPDATE 2**
Well, I've so far resolved to simple use `mydomain.com/api`, as that seems to fix everything. So I suppose it's just something to do with how Apache handles domain communication with Express!
|
2012/09/06
|
[
"https://Stackoverflow.com/questions/12295963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731814/"
] |
Judging by [Apache ProxyPass and Sessions](https://stackoverflow.com/questions/8676890/apache-proxypass-and-sessions) This apache config Maybe ...
```
<VirtualHost *:80>
ServerName api.mydomain.com
ProxyPass / http://localhost:2000/
ProxyPassReverse / http://localhost:2000/
ProxyPassReverseCookiePath / /
</VirtualHost>
```
|
8,054,360 |
I have written my own `PopupPanel` in GWT. I want to show the popup relative to an other widget. My implementation of the class looks like the following:
```java
public class Popover extends PopupPanel implements PositionCallback {
private static final Binder binder = GWT.create(Binder.class);
private UIObject relative;
interface Binder extends UiBinder<Widget, Popover> {
}
public Popover() {
setWidget(binder.createAndBindUi(this));
setStylePrimaryName("popover");
}
public void show(UIObject relative) {
this.relative = relative;
setPopupPositionAndShow(this);
}
public void setPosition(int offsetWidth, int offsetHeight) {
if (relative != null) {
int left = relative.getAbsoluteLeft();
int top = relative.getAbsoluteTop();
int width = relative.getOffsetWidth();
int height = relative.getOffsetHeight();
int topCenter = top + height / 2 - offsetHeight / 2;
if (offsetWidth < left) {
setPopupPosition(left - offsetWidth, topCenter);
} else {
setPopupPosition(left + width, topCenter);
}
}
}
}
```
The problem is that `offsetWidth` and `offsetHeight` is always `10`?
My `Popover.ui.xml` looks like the following:
```xml
<g:FlowPanel stylePrimaryName="popover">
<g:FlowPanel stylePrimaryName="arrow" />
<g:FlowPanel stylePrimaryName="inner">
<g:Label stylePrimaryName="title" text="New Label" />
<g:FlowPanel stylePrimaryName="content">
<g:Label text="Hallo" />
</g:FlowPanel>
</g:FlowPanel>
</g:FlowPanel>
```
|
2011/11/08
|
[
"https://Stackoverflow.com/questions/8054360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
To solve this issue, I followed the steps used by `PopupPanel`'s `setPopupPositionAndShow()`, but I made the positioning step a deferred command. My code didn't extend `PopupPanel`, hence the `popupPanel` variable:
```java
popupPanel.setVisible(false);
popupPanel.show();
// Pausing until the event loop is clear appears to give the browser
// sufficient time to apply CSS styling. We use the popup's offset
// width and height to calculate the display position, but those
// dimensions are not accurate until styling has been applied.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
yourMethodToSetPositionGoesHere(popupPanel);
popupPanel.setVisible(true);
}
});
```
|
70,110,718 |
I'm trying to create a ENV VAR called SETTINGS in a Python image with Dockerfile. This env var must be dynamic, because I need to change the conf profile betweet production and preproduction.
I've created an script (entrypoint.sh) with two commands, the first one create the SETTINGS VAR and the second one is a python command.
The problem is that the python line works properly but the SETTINGS var doesn't.
Script
```
#!/bin/bash
profile=$profile
export SETTINGS=/acalls-service/${profile}.cfg
python -m "_acalls_clasiffier"
exec
```
Dockerfile
```
ENTRYPOINT ["/bin/bash", "-c", ". entrypoint.sh"]
```
I've tried with ["./entrypoint.sh] also but I doesn't work.
|
2021/11/25
|
[
"https://Stackoverflow.com/questions/70110718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10744148/"
] |
This would be a pretty typical use of an entrypoint wrapper script. Remember that a container only runs a single process. If your Dockerfile specifies an `ENTRYPOINT`, that's the process, and the `CMD` is passed as additional arguments to it. That lets you set up a script that does some first-time setup and then replaces itself with the real command:
```sh
#!/bin/sh
# Set the environment variable
export SETTINGS=/acalls-service/${profile}.cfg
# Run the CMD
exec "$@"
```
In your Dockerfile you'd specify this script as the `ENTRYPOINT` and then the actual command as `CMD`.
```sh
ENTRYPOINT ["./entrypoint.sh"] # must be JSON-array syntax
CMD ["python", "-m", "_acalls_clasiffier"] # shell syntax allowed here too
```
Since you can easily provide a replacement `CMD`, you can check that this is working
```sh
docker run --rm myimage \
sh -c 'echo $SETTINGS' # <-- run in the container, single-quoted so the
# host shell doesn't expand it
```
If you get a debugging shell in the container with `docker exec`, it won't see the variable set because it doesn't run through the entrypoint sequence. That's not usually a practical problem. You can always `docker run` a new container with an interactive shell instead of the Python script.
|
60,408,730 |
I am using spring boot starter 2.2.0.RELEASE for my application. I have one kafka consumer. Now I want to inject my spring entities into my kafka consumer (kafka consumer is not managed by spring container).
I tried ApplicationContextAware but it didn't helped me. I am getting applicationContext as null in my kafka consumer and hence I am not able to get bean from spring container. First time applicationContext is getting set properly but when context loads second time it set to null.
Below are the details of my application in short
```
@SpringBootApplication
@ComponentScan({"com.xyz.config_assign.service"})
public class ConfigAssignServer {
private static Logger log = LoggerFactory.getLogger(ConfigAssignServer.class);
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigAssignServer.class, args);
log.info("Started ConfigAssign Server!!! AppName= {} ", applicationContext.getApplicationName());
QkafkaClient.loadConfiguration();
}
}
```
All my application classes are present in com.xyz.config\_assign.service so no issue of bean scanning problem. It worked well before I add Kafka consumer
My ApplicationContextProvider which is using famous ApplicationContextAware
```
@Component
public class ApplicationContextProvider implements ApplicationContextAware{
public static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
```
And now my kafkaconsumer
```
public class ConfigAssignmentAssetTagChangeKafkaTopicProcessor implements BatchTopicProcessor<String, String> {
private Logger log = LoggerFactory.getLogger(ConfigAssignmentAssetTagChangeKafkaTopicProcessor.class);
private AssignConfigServiceImpl assignConfigServiceImpl;
public ConfigAssignmentAssetTagChangeKafkaTopicProcessor(){
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
assignConfigServiceImpl = applicationContext.getBean(AssignConfigServiceImpl.class);
}
@Override
public void handleError(ConsumerRecords<String, String> arg0, Exception arg1) {
// TODO Auto-generated method stub
}
@Override
public void process(ConsumerRecords<String, String> records, long arg1) {}
}
```
And the service I want to inject into kafka consumer is
```
@Service
public class AssignConfigServiceImpl implements AssignConfigService {
private Logger log = LoggerFactory.getLogger(AssignConfigServiceImpl.class);
@Autowired
private ConfigProfileDBService dbService;
public boolean assignConfigToAgents(List<UUID> agentList, long customerId) {
List<AgentConfigurationProfile> configProfiles =
dbService.getConfigurationProfilesForCustomer(customerId);
boolean isAssignSuccessful = assignConfigToAgents(agentList, customerId, configProfiles);
log.info("Config Assignment status ={}", isAssignSuccessful);
return isAssignSuccessful;
}
```
The other service I used is
```
@Service
public class ConfigProfileDBService implements DBService {
private static Logger log = LoggerFactory.getLogger(ConfigProfileDBService.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public List<AgentConfigurationProfile> getConfigurationProfilesForCustomer(Long customerId) {
List<AgentConfigurationProfile> agentConfigList;
}
```
}
Can someone please let me know what went wrong, I tried multiple online solution but didn't worked for me. Thanks in advance.
Note : I haven't initialized any class using new operator.
|
2020/02/26
|
[
"https://Stackoverflow.com/questions/60408730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8086483/"
] |
Based on clarifications in question and comments, and assuming its impossible to move KafkaConsumer to be spring managed (which is I believe the best solution):
`@Autowired` won't work in KafkaConsumer, so no need to put that annotation.
I assume that you're getting null for Application context in this line:
```
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
```
This means that `ApplicationContextProvider#setApplicationContext` has not been called by the time you create Kafka Consumer. Spring in addition to injection also manages lifecyle of the managed objects. Since you're not in spring, you're "on-your-own" and you have to make sure that Application Context gets created first and only after that create other objects (like Kafka Consumer for example).
When application context starts it adds beans one by one at some point, among other beans it also gets to the `ApplicationContextProvider` and calls its setter.
|
20,131,144 |
I'm running the following query using NHibernate:
```
var query = session.QueryOver<TaskMeeting>()
.JoinQueryOver(x => x.Task)
.Where(x => x.CloseOn == null)
.List();
```
Which then generates the following SQL:
```
SELECT
this_.Id as Id89_1_,
this_.TaskMeetingTypeID as TaskMeet2_89_1_,
this_.DateTime as DateTime89_1_,
this_.Description as Descript4_89_1_,
this_.TaskID as TaskID89_1_,
ltaskalias1_.Id as Id87_0_,
ltaskalias1_.Title as Title87_0_,
ltaskalias1_.Description as Descript7_87_0_,
ltaskalias1_.CreatedOn as CreatedOn87_0_,
ltaskalias1_.LastUpdated as LastUpda9_87_0_,
ltaskalias1_.ClosedOn as ClosedOn87_0_,
FROM
dbo.[TaskMeeting] this_
inner join
dbo.[Task] ltaskalias1_
on this_.TaskID=ltaskalias1_.Id
WHERE
ltaskalias1_.ClosedOn is null
```
Is pulling joined table information normal behavior? I would think it should only be selecting data pertaining to the root entity unless I specify a `.Fetch` clause or manually select the data.
I'm using `Fluent NHibernate` for the class mappings, but they are basic mappings for something like this, no eager loading specified - just simple `Map` and `References` where appropriate.
I've tried removing the where clause thinking perhaps that was the cause. The additional `SELECT`s continue to persist unless I remove the join itself.
|
2013/11/21
|
[
"https://Stackoverflow.com/questions/20131144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467172/"
] |
The way you queried your data, you get back a generic IList<> containing TaskMeeting entities. So it's normal for NHibernate to query all columns of your TaskMeeting table to put that data into your TaskMeeting entity properties. But i guess that is known already.
But because you want to restrict the data through another table you have to make a join to it. And that's the expensive part for the database server. Querying those few additional columns is peanuts compared to it and NHibernate might as well use the data to fill the Task references in your TaskMeeting entities.
At least that's how i understand it.
|
14,150,565 |
The following code is to add the font tag to every character, but it don't work
```
Function AddFontTag (counter)
Do While Len (counter) < 7
newStr = newStr & "<font>" & Left (counter, i) & "</font>"
i = i + 1
Loop
AddFontTag = newStr
End Function
```
Because i'm not skilled in classic asp, such as variable scope, syntax. Does anyone know what's the problems of the above code?
thanks
|
2013/01/04
|
[
"https://Stackoverflow.com/questions/14150565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925552/"
] |
Your `do..while` loop is an infinite loop - assuming `counter` is a string variable, its length never changes so if `Len(counter)` is less than `7` upon entering the function, it'll always stay less than `7` so your function never exits.
Your `newStr` variable is undefined - this works in VBScript but it's really bad practice and it's a source of countless errors. Is it a global variable or is it supposed to be a local? (It looks like a local.)
|
2,137,187 |
I am stuck on this limit.
$$\lim\_{n\to\infty} \sqrt[3]{n^2+5}-\sqrt[3]{n^2+3}$$
I couldn't find the limit using the basic properties of limits, since that just yields: $$\infty-\infty$$ which is undefined. Could I get any hints for finding this limit?
|
2017/02/09
|
[
"https://math.stackexchange.com/questions/2137187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409174/"
] |
Hint: Mulitply by
$$
\frac{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}{\left(\sqrt[3]{n^2+5}\right)^2 + \sqrt[3]{n^2+5}\sqrt[3]{n^2+3} + \left(\sqrt[3]{n^2+3}\right)^2}
$$
|
32,500 |
Could you please explain why the syntax in the following stanza is wrong?
>
> Surrounded
>
> by that sturdy assertiveness
>
> that walled England the din
>
> of traffic in my mind quietens,
>
>
>
|
2011/07/02
|
[
"https://english.stackexchange.com/questions/32500",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/10536/"
] |
There is nothing I can see wrong in the syntax of that stanza. In fact, unlike much poetry, there is no serious lexical ambiguity; and with a single comma it would render just fine as a prose sentence:
>
> Surrounded by that sturdy assertiveness that walled England, the din of traffic in my mind quietens.
>
>
>
Take "that sturdy assertiveness that walled England" to mean "the trait that formed a wall around England, which I will call 'sturdy assertiveness'" ... and thus shielded [as I am from such assertiveness], the noise of traffic in my mind becomes still.
|
33,061,827 |
This question has been asked before: [Start the thumbnails from the left of the slideshow instead of the middle](https://stackoverflow.com/q/30867297/4220943), but there's no answer yet.
I'm trying to get the thumbnail bar at the bottom to align the thumbnails to the left when fotorama is loaded. By default, it's centered.
|
2015/10/11
|
[
"https://Stackoverflow.com/questions/33061827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220943/"
] |
As I answered it here, [Start the thumbnails from the left of the slideshow instead of the middle](https://stackoverflow.com/questions/30867297/start-the-thumbnails-from-the-left-of-the-sldieshow-instead-of-middle-of-the-sli/33062159#33062159), It is simple. The fotorama plugin uses css3 transform property to align thumbnails under the main image. just calculate the parent width and children container width using jQuery and if the parent is wider than children container, make a transform across X axis to shift all thumbnails to the left.
**EDIT:**
I made an edit that when you click on on arrows or thumbnails, it also does the alignment fix!
```
$(document).ready(function() {
var pw = $('.fotorama__nav--thumbs').innerWidth();
var cw = $('.fotorama__nav__shaft').innerWidth();
var offset = pw -cw;
var negOffset = (-1 * offset) / 2;
var totalOffset = negOffset + 'px';
if (pw > cw) {
$('.fotorama__nav__shaft').css('transform', 'translate3d(' + totalOffset + ', 0, 0)');
}
$('.fotorama__nav__frame--thumb, .fotorama__arr, .fotorama__stage__frame, .fotorama__img, .fotorama__stage__shaft').click(function() {
if (pw > cw) {
$('.fotorama__nav__shaft').css('transform', 'translate3d(' + totalOffset + ', 0, 0)');
}
});
});
```
|
47,171 |
I'm running an alter table, alter column on a table with nearly 30 million rows and SQL Azure fails after approximately 18 minutes saying that `The session has been terminated because of excessive transaction log space usage. Try modifying fewer rows in a single transaction.`
I'm guessing that it's not possible to break this down into modifying fewer rows at a time, so I'm wondering what my options are for making this change to the database. SQL Azure will not let me change the size of the transaction log (limited to 1gb).
I'm guessing that my best bet is going to be creating a new table with the new layout, migrating the data across into that one, deleting the original table and then renaming the new table to match the name of the old table. If that's the case, how is it best to structure those commands?
Scheduled downtime for our system is not an issue currently so this operation can take as long as it needs to.
|
2013/07/28
|
[
"https://dba.stackexchange.com/questions/47171",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/574/"
] |
You will want to load your data into a new table, doing this in small batches, then drop the existing table. I put together a quick example using the Sales.Customer table in AdventureWorks, something similar should work for you also.
First, create your new table, complete with the new datatype you want to use:
```
CREATE TABLE [Sales].[Currency_New](
[CurrencyCode] [nchar](4) NOT NULL,
[Name] [varchar](128) NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
CONSTRAINT [PK_Currency_New_CurrencyCode] PRIMARY KEY CLUSTERED
(
[CurrencyCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
```
Then, insert your records and define your batch. I am using 10 here, but you will likely want to use something larger, say 10,000 rows at a time. For 30MM rows I'd even suggest you go to 100k row batch size at a time, that's the limit I typically used with larger tables:
```
DECLARE @RowsInserted INT, @InsertVolume INT
SET @RowsInserted = 1
SET @InsertVolume = 10 --Set to # of rows
WHILE @RowsInserted > 0
BEGIN
INSERT INTO [Sales].[Currency_New] ([CurrencyCode]
,[Name]
,[ModifiedDate])
SELECT TOP (@InsertVolume)
SC.[CurrencyCode]
,SC.[Name]
,SC.[ModifiedDate]
FROM [Sales].[Currency] AS SC
LEFT JOIN [Sales].[Currency_New] AS SCN
ON SC.[CurrencyCode] = SCN.[CurrencyCode]
WHERE SCN.[CurrencyCode] IS NULL
SET @RowsInserted = @@ROWCOUNT
END
```
I usually do a sanity check and verify the rowcounts are the same before cleaning up:
```
SELECT COUNT(*) FROM [Sales].[Currency]
SELECT COUNT(*) FROM [Sales].[Currency_New]
```
Once you are confident you have migrated your data, you can drop the original table:
```
DROP TABLE [Sales].[Currency]
```
Last step, rename the new table, so that users don't have to change any code:
```
EXEC sp_rename '[Sales].[Currency_New]', '[Sales].[Currency]';
GO
```
I don't know how long this will take. I'd suggest you try doing this when you have a clear maintenance window and users aren't connected.
HTH
|
914,814 |
```
class Object
attr_reader :foo
def initialize
@foo = 'bar'
end
end
Object.new.foo # => 'bar'
''.foo # => nil
//.foo # => nil
[].foo # => nil
```
I want them all to return `'bar'`
Am aware that you can do this already:
```
class Object
def foo
'bar'
end
end
```
But I specifically want to initialize a state variable. Also note that this doesn't work.
```
class String
alias_method :old_init, :initialize
def initialize(*args)
super
old_init(*args)
end
end
class Object
attr_reader :foo
def initialize
@foo = 'bar'
super
end
end
''.foo # => nil
```
Nor does this:
```
class String
attr_reader :foo
def initialize
@foo = 'bar'
end
end
''.instance_variables # => []
```
I'm beginning to think that this isn't actually possible.
|
2009/05/27
|
[
"https://Stackoverflow.com/questions/914814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113019/"
] |
This **is** possible.
```
class Object
class << self
Kernel.send :define_method, :foo do #Object.send to be more restrictive
@foo = 'bar'
end
end
end
```
.
```
irb(main):023:0> class Object
irb(main):024:1> class << self
irb(main):025:2> Kernel.send :define_method, :foo do
irb(main):026:3* @foo = 'bar'
irb(main):027:3> end
irb(main):028:2> end
irb(main):029:1> end
=> #<Proc:0x00007f5ac89db168@(irb):25>
irb(main):030:0> x = Object.new
=> #<Object:0x7f5ac89d6348>
irb(main):031:0> x.foo
=> "bar"
irb(main):032:0> [].foo
=> "bar"
irb(main):033:0> //.foo
=> "bar"
```
It's important to understand eigenclasses. Every class is implemented mysteriously by the Ruby interpreter as a hidden class type:
```
irb(main):001:0> class Object
irb(main):002:1> def eigenclass
irb(main):003:2> class << self; self; end
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> x = Object.new
=> #<Object:0x7fb6f285cd10>
irb(main):007:0> x.eigenclass
=> #<Class:#<Object:0x7fb6f285cd10>>
irb(main):008:0> Object.eigenclass
=> #<Class:Object>
irb(main):009:0> Object.class
=> Class
```
So, in your example, when you're trying to call foo on your objects, it's operating on the class `#<Object:0x7fb6f285cd10>`. However, what you want it to operate on is the secret class `#<Class:#<Object:0x7fb6f285cd10>>`
I hope this helps!
|
91,576 |
Are the Jazz Masses, like the ones Mary Lou Williams and Joe Masters composed still licit forms of the Mass or have they been officially suppressed at some point in the last 50-60 years?
|
2022/06/14
|
[
"https://christianity.stackexchange.com/questions/91576",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/4/"
] |
The 1967 instruction *[Musicam Sacram](https://www.vatican.va/archive/hist_councils/ii_vatican_council/documents/vat-ii_instr_19670305_musicam-sacram_en.html)* stated
>
> In permitting and using musical instruments, the culture and traditions of individual peoples must be taken into account. However, those instruments which are, by common opinion and use, suitable for secular music only, are to be altogether prohibited from every liturgical celebration and from popular devotions.
>
>
>
Note that this was written 8 years before *Mary Lou's Mass*, and the same year as Masters' *The Jazz Mass*.
In the 2003 *[Chirograph for the Centenary of the Motu Proprio "Tra le Sollecitudini" On Sacred Music](https://www.vatican.va/content/john-paul-ii/en/letters/2003/documents/hf_jp-ii_let_20031203_musica-sacra.html)* St John Paul II wrote:
>
> With regard to compositions of liturgical music, I make my own the "general rule" that St Pius X formulated in these words: "The more closely a composition for church approaches in its movement, inspiration and savour the Gregorian melodic form, the more sacred and liturgical it becomes; and the more out of harmony it is with that supreme model, the less worthy it is of the temple"
>
>
>
And so in 1903 the rules for church music had been thoroughly formulated by St Pius X in *[Tra Le Sollecitudini](https://adoremus.org/1903/11/tra-le-sollecitudini/)*
Therefore, it seems any "jazz mass" could only take place either outside of a Catholic Mass, or in a Catholic Mass only illicitly.
|
51,153,183 |
I am trying to cherry-pick a commit from one branch to another. Consider the below scenario.
Branch A -> commit1 -> commit message "12345 Hello World"
I want to add a new message at the beginning of the commit message while doing cherry-pick. So after cherry-pick it should look like,
Branch B -> commit2 -> commit message "98765 ........"
Here 98765 is the extra message I want to add. From Git documentation I found a command "git cherry-pick --edit" but I didn't find any example to understand its proper use.
|
2018/07/03
|
[
"https://Stackoverflow.com/questions/51153183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6096034/"
] |
There isn't much to explain about `git cherry-pick --edit`. If you cherry pick with the `--edit` option, Git will bring up the commit message editor window before making the commit. There, you may customize the commit message however you want.
As to the logistics of *why* this is possible, when you cherry pick a commit you actually are making a *new* commit. So there is nothing extra to prevent you from using any commit message you want.
|
53,855,437 |
I'm a beginner and I'm working on a little exercice right now where I need to implement a function that will vote for a specific picture every time we click on the "Vote" button.
[](https://i.stack.imgur.com/CgrDy.png)
Here is what it looks like, for example if I click on the first button, I need to increment the number of vote for this picture.
Here is what i did :
```
<div id="display" class="container">
<table class="w3-table-all" id="tableDisplay">
<tr>
<th>Cat</th>
<th>Vote</th>
</tr>
</table>
<div v-for="display in gridData">
<table class="w3-striped w3-table-all table table-bordered" id="tableDisplay">
<tr class="w3-hover-light-grey">
<th>
<img :src="display.url" height="200px" width="300px"/>
</th>
<th>
<button class="w3-button w3-green w3-hover-light-green"v-on:click="test(display.counter,display.id)" v-bind:id="display.id">Vote !</button>
</th>
</tr>
</table>
</div>
</div>
```
And the vueJs part :
```
new Vue({
el :'#display',
data: {
gridData :[
{
"url": "http://24.media.tumblr.com/tumblr_m82woaL5AD1rro1o5o1_1280.jpg",
"id": "MTgwODA3MA",
"counter" : 0
},
{
"url": "http://24.media.tumblr.com/tumblr_m29a9d62C81r2rj8po1_500.jpg",
"id": "tt",
"counter" : 0
}
],
},
methods:{
test: function(count,id){
count ++;
alert(count);
}
},
})
```
And the problem is that it doesn't update the change, in the "counter" section it still at 0.
Thank you for any help.
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53855437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9736244/"
] |
Easiest way is to pipe `node`'s stdout to `python`'s stdin and keep reading `stdin` in Python until it is over. What is not good is that you most probably want to have some console output from Node application, and you definately dont want it to be passed to Python.
Second, recommended approach is to use `tcp/ip` channel. In this case you also benefit from being able to move Python app to another machine/container. Listening tcp/ip input in Python is very simple, I usually use following approach:
```
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import LineReceiver
class DataProcessor(LineReceiver):
def lineReceived(self, line):
print('Line received: {}'.format(line))
Factory factory = Factory()
factory.protocol = DataProcessor
reactor.listenTCP(8080, factory)
```
|
17,374,871 |
My project has a bare repo setup on the server. I'm currently on branch `0.9/develop`. I merged `0.9/develop` with a branch that another developer was working on. It turns out that it would be **way** more work to fix his code than to obliterate his changes entirely. Unfortunately, I already ran a `git push origin 0.9/develop` after having committed the merge AND I pulled those changes to my development AND staging servers (yes, I'm stupid).
I've been going through a bunch of somewhat similar questions on SO, but none of them quite seem to cover my exact case. This one was particularly useful: [How to revert Git repository to a previous commit?](https://stackoverflow.com/questions/4114095/git-revert-to-previous-commit-how)
Using info from that question, I was able to successfully obliterate the last commit off of the project. Specifically, I did a `git reset --hard f6c84a0`, which successfully reset my local repository to the commit right before I merged the other developer's n00bery into my poetry.
Okay, great. Now I just need to get the bare repo fixed up. So I tried `git push --force origin 0.9/develop`. Unfortunately I lost the specific message that the server sent back, but it was something along the lines of "success", and it showed that the remote repo had been updated to commit f6c84a0.
When I tried to ssh into the server and then go to my staging environment and run a `git pull`, the response was:
```
From /home/ben/web/example
+ 77d54e4...f6c84a0 0.9/develop -> origin/0.9/develop (forced update)
Already up-to-date.
```
However, when I ran a `git log` from the staging server, all of the commits from the merge are still on the `0.9/develop` branch. I tried a couple of things, like `git pull --force`, but I couldn't get the bad commits to go away.
Okay, fine. There's more than one way to skin a cat. I wiped the staging server clean and did a fresh `git clone --recursive --no-hardlinks example.git stage.example.com` and ran the necessary setup script that does a few little server maintenance things.
Now I can't get back to my `0.9/develop branch`. In the past, I have simply run `git checkout 0.9/develop`, but if I try that now, I get this:
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
Wait...what? `0.9/develop` is not a new branch. Working with info from this question: [How to clone all remote branches in Git?](https://stackoverflow.com/questions/67699/how-do-i-clone-all-remote-branches-with-git) I did a `git branch -a` and got the following:
```
* 0.9/develop
master
remotes/origin/0.8/develop
remotes/origin/0.8/master
remotes/origin/0.9/develop
remotes/origin/HEAD -> origin/master
remotes/origin/category-address
remotes/origin/jaminimaj
remotes/origin/master
remotes/origin/permissions
remotes/origin/ticket-duration
remotes/origin/timzone-support
```
I then tried `git checkout origin/0.9/develop`, but I got the following message:
```
Note: checking out 'origin/0.9/develop'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at f6c84a0... bugfix: revert email helper
```
Well, the good news is the staging server now has the proper code base, but I'm in a detached HEAD state. I realize that I'm probably missing something very minor here, but it certainly is messing with my Friday evening. How can I get my staging server HEAD pointing back to the HEAD of `0.9/develop`? Also, I want to do the same thing on my development environment, but I'd rather do it in the proper `git` fashion than erasing the whole server and starting over again. Can I do that, or will I just have to brute-force it by rebuilding the server from the repo? Thanks for the help everybody!
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17374871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023812/"
] |
The message
```
Branch 0.9/develop set up to track remote branch 0.9/develop from origin.
Switched to a new branch '0.9/develop'
```
means the following:
* git created a new branch pointer named 0.9/develop that points to the current head of origin/0.9/develop
* This branch pointer has auto-generated configuration settings to track the remote branch so that git pull and git push work as expected.
So it does what it's supposed to do. It's just a bit counter-intuitive, basically to work with a branch you need a local branch in the repository you cloned. This is merged with the remote branch whenever you run `git pull`.
By the way, git pull in the tracking branch is equivalent to
```
git fetch
git merge remotes/origin/0.9/develop
```
|
23,318,767 |
I have this little class:
```
var SwitchHider;
SwitchHider = {
inputSelector: 'body.socials input',
_showOrHideClosestSwitch: function(element) {
var socialUrl, swich_wrapper;
socialUrl = $(element).val();
swich_wrapper = $(element).closest('.white-box').find('.switch');
if (socialUrl.length > 0) {
return swich_wrapper.show();
} else {
return swich_wrapper.hide();
}
},
_bindCallbacks: function() {
$(document).on('ready', function() {
return $(self.inputSelector).each(function(index, element) {
return self._showOrHideClosestSwitch(element);
});
});
return $(document).on('change keyup input', self.inputSelector, function() {
return self._showOrHideClosestSwitch(this);
});
},
initialize: function() {
var self;
self = this;
this._bindCallbacks();
}
};
window.SwitchHider = SwitchHider;
$(function() {
SwitchHider.initialize();
});
```
(it's compiled from this CoffeeScript file, hope it makes sense):
```
SwitchHider =
inputSelector: 'body.socials input'
_showOrHideClosestSwitch: (element) ->
socialUrl = $(element).val()
swich_wrapper = $(element).closest('.white-box').find('.switch')
if socialUrl.length > 0
swich_wrapper.show()
else
swich_wrapper.hide()
_bindCallbacks: ->
$(document).on 'ready', ->
$(self.inputSelector).each (index, element) ->
self._showOrHideClosestSwitch(element)
$(document).on 'change keyup input', self.inputSelector, ->
self._showOrHideClosestSwitch(@)
initialize: ->
self = this
@_bindCallbacks()
return
# Send to global namespace
window.SwitchHider = SwitchHider
# DOM Ready
$ ->
SwitchHider.initialize()
return
```
And when event is triggered - it gives this error:
```
TypeError: self._showOrHideClosestSwitch is not a function
```
Does anyone see why? It's my first attempt to write classes like that, don't fully understand what I'm doing.
|
2014/04/27
|
[
"https://Stackoverflow.com/questions/23318767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988673/"
] |
The two commands have absolutely nothing in common, so no, you cannot use parentheses like that.
You must execute all the commands within a single CMD /C. You can concatenate commands on one line using `&`. I've defined a simple XCOPY "macro" to save a bit of typing.
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c "cmd /c echo Copying World: @path&%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2%&%XCOPY% @file %backdir%\%itdate%D\worlds\@file"
```
If you escape the quotes, then you can use line continuation to split the logical line accross multiple lines. But then you must also escape the `&`.
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c ^"cmd /c ^
echo Copying World: @path ^&^
%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2% ^&^
%XCOPY% @file %backdir%\%itdate%D\worlds\@file^"
```
Or you could put the `&` in the front of the line so that you don't need to escape it. The line continuation also escapes the first character of the next line:
```
set XCOPY=xcopy /e /c /h /i /v /r /y /q"
forfiles /m "%worldprefix%*" /c ^"cmd /c ^
echo Copying World: @path^
&%XCOPY% @file %snapshotdir%\@file\%itdate%-%hour%-%time:~3,2%-%time:~6,2%^
&%XCOPY% @file %backdir%\%itdate%D\worlds\@file^"
```
|
40,765,504 |
I upload image files with codeigniter to my website using:
```
$uploaded = $this->upload->data();
```
and getting the filename in this way:
```
$uploaded['file_name'];
```
I want to change this filename adding "\_thumb" before extension and after the name. Like 'sda8sda8fa8f9.jpg' to 'sda8sda8fa8f9\_thumb.jpg'. Since I need to keep hashed name, what is the simpliest way to do this?
|
2016/11/23
|
[
"https://Stackoverflow.com/questions/40765504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5830157/"
] |
When configuring [CI's file uploader](https://www.codeigniter.com/user_guide/libraries/file_uploading.html), you can pass a `file_name` option to the class. That will change the name of the uploaded file. Here's the description from the docs:
>
> If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file\_name will be used.
>
>
>
And an example:
```php
$this->load->library('upload', ['file_name' => 'new-file-name.ext']);
$this->upload->do_upload('file_field_name');
```
So, you want to **modify** the uploaded file's name. The uploaded filename can be accessed from PHP's `$_FILES` array. First, we figure out the new name, then we hit CI's upload library. Assuming that the fieldname is `fieldname`:
```php
// Modify the filename, adding that "_thumb" thing
// I assumed the extension is always ".jpg" for the sake of simplicity,
// but if that's not the case, you can use "pathinfo()" to get info on
// the filename in order to modify it.
$new_filename = str_replace('.jpg', '_thumb.jpg', $_FILES['fieldname']['name']);
// Configure CI's upload library with the filename and hit it
$this->upload->initialize([
'file_name' => $new_filename
// Other config options...
]);
$this->upload->do_upload('fieldname');
```
Please note that the original filename (that from the `$_FILES['fieldname']['name']`) comes from the user's browser. It's the actual filename on user's device. As you decided to depend on it in your code, **always treat it as tainted.**
|
51,800,460 |
beginner in React and javascript, i'm stuck to this problem:
How can i show/hide a specific div when i click to his dedicated shutter button?
here is the idea i came with but as you may see , when i click an "open" or " close " link, it justs affect every div.
```
import React from 'react'
class Qui extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return(
<div>
<h1>first part</h1>
<a onClick={this.handleClick>
{this.state.isToggleOn ? 'open' : 'close'}
</a>
<div className={this.state.isToggleOn ? 'hidden':'visible'}>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
</div>
<h1>second part</h1>
<a onClick={this.handleClick>
{this.state.isToggleOn ? 'open' : 'close'}
</a>
<div className={this.state.isToggleOn ? 'hidden':'visible'}>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
</div>
</div>
)
}
}
```
Thanks for helping me :) .
|
2018/08/11
|
[
"https://Stackoverflow.com/questions/51800460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10212365/"
] |
You can set the activeDivIndex in the state, and then show the div based on the activeDivIndex value.
```
state = {
activeDivIndex: 0
};
handleClick = index => {
this.setState({ activeDivIndex: index });
};
render() {
return (
<div>
<h1>first part</h1>
<a onClick={() => this.handleClick(0)}>
{this.state.activeDivIndex === 0 ? "open" : "close"}
</a>
{this.state.activeDivIndex === 0 && (
<div>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
</div>
)}
<h1>second part</h1>
<a onClick={() => this.handleClick(1)}>
{this.state.activeDivIndex === 1 ? "open" : "close"}
</a>
{this.state.activeDivIndex === 1 && (
<div>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
</div>
)}
</div>
);
}
```
You can check it live in codesandbox [here](https://codesandbox.io/s/m458rr71rx).
|
4,618 |
I didn't see a related or similar question, but if you can find one, please link it and I'll close this.
**Background**
I had little experience in high school and college and learned some of my skills later. My first two serious girlfriends were in my twenties and they both cheated. From this I realized I didn't enjoy serious relationships, so I've avoided them. I have always been honest about this with people I date: "I'm just having fun and don't want this to ever get serious." This is my way of making it clear so that if the person wants "something more" - like marriage - they can move on faster. I just want to have fun - hang out, party, etc with the expectation that we'll be together for a few months with no intention of it leading to cohabitation or marriage.
I live in the US and am about to be 30.
My latest three dating experiences have ended with the other person upset about the relationship not becoming more serious, even though I made it clear that I would never get serious with the person.
*Example:*
>
> Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.
>
>
>
>
> Her (later): So we've been seeing each other for a few months ... [or some derivative that usually starts a conversation about where is this going, even though we both agreed initially "nowhere"].
>
>
>
**Problem**
When I meet someone to date, how can I communicate clearly that I am **only** interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?
|
2017/09/26
|
[
"https://interpersonal.stackexchange.com/questions/4618",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/6485/"
] |
I don't have much experience with dating. But I want to leave this here.
>
> *When I meet someone to date, how can I communicate clearly that I am only interested in a casual/short-term dating relationship, such as dating for a few months by doing fun activities, going to parties, attending concerts, etc?*
>
>
>
I think the problem here is the words **date** and **relationship**. It's sort of like [my answer to this question](https://interpersonal.stackexchange.com/a/4299/1599), only reversed: **You shouldn't mention those words!**
You are clearly looking for **friends**, not people you can have a short-term dating relationship with. It's okay to look for new friends, to do fun stuff with. But you don't take friends on dates, and you don't have 'relationships' with them (I prefer to call that particular form of a relation 'friendship', just to keep the two separated).
>
> *Me (initially): I don't do serious relationship; no boyfriend/girlfriend - just hanging out and having fun together.
>
> Her (initially): Great, I'm not looking for anything serious either.*
>
>
>
If you mention this on a first date, of course, people might say that they are fine with it. They are on a first date with you, they don't know you. But the fact that they are on a **date** with you, means to me that they are at least interested in trying to see if a **serious relationship** can grow out of it. She might not have been looking for anything serious **right at that moment**. But the fact that she's dating, means that she is looking for something that can grow into something serious.
At least, I've never dated a guy for any other reason. If I don't want a serious relationship or a something casual that can grow into a serious one, I'm not going on a date with you. Then, we're just doing stuff together, without calling it a date.
I don't know how you are meeting these people, but I get the impression that they are firm believers that they are 'on a date' with you. If you get them via dating-apps or websites, I think it might be wise to quit doing so. People are there to find somebody to 'date'. Even though they might not be there to start a serious relationship right away, I think most people on these platforms are hoping for something that can develop into one given the time to grow.
If these are persons that you have a mutual friend with, that mutual friend might have acted like a middle-man. Make sure your friends know that you are willing to be introduced to new people, but that you are only looking for **friends** that share your interests, **not a girlfriend**.
I would believe that in this case, the magic words are **friend** and **shared interests**. And that you should avoid the words **date** and **relationship**.
|
71,591,314 |
I'm working in an Electron application. There are alot of events being passed around with specific listeners for each event. For instance BrowserWindow.on:
```
Electron.BrowserWindow.on(event, listener)
```
`event` can be any of `'always-on-top-changed', 'app-command', etc etc...` . I want a list of all of these events in a single type that I can use, for example, to restrict other functions from passing in an invalid event.
I have tried:
`type BrowserWindowOnEvents = Parameters<InstanceType<typeof Electron.BrowserWindow>['on']>[0];`
But that only gives, at least for Intellisense, the last defined event in BrowserWindow class in electron.d.ts, which is currently `'will-resize'`. I am expecting a list with all valid events.
When I have `new BrowserWindow.on('')` the Intellisense does provide me with the list of possibilities, but I want access to the list when creating a type definition not only when I have an instance of BrowserWindow available.
---
Here's a link to Electron's [BrowserWindow](https://github.com/electron/electron/blob/main/lib/browser/api/browser-window.ts)
And in `electron.d.ts` this is how the methods are defined:
```
class BrowserWindow extends NodeEventEmitter {
// Docs: https://electronjs.org/docs/api/browser-window
/**
* Emitted when the window is set or unset to show always on top of other windows.
*/
on(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
once(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
addListener(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
removeListener(event: 'always-on-top-changed', listener: (event: Event,
isAlwaysOnTop: boolean) => void): this;
...
}
```
|
2022/03/23
|
[
"https://Stackoverflow.com/questions/71591314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5839529/"
] |
Turns out it is possible to do this, but it's not pretty. The problem is that the `on` method is declared with a separate overload for each event name, and type inference on overloaded functions only considers the last one (in this case the overload for `'will-resize'`).
There is a way to infer types from overloaded functions though ([see this TypeScript issue](https://github.com/microsoft/TypeScript/issues/32164#issuecomment-764660652)):
```
type Args<F extends (...args: any[]) => unknown> = F extends {
(...args: infer A1): void
(...args: infer A2): void
} ? [A1, A2] : never
declare function f(event: 'n1', l: (n: number) => void): void
declare function f(event: 'n2', l: (s: string) => void): void
type TestArgs = Args<typeof f>
// type TestArgs = [
// [event: "n1", l: (n: number) => void],
// [event: "n2", l: (s: string) => void]
// ]
```
The downside is that this requires creating a function object with at least as many overloads as the function we wish to extract the parameter types from. The `on` method on `BrowserWindow` has 36 overloads, so let's use 40 to be on the safe side:
```
type BuildOverloads<
A01 extends unknown[], A02 extends unknown[], A03 extends unknown[],
A04 extends unknown[], A05 extends unknown[], A06 extends unknown[],
A07 extends unknown[], A08 extends unknown[], A09 extends unknown[],
A10 extends unknown[], A11 extends unknown[], A12 extends unknown[],
A13 extends unknown[], A14 extends unknown[], A15 extends unknown[],
A16 extends unknown[], A17 extends unknown[], A18 extends unknown[],
A19 extends unknown[], A20 extends unknown[], A21 extends unknown[],
A22 extends unknown[], A23 extends unknown[], A24 extends unknown[],
A25 extends unknown[], A26 extends unknown[], A27 extends unknown[],
A28 extends unknown[], A29 extends unknown[], A30 extends unknown[],
A31 extends unknown[], A32 extends unknown[], A33 extends unknown[],
A34 extends unknown[], A35 extends unknown[], A36 extends unknown[],
A37 extends unknown[], A38 extends unknown[], A39 extends unknown[],
A40 extends unknown[]
> = {
(...args: A01): unknown; (...args: A02): unknown; (...args: A03): unknown;
(...args: A04): unknown; (...args: A05): unknown; (...args: A06): unknown;
(...args: A07): unknown; (...args: A08): unknown; (...args: A09): unknown;
(...args: A10): unknown; (...args: A11): unknown; (...args: A12): unknown;
(...args: A13): unknown; (...args: A14): unknown; (...args: A15): unknown;
(...args: A16): unknown; (...args: A17): unknown; (...args: A18): unknown;
(...args: A19): unknown; (...args: A20): unknown; (...args: A21): unknown;
(...args: A22): unknown; (...args: A23): unknown; (...args: A24): unknown;
(...args: A25): unknown; (...args: A26): unknown; (...args: A27): unknown;
(...args: A28): unknown; (...args: A29): unknown; (...args: A30): unknown;
(...args: A31): unknown; (...args: A32): unknown; (...args: A33): unknown;
(...args: A34): unknown; (...args: A35): unknown; (...args: A36): unknown;
(...args: A37): unknown; (...args: A38): unknown; (...args: A39): unknown;
(...args: A40): unknown;
}
```
There's a minor issue with the solutions in the issue thread, in that they only work if one of the overloads takes either no parameters or only unknown parameters, which is not the case for `on`. The solution by jcalz doesn't have this problem, but it would require writing 41 \* 40 = 1640 function signatures, which is impractical.
To remedy the problem we can simply add this extra overload by inferring on `T & ((...args: unknown[]) => unknown)` instead of `T`, and removing any `unknown[]` elements from the resulting list.
```
type ElementTypeWithoutUnknown<T extends unknown[]> =
{[K in keyof T]: unknown[] extends T[K] ? never : T[K]}[number]
```
Now we have everything we need to define `GetOverloadParameters`:
```
type GetOverloadParameters<T extends (...args: any) => unknown> =
T & ((...args: unknown[]) => unknown) extends BuildOverloads<
infer A01, infer A02, infer A03, infer A04, infer A05, infer A06, infer A07,
infer A08, infer A09, infer A10, infer A11, infer A12, infer A13, infer A14,
infer A15, infer A16, infer A17, infer A18, infer A19, infer A20, infer A21,
infer A22, infer A23, infer A24, infer A25, infer A26, infer A27, infer A28,
infer A29, infer A30, infer A31, infer A32, infer A33, infer A34, infer A35,
infer A36, infer A37, infer A38, infer A39, infer A40
> ?
ElementTypeWithoutUnknown<[
A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15,
A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30,
A31, A32, A33, A34, A35, A36, A37, A38, A39, A40
]> : never
```
And we can apply it like this:
```
type EventName = GetOverloadParameters<Electron.BrowserWindow['on']>[0]
// type EventName = "always-on-top-changed" | "app-command" | .. | "will-resize"
```
(Note that the type `Electron.BrowserWindow` denotes the type of the object rather than the class, so there's no need to do `InstanceType<typeof Electron.BrowserWindow>`.)
Because the union of 36 event names is too big to show in a hover type, we can declare a couple of helpers to group them based on the number of dashes in the name (just to verify they are all present, you won't need to do this in your code):
```
type Dash0<S extends string> = S extends `${string}-${string}` ? never : S
type Dash1<S extends string> = S extends `${string}-${Dash0<infer _>}` ? S : never
type Dash2<S extends string> = S extends `${string}-${Dash1<infer _>}` ? S : never
type Dash3<S extends string> = S extends `${string}-${Dash2<infer _>}` ? S : never
type EventName1 = Dash0<EventName>
// EventName1 = "blur" | "close" | "closed" | "focus" | "hide" | "maximize" |
// "minimize" | "move" | "moved" | "resize" | "resized" |
// "responsive" | "restore" | "show" | "swipe" | "unmaximize" |
// "unresponsive"
type EventName2 = Dash1<EventName>
// EventName2 = "app-command" | "rotate-gesture" | "session-end" | "sheet-begin" |
// "sheet-end" | "will-move" | "will-resize"
type EventName3 = Dash2<EventName>
// EventName3 = "enter-full-screen" | "leave-full-screen" | "page-title-updated" |
// "ready-to-show" | "scroll-touch-begin" | "scroll-touch-edge" |
// "scroll-touch-end" | "system-context-menu"
type EventName4 = Dash3<EventName>
// EventName4 = "always-on-top-changed" | "enter-html-full-screen" |
// "leave-html-full-screen" | "new-window-for-tab"
```
[TypeScript playground](https://www.typescriptlang.org/play?jsx=0#code/JYWwDg9gTgLgBAUQDYFMDGMoQHZwGZYhwDkKqGW2xAUNTAJ5gpwCCUA5gM4A8AYnCgAeMFNgAmnOAAoAdHICGHTgC4487PQDaAXQCUcALwA+OAFdsAa2wQA7thMG4-ISPGSA3tTjS5MxV1VgbDwUKFYARl1VADcIYDEvHwUlQODQ1gAmKLhY+OoAXzgAfjhNFnCAGkztOFVsFGjQ2jF0JEVmPHMMYBx8KQbRGFVibHDiKqRVKWw60xAAI1D9Yxy4sWzchJa0NqgOrpge3Dx+xuwhkmwM8bhJ6RU4Tkwg9mWTTY212gYmOAAVFBPNhcQysJTcH4oCB4fBGagAenh3jgAD0it9GMxkCgQIM-piAOrAGAACwgphgAFVLNY7Nw-gJhKIJGYabZsDoHIl3JoANJwIJwCwoejQ-7aVTmKzsnSM1wsv58moleqNMKqRW87T5TTYOaLKDaDG-AFPbG4874phE0nkqlsuyg814wnEskU6nSumaKW0jnaKqaEZjKpPKAvAOlEbXKp6hahbTaOGI5Fo43MABCpmASDEAHk1UgIPIJNxEiwAAzhOXMyS+mWRysZGtuVle-1VSsAZhbLPrdh0FXLFYALL26w6O6wKwBWcdtv2D6cANnn-Y7w4A7GvJ0vKwAOHftvcVgCcR8XAfL4QrF4bnfC1ZctYX94izefrfXg+vPc-fd3RtwjHf8J2PIC51A18ByvbxylXKDvyA7dEMAh9D1Q8Chzg8Jz0wy9OwyW98LfFgMifJkvzQ8sMg-SiAKwzI-3osCCMyECWOgjc4IySDOKQwiEP4tDMhQ4SsJojDxLYsi8Ok0iu2I+SYOw1guwo+VWIUujNK4vcu2Y3SBPLLsOKMkSWC7PjzMYyyhJsgiTLEhyFKklyVLUuT3O41gRyU7ydGoBw4E8bxZGSAJp0iSVJwAbiSPwUmnLIYvbeLwsSyLu2yddYsSDL-AeSsRxyuKEsK1RKxnUq0vKpLK2XGq-TysLfAq6dNya9l0ra+qK33Lq7B6iKirPQbsBauqspvcbhsyorH1mqaFpSrjJoK+rwi7JaNumkrUua5bKvCaqDu6-LeumxqzqGo6Ik6m6Jru8oBse9bLoW08do+yqiO+kbfuitaLoBzJVty56Mm2t7If24HWtBsjTrWyHrpR3aioyB74ch170Z+zIvphjHKsU2aQfm0mgYhkm1PBsracs6GccZ0z-sptTkZpgm7PJhGOcs7HucRrs8eFgWuyJlmeb88n8nTOAAHEUBgAtQiLEsAAVFHkXERCgHgGSg2n1HoN4uK5bwGQAMmkWmkPN9d9CgrMc3zQti1LRJvCCEIwkrSoBTSf2KwyKpffSbtw+D6cR2jv3pxnePI4rZdk5DzdVJ9mOD3T6dTzz8oK0Lx8S7DoOE-KLsS7j72K8jk6S7T+v-fCTOW4ifcS4LjuyOL3vyKzgfy4j-2ocLjI44HpOB+b0fRInru6-n2TC8UtfA5XrsR5zgy16nrek+X3e5939ut673vJcLvzEhMdFvGdS1XVtD1J24TQ64DztQ5-6vY5-jPBqP92653zg+fu5RA7lHLlXB8U9yhH2RBEZu5RQHhEvuUHufdCLQNooRf+ZEEG8UEoRUBGRMEZGwevL+6lOzb3oYQ0y9CgFdlQV2UBot6HYNvt4JMtQ4CqiaCmAAcnmP4CBVC8GgI8UAYAkDADQMSegVRSShGYMASQ1g4BoBJOgCwcAbB6P1nAAABn8UxagkB7BLPQOAJJ5CSHUHACAHsSz4BkaY+2gFHaTlMTIBWCAzgwBEbrZgjhlaqzcWIbWUAwn6x4NiCgOAZAZiwDYTgoQiTiFsEGHAxAkyaArEaFM3g0wKwACKOJJBWbgABlecYYXjBQaVBUxAASdwTTsDsHyAAWk6d03pliVQDHVHAOpdBMRwCqZwEk4R6mNOeD0lp84OldOWb0gZ7hZk1O4PPAA+kYfIIyJkCKEVAKZvxdkZEWVBIZqy2mDM2f0zpuyFmHOOachpdQxlXOYLsrsdzOIPNBK0zi6yhmvJ2dU25nyTnFDOb8tUtAUwAAlXHpExWENRcBISSEWEWGweKICPBQMwXFaAIDgFQCIVkRxOABP+YgYJoTcTVkcLs2pQTBhspQMmJEZT0TMp5ecPlzZOXVIWaKkJYSBWpmFZCFlvKwk9klXM25Mq+XyqFYE1lYSxzqpJECrVcqESCtROiIAA)
|
311,124 |
I can't figure out how to set up a simple search. I am trying to find all messages that 'start with' a particular string. Here is an example of 4 message
```
1) Subject: ABC DEF
2) Subject: ABC XYZ
3) Subject: RE: ABC DEF
4) Subject: FW: ABC XYX
```
From this list; I only want to search for message 1 and message 2. But for some reason; the advanced find only show me options like
```
a) contains
b) is
c) doesn't contain
d) word starts with
..... and so on
```
but none of those work for me :(
|
2011/07/16
|
[
"https://superuser.com/questions/311124",
"https://superuser.com",
"https://superuser.com/users/90470/"
] |
There is no space between NOT and (Subject... ).
the right search is
(subject: "ABC ") and NOT(subject: "RE: ") and NOT(subject: "FW: " )
|
35,613,103 |
Today i ran into a problem. I was trying to install a plugin via the Wordpress enviroment and all of a sudden I got the following error: "an error occurred while installing IshYoBoy Multicorp Assets: unable to create directory ishyoboy-multicorp-assets."
I have already tried to give the files in wp-content the 777 permission but that didn't work. Installing the plugins locally works though (downloading the plugin and placing it in the destination folder). It feels like I have tried everything I know.
|
2016/02/24
|
[
"https://Stackoverflow.com/questions/35613103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5967896/"
] |
Simply append owner and group arguments to the `synced_folder` config in the Vagrantfile
>
> ,:owner=> 'www-data', :group=>'www-data'
>
>
>
### Example
```
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
config.vm.synced_folder "wp-root/", "/var/www",:owner=> 'www-data', :group=>'www-data'
config.vm.network "forwarded_port", guest: 80, host: 8000
end
```
|
48,201,696 |
I'm loading image url using glide and applying rounded corner transformation. It works fine for first setup of recyclerview. Later when i call `notifydatasetchanged()` after pagination it becomes square. What am I missing?
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0, RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
```
|
2018/01/11
|
[
"https://Stackoverflow.com/questions/48201696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7923473/"
] |
Use this diskCacheStrategy Saves the media item after all transformations to cache.
```
Glide.with(mContext)
.load(primary.getpSmallImage())
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.bitmapTransform(new RoundedCornersTransformation(mContext, 8, 0,
RoundedCornersTransformation.CornerType.ALL))
.placeholder(R.drawable.ic_ph_small)
.into(thumbnailImage);
```
|
2,245 |
>
> Только три процента всей воды на Земле явля(Е/Ю)тся пресной
>
>
>
What letter should I choose there? Е or Ю?
|
2013/05/15
|
[
"https://russian.stackexchange.com/questions/2245",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/170/"
] |
In this case the following rule would apply (Rosenthal et al., №184.2):
>
> Форма единственного числа сказуемого указывает на совокупность предметов, форма множественного числа – на отдельные предметы. Ср.: *В городе строится пять объектов соцкультбыта* (единое нерасчлененное представление о действии). – *В крупнейших городах страны строятся еще пять объектов соцкультбыта* (расчлененное представление о действии).
>
>
>
Since we do not refer each percent separately, we should use the singular form.
|
50,727,539 |
I made some elements in JavaScript that i add to the website. When i add an eventlistener to the button, only the first button works and runs the function.
I used to do this before and worked fine, any idea what i'm doing here wrong?
my javascript function:
```js
function laadProjectDetails(){
fetch("restservices/projectdetails")
.then(response => response.json())
.then(function(myJson) {
for (const object of myJson) {
var projextX = '<div class="row"><div class="cause content-box"><div class="col-md-5 col-sm-6"><div class="img-wrapper"><div class="overlay"></div><img class="img-responsive" src="assets/img/causes/img-1.jpg" alt=""></div></div><div class="col-md-7 col-sm-6"><div class="info-block"><h4><a href="#">'+object.projectNaam+'</a></h4><p>'+ object.projectBeschrijving +'</p><div class="foundings"><div class="progress-bar-wrapper min"><div class="progress-bar-outer"><p class="values"><span class="value one">Opgehaald: XXXX</span>-<span class="value two">Doel: €'+object.totaalBedrag+'</span></p><div class="progress-bar-inner"><div class="progress-bar"><span data-percent="55"><span class="pretng">55%</span> </span></div></div></div></div></div><div class="donet_btn"><input id="'+object.projectID+'" type="submit" value="Doneer" class="btn btn-min btn-solid"></input></div></div></div></div></div>';
document.querySelector("#showProject").innerHTML += projextX;
var valueVerwijder = document.querySelector("div.donet_btn input[value='Doneer']");
valueVerwijder.addEventListener("click", doneerFunc);
}
});
}
laadProjectDetails();
function doneerFunc(){
console.log("test");
}
```
|
2018/06/06
|
[
"https://Stackoverflow.com/questions/50727539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9528069/"
] |
I wasn't satisfied with the previous answer (specially concerning the beta macOS component) ... and I really wanted to install Mojave, so I went hunting for some docs or verification. The closest I got is this quoted answer from Apple Developer Technical Support related to a failed submission with an odd ITMS error: <https://stackoverflow.com/a/44323416/322147>
>
> I looked at the .ipa you provided that was giving trouble, and
> compared it to the one successfully submitted to the App Store. The
> one giving you trouble was built on a beta version of macOS, which is
> not supported for distribution. Apps released to the App Store need to
> be built for a GM version of macOS, with a GM version of Xcode, using
> a GM version of the iOS SDK.
>
>
> Normally, apps submitted with any beta software receive a message
> indicating this problem, and the message you received was completely
> misleading.
>
>
>
|
67,184,541 |
I am trying to extract a CSV report from our company's ASP.NET ReportViewer via selenium.
I have got as far as clicking the the export dropdown menu (see image), but I am unable to click the csv button (which will download the CSV report) I have tried waiting then clicking with no results.
**My code:**
```
driver = webdriver.Chrome(r'C:\Users\User\chromedriver.exe')
url = 'Logon.aspx' # target url
driver.get(url) # open url
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_txtUsername"]').send_keys('_user') # username cred
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_txtPassword"]').send_keys('_pswd') # pass
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_btnLogin"]').click() # click login btn
driver.find_element_by_xpath('//*[@id="JobsReports"]').click() # click job report btn
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_TRCB3"]').click() # click 'Task details' check box
driver.find_element_by_xpath('//*[@id="ctl00_maincontent_RunReportsBtn"]').click() # click view report btn
time.sleep(3)
driver.switch_to.window(driver.window_handles[-1])
driver.implicitly_wait(120)
# driver.find_element_by_xpath('//*[@id="ReportViewer1_ctl05_ctl05_ctl00_ctl00"]/table/tbody/tr/td/input').click()
# driver.implicitly_wait(120)
driver.find_element_by_xpath('//*[@id="ReportViewer1_ctl05_ctl04_ctl00_ButtonLink"]').click() # click save dropdown
driver.implicitly_wait(3)
driver.find_element_by_xpath('/html/body/form/div[3]/div/span/div/table/tbody/tr[3]/td/div/div/div[4]/table/tbody/tr/td/div[2]/div[2]/a').click() # click 'CSV' to download
```
**HTML / Layout:**
[HTML SNIPPET](https://i.stack.imgur.com/jWP9x.png)
```
<div style="border: 1px solid rgb(51, 102, 153); background-color: rgb(221, 238, 247); cursor: pointer;">
<a title="CSV (comma delimited)" alt="CSV (comma delimited)" onclick="$find('ReportViewer1').exportReport('CSV');" href="javascript:void(0)" style="color: rgb(51, 102, 204); font-family: Verdana; font-size: 8pt; padding: 3px 8px 3px 32px; display: block; white-space: nowrap; text-decoration: none;">CSV (comma delimited)</a>
</div>
```
**Error:**
```
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Onsite_automation\main.py", line 32, in <module>
driver.find_element_by_xpath('/html/body/form/div[3]/div/span/div/table/tbody/tr[3]/td/div/div/div[4]/table/tbody/tr/td/div[2]/div[2]/a').click() # click 'view report' btn
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\User\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=90.0.4430.72)
```
Thanks for your help!
|
2021/04/20
|
[
"https://Stackoverflow.com/questions/67184541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12734203/"
] |
You need to await connection first inorder to use execute function:
```
const [rows] = await (await connection()).execute('SELECT * FROM media');
```
OR
```
const conn = await connection();
const [rows] = await conn.execute('SELECT * FROM media');
```
|
5,938,594 |
I have a range slider on my site for min-max price ranges. On either side of the slider are two text input boxes. I've created a callback function with the slider which adjusts the vals of the text boxes based on a val change within the slider.
At the same time, I would also like to adjust the values of the slider based on changes to th vals of the text boxes. Right now, the change (also tried keyup) event that I'm binding on the text inputs are not changing the values (position) of the two range slider hands. What's wrong here?
```
$('.price_slider').slider({orientation:"horizontal",range:true, animate:200,min:0,max:10000, step:100,value:0,values:[{{min_rent}},{{max_rent}}], slide:function(event,ui){
$('input#lower_bound').val(ui.values[0]);
$('input#upper_bound').val(ui.values[1]);
}
});
$('input#lower_bound').change(function(){
$('.price_slider').slider("values",[$(this).val(),$('input#upper_bound').val()]);
});
$('input#upper_bound').change(function(){
$('.price_slider').slider("values",[$('input#lower_bound').val(),$(this).val()]);
});
```
EDIT--
Matt, I saw your revision. Just curious if your version is more efficient than mine. Mine does seem to be working but I'm clearly not an expert:
```
$lower.add($upper).change(function () {
var lowEnd=parseInt($lower.val());
var highEnd=parseInt($upper.val());
if(highEnd>lowEnd){
$slider.slider('values', 0, parseInt($lower.val(), 10));
$slider.slider('values', 1, parseInt($upper.val(), 10));
}
else{
$slider.slider('values', 0, parseInt($lower.val(), 10));
$slider.slider('values', 1, parseInt($lower.val(), 10));
$upper.val([$lower.val()]);
}
});
```
|
2011/05/09
|
[
"https://Stackoverflow.com/questions/5938594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558699/"
] |
* For multi-handle sliders, you need to use `'values'` rather than `'value'` (which you're doing) but `'values'` takes this format:
```
.slider( "values" , index , [value] )
```
* You probably want to enforce `max >= min` when setting the slider values based on the textboxes.
* You are passing the initial values to `.slider()` incorrectly, I don't know where that `{{...}}` nonsense came from (is that a jQuery template?).
* It's generally [not a great idea to use underscores in class names](https://developer.mozilla.org/en/underscores_in_class_and_id_names). Use `-` instead of `_`.
The fixes:
```
var $slider = $('.price-slider'),
$lower = $('#lower_bound'),
$upper = $('#upper_bound'),
min_rent = 1000,
max_rent = 9000;
$lower.val(min_rent);
$upper.val(max_rent);
$('.price-slider').slider({
orientation: 'horizontal',
range: true,
animate: 200,
min: 0,
max: 10000,
step: 100,
value: 0,
values: [min_rent, max_rent],
slide: function(event,ui) {
$lower.val(ui.values[0]);
$upper.val(ui.values[1]);
}
});
$lower.change(function () {
var low = $lower.val(),
high = $upper.val();
low = Math.min(low, high);
$lower.val(low);
$slider.slider('values', 0, low);
});
$upper.change(function () {
var low = $lower.val(),
high = $upper.val();
high = Math.max(low, high);
$upper.val(high);
$slider.slider('values', 1, high);
});
```
Demo: <http://jsfiddle.net/mattball/pLP2e/>
|
15,226,630 |
I'm struggling on replacing text in each link.
```
$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';
if(preg_match_all($reg_ex, $text, $urls))
{
foreach($urls[0] as $url)
{
echo $replace = str_replace($url,'http://www.sometext'.$url, $text);
}
}
```
From the code above, I'm getting 3x the same text, and the links are changed one by one: everytime is replaced only one link - because I use foreach, I know.
But I don't know how to replace them all at once.
Your help would be great!
|
2013/03/05
|
[
"https://Stackoverflow.com/questions/15226630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/548278/"
] |
You don't use regexes on html. use [DOM](http://php.net/dom) instead. That being said, your bug is here:
```
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
```
you never update $text, so you continually trash the replacement on every iteration of the loop. You probably want
```
$text = str_replace(...., $text);
```
instead, so the changes "propagate"
|
11,332,269 |
I need to create route `/branch` which run script `/lib/branch.rb`, I need to display only one string which displayed in browser my current git branch which deployed at staging server. I already write script, but cant understand how to mount it to rails routes
|
2012/07/04
|
[
"https://Stackoverflow.com/questions/11332269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/548618/"
] |
Try the following solutions by Directly targeting the `ul`
***Solution A***:
---
```js
// previous (following) is very inefficient and slow:
// -- $(this).find("ul.sub-menu").not("ul.sub-menu li ul.sub-menu").slideDown();
// Rather, target the exact ULs which are Direct Children
$("ul.menu").find('li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').slideUp();
// If something Slides Down, it should slide up as well,
// instead of plain hide(), your choice - :)
}
);
```
***Solution B***:
---
for more Precision over both ULs
**Update**: Solution A works fine and makes B redundant
```
$("ul.menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
$("ul.sub-menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
```
Check the **[Fiddle](http://jsfiddle.net/OMS_/XDkXq/)**
|
32,811,437 |
Is it wrong way to pass $\_GET variable in MVC design?
```
http://localhost/video?id=123
```
I started to learn MCV design pattern and some people were telling me, that I'm doing wrong. The correct way would be:
```
http://localhost/video/?id=123
```
They were saying its kinda of 'standard' for passing $\_GET in MVC. The slash isnt needed only if you access file directly, like:
```
http://localhost/video.php?id=123
```
|
2015/09/27
|
[
"https://Stackoverflow.com/questions/32811437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This has nothing to do with MVC. MVC is just a way to organize your code.
The way you rewrite/route URLs to controllers is up to you. Both ways work, as long as the URL matches what you defined on your backend!
|
72,170,760 |
I'm new in VBA and actually don't know how to deal with that task. Maybe you can help me.
I have two tables in two sheets.
Table from sheet 1 is updated daily.
What I need to do is check if any value in column A (sheet 1) is in column A (sheet 2).
If yes, then do nothing.
If no, then copy whole row into the table in sheet 2.
Basing on google results I started to write some code but I stuck.
```
Dim source As Worksheet
Dim finaltbl As Worksheet
Dim rngsource As Range
Dim rngfinaltbl As Range
'Set Workbook
Set source = ThisWorkbook.Worksheets("Sheet 1")
Set finaltbl = ThisWorkbook.Worksheets("Sheet 2")
'Set Column
Set rngsource = source.Columns("A")
Set rngfinaltbl = finaltbl.Columns("A")
```
I assume that next I need to write some loop but I really don't know how it works.
|
2022/05/09
|
[
"https://Stackoverflow.com/questions/72170760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902492/"
] |
Update Worksheet With Missing (Unique) Rows (Dictionary)
--------------------------------------------------------
* Adjust the values in the constants section.
```vb
Sub UpdateData()
' Source
Const sName As String = "Sheet1"
Const sFirstCellAddress As String = "A2"
' Destination
Const dName As String = "Sheet2"
Const dFirstCellAddress As String = "A2"
' Reference the destination worksheet.
Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets(dName)
Dim drg As Range
Dim dCell As Range
Dim drCount As Long
' Reference the destination data range.
With dws.Range(dFirstCellAddress)
Set dCell = .Resize(dws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If dCell Is Nothing Then Exit Sub ' no data in column range
drCount = dCell.Row - .Row + 1
Set drg = .Resize(drCount)
End With
Dim Data As Variant
' Write the values from the destination range to an array.
If drCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = drg.Value
Else
Data = drg.Value
End If
' Write the unique values from the array to a dictionary.
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim Key As Variant
Dim dr As Long
For dr = 1 To drCount
Key = Data(dr, 1)
If Not IsError(Key) Then ' exclude errors
If Len(Key) > 0 Then ' exclude blanks
dict(Key) = Empty
End If
End If
Next dr
' Reference the source worksheet.
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets(sName)
Dim srg As Range
Dim sCell As Range
Dim srCount As Long
' Reference the source data range.
With sws.Range(sFirstCellAddress)
Set sCell = .Resize(sws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If sCell Is Nothing Then Exit Sub ' no data in column range
srCount = sCell.Row - .Row + 1
Set srg = .Resize(srCount)
End With
' Write the values from the source range to an array.
If srCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = srg.Value
Else
Data = srg.Value
End If
Dim surg As Range
Dim sr As Long
' Loop through the source values...
For sr = 1 To srCount
Key = Data(sr, 1)
If Not IsError(Key) Then ' exclude errors
If Len(Key) > 0 Then ' exclude blanks
If Not dict.Exists(Key) Then ' if source value doesn't exist...
dict(Key) = Empty ' ... add it (to the dictionary)...
If surg Is Nothing Then ' and combine the cell into a range.
Set surg = srg.Cells(sr)
Else
Set surg = Union(surg, srg.Cells(sr))
End If
End If
End If
End If
Next sr
' Copy all source rows in one go below ('.Offset(1)') the last cell.
If Not surg Is Nothing Then
surg.EntireRow.Copy dCell.Offset(1).EntireRow
End If
MsgBox "Data updated.", vbInformation
End Sub
```
|
366,432 |
I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
```
I can compile it but I get a linker error if I try to use it. Any ideas?
|
2008/12/14
|
[
"https://Stackoverflow.com/questions/366432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] |
Depending on your needs, you should use `std::vector` (if you need often appends/removes at the end, and random access), or `std::deque` (if you need often appends/removes at the end or at the beginning, and your dataset is huge, and still want random access). Here is a good picture showing you how to make the decision:
[](https://i.stack.imgur.com/qWf2C.png)
(source: [adrinael.net](http://adrinael.net/containerchoice.png))
|
10,453,431 |
Is there any open source findbugs detectors extensions, espcially for performance bugs, for low-latency? I didn't find any meaningful extension beyond barebone findbugs impl.
|
2012/05/04
|
[
"https://Stackoverflow.com/questions/10453431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294552/"
] |
Your code seems ok - did you copy the db to the ressource folder of your project?
**EDIT**
Make sure you access your db file with something like that:
```
- (void) initializeDB {
// Get the database from the application bundle
NSString* path = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSLog(@"Opening Database");
}
else
{
// Call close to properly clean up
sqlite3_close(database);
NSAssert1(0, @"Error: failed to open database: '%s'.",
sqlite3_errmsg(database));
}
}
```
|
2,318,002 |
$$|x-2|+|x+3|= 5$$
What are the real values of $x$ satisfies the equation?
I tried doing this but it somehow did not work. Could someone explaim why please? Here's my workings :
$$|x-2|+|x+3|=5$$
$$\Rightarrow (x-2)+(x+3)=5$$
$$\Rightarrow x+2+x+3=5$$
$$\Rightarrow x=6$$
$$\Rightarrow x=3$$
The answer is $[-3,2]$
|
2017/06/11
|
[
"https://math.stackexchange.com/questions/2318002",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/454081/"
] |
Hint:
For a number to be bigger than $340$.
The first digit can be either $3$ or $4$.
If the first digit is $3$, the second digit must be $4$ and the last digit can be anything.
If the first digit is $4$, the last two digit can be anything.
Can you compute the probability now?
|
14,059,274 |
I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:
>
> Define a class to represent a Sugar Bowl sugar characterized by three
> things: total capacity (in grams), available quantity and quantity of
> the spoon (how many grams of sugar takes the spoon associated with
> it). Set in this class:
>
>
> 1. A constructor method to create a sugar bowl.
> 2. A method that allows to know the amount of sugar in the sugar bowl.
> 3. A method that allows to know how much it takes a spoonful of sugar.
> 4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.
> 5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
> returned. In other cases, should return zero.
>
>
> Set the class `RunSugarBowl` as main and play around.
>
>
>
>
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.
SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}
public int spoon(){
return spoonSize;
}
public int occupied(){
return occupiedSpace;
}
public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}
```
My problem **now** is that my `one.occupied` method returns `0` instead off the `200` in:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
|
2012/12/27
|
[
"https://Stackoverflow.com/questions/14059274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932739/"
] |
First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).
You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).
I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.
```
public class SugarBowl {
private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace;//starts at 0, because there's nothing in the bowl.
/**
* Constructor for the sugar bowl.
* @param totalCapacity The total capacity of the bowl.
*/
public SugarBowl (int totalCapacity){
this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
occupiedSpace = 0;
}
/**
* Shows how much sugar can fit in a spoon.
* @return The size of the spoon
*/
public int spoon(){
return spoonSize;
}
/**
* Returns amount of sugar in the bowl.
* @return The amount of occupied space
*/
public int occupied(){
return occupiedSpace;
}
/**
* Removes the amount of sugar based on the
* number of scoops passed into it.
* @param numberOfScoops The number of scoops
* @return The amount of sugar removed
*/
public int scoops (int numberOfScoops){
int possibleAmountTaken = numberOfScoops * spoonSize;
int actualAmountTaken = 0;
//Think about sugar, even if there is less sugar than the spoon size,
//can a spoon still remove that amount?
//aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
if (possibleAmountTaken<=occupiedSpace){
actualAmountTaken = possibleAmountTaken;
}
else{
//there may still be sugar, just not enough for every scoop, you still have to remove it
//actualAmountTaken = ???
}
occupiedSpace = occupiedSpace - actualAmountTaken;
//what about availableSpace?
//availableSpace = ???
return actualAmountTaken;
}
/**
* Adds the specified amount of sugar to the bowl.
*
* @param addedAmount The amount of sugar added to the bowl
* @return The overflow amount of sugar or 0 if there was no overflow
*/
public int addSugar (int addedAmount){
int overflow = 0;
if (addedAmount>availableSpace){
overflow = addedAmount-availableSpace;
//your bowl is going to be full, what happens to occupiedSpace and availableSpace?
//availableSpace = ???
//occupiedSpace = ???
}
else{
//overflow is already 0 so you don't have to do anything with it
//update availableSpace and occupiedSpace
//availableSpace = ???
//occupiedSpace = ???
}
return overflow;
}
}
```
With your above main example:
```
public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
System.out.println("Occupied size is : "+ one.occupied());
}
}
```
**UPDATE**
The reason you would use this.totalCapacity is because of the following lines of code:
```
public class SugarBowl {
private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
//..
public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
//..
```
Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:
```
public class SugarBowl {
private int bowlTotalCapacity; //totalCapacity for this object
//..
public SugarBowl (int totalCapacity){
bowlTotalCapacity = totalCapacity;
//..
```
You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: <http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html>.
Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:
```
public class ThisExample {
private int wrongExample = 0;
private int thisExample = 0;
public ThisExample (int wrongExample, int thisExample){
wrongExample = wrongExample;
this.thisExample = thisExample;
}
public int getThisExample(){
return thisExample;
}
public int getWrongExample(){
return wrongExample;
}
}
```
Running the following may help you understand better:
```
public class ThisExampleMain {
public static void main(String[] args) {
ThisExample ts = new ThisExample(50, 50);
//you want this to be 50 but it ends up being 0:
System.out.println("Wrong: " + ts.getWrongExample());
//this returns the correct answer:
System.out.println("Right: " + ts.getThisExample());
}
}
```
|
1,690,743 |
I'm investigating a possible memory leak which is causing an "Error creating window handle" Win32Exception in my .NET 2.0 WinForms app. This is related to number of Handles and number of USER objects (most likely) so I'm trying to log these metrics the next time the exception is thrown.
HandleCount is easy to find: `Process.HandleCount`.
Does anyone know how to find the Number of USER objects? (Value can be seen in a column of the Task Manager->Processes) .NET or win API functions will do.
Thanks!
|
2009/11/06
|
[
"https://Stackoverflow.com/questions/1690743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177227/"
] |
Try [GetGuiResources](http://msdn.microsoft.com/en-us/library/ms683192(VS.85).aspx) which you can call using [P/Invoke](http://www.pinvoke.net/default.aspx/user32/GetGuiResources.html?DelayRedirect=1)
|
29,604,313 |
I would like to change the vmsize of a running Azure web role during deployment preferrably using powershell.
Is this at all possible?
The use case here is that not all of our customers (and test environments) should run the same vm sizes, but they all use the same .csdef file.
|
2015/04/13
|
[
"https://Stackoverflow.com/questions/29604313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571308/"
] |
You can use the Set-AzureDeployment cmdlet to upgrade a webrole size, which you could then work into your existing PowerShell script. For instance, if you automatically deploy every customer web service/web role at a basic level/scale and then only upgraded them to larger capacity as needed, you could then use the following cmdlet as needed:
```
Set-AzureDeployment -Upgrade -ServiceName "MySvc1" -Mode Auto `
-Package "C:\Temp\MyApp.cspkg" -Configuration "C:\Temp\MyServiceConfig.Cloud.csfg"
```
I would envision you just adding a parameter to your current PowerShell script, and if specified, run the above cmdlet to Upgrade the Azure Web role.
|
28,853,341 |
I have a HTML page which is divided into two frame sets,
the first frame contains 4 buttons, the second frame shows forms, only 1 of 4 forms can be shown according to which button is clicked.
e.g. if the user clicks on button 'form1' in frame1, the 2nd frame should show 'FORM1' if the user clicks on button 'frame3' in frame1, the 2nd frame should show 'FORM3'.
What I need is to be able to change the source of the form in the second frame based on the button clicked in the first frame.
Here is main frame file:
```
<html>
<head>
<title>User Management</title>
</head>
<frameset rows="9% ,91%" >
<frame src="buttons.php"
name='Frame1'
scrolling="no"
name="work_disply"
noresize="noresize" />
<frame src="form1.php"
name='Frame2'
scrolling="yes"
name="work_ground"
noresize="noresize" />
</frameset>
</html>
```
|
2015/03/04
|
[
"https://Stackoverflow.com/questions/28853341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2339140/"
] |
This should do what you need:
```
<a target="Frame2" href="form1.php">Show form 1</a>
<a target="Frame2" href="form2.php">Show form 2</a>
<a target="Frame2" href="form3.php">Show form 3</a>
<a target="Frame2" href="form4.php">Show form 4</a>
```
More about targets and frames in [HTML 4 spec](http://www.w3.org/TR/html401/present/frames.html#adef-target).
|
39,965,322 |
I know recipes aren't versioned, but is it possible in an environment to have some recipes use a specific version of their cookbook and some use a different version?
|
2016/10/10
|
[
"https://Stackoverflow.com/questions/39965322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1028270/"
] |
You can only pin cookbooks in environments. There is no way to mix a cookbook with recipes from different cookbook versions.
|
6,781,204 |
How does WebLogic 11g load libraries in an EAR file? I have this problem with a web application, that when deployed as a WAR (with libraries it depends on in WEB-INF/lib), it works just fine. However, when it's inside an EAR file, WebLogic does not find those libraries unless I put them in APP-INF/lib. Does that mean that if I'm deploying as an EAR I'd have to pull out all JAR files from the WEB-INF/lib directory and place them in APP-INF/lib ? or is there a configuration that can be done in WebLogic to avoid this?
Thanks!
|
2011/07/21
|
[
"https://Stackoverflow.com/questions/6781204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86857/"
] |
If you have JAR files that you need to share between multiple WAR files or between WAR files and EAR files then you will need to package them in the EAR.
If WAR#1 has a JAR in its WEB-INF/lib and is packaged in an EAR with WAR#2, then WAR#2 will not be able to see the JAR files in WAR#1/WEB-INF/lib.
|
49,018,118 |
I have decided to make my own Tool bar
So i removed the regular ToolBar :
```
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="false"
android:theme="@style/Theme.AppCompat.Light.NoActionBar> //removetollbar
```
and make my own tool bar
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
```
then i include in main xml
```
<include
layout="@layout/customtoolbar"
android:id="@+id/custombar" >
</include>
```
and in the code i set it up :
```
_CustomToolBar = (android.support.v7.widget.Toolbar)
findViewById(R.id.custombar);
setSupportActionBar(_CustomToolBar);
android.support.v7.widget.Toolbar _CustomToolBar;
```
>
> now when the app run the custom toolbar is not there
>
>
>
Please help.
|
2018/02/27
|
[
"https://Stackoverflow.com/questions/49018118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6528032/"
] |
In your `<include>` tag, you've set the id of the toolbar to be `@+id/custombar`, but you're looking it up using `R.id.toolbar`. Change that line to this:
```
_CustomToolBar = (android.support.v7.widget.Toolbar) findViewById(R.id.custombar);
```
|
16,594,511 |
So I need to upgrade an rails 2.3.14 app to rails 3. We use git, so decided to create another branch 'rails3' (git checkout -b rails3). The easiest solution I found to the problem of the upgrade was removing all stuff and generating a new project and copy/pasting controllers , views, etc.. from master. But now `git status` tells me those files were deleted and regenerated, not *modified*, although most of them are in the same place they were before. So changes remain obscure, other programmers wont see the subtle changes to files.
What have I've done:
```none
/path/to/rails_project/ (master) $ git checkout -b rails3
/path/to/rails_project/ (rails3) $ rm -rf ./* # not git rm
/path/to/ $ rails new rails_project
/path/to/rails_project/ (rails3) $ cp old/project/stuff/from/another/dir
```
How can I 'tell' git that these files were modified, not deleted and regenerated? I have the upgraded app in a totally different directory so its fine to implode cosmos and do all from start.
|
2013/05/16
|
[
"https://Stackoverflow.com/questions/16594511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1740079/"
] |
this might be a clean solution for you:
```
<form action="" method="post">
<input type="submit" name="page" value="Home" />
<input type="submit" name="page" value="About Us" />
<input type="submit" name="page" value="Games" />
<input type="submit" name="page" value="Pages" />
</form>
<?php
switch($_POST["page"]){
case "About Us":
include 'au.php';
break;
case "Games":
include 'games.php';
break;
case "Pages":
include 'pages.php';
break;
default:
include 'home.php';
break;
}
```
|
37,894,081 |
I see that no active development is going on from vogels page from a long time i.e, about 5 months <https://github.com/ryanfitz/vogels>
Are there any better options?
Has anyone faced issues with scalibility or I/O time with it?
|
2016/06/18
|
[
"https://Stackoverflow.com/questions/37894081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2379271/"
] |
I've been using vogels on a project recently. While it seems like it isn't as well maintained as it used to be, it's still quite a nice API wrapper - certainly much nicer than using the SDK directly.
I haven't encountered any performance cost with it - it's really just assembling AWS SDK calls, and doesn't do anything too crazy. The code is simple enough that anything I was unsure about I can dive in and check it out, and the docs are pretty good.
However another option that I've found recently is this library, open sourced by Medium. It's promised based and looks well maintained:
<https://github.com/Medium/dynamite>
|
50,309,017 |
I have a invite link of private channel, and I wanna forwards (or delivery) posts from this channel to me. My desired pseudo code is like below.
```
def get_channel(bot, update):
message=update.channel_post.text
print(message)
updater = Updater(my_token)
channel_handler = MessageHandler(Filters.text, get_channel,
channel_post_updates=True, invite_link='http://t.me/aa23faba22939bf')
updater.dispatcher.add_handler(channel_handler)
```
This works well when my bot is in the channel which I created(invite\_link is added for my purpose. I don't know where invite\_link should be input). But what I want is that my bot forwards posts from channel in which my bot is 'not' included. I prefer python, but any API will be ok. I searched all the google world but have no clues.. Any tips appreciated.
|
2018/05/12
|
[
"https://Stackoverflow.com/questions/50309017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9247484/"
] |
With awk:
```
kubectl get pods -l run=hello-kube -o yaml | awk '/podIP:/ {print $2}'
```
Output:
```
10.244.1.9
```
|
4,298,595 |
I have the following from the slime repl (no clojure.contib functions found):
```
M-X slime
user=> (:require 'clojure.contrib.string)
nil
user=> (doc clojure.contrib.string/blank?)
java.lang.Exception: Unable to resolve var: clojure.contrib.string/blank? in this context (NO_SOURCE_FILE:10)
```
And the following when starting clojure from console (but here everything is being found OK):
```
adr@~/clojure/cloj-1.2$ java -cp /home/adr/clojure/cloj-1.2/clojure.jar:/home/adr/clojure/cloj-1.2/clojure-contrib.jar -server clojure.main
user=> (:require 'clojure.contrib.string)
nil
user=> (doc clojure.contrib.string/blank?)
-------------------------
clojure.contrib.string/blank?
([s])
True if s is nil, empty, or contains only whitespace.
nil
```
In my .emacs I have the following:
```
(setq inferior-lisp-program "java -cp /home/adr/clojure/cloj-1.2/clojure.jar:/home/adr/clojure/cloj-1.2/clojure-contrib.jar -server clojure.main")
```
My clojure jars (1.2) are at '/home/adr/clojure/cloj-1.2'.
I;m a newbie with emacs, been following some tutorials. For some time I've been trying to use the clojure.contrib library from Emacs, but "M-X slime" finds no clojure.contrib. Please, help
**Edit**: if that would help, now i saw that when using M-X slime there is a message:
```
(progn (load "/home/adr/.emacs.d/elpa/slime-20100404/swank-loader.lisp" :verbose t) (funcall (read-from-string "swank-loader:init")) (funcall (read-from-string "swank:start-server") "/tmp/slime.4493" :coding-system "iso-latin-1-unix"))
Clojure 1.2.0
user=> java.lang.Exception: Unable to resolve symbol: progn in this context (NO_SOURCE_FILE:1)
```
**Edit2:** But there is no such error message if I use M-X slime-connect after having started a "lein swank" in a directory (though even starting with "M-X slime-connect" there are no clojure-contrib libraries found in the REPL (though they are downloaded by leiningen as dependency)).
|
2010/11/28
|
[
"https://Stackoverflow.com/questions/4298595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160992/"
] |
The new [ECMAScript 5 specification](http://www.ecma262-5.com/ELS5_HTML.htm) allows property names to be reserved words. Some engines might have adopted this new "feature", while others might still require property names to be quoted when they happen to be reserved words.
|
10,515,412 |
I have a table with column node\_id as number, where,
```
node_id
0
2000
300300300
400400400
```
what i am trying to get is convert this number into string and add '-' after every third digit from right.
So expected output is,
```
node_id
000-000-000
000-002-000
300-300-300
400-400-400
```
This is the query which i am using,
```
select TO_CHAR( lpad(t1.node_id,9,'0'), '999G999G999', 'NLS_NUMERIC_CHARACTERS="-"'), node_id from table t1;
```
The output i am getting is,
```
node_id
0
2-000
300-300-300
400-400-400
```
My problem is I also need to prepend '0' to each record such that the total length is 11.
I tried adding to\_char immediately around lpad so as to convert the lpad output to varchar, but that also gives the same output.
|
2012/05/09
|
[
"https://Stackoverflow.com/questions/10515412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073023/"
] |
Just change your format mask to:
```
'099G999G999'
```
(Note the leading '0')
|
6,345 |
Nel romanzo *Non so niente di te* di Paola Mastrocola, pubblicato da Einaudi, ho letto (il corsivo è mio):
>
> Ognuno ha il suo modo di non dormire, la notte, il suo stile, le sue tecniche di insonnia. C'è chi [...]. E c'è chi si ribella, non ammette, non concepisce che possa capitare a lui, è ostile, sbuffa, *sbraita*, finge di dormire, strizza gli occhi perché il sonno arrivi, si sforza di non pensarci e ci pensa sempre di piú, finendo per restare a letto teso come una corda di violino.
>
>
>
Siccome non conoscevo il significato del verbo "sbraitare", l'ho cercato nel [vocabolario Treccani](http://www.treccani.it/vocabolario/sbraitare/), dove ho trovato questa accezione del termine:
>
> protestare manifestando a voce alta il proprio risentimento: *s. contro il governo, contro le tasse; tutti sbraitano, ma nessuno ha il coraggio di ribellarsi*.
>
>
>
Comunque, non mi sembra il caso di mettersi a gridare durante la notte quando si ha l'insonnia. Per questa ragione vi chiedo: il verbo "sbraitare" può avere un uso figurato che non implichi parlare a voce alta o gridare? Si tratta di un uso letterario o è invece comune?
|
2015/12/20
|
[
"https://italian.stackexchange.com/questions/6345",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/707/"
] |
>
> Comunque, non mi sembra il caso di mettersi a gridare durante la notte quando si ha l'insonnia.
>
>
>
Beh, sicuramente non è il caso, ma se lo vedi come un gesto di disappunto ha senso che capiti.
>
> il verbo "sbraitare" può avere un uso figurato che non implichi parlare a voce alta o gridare?
>
>
>
Non che io sappia (salvo il caso citato da Josh61), oltretutto appunto, come ho già detto implicitamente sopra ritengo che nel brano sia usato in modo letterale. Se ci fai caso nessuna delle altre azioni è usata in senso figurato (in particolare "sbuffa", "finge di dormire", e "strizza gli occhi" sembrano voler descrivere la situazione in senso letterale), il che suggerisce che anche lo sbraitare non lo sia.
>
> Si tratta di un uso letterario o è invece comune?
>
>
>
È molto comune, assolutamente non letterario.
|
46,622,918 |
This is my sample html code.
```
<div class="content">
<M class="mclass">
<section id="sideA">
<div id="mainContent">
<div class="requestClass">
<span>Check</span>
<input type="text" id="box">
</div>
</div>
<section>
<section id="sideB">
...
<section>
</M>
</div>
```
I want to set some value to my text field ("box"). So I tired to set like below code
```
driver.findElement(By.xpath("...")).sendKeys("SetValue");
```
My Xpath id is correct, it's exist in the page but am getting this error
```
no such element: Unable to locate element: {"method":"xpath","selector":"id("..."}
```
Why I am getting this error because of my custom tag,if yes how to get element inside custom tag?
|
2017/10/07
|
[
"https://Stackoverflow.com/questions/46622918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4804899/"
] |
As per the `HTML` you have provided to fill in some value to the text field represented by `<input type="text" id="box">` you can use either of the following line of code:
1. `cssSelector` :
```
driver.findElement(By.cssSelector("section#sideA input#box")).sendKeys("SetValue");
```
2. `xpath` :
```
driver.findElement(By.xpath("//section[@id='sideA']//input[@id='box']")).sendKeys("SetValue");
```
|
2,869,504 |
>
> I would like a **hint and only a hint** to prove
>
>
> $\forall \sigma\in S\_n$ , $S\_n$ is a finite symmetric group of permutation
>
>
> $\displaystyle \left|\prod\limits\_{1\le i<j\le n}\big(\sigma(i)-\sigma(j)\big)\right|=\left|\prod\limits\_{1\le i<j\le n}\big(i-j\big)\right|$
>
>
>
thanks !!
|
2018/08/01
|
[
"https://math.stackexchange.com/questions/2869504",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/460772/"
] |
HINT: try by induction, starting from $n=2$
|
29,498,006 |
I tried some commands such as
```
echo "Your text here" | ssh hostname 'cat >> output.txt'
```
but it didnt work.
How can I write in a file inside the server using this exec code or just the ssh command that I will put to String command.
```
public class TestWrite{
private static final String user = "username here";
private static final String host = "host here";
private static final String password = "pass here";
public static void main(String[] arg){
try{
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "Command here";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
```
|
2015/04/07
|
[
"https://Stackoverflow.com/questions/29498006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880831/"
] |
You can write to a file with
```
echo "your text here" > file
```
You don't need `ssh` because Jsch takes its place.
|
11,671 |
Vistors to our website can fill out a form to create an account. It is a CiviCRM profile, and "WordPress user account registration option" is set to "Account creation required". The username and password fields are shown above the profile but a Wordpress account is not created when the form is saved. A Contact is created, but it is linked to the Wordpress admin account (ID #1).
I attempted to replicate this on the [Wordpress Demo site](http://wpmaster.demo.civicrm.org/). I created a profile that required Wordpress registration, but it (quite reasonably) would not allow me, as the demo user, to create a page for embedding it. When I view the profile in "Create Mode", it does not show the username and password fields (even when not logged in), and no new contact or account is created.
|
2016/05/06
|
[
"https://civicrm.stackexchange.com/questions/11671",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/897/"
] |
Occasionally WordPress plugins can interfere with user account creation. Have you installed any spam prevention plugins recently? If so, try turning it off and seeing if the user creation option shows up on your profile.
The reason this isn't working with WordPress demo site, is that User Creation is turned off on all demo sites. You may want to check that this is enabled on your own site as well.
|
24,752,810 |
While browsing the web, **I need to fake my screen resolution** to websites I'm viewing but **keep my viewport the same** (Chrome's or FF's emulating doesn't solve my problem).
For instance, if I go to <http://www.whatismyscreenresolution.com/> from a browser in full screen mode which has 1920x1080px resolution **I want that site to think I am using 1024x728px** but still be able to browse in full screen mode.
One of my guessess is I need to override js variables screen.width and screen.height somehow (or get rid of js completely but the particular site won't work with js disabled), but how? And would that be enough?
**It's for anonymous purposes** I hope I don't need to explain in detail. I need to look as one device even though I am accessing the site from various devices (Tor browser not an option - changes IP). The browser I'm using is firefox 30.0 and it runs on VPS (Xubuntu 14.04) I'm connecting to remotely.
This thread ([Spoof JS Objects](https://stackoverflow.com/questions/6713434/spoof-js-objects)) brought me close but not quite enough, it remains unanswered. I've struggeled upon this question for quite a long time so any recommedation is highly appreciated!
|
2014/07/15
|
[
"https://Stackoverflow.com/questions/24752810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839707/"
] |
A very, very lazy option (to avoid setting up a [Google Custom Search Engine](http://google.com/cse)) is to make a form that points at Google with a hidden query element that limits the search to your own site:
```
<div id="contentsearch">
<form id="searchForm" name="searchForm" action="http://google.com/search">
<input name="q" type="text" value="search" maxlength="200" />
<input name="q" type="hidden" value="site:mysite.com"/>
<input name="submit" type="submit" value="Search" />
</form>
</div>
```
Aside from the laziness, this method gives you a bit more control over the appearance of the search form, compared to a CSE.
|
402,150 |
For a prime $p$, let $N(p)$ be the number of solutions $1 \le x \le p$ to $x^x \equiv 1 \mod p$. I am interested in methods to bound $N(p)$.
**Background:** This quantity appears in Problem 1 of the Miklós Schweitzer Competition 2010 where it was asked to prove $N(p) \ll p^{c}$ for some $c<\frac{1}{2}$. Let me quickly explain how one can solve this problem and why the exponent $\frac{1}{2}$ is critical.
For each divisor $d$ of $p-1$, let $A\_d$ be the set of numbers $1 \le x \le p$ for which $(x;p-1)=d$ and $x^x \equiv 1 \mod p$ so $N(p)=\sum\_{d \mid p-1} \vert A\_d\vert$.
The condition $x^x \equiv 1 \mod p$ now just says that $x$ is a $e$-th power modulo $p$ where $e=\frac{p-1}{d}$ is the complementary divisor.
So trivially $\vert A\_d\vert \ll \min(d,e) \ll p^{1/2}$ and hence $N(p) \ll p^{1/2+\varepsilon}$.
To improve this exponent, it clearly suffices to improve the bound for $\vert A\_d\vert$ when $d \approx e \approx p^{1/2}$.
Here the sum-product theorem over finite fields comes in handy: Since $A\_d+A\_d$ still contains essentially only multiples of $d$, it is easy to see that $\vert A\_d+A\_d\vert \le 2e$ and similarly $A\_d \cdot A\_d$ still contains only $e$-th powers so that $\vert A\_d \cdot A\_d\vert \le d$. Hence $\max(\vert A\_d +A\_d\vert, \vert A\_d \cdot A\_d\vert) \ll \max(d,e)$.
But by the (currently best-known version of the) sum-product theorem the LHS is at least $\vert A\_d\vert^{5/4-\varepsilon}$ so that we get the bound $\vert A\_d\vert \ll \max(d,e)^{4/5+\varepsilon}$ and we win.
Indeed, working out the exponents, we can prove $N(p) \ll p^{4/9+\varepsilon}$ this way.
Now I would be curious to learn about
**Question 1:** What are some other techniques that can be applied to get a non-trivial bound for $N(p)$? To be clear, I would be equally interested in (possibly more difficult) techniques that lead to an exponent $c<\frac{4}{9}$ as well as more elementary techniques that lead to a (possibly worse, but) non-trivial result.
Now even if one assumes a best possible sum-product conjecture to be true, it seems that by the method described above we could only prove $N(p) \ll p^{1/3+\varepsilon}$. On the other hand, it seems natural to conjecture that even $N(p) \ll p^{\varepsilon}$ is true, albeit very hard to prove. Given this gap, I am wondering about
**Question 2:** Are there some "natural/standard" conjectures that would imply an exponent less than $\frac{1}{3}$, possibly even as small as an $\varepsilon$? Or is there a good heuristic why the exponent $\frac{1}{3}$ is a natural barrier here?
EDIT: As pointed out in the answers, Cilleruelo and Garaev (2016) proved $N(p) \ll p^{27/82}$. This leaves us with the question of whether there is a natural/standard conjecture that would imply that $N(p) \ll p^{\varepsilon}$.
PS: To be clear, I don't claim that this is a very important problem on its own right. It just seems like a good toy problem to test our understanding of the interference between multiplicative and additive structures.
|
2021/08/20
|
[
"https://mathoverflow.net/questions/402150",
"https://mathoverflow.net",
"https://mathoverflow.net/users/81145/"
] |
The $1/3 + \varepsilon$ is not a barrier anymore!
Resorting to estimates of exponential sums over subgroups due to Shkredov and Shteinikov, in the paper ["On the congruence $x^{x} \equiv 1 \pmod{p}$" (PAMS, **144** (2016), no. 6, pp. 2411 - 2418)](https://www.ams.org/journals/proc/2016-144-06/S0002-9939-2015-12919-X/S0002-9939-2015-12919-X.pdf), [J. Cilleruelo](https://mathoverflow.net/users/31020/javier) (†) and M. Z. Garaev proved the following result:
>
> Let $J(p)$ denote the number of solutions to the congruence $$x^{x} \equiv 1 \pmod{p}, \quad 1 \leq x \leq p-1.$$ Then, for any $\varepsilon>0$, there exists $c:=c(\varepsilon)>0$ such that $J(p) < c \, p^{27/82 + \varepsilon}$.
>
>
>
I am not totally sure, but I believe that this theorem is the state of the art on this problem...
|
18,770,450 |
I have a header on my website with a large image ( 1000px width ).
This image is centered (horizontally). If a user comes to this website with a browser window which is slimmer than 1000px in width, he can scroll horizontally. This is what I would like to prevent, since the outer parts of the image are not important and the rest of the page is as wide as the users browser window.
For instance:
A users browser window is 600px in width, what I would like to happen is:
The first 200px of the image are invisible, the next 600px are visible and the last 200px of the image are invisible again.
```
<html>
<body>
<div id="outer" style="width:100%;overflow-x:hidden;">
<div id="inner" style="display: table;margin: 0 auto;width:1300px">
<img src="image.jpg" alt="image" width="1300px">
</div>
</div>
</body>
</html>
```
|
2013/09/12
|
[
"https://Stackoverflow.com/questions/18770450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816644/"
] |
You will need to use CSS for that.
```
div {
overflow-x: hidden;
}
```
|
6,513,207 |
I'm trying to understand how the events in a BSD socket interface translate to the state of a TCP Connection. In particular, I'm trying to understand at what stage in the connection process `accept()` returns on the server side
1. client sends SYN
2. server sends SYN+ACK
3. client sends ACK
In which one of these steps does `accept()` return?
|
2011/06/28
|
[
"https://Stackoverflow.com/questions/6513207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357024/"
] |
`accept` returns when the connection is complete. The connection is complete **after the client sends his ACK**.
`accept` gives you a socket on which you can communicate. Of course you know, you can't communicate until the connection is established. And the connection can't be established before the handshake.
It wouldn't make sense to return before the client sens his ACK. It is entirely possible he won't say anything after the initial SYN.
|
65,709,060 |
My employee's IT department refuses to install R for me (claiming the open source version is a security risk) and I tried to create reports with Microsoft Access 2010.
I got stuck trying to create a query on a simple table of hospital wards (for the purpose of keeping track of a data collection exercise):
[](https://i.stack.imgur.com/YQwKc.png)
I did not manage to allocate each ward a sample size that would be proportional to its bed capacity (third column above) as I was not able to refer to the sum of the elements in the "bedCapacity" column. With Excel, I would try something like this:
[](https://i.stack.imgur.com/z2uYU.png)
Cell D2 in Excel contains `=INT(C2/SUM(C$2:C$6)*50)+1` and cells D3 to D6 according formulae.
Is there any way I can refer to the sum in the `bedCapacity` column in Access 2010? I tried creating a separate query that would sum up the the 'bedCapacity` column, however could not figure out how to refer to the value in that query.
I'm trying to use Access 2010 so I can create standardised reports for the data collectors on their progress (which is not easily possible with Excel 2010, as it requires too much manual manipulation - I tried pivot tables etc.).
Would be grateful for any insights.
|
2021/01/13
|
[
"https://Stackoverflow.com/questions/65709060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11451936/"
] |
**Amazon Simple Storage Service (S3)**
>
> It allows you to store an infinite amount of data that can be accessed
> programmatically via different methods like REST API, SOAP, web
> interface, and more. It is an ideal storage option for videos, images
> and application data.
>
>
>
Features:
* Fully managed
* Store in buckets
* Versioning
* Access control lists and bucket policies
* AES-256 bit encryption at rest
* Private by default
Best used for:
* Hosting entire static websites
* Static web content and media
* Store data for computation and large-scale analytics, like analyzing
financial transactions, clickstream analytics, and media transcoding
* Disaster recovery solutions for business continuity
* **Secure solution for backup & archival of sensitive data**
**Use encryption to protect your data:**
If your use case requires encryption during transmission, Amazon S3 supports the HTTPS protocol, which encrypts data in transit to and from Amazon S3. All AWS SDKs and AWS tools use HTTPS by default
**Restrict access to your S3 resources:**
By default, all S3 buckets are private and can be accessed only by users that are explicitly granted access. When using AWS, it's a best practice to restrict access to your resources to the people that absolutely need it, you can see in that [Doc](https://aws.amazon.com/premiumsupport/knowledge-center/secure-s3-resources/).
|
55,521,985 |
Im trying to display the results from the json response from the server on my page, but some variables are displaying as NaN?
This is my json response from the server:
```
{"data":[{"id":"2","attributes":{"title":"Customer 1","status":"cancelled","end-date":"2019-01-01"}}]}
```
My customer service:
```
getCustomers(): Observable<Customer[]> {
return this.http.get<Customer[]>(this.url);
}
```
My customer component:
```
getCustomers(): void {
this.customerService.getCustomers()
.subscribe(cs => {
this.customers = cs;
//console.log(this.customers);
});
}
```
My customer html:
```
<tr *ngFor="let customer of customers.data">
<td>{{ customer.id }}</td>
<td>{{ customer.attributes.title }}</td>
<td>{{ customer.attributes.status }}</td>
<td>{{ customer.attributes.end-date }}</td>
</tr>
```
This displays title and status but not end-date...? end-date returns NaN. Im guessing it is the "-" thats messing this up? How can I solve this?
|
2019/04/04
|
[
"https://Stackoverflow.com/questions/55521985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10847474/"
] |
Dashes are not allowed in Typescript/JavaScript identifiers, you will have to use array syntax to get the end date.
```
<td>{{ customer.attributes["end-date"] }}</td>
```
|
47,675,065 |
Well i am using laratrust to handle roles and permissions for my application.
I want to attach a role to a user when registering but after reading laratrust documentation i cant seem to figure out whats the issue!
Here is my code
```
public function register(Request $request) {
$this->validation($request);
User::create([
'name' => $request->name,
'lastname' => $request->lastname,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->attachRole($employer);
Auth::attempt([
'email' =>$request->email,
'password' => $request->password]);
// Authentication passed...
return redirect('/');
}
```
With the above i get error unknown query builder attacheRole!
Any suggestions?
|
2017/12/06
|
[
"https://Stackoverflow.com/questions/47675065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
you forget to define **$user** (see in my code example) but there would be also error with the **$employer** it isn't definied in the function...
```
$user = User::create([
'name' => $request->name,
'lastname' => $request->lastname,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->attachRole($employer);
```
[Laratrust Examples & doc](https://github.com/santigarcor/laratrust/blob/5.0/docs/usage/concepts.rst)
|
6,131,896 |
Where I got stuck:
------------------
In my spare time I work on a private website. My self-teaching is *really* unstructured, and I've run up against a huge hole in my fundamentals.
I'm looking at a jQuery example from the jQuery API website, [serializeArray](http://api.jquery.com/serializeArray/), and I can't wrap my head around the ShowValues function.
Here's how it goes:
```
function showValues() {
var fields = $(":input").serializeArray();
$("#results").empty();
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
});
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
```
And I'm pretty sure I get what's going on in everything except lines 4 and 5:
```
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
```
jQuery goes through each key in the *fields* array and puts what it finds through the generic function: *function(i,field)*
that function uses its two parameters to produce a string to append to #results.
**My questions**:
Why does that function need two parameters? The variable *i* seems to count up from zero, for each time the function is run. and if it's taken out of the function, field.value returns undefined.
Since the values coming in to the two-parameter function are arranged into an array, the function has to...match the dimensions of the array?
Is `i` special, or could any spare variable be used?
And what's happening with `field.value`? `.value` isn't in the jQuery API, but I think it's still plucking values from the second position in the fields array?
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769780/"
] |
**Why does the function need two parameters?**
First of all you should read the documentation of [.each](http://api.jquery.com/jQuery.each/). It tells you that it expects a function defined as such:
```
callback(indexInArray, valueOfElement)
```
That has been decided, so you have to abide to it (the reasoning is beyond this answer).
If you define your callback as such
```
function(indexInArray, valueOfElement, foo) { ... }
```
and it is called as
```
callback(indexInArray, valueOfElement)
```
then `foo` will be undefined.
If you define your callback as
```
function(foo) { ... }
```
it will still be called as
```
callback(indexInArray, valueOfElement)
```
and `foo` will contain the `indexInArray` - and `0.value` will of course be undefined if you "leave out the `i`".
**Can I use a spare variable?**
Yes you can. In most functional languages you will find `_` used for parameter that you don't care about (be careful if you use libraries like `underscore.js` though). Any other name can be used.
```
$(...).each(function(_, elem) {
...
});
```
|
366,496 |
I've seen that both 'hoi polloi' and 'the hoi polloi' can be used. Does anyone know which is more accepted or correct? Or are they the same?
|
2017/01/03
|
[
"https://english.stackexchange.com/questions/366496",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/170840/"
] |
In its definition of *[hoi polloi](http://unabridged.merriam-webster.com/unabridged/hoi%20polloi)*, M-W Unabridged notes:
>
> Since *hoi polloi* is a transliteration of the Greek for “the many,”
> some critics have asserted that the phrase should not be preceded by
> the. They find “the hoi polloi” to be redundant, equivalent to “the
> the many”—an opinion that fails to recognize that *hoi* means nothing
> at all in English. Nonetheless, the opinion has influenced the
> omission of *the* in the usage of some writers.
>
>
> But most writers use *the*, which is normal English grammar.
>
>
>
In its example usage sentences, M-W Unabridged gives examples of both usages:
>
> "strain so hard in making their questions comprehensible to *hoi
> polloi*" — S. L. Payne
>
>
> "burlesque performance … for the *hoi polloi*" — Henry Miller
>
>
>
|
230,299 |
I've been looking for and thinking of a solution to the following but I cant come up with it, and hope someone can help me.
I have the following table:
```
ClientId RecordDateTime
-------- -------------------
1 2019-02-14 14:05:49
1 2019-02-14 14:06:34
1 2019-02-14 14:07:19
1 2019-02-14 14:08:49
1 2019-02-14 14:09:34
1 2019-02-14 14:10:32
1 2019-02-14 14:12:32
1 2019-02-14 14:14:18
1 2019-02-14 14:15:10
```
I need to count the amount of occurrences using a determined amount of minutes to split the occurrences. For example:
* I set the limit to 1 minutes
* First datetime is 14:05:49
* Second datetime is 14:06:34, which has less than 1 minute difference with the previous one (14:05:49), so I consider it belongs to the same occurrence.
* Third datetime is 14:07:19, which also has less than 1 minute difference with the previous one (14:06:34), so is still same occurrence
* Now it comes 14:08:49, which has a difference with the previous one of MORE than 1 minute, so I consider its a new occurence.
* Next 14:09:34, which has a difference of less than 1 minute with 14:08:49.
And so it goes.
At the end, the result I want is:
```
ClientId Occurrence Start Occurrence End
-------- ------------------- -------------------
1 2019-02-14 14:05:49 2019-02-14 14:07:19
1 2019-02-14 14:08:49 2019-02-14 14:10:32
1 2019-02-14 14:12:32 2019-02-14 14:12:32
1 2019-02-14 14:14:18 2019-02-14 14:15:10
```
This is just an example, but I have a lot of data, from multiple `ClientIds`.
Is there way of doing this without using stored procedures and looping through each row?
Thanks in advance for any help
|
2019/02/20
|
[
"https://dba.stackexchange.com/questions/230299",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/172985/"
] |
You need to do some grouping for it
```
CREATE TABLE Table1
([ClientId] int, [RecordDateTime] datetime)
;
INSERT INTO Table1
([ClientId], [RecordDateTime])
VALUES
(1, '2019-02-14 14:05:49'),
(1, '2019-02-14 14:06:34'),
(1, '2019-02-14 14:07:19'),
(1, '2019-02-14 14:08:49'),
(1, '2019-02-14 14:09:34'),
(1, '2019-02-14 14:10:32'),
(1, '2019-02-14 14:12:32'),
(1, '2019-02-14 14:14:18'),
(1, '2019-02-14 14:15:10')
;
select
ClientID
,min(RecordDateTime) as [Occurrence Start]
,max(RecordDateTime) as [Occurrence End]
from
(
select
ClientID
,RecordDateTime
,sum(grp) over(PARTITION BY ClientID ORDER BY RecordDateTime) as sgrp
from
(
select
ClientID
,RecordDateTime
,isnull(prevRecordDT,RecordDateTime) as prevRecordDT
,case when datediff(second,prevRecordDT,RecordDateTime) <=60 then 0 else 1 end as grp
from
(
select
ClientID, RecordDateTime,
LAG(RecordDateTime,1,NULL)OVER(PARTITION BY ClientID ORDER BY RecordDateTime) as prevRecordDT
from Table1
) as s
) as g
) as a
group by ClientID,sgrp
```
output of it:
```
ClientID Occurrence Start Occurrence End
1 14/02/2019 14:05:49 14/02/2019 14:07:19
1 14/02/2019 14:08:49 14/02/2019 14:10:32
1 14/02/2019 14:12:32 14/02/2019 14:12:32
1 14/02/2019 14:14:18 14/02/2019 14:15:10
```
[dbfiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=2ccca3dc3e3767e06c92a1bd0aa2237f)
[source of inspiration](https://sqlperformance.com/2018/09/t-sql-queries/special-islands)
A short description:
```
select
ClientID, RecordDateTime,
LAG(RecordDateTime,1,NULL)OVER(PARTITION BY ClientID ORDER BY RecordDateTime) as prevRecordDT
from Table1
```
key point here is the LAG function , to get the previous value
```
ClientID RecordDateTime prevRecordDT
1 14/02/2019 14:05:49
1 14/02/2019 14:06:34 14/02/2019 14:05:49
1 14/02/2019 14:07:19 14/02/2019 14:06:34
```
Then, do a difference, in seconds , to test if it's in interval:
**,case when datediff(second,prevRecordDT,RecordDateTime) <= 60 then 0 else 1 end as grp**
```
select
ClientID
,RecordDateTime
,isnull(prevRecordDT,RecordDateTime) as prevRecordDT
,case when datediff(second,prevRecordDT,RecordDateTime) <= 60 then 0 else 1 end as grp
from
(
select
ClientID, RecordDateTime,
LAG(RecordDateTime,1,NULL)OVER(PARTITION BY ClientID ORDER BY RecordDateTime) as prevRecordDT
from Table1
) as s
ClientID RecordDateTime prevRecordDT grp
1 14/02/2019 14:05:49 14/02/2019 14:05:49 1
1 14/02/2019 14:06:34 14/02/2019 14:05:49 0
1 14/02/2019 14:07:19 14/02/2019 14:06:34 0
1 14/02/2019 14:08:49 14/02/2019 14:07:19 1
```
After this, just do a sum base on `grp` column
**,sum(grp) over(PARTITION BY ClientID ORDER BY RecordDateTime) as sgrp**
```
select
ClientID
,RecordDateTime
,sum(grp) over(PARTITION BY ClientID ORDER BY RecordDateTime) as sgrp
from
(
select
ClientID
,RecordDateTime
,isnull(prevRecordDT,RecordDateTime) as prevRecordDT
,case when datediff(second,prevRecordDT,RecordDateTime) <= 60 then 0 else 1 end as grp
from
(
select
ClientID, RecordDateTime,
LAG(RecordDateTime,1,NULL)OVER(PARTITION BY ClientID ORDER BY RecordDateTime) as prevRecordDT
from Table1
) as s
) as g
ClientID RecordDateTime sgrp
1 14/02/2019 14:05:49 1
1 14/02/2019 14:06:34 1
1 14/02/2019 14:07:19 1
1 14/02/2019 14:08:49 2
1 14/02/2019 14:09:34 2
```
And finally, do `min` and `max` grouping by ClientID and sgrp
|
57,649,122 |
I want to wait till the execution of one loop is completed in below code.Dont intended to process next item in list until one is done. How to ensure that execution inside foreach loop is completed once at a time or one loop at a time in the below scenario
Please note, this is a sample code only to demonstrate the issue, I know that if I remove the Task.Run from for each loop, it may work, but I need to have that task.Run in the foreach loop for some reason in my code.
```
List<int> Items = new List<int>();
Items.Add(1);
Items.Add(2);
Items.Add(3);
foreach(var itm in Items)
{
Task.Run(() =>
{
MyFunction(itm);
});
// I want to wait here till one execution is complete, e.g till execution of Item with Value 1 is completed,
//I dont' intend to execute next item value of 2 until processing with value 1 is completed.
}
private void MyFunction(int value)
{
Task.Factory.StartNew(() =>
{
MyFunction2(value);
});
}
private void MyFunction2 (int number)
{
// do some ops
// update UI
}
```
|
2019/08/25
|
[
"https://Stackoverflow.com/questions/57649122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8143566/"
] |
Use async await. `await` allows you to wait for a `Task` to finish without blocking the thread (thus your application won't freeze)
```cs
foreach(var itm in Items)
{
await MyFunction(itm);
}
// you must return Task to await it. void won't work
private Task MyFunction(int value)
{
// Task.Run is preferred over Task.Factory.StartNew,
// although it won't make any difference
return Task.Run(() => MyFunction2(value));
}
```
Also don't forget to make the method containing the foreach loop `async Task`. You can await Tasks only in `async` methods. Return type should be `Task`, so you can later await it and possibly catch exceptions. Avoid `async void`, unless the method is an event handler.
```cs
public async Task Foo()
{
foreach(var itm in Items)
{
await MyFunction(itm);
}
}
```
|
18,076,879 |
RTFM is the most natural reply but I have tried that and it did not work.
This is what I have done so far:
1. Install all the necessary USB drivers from the vendor's site. The USB device is properly installed.
2. Add `android:debuggable="true"` to my manifest
3. Tried `adb devices` in command prompt and it shows the device as connected
4. Enabled USB debugging via `Developer Settings`
Still, my phone is **not detected in Eclipse**
What is going wrong ?
I am using Windows 7 32 bit and trying to connect a Samsung Galaxy S3 (GT-I9300) with the latest firmware :)
|
2013/08/06
|
[
"https://Stackoverflow.com/questions/18076879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894684/"
] |
I have same issue with my Galaxy S3 (GT-I9300). I solved this issue after "Factory Data Reset". Now when i connect my phone with USB ,Eclipse shows my device perfectly.
Hope its helpful to you...
|
51,117,498 |
I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me.
The current script I have is:
```
x = input()
print(x)
print(type(x))
```
However, regardless of i input a string, integer or float it will always print string? Any suggestions?
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51117498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10015517/"
] |
In Python `input` always returns a `string`.
If you want to consider it as an `int` you have to convert it.
```
num = int(input('Choose a number: '))
print(num, type(num))
```
If you aren't sure of the type you can do:
```
num = input('Choose a number: ')
try:
num = int(num)
except:
pass
print(num, type(num))
```
|
6,365,448 |
As per the title, it seems only Chrome isn't playign along. Note that form fields cannot be clicked on which are on the left portion of the screen. This only occurs on some pages (such as the Contact page). It appears that the #left\_outer div is overlaying the content. When I edit the css via Firebug or Chrome's dev toools, it works, when I edit the actual css and refresh, it does not.
Any ideas?
**LINK:**
Thanks!
|
2011/06/15
|
[
"https://Stackoverflow.com/questions/6365448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262374/"
] |
Usually when you have set the `z-index` property, but things aren't working as you might expect, it is related to the `position` attribute.
In order for `z-index` to work properly, the element needs to be "positioned". This means that it must have the `position` attribute set to one of `absolute`, `relative`, or `fixed`.
Note that your element will also be positioned relative to the first ancestor that is positioned if you use `position: absolute` and `top`, `left`, `right`, `bottom`, etc.
|
54,174 |
Lately I've started learning some basic music theory and I have been trying to rationalize some of the interesting chords I have heard of from famous pieces. Here is an example of which I am not sure if my understanding is correct.
Below are bar 11-12 from Mozart's Piano Sonata No.11 in A major, K.331. I have marked the chords using Roman numeral notations.
[](https://i.stack.imgur.com/Px8LY.png)
The blue text shows a naive marking. To me the ♯iv° chord gives a warm and sweet shifting feeling. I found that if I think of it as an applied chord (by tonicizing V) then the last three chords becomes a (vii° - IV - I) progression. If this is the case I was wondering how come the IV chord, as a pre-dominant chord, appears *after* the dominant chord vii° instead of before it? Why would the progression still sound inevitable when the strong dominant -> tonic progression is broken?
---
Per @Dekkadeci's answer I revised the analysis as follows. The final three-chord progression simultaneously resolves two tension (cadential I chord to V, and on the V scale, dominant vii° to tonic I.
[](https://i.stack.imgur.com/mf2pZ.png)
|
2017/03/08
|
[
"https://music.stackexchange.com/questions/54174",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37541/"
] |
>
> If this is the case I was wondering how come the IV chord, as a pre-dominant chord, appears after the dominant chord vii° instead of before it? Why would the progression still sound inevitable when the strong dominant -> tonic progression is broken?
>
>
>
Due to the E as a root instead of an A, the second last chord is not formally a I or a plain IV/V chord, but it is actually a I 6/4 chord. The I 6/4 chord is treated as a pre-dominant chord that must be immediately followed by a dominant-function chord (often V, just like the last chord). Its pre-dominant function is so strong that one of the theory books I was told to use in harmony class labels it as V 6/4 instead.
(I also believe that the "#iv° 6" is actually vii° 6 of V.)
|
39,640,684 |
I have these in my header rather than under the body as it said bootstrap needs jQuery to run:
```
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
```
And this is the actual navbar part. I'm pretty sure something is missing but can't see what i'm doing wrong:
```
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed navbar-right " data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</div>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right" id="bs-example-navbar-collapse-1">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="button0"><a href="#landing-page">Home</a></li>
<li id="button1"><a href="#what-we-do">What We Do</a></li>
<li id="button2"><a href="#contact">Contact Us</a></li>
</div>
</ul>
</div>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
```
|
2016/09/22
|
[
"https://Stackoverflow.com/questions/39640684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6864067/"
] |
HTML Some Unwanted div change HTML
```
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed navbar-right " data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right" id="bs-example-navbar-collapse-1">
<div class="navbar-collapse">
<ul class="nav navbar-nav">
<li id="button0"><a href="#landing-page">Home</a></li>
<li id="button1"><a href="#what-we-do">What We Do</a></li>
<li id="button2"><a href="#contact">Contact Us</a></li>
</ul>
</div>
</div>
</nav>
```
<https://jsfiddle.net/o6p71fko/1/>
|
18,514,346 |
im very new to C# and ASP.Net. Does anybody know how to create a popup in Asp?
My scenario:
When I click on a button, it checks some states. If a condition is being fulfilled a popup shall be thrown due to the state (here: achieved percentages).
So 2 invidual Popup Windows shall be thrown by clicking the same button.
>
> (Do you want to abort the contract, which wasn't completed? Yes - No)
>
>
> (Do you want to completed the contract, which hasn't achieved the target? Yes - No)
>
>
>
So the dialog boxes shall appear according for the same button when the condition was fullfilled.
Can anybody help me? (Code behind in C# and javascript?)
|
2013/08/29
|
[
"https://Stackoverflow.com/questions/18514346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729782/"
] |
Hmm. Well, first of all,this code is probably so heavily I/O bound that optimizing anything but disk access is probably inconsequential. You might try throwing a pointless loop to 1000 before every if-test just to see how much difference that makes.
It doesn't appear like indexing would help you here, since you must access all the data when a value isn't specified, but if you are computing aggregates then caching those might help. [Intersystem's DeepSee](http://docs.intersystems.com/cache20101/csp/docbook/DocBook.UI.Page.cls?KEY=SETDeepSee) product is designed for that.
But it sounds like maybe you are just running a big report printing all the data, and want to optimize what you can. In that case, I think your solution does that. As far as elegance, well, it usually isn't found in conjunction with heavy optimization. The problem with generalizing a solution is that it's usually slower than a tailored solution.
I think possibly using tags and goto statements, while much harder to read, might run a little faster than your solution - if you think it's worth it. The fact that Intersystems does tags and gotos in their compiled SQL routines makes me think it's likely the fastest option. I haven't measured the difference, but I suppose Intersystems probably has. If you really need speed then you should try different approaches and measure the speed. Be sure to test with warm and cold routine and global caches.
As far as a general solution, you could, if you really wanted to, write something that *generates* code similar to what you hand-coded, but can generate it for a general n level solution. You tell it about the levels and it generates the solution. That would be both general and fast - but I very much doubt that for this example it would be a good use of your time to write that general solution, since hand-coding is pretty trivial and most likely not that common.
|
31,399,011 |
I've installed django-nested-inline but I have problems. Here's my code:
```
from django.contrib import admin
from nested_inline.admin import NestedStackedInline, NestedModelAdmin
from .models import Positive, Negative, Option, Question
class PositiveInline(NestedStackedInline):
model = Positive
class NegativeInline(NestedStackedInline):
model = Negative
class OptionInline(NestedStackedInline):
model = Option
inlines = [PositiveInline, NegativeInline,]
class QuestionAdmin(NestedModelAdmin):
fieldsets = [
(None, {'fields': ['question_title']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [OptionInline,]
admin.site.register(Question, QuestionAdmin)
```
When I try to add a new Question, I have this error:
```
AttributeError at /admin/question/question/add/
'OptionInline' object has no attribute 'queryset'
```
Am I doing something wrong?
|
2015/07/14
|
[
"https://Stackoverflow.com/questions/31399011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938884/"
] |
Posted this as a comment, but since it worked out I'll post this here for future reference. Seems like this is the result of a bug, referenced and a fix has been applied here: <https://github.com/s-block/django-nested-inline/issues/31>
|
4,950,396 |
We are getting a CommunicationsException (from DBCP) after iding for a while (a few hours). The error message (in the Exception) is at the end of this question - but I dont see wait\_timeout defined in any of the configuration files. (Where should we look? Somewhere out of the tomcat/conf directory?).
Secondly, as suggested by the Exception, where does one put the "Connector/J connection property 'autoReconnect=true'"? Here is the resource definition in the file conf/context.xml in tomcat set up:
```
<Resource name="jdbc/TomcatResourceName" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
username="xxxx" password="yyyy"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/dbname?autoReconnect=true"/>
```
Thirdly, why does the JVM wait till the call to executeQuery() to throw the Exception? If the connection has timed out, the getConnection method should throw the Exception, shouldn't it? This is the section of the source code I am talking about:
```
try {
conn = getConnection (true);
stmt = conn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rset = stmt.executeQuery (bQuery);
while (rset.next()) {
....
```
Finally, here are the 1st few lines of the Stack trace...
```
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 84,160,724 milliseconds ago. The last packet sent successfully to the server was 84,160,848 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3291)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1938)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2107)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2642)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2571)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1451)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
```
These are the reasons some of us are thinking "forget dbcp, it may be so dependent on IDE configurations and under-the-hood magic that DriverManager.getConnection(...) may be more reliable". Any comments on that? Thank you for your insights, - MS
|
2011/02/09
|
[
"https://Stackoverflow.com/questions/4950396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580796/"
] |
Since DBCP keeps returned mysql connections open for upcoming connection requests, they fall victims to the [MySQL Server timeout](http://dev.mysql.com/doc/refman/5.0/en/gone-away.html).
DBCP has a number of features that can help (can be used starting with Tomcat 5.5 IIRC).
```
validationQuery="SELECT 1"
testOnBorrow="true"
```
The validation makes sure that a connection is valid before returning it to a webapp executing the 'borrow' method. The flag of course, enables this feature.
If the timeout (8 hours I believe) is elapsed and the connection is dead, then a new connection is tested (if there are none anymore, it is created) and provided to the webapp.
Other possible approaches:
1. use the `testWhileIdle="true"` DBCP in your resource settings to also check idle connections before an effective request is detected.
2. Use the 'connectionProperties' to harden your MySQL connection (e.g. `autoReconnect/autoReconnectForPools=true`)
|
17,487,538 |
i am working with Sencha touch application like multiple choice Questions Quiz.
in sencha touch there is model-store concept,but i want to use database like Sqlite for Questions and answers.
so, is there any way to use database in Sencha toch ?
or can we make queries for databas operation ?
any help will be appreciated.
thanks in advance.
|
2013/07/05
|
[
"https://Stackoverflow.com/questions/17487538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1992254/"
] |
Take a look at the [Filter menu customization](http://demos.kendoui.com/web/grid/filter-menu-customization.html) demo. It appears you would do something along these lines:
```
@(Html.Kendo()
.Grid<MyClass>()
.Name("grid")
.DataSource(data =>
data.Ajax()
.ServerOperation(false)
.Read(read =>
read.Action("MyAction", "MyController"))
)
.Columns(cols =>
{
cols.Bound(x => x.dt).Title("Date").Width(150);
cols.Bound(x => x.name).Title("Name").Width(250);
})
.Filterable(filterable => filterable
.Extra(false)
.Operators(ops => ops
.ForString(str => str.Clear()
.Contains("Contains")
.StartsWith("Starts with")
// any other filters you want in there
)))
.Sortable())
```
If I'm interpreting it correctly, the `str.Clear()` clears out the filters that exist so you'll be building your own from there. So if you don't think the client needs or wants the `.EndsWith` filter, for example, you would not include it here.
|
89,052 |
We read in Lk 4: 38-39 :
>
> After leaving the synagogue he entered Simon’s house. Now Simon’s mother-in-law was suffering from a high fever, and they asked him about her. Then he stood over her and rebuked the fever, and it left her.
>
>
>
Elsewhere, we see Jesus rebuking the evil spirit (Lk 9: 42). But it is doubtful if anyone who witnessed the healing believed that the fever of Simon's MiL had been caused by evil spirit. Even more doubtful is the existence of knowledge that it could have been caused by an animate thing say, virus . Even today, fever is more often than not, measured by the external symptom namely high temperature. Is it that Jesus rebuked the temperature which is an inanimate entity?
My question therefore is: **According to Catholic scholars, what exactly did Jesus rebuke while healing the mother-in-law of Simon?**
|
2022/01/17
|
[
"https://christianity.stackexchange.com/questions/89052",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/21496/"
] |
**What exactly did Jesus rebuke while healing the mother-in-law of Simon?**
English translations vary and if you do not mind I would like to use another version than the one you used. Translation can make a big difference. Thus I will use the Douay-Rheims 1899 American Edition (DRA). After all it is a Catholic Catholic Bible.
>
> 38 And Jesus rising up out of the synagogue, went into Simon's house. And Simon's wife's mother was taken with a great fever, and they besought him for her.
>
>
> 39 And standing over her, he commanded the fever, and it left her. And immediately rising, she ministered to them. - [Luke 4:38-39](https://www.biblegateway.com/passage/?search=Luke%204%3A38-39&version=DRA)
>
>
>
Now it becomes abundantly clear that Jesus simply commanded the fever to leave Peter’s Mother-in-Law. It much more than a simply rebuke! The Divine Healer cured her!
I would simply like to add a few reflections of the Church Fathers on this passage.
>
> [**Commentary from the Church Fathers**](https://en.m.wikipedia.org/wiki/Healing_the_mother_of_Peter%27s_wife)
>
>
> * **Glossa Ordinaria**: And it is not enough that she is cured, but strength is given her besides, for she arose and ministered unto them.
> * **Chrysostom**: This, she arose and ministered unto them, shows at once the Lord's power, and the woman's feeling towards Christ.
> * **Bede**: Figuratively; Peter's house is the Law, or the circumcision, his mother-in-law the synagogue, which is as it were the mother of the Church committed to Peter. She is in a fever, that is, she is sick of zealous hate, and persecutes the Church. The Lord touches her hand, when He turns her carnal works to spiritual uses.[6]
> * **Saint Remigius**: Or by Peter's mother-in-law may be understood the Law, which according to the Apostle was made weak through the flesh, i. e. the carnal understanding. But when the Lord through the mystery of the Incarnation appeared visibly in the synagogue, and fulfilled the Law in action, and taught that it was to be understood spiritually; straightway it thus allied with the grace of the Gospel received such strength, that what had been the minister of death and punishment, became the minister of life and glory.
> * **Rabanus Maurus**: Or, every soul that struggles with fleshly lusts is sick of a fever, but touched with the hand of Divine mercy, it recovers health, and restrains the concupiscence of the flesh by the bridle of continence, and with those limbs with which it had served uncleanness, it now ministers to righteousness.
> * **Hilary of Poitiers**: Or; In Peter's wife's mother is shown the sickly condition of infidelity, to which freedom of will is near akin, being united by the bonds as it were of wedlock. By the Lord's entrance into Peter's house, that is into the body, unbelief is cured, which was before sick of the fever of sin, and ministers in duties of righteousness to the Saviour.
>
>
>
|
180,382 |
Which one is the correct way of asking this question? When?
a) Why you changed your job?
b) Why did you change your Job?
c) Let me know why you changed your job?
d) Let me know why did you change your job?
|
2018/09/21
|
[
"https://ell.stackexchange.com/questions/180382",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/4084/"
] |
Not in Standard English. Main clause interrogatives like this require subject-auxiliary inversion: "Where did you bring all these vegetables from?" Note that the plain verb-form "bring" is required after the auxiliary verb "did".
(answer transcribed from comment)
|
8,132,594 |
While making a project with Makefile, I get this error:
```
error: implicit declaration of function ‘fatal’ [-Werror=implicit-function-declaration]
cc1: all warnings being treated as errors
```
The `./configure --help` shows:
```
Optional Features:
--disable-option-checking ignore unrecognized --enable/--with options
--disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
--enable-FEATURE[=ARG] include FEATURE [ARG=yes]
--disable-dependency-tracking speeds up one-time build
--enable-dependency-tracking do not reject slow dependency extractors
--disable-gtktest do not try to compile and run a test GTK+ program
--enable-debug Turn on debugging
```
How can I tell *configure* not to include [-Werror](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror)?
|
2011/11/15
|
[
"https://Stackoverflow.com/questions/8132594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859227/"
] |
[Werror](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror) is a GCC argument, and you cannot remove it directly via [./configure](https://en.wikipedia.org/wiki/Configure_script). Otherwise, an option like `--disable-error` would show up in the help text. However, it's possible.
Set an environment variable:
```
export CFLAGS="-Wno-error"
```
That's for C compilers. If the project uses C++, do:
```
export CXXFLAGS="-Wno-error"
```
In the very rare case the project does not honor this variables, your last resort is to edit the `configure.ac` file and search for `-Werror` and remove it from the string it occurs in (be careful though).
|
15,769,521 |
I ran the following code to install the underscore js module:
```
npm install -g underscore
```
I then tried to access it via the node console, but I get the following error:
```
node
> __ = require('underscore');
Error: Cannot find module 'underscore'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at repl:1:6
at REPLServer.self.eval (repl.js:109:21)
at rli.on.self.bufferedCmd (repl.js:258:20)
at REPLServer.self.eval (repl.js:116:5)
at Interface.<anonymous> (repl.js:248:12)
at Interface.EventEmitter.emit (events.js:96:17)
```
Why doesn't this example work?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15769521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89761/"
] |
I don't really know why, but it fails indeed (when installing underscore globally, as you have done).
If you install it without -g, it should work (be careful, however, as '\_' is already used by Node REPL to hold the result of the last operation, as explained here:
[Using the Underscore module with Node.js](https://stackoverflow.com/questions/5691901/using-the-underscore-module-with-node-js?rq=1)
Do you really need to install it globally?
|