INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Display Customer Firstname and User Meta to New Woocomerce account email
I want to get the the new registrant first name and display it on my email template:
$firstname = get_user_meta($userid,'first_name',true);
echo '<pre>';
print_r($firstname);
echo '</pre>'
But it is not returning the value. Any ideas?
Thanks
|
The issue was how the user is created and this is my code for creating the user:
$user = wc_create_new_customer($email,$email,$password);
In order to fix that I change the code to:
$new_customer_data = apply_filters( 'woocommerce_new_customer_data', array(
'user_login' => $email,
'user_pass' => $password ,
'first_name' => $firstname ,
'last_name' => $lastname ,
'user_email' =>$email ,
'display_name' => $firstname . ' ' . $lastname ,
'nickname' => $firstname . ' ' . $lastname ,
'role' => 'customer'
) );
$user_id = wp_insert_user( $new_customer_data );
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, wordpress, forms, woocommerce, user data"
}
|
Is there any way to supply generic arguments to a function-like proc macro?
So let's say I have a proc macro defined like this:
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream { ... }
Is there any way to introduce a generic argument? For instance, I would like to be able to do something like this:
#[proc_macro]
pub fn my_macro<T>(input: TokenStream) -> TokenStream {
...
T::do_something_with(input);
...
}
And at the call site:
my_macro::<Foo>! { some input }
Is there any way to achieve something like this?
|
No, this is not possible, for two reasons:
* The syntax for function-like proc macros does not include generic parameters.
* If there _was_ such a thing, the generic parameters would necessarily come as annother `TokenStream` — not something you can call a function on. The types of the program where the macro is used don't exist yet — they're still being parsed.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "rust, rust proc macros"
}
|
Prove $|x+y| \leq (1+x^2)(1+y^2)$.
> Prove $|x+y| \leq (1+x^2)(1+y^2)$.
I don't know if this is true, but I'm trying to build a proof with this property. I know this is true when both $x,y \geq 1$ and $x,y =0$ as well as $\vert x+y\vert < 1$. But the case when $1 < \vert x+y\vert < 2$ is what's giving me trouble. If this property is false, _could you provide a counterexample?_
(Sorry for the tag, not sure what else to put it under).
|
By C-S $$\sqrt{(1+x^2)(y^2+1)}\geq\sqrt{(x+y)^2}=|x+y|.$$
Also, by AM-GM and C-S we obtain: $$(x^2+1)(y^2+1)=x^2y^2+x^2+y^2+1\geq x^2+y^2+1\geq$$ $$\geq2\sqrt{x^2+y^2}=\sqrt2\sqrt{(1^2+1^2)(x^2+y^2)}\geq\sqrt2|x+y|\geq|x+y|$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "inequality, radicals, absolute value, a.m. g.m. inequality, cauchy schwarz inequality"
}
|
Is it appropriate to caution someone "from" something?
Is the word "from" used appropriately in --
> The fact that ... has happened before and could happen again, should caution us from being ...
Or is it a colloquial sort of thing?
Specifically, I'm concerned about "caution us from" in lieu of "caution us away from" or some other idiom.
|
Yes, it's appropriate, and it's not only colloquial. Consider this 1845 English translation of Pinamonti's _L'inferno aperto_ , where the first part of the title is _Hell Opened to Christians to Caution Them from Entering into It_.
For a more modern example, consider this informational publication from the Wisconsin Department of Health Services, educating camp staff on how to keep campers safe: "Caution them from swallowing lake, river, or pond water and encourage them to shower off after swimming."
Granted, _against_ and _about_ are likely more common in conjunction with this verb, but _from_ as used in your question is not inappropriate.
|
stackexchange-english
|
{
"answer_score": 11,
"question_score": 6,
"tags": "grammar"
}
|
Apple Mach-O Linker Error - ld: file not found: -ObjC
I've inherited an iOS project and can't even get it to build. I keep getting the following error:
ld: file not found: -ObjC
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I've seen posts about the 'file not found' error but none pertaining to the '-ObjC' bit that looks like a switch.
Any ideas?
|
Thanks everyone, I managed to sort it.
@Droppy pointed me in the right direction.
Before the `-ObjC` flag there was another called `-force_all`. I then stumbled across this answer which indicated that you only need the `-ObjC` flag. I removed `-force_all` and it started to work!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, objective c, iphone, xcode, clang"
}
|
Prompt a question similar to AskYesNo, but different value
I want to display a similar looking prompt question to askYesNo() but with different values to select.
I want to be able to select with a click, not through the console, a unique value. I am trying the following:
next_step = askYesNo("Choose a country", default = TRUE,
prompts = getOption("askYesNo", gettext(c("Morocco", "Tunisia", "Cancel"))),)
But it still appears as
` for more flexibility. For example,
menu(gettext(c("Morocco", "Tunisie", "Cancel")),
graphics = TRUE,
title = "Choose a country")
should display something useful for you. I'm not on Windows, so I can't show you what it will look like for you. On a Mac it looks like this:  {
( [ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S]
}
Any help would be appreciated. Thanks
|
$previous is defined in `/etc/init.d/rc` on line 49 as previous=$PREVLEVEL and refers to the previous run level.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 1,
"tags": "18.04, scripts"
}
|
Git Flow merging a release branch back to Development
I have a feature branch (let's call it A) that I've merged with my Development branch from which I've created a release-A branch which has no changes. I merged release-A to master and have tagged master with a release identifier. Git Flow says that release-A should be merged back to Development but I'm reasonably assuming this is only needed if there are differences between release A and Development?
I'm supposing that if a branch from Development is taken and then merged back, then Git will realise that there are no differences and effectively ignore the merge?
I'm pretty new to Git so please excuse if this is a dumb question.
|
since release-A and Development branches point both to the same commit, merging will not change anything. So yes, `git` realizes that there is nothing to do.
**EDIT** for "simple" questions like this, you can always create a dummy git repository and see what happens. In this case:
mkdir test
cd test
git init
echo a > a
git add a
git commit -m "add a"
git branch release-A
git merge release-A
this gives:
> Already up to date.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "git, git flow"
}
|
How to get class by name in PHP?
I have the string with class name. I want to get a class with this name and call a static methods of this class.
How to make something like this?
$className = "Model";
getClassByName($className)::sayHello();
|
You can simply call the method on the variable, you might want to wrap an "if" around it to check if the class exists.
$className = "Model";
if (class_exists($className)) {
$className::sayHello();
}
You can check out this 3v4l for a repro case.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
.on not working on dynamically generated elements
I have a table which populates _several_ rows with a button element, these rows are generated dynamically using php script:
<button class="btn btn-default btn-xs data_upload">Upload</button>
I simply want to detect a click on this button using jquery -
$(".data_upload").on("click", function() {
alert("asdf");
});
|
You have to delegate the event with the nearest static parent, i just used `document` since i dont know the nearest static parent in your context.
Try,
$(document).on("click",".data_upload", function() {
alert("asdf");
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -4,
"tags": "php, jquery"
}
|
Passing values to Javascript functions
Is A or B better and why?
A) var myvar = this.value(); myFunc(myvar);
B) myFunc(this.value());
|
`B` is better because you don't pollute the current function's scope with a _one shot_ variable. However you should be able to figure out these things by yourself.
Also, as others pointed out, it's 2 line vs 1 line of code. Not such a dramatic improvement, but still...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "javascript"
}
|
Aerospike In-Memory configuration
Consider a scenario in Aerospike:
_data-in-memory is set as true and memory space < disk space_
what happens when memory is filled up (stop-writes-pct is reached). Does aerospike stop accepting writes all together? OR it will continue to write to disk (if disk space is available) ?
How does the above behaviour is affected, in a multinode setup ?
|
Writes will start to fail completely when stop-writes-pct is reached. In data-in-memory configuration, stop-writes triggered by any reason (either disk or memory being full) will be honored by both.
This behavior is per node (since stop-writes-pct is related to a node and not to a cluster).
In case of a cluster, if its the node with the master copy of the data/partition which has hit stop-writes, that write will fail.
In case the node which has hit stop writes is supposed to be the replica partition node, the write is allowed for the replica data.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "in memory database, aerospike"
}
|
Commandline complete list of commands
Is there a way/command to get a listing of all the commands available on my system from the commandline prompt?
|
Usually pressing `tab` once or twice will display a message such as:
Display all 435 possibilities? (y or n)
Pressing `Y` will display all commands you can run that are on your default path.
|
stackexchange-superuser
|
{
"answer_score": 10,
"question_score": 5,
"tags": "linux, command line, unix"
}
|
Redirecionando o conteúdo do Adobe XD no WordPress
A empresa onde eu trabalho contratou alguém para fazer um dashboard simples usando o Adobe XD.
Exemplo: <
Mas nós gostaríamos de hospedar o dashboard no nosso site, que foi desenvolvido usando o WordPress. Isso é possível? Acredito que soluções envolvendo embedding da página com o dashboard no WordPress (provavelmente mais fácil) ou de alguma forma importando o programa Adobe XD em nossa página do WordPress (não sei se é possível) seriam válidas. Obrigado!
|
Oi, Na realidade adobe XD é uma ferramenta de design e prototipagem para designers. É bem parecido com o Sketch e Figma. São ferramentas para design. o Adobe XD hoje não oferece plugin para conversão em HTML e CSS, mas mesmo que oferecesse não resolve o seu problema que é colocar um dashboard no wordpress. O que você pode fazer é desenvolver o template e trabalhar no functions.php e colocar nas pastas do seu tema, porém para integrar com o wordpress e imprimir informações do painel, precisa rpogramar em PHP, colocar as variáveis corretas conforme documentação do wordpress etc.
Dá uma olhada nesse link também:<
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "html, wordpress, embed"
}
|
Limit user participation to a server regulated competition? (iphone sdk)
I am new to programming for the iPhone. I want to allow my users to participate in a competition, to a maximum of n times a day. Is there anyway of going about that programmatically and/or through a server for optimal security (i have done NSUserDefaults). ?
Is it possible to get the database server to check the number of entries made by a device and send a call back to the application if it has exceeded n number of attempts for that day?
thank you for any suggestions.
|
Sure you can!
Each iPhone/iPod Touch device has a unique identifier you can get from the UIDevice class. When the app launches, bring up a screen that says "authenticating" and send that unique ID to your server in a simple HTTP GET request. On the server, you can log the identifier and a timestamp to a database and see how many times that same identifier has been seen in a 24 hour period. For this, you could use standard MySQL + PHP. The server could send back a simple "Yes" or "No" depending on the competition rules.
You definitely want it to go through a server. People can get around limitations saved in your NSUserDefaults by uninstalling and reinstalling the app. Using a server also has other benefits. It would allow you to modify the competition rules after deploying the application without waiting for a 14-day app update review from Apple.
Ben
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, database"
}
|
How to programmatically determine name of CKEditor instance
I've added a CKEditor instance programmatically to my page in the code-behind of my ASP.NET page:
VB.NET:
itemEditor = New CkEditor
cell.Controls.Add(itemEditor)
... which works fine. I can get the HTML on the postback and do stuff with it.
However, I also want to do some client-side stuff with it, specifically take a selected item out of another control, and insert it into the text by handling the `onchange` event.
So, how can I get the name of the editor instance in the JavaScript, so that I can do stuff like:
function GetCkText()
{
var htmlFromEditor = CKEDITOR.instances['editorName'].getData();
// do stuff with htmlFromEditor
}
|
Assuming you only have one editor instance:
for ( var i in CKEDITOR.instances ){
var currentInstance = i;
break;
}
var oEditor = CKEDITOR.instances[currentInstance];
Here is what the JavaScript API says about instances.
Here is another way of defining the CKEditor. Here 'fck' is the input fields id:
CKEDITOR.replace( 'fck', {
customConfig : prefix + 'js/ckeditor/config.js',
height: 600,
width: 950
});
editor = CKEDITOR.instances.fck;
Notice how I am then able to reference the instance using `.fck`.
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 8,
"tags": "javascript, ckeditor"
}
|
ASP.NET code blocks in server tags
Can you not have code blocks in server tags? For example, I wish to create custom id fields using code blocks. (I know there are other way to do this with repeaters, but in my particular situation I'd like to do things this way if its possible for irrelevant reasons.)
<% foreach(var reference in references) { %>
...
<asp:LinkButton runat="server" ID='lbUpdateEmail_<%=reference.ReferenceId%>' OnClick="lbUpdateEmail_Click" style="float:right;">Update Email</asp:LinkButton>
...
<% } %>
|
It is not possible to use <% %> inside server tags.
Although ASP.NET seems very dynamic in it's behavior, you have to remember that the pages are actually compiled to .NET classes.
In this case the LinkButton tag you are using indicates that you want your page class to contain an instance of LinkButton, and the ID gives you the name of the Property you will use to access this at design time (when you are editing your code.)
Let's say in your code behind you wanted to disable the link button? How would you refer to it if the ID was not yet determined?
Also, remember that the "ID" you set is not the the "id" that gets rendered in HTML - if that was what you were looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "asp.net"
}
|
Tools for doing a RESTful POST to multiple URLs
Are there any tools that can hit multiple URLs with a POST request at the same time? I need it for doing some validation on many restful servers at once instead of 1 at a time for time sake.
|
I think that < is sufficiently sound to accomplish what you need: \- You can trigger multiple URLs at the same time \- You can concurrently load a single URL with multiple requests \- You can assess the response time \- You can make assertion testing to check everything is OK.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "url, rest, post"
}
|
Installing migx on modx 2.3.1
I am pretty new to modx and trying to install migx. I have been trying for some time now today to follow action two of setup: Set up the MIGX Configurator Custom Manager Page (CMP) and Package Manager.
My problem is that the step by step instructions do not correspond to the latest version of modx, 2.3.1 (I am pretty certain it has installed properly, but may be wrong). It asks for systems > actions > migx from the modx dashboard, but the new version of modx does not have the systems menu, only content, media, extras and manage. Does anybody know therefore how I can complete step two of setup?
link to setup instructions here
Thanks in advance
|
You should be able to skip the whole systems > action part in 2.3. After installing migx you should see it in the Extras top menu, and you can skip directly to step #16 in <
If you installed before upgrading to 2.3 you should only need to reinstall through "extras > installer"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "modx revolution, migx"
}
|
Reputation resets to 1 after clicking on a proposal in Area 51
I recently signed up for Area 51 and confirmed my email to gain 50 reputation, bringing it to a total of 51.
Then, I went to browse the Nutrition proposal and clicked on one of the questions. Now my reputation count is 1, and I can't upvote or comment on the question. When I return to the Area 51 homepage, my reputation is back to 51.
My badges do not change at all.
Is this a bug or do I have to gain reputation specific to that proposal?
|
When you click on one of the questions in the announcements box, you are being taken to Area 51 Discuss. This site acts like Area 51's Meta site and follows the same rules as other Meta sites on the network. Namely: **the reputation there is only updated once an hour** and is inherited from the main user (your Area 51 profile) when that update happens.
Your Area 51 profile: <
Your Area 51 Discuss profile: <
|
stackexchange-meta
|
{
"answer_score": 10,
"question_score": 4,
"tags": "support, reputation, area 51"
}
|
Addon for placing pinpoints on an image?
I'm looking to do something similar to the pink pinpoints seen on the screenshots here: <
I want the client to be able to add pins at a certain point on the image and optionally add some content to that pin.
I tried looking through Devot-ee, but couldn't find anything.
|
I built Pointee a while back, should cover a fair amount of what you need.
<
Looking forward to the pull requests :)
|
stackexchange-expressionengine
|
{
"answer_score": 3,
"question_score": 1,
"tags": "image"
}
|
Hexadecimal enumeration OR integer (ASCII) enumeration to fill a byte array with?
I need to fill a byte array in c language by the possible enumerations.
Here it is how I declare my byte array:
unsigned char byteArray[6];
And now I hesitate if my enumrations should look like `MyEnum1` or `MyEnum2`:
enum MyEnum1 { A1 = 0, B1 = 1, C1 = 2};
enum MyEnum2 { A2 = 0x00, B2 = 0x01, C2 = 0x02};
The purpose is something like this:
byteArray[0]=A1;
byteArray[1]=B1;
byteArray[2]=C1;
byteArray[3]=A2;
byteArray[4]=B2;
byteArray[5]=C2;
So, is there any recommandations about if my enumerations should contain hexadecimal or integers or another type of data??
Thank you!
|
In your case no matter how you will organize your `enum`. You can do it in both ways and the result will be the same.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c, arrays, hex, byte, unsigned char"
}
|
Werror doesn't make all warnings into errors
In general, the flag `-Werror` is to make all warnings into errors. But it is not always the same.
int j;
int main()
{
int i = 10;
return 0;
}
If I type `g++ -Werror main.cpp`, there aren't any tips.
If I type `g++ -Wall main.cpp`, there is a warning:
> main.c: In function ‘main’: main.c:5:9: warning: unused variable ‘i’ [-Wunused-variable]
Can anyone explain it?
Moreover,
1. Why isn't there a warning about the variable `j`?
2. How can I remove "warnings being treated as errors"?
Thanks.
|
`-Werror` turns all warnings defined by other switches into errors, so you'll have to use `-Wall` as well as `-Werror`.
g++ -Werror -Wall main.cpp
Moreover, since `j` isn't marked `static`, there is no guarantee that it won't be used outside of the compilation unit it's defined in, so the compiler can't assume it's unused.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c++, gcc, g++"
}
|
How to disable windows' contents being moved on dragging, so that only the frame is dragged and the whole window is only redrawn on drop?
How to disable windows' contents being moved on dragging, so that only the frame is dragged and the whole window is only redrawn on drop?
In Windows, KDE and XFCE this can be easily configured, but in Gnome (Ubuntu 10.10) I couldn't find where to set this up :-(
|
First, disable desktop effects to get metacity instead of compiz. Then open gconf-editor, find `/apps/metacity/general`, and enable `reduced_resources`. Here's a description of that option:
> If true, metacity will give the user less feedback by using wireframes, avoiding animations, or other means. This is a significant reduction in usability for many users, but may allow legacy applications to continue working, and may also be a useful tradeoff for terminal servers. However, the wireframe feature is disabled when accessibility is on.
As far as I know there's no option to enable it through the GUI, gconf is the only way.
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 2,
"tags": "gnome, metacity"
}
|
Is there a way to efficiently compile already preprocessed file with clang?
I got a preprocessed file with command: `clang++ -E test.cc > test.E` Then I want to quickly compile it. To do it, I run `clang++ -### -c test.cc`, then I take all those flags and just replace input file name from `test.cc` to `test.E`.
But I wonder, if there are some redundant flags in output of `clang++ -###` for already preprocessed file, or may be there are some flags, that force clang to skip preprocessing or some other unnecessary steps.
The aim is to speed up the compilation of a **preprocessed** file.
|
To speed-up compilation I need to replace the flag's "-x" argument to the proper language, like: "c" -> "cpp-output", "c++" -> "c++-cpp-output", etc. In this case clang won't run preprocessing at all.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c++, clang, c preprocessor, clang++"
}
|
Usage data not showing after importing data
After performing two successful imports (one for users and one for follow relationships) the usage data view has not updated with the expected values. Does this mean my records were not created from the import?
I was expecting around 50k user records with as many follow relationships.
Currently, I'm just creating user records as only having their ID set. When I do this via the api `get_or_create` I can see the usage update in real time. However, doing this via an import appears to have had no effect? Same for follow relationships.
I've noticed in the docs that it states `An array of users in which each line can have up to 10,000 entries`, does that mean I'm limited to 10k users per instruction?
|
Some details about what the issue was.
Automatic import has a config to disable tracking statistics for dashboard.
This configuration exists to support very big imports. However, automatic import limited by 300MB by default and it doesn't need to disable it because it's a manageable amount without any care.
That's why running configuration was wrong and it's enabled now.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "getstream io"
}
|
Numpy array comprehensions, where problem
I have a little problem with np.where and I can't find any answers in google so here's my question. Consider I have these arrays:
a = np.array([[1, 0.5, 2], [5, 0.25, 9], [-1, 0.77, 3]])
b = np.array([0.6, 0.2, 0.6])
What I want is: `if a[x, 1] < b[x] then a[x, 0] else a[x, 2]`. So I want to get this:
[1, 9, 3]
I thought code like this would work, but it doesn't
np.where(a[1] < b, a[0], a[2])
|
You almost got it:
np.where(a[:,1] < b, a[:,0], a[:,2])
You need to specify which axis you want to make the comparisons and take the elements, else as a default it will use the 0 axis, check the values for:
a[1]
a[1,:]
a[:,1]
See that the first two are the same (the default behaviour), and you are looking for the third.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, arrays, numpy"
}
|
count relations inside loop in twig
I use Symfony2 and twig templating. Think of the Q&A exact same as stackoverflow. There are list of questions with the count of score, answers, views and so on. How to count the answers of the qeustions inside loop in twig? There are OneToMany relation between Question and Answer tables.
{% for question in questions %}
<li>{{ question.score }}</li>
<li>{# there should be the count // count($question->getAnswers()) #}</li>
<li>{{ question.view }}</li>
{% endfor %}
Or if there is any better way to achieve this, I am open to suggestions.
|
This will print the count:
{{ question.answers|length }}
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 15,
"tags": "php, symfony, one to many, twig"
}
|
Algorithm to find best in class of groups with weighting?
I have widgets and a single widget will have attributes of:
Name
Weight (decimal from 0-1)
Group (letter A-F)
Price (an integer from 1 - 100)
I must pick one widget from each Group (A-F) for a total of 6 widgets. How do I write an algorithm to find the 6 widgets that give me the aggregate highest Price while at the same time keeping the aggregate Weight less-than or equal to 1? Obviously, a lot of combinations will have an aggregate weight less than 1, but I need to come up with a way to get the combination that ALSO results in the highest Price. I suppose I could solve this with a Monte Carlo simulation, but I'm hoping there is a better way.
|
This is somewhat reminiscent of the "Knapsack problem". As we know, it is NP-complete, so no algorithm exists to solve it fast. I am not going to try to prove that this problem is NP-complete, but it certainly looks that way.
You can however solve it in exponential time like this:
* Generate all combinations (this will be $n_A * n_B * \cdots * n_F$ combinations where $n_A$ i s no. of elements in $A$ and so on)
* sort combinations by aggregate price
* pick the first combination with weight $\leq 1$
**Edit** : This is in fact the equivalent of the so-called "Multiple choice Knapsack problem". There seems to exist $O(n)$-time algorithms for this using linear programming. You can read about some of their implementations in this paper by David Pisinger: link
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "linear algebra, statistics, monte carlo"
}
|
JQuery change not firing until blur
I use change(handler) to listen to change events to a textarea, but I only receive an event when the textarea loses focus, but I want to receive an event as soon as the value changes.
$("#text_object").change(listener);
function listener(dom){
alert("I'm not getting here before the textarea loses focus");
}
|
Unfortunately the browser only recognises a change when the field blurs, so you might want to try attaching a keyup listener. Not the most elegant solution, unfortunately.
Details at <
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 40,
"tags": "jquery"
}
|
"blkclr (mach_kernel)" shows up in mac's shark profiler. What does it do?
I am profiling a C program using Mac's Shark which shows that some of CPU time goes to "blkclr" in "mach_kernel". What does this kernel function do? I speculate it is related to memory allocation, but I am not sure. I have googled for some time, but could not find the answer, either. Does someone know this? Thanks in advance.
|
Zeroes out a block of memory
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c, macos, profiling, shark"
}
|
for as - meaning
An excerpt from _Pi: A Biography of the World's Most Mysterious Number_ :
> Since Euler is the father of the symbol that has the title role of this book, we ought to take a glimpse into his interesting life history. Born in Basel, Switzerland, in 1707, he was initially taught mathematics by this father, who himself studied under the famous mathematician Jakob Bernoulli. This connection served him well, **for as** the father noticed his son's proclivity for the subject, he arranged for him to study with Jakob Bernoulli's son (also a famous mathematician) Johann Bernoulli.
How to understand the construction **for as**?
|
**For** and **as** in this sentence are two separate components.
**For** can be used as a conjunction meaning "because." So you could rewrite this as follows:
> This connection served him well, **because** as the father noticed his son's proclivity for the subject, he arranged...
"as" here describes a process - the father noticed more and more his son's proclivity, which led him to arrange for him to study with the mathematician.
|
stackexchange-ell
|
{
"answer_score": 3,
"question_score": 3,
"tags": "prepositions, conjunctions, as, literature"
}
|
Reconnect USB Modem every 12 hours
I'm planning on having a 4G LTE USB Modem plugged into a server computer at home. I will then go somewhere else. I'm afraid it will disconnect, and if it does not work I would have to go home to fix it.
Is there a possibility to automatically remount / reconnect USB 4G Modem with a command every 12 hours?
It's a ZTE MF821D Modem, which means, it will connect to internet just by plug out and in.
|
You can do that very easily , while you are creating the connection for Mobile broadband ,look at the 1st TAB[ General ] there you can have the option as Automatically connect to this network when it is available .
so you even because of network problem you got disconnected your connection , it will reconnect again after sometime when network is available. so you can automate it very easily.!enter image description here
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 2,
"tags": "command line, modem, 4g"
}
|
Ocultar senha no terminal
Estou desenvolvendo uma aplicação em python que vai funcionar pelo terminal
Em certo momento, preciso realizar um login:
print('É necessário informar suas credenciais para se comunicar com a API')
email = input('Email: ')
password = input('Senha: ')
O problema é que a saída no console, fica dessa forma:
É necessário informar suas credenciais para se comunicar com a API:
Email: [email protected]
Senha: senhaTeste
Eu preciso que o campo senha não mostre os caracteres, que substitua por "*" ou algo do tipo:
A saída que eu procuro no terminal é algo assim:
É necessário informar suas credenciais para se comunicar com a API:
Email: [email protected]
Senha: **********
|
Você pode usar o `getpass.getpass`
import getpass
print('É necessário informar suas credenciais para se comunicar com a API')
email = input('Email: ')
password = getpass.getpass('Senha: ')
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "python"
}
|
SQL: Simple if-then-else-statement without any select
I would like to use an if-then-else structure to decide which of two different commands to run. However, I always get a syntax error when trying to use an if-statement.
The query should run both in MySQL and in postgresql.
IF EXISTS (SELECT * FROM Table WHERE col1 = val1 AND col2 = val2)
UPDATE Table SET col3 = val3 WHERE col1 = val1 AND col2 = val2
ELSE
INSERT INTO Table VALUES (val1, val2, val3) END IF;
What I get is `ERROR: syntax error at or near "IF"`.
I have tried various versions of this, including a 'then' after the if, with or without 'end if', with 'begin' and 'end', but nothing seems to work, so I think I must be getting something very wrong. Other questions on here that I have found always included a SELECT statement in which the if-statements were embedded, which I don't seem to need.
|
OK, with little bit of searching I found the answer.
On mysql use insert ... on duplicate key update ... command. All you need to do is create a pk or unique index on col1 and col2.
In postgresql you can use upsert (insert ... on conflict update ...) to achieve the same result.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql, postgresql"
}
|
c# extract value from nextnode
I have the following xml part and am trying to extract the value where key is known. The example below is a snippet, from a larger xml that contains 1000's of nodes.
<?xml version="1.0" encoding="utf-8"?>
<DictionarySerializer>
<item>
<key>key1</key>
<value>CONTENT1</value>
</item>
<item>
<key>key2</key>
<value>CONTENT2</value>
</item>
</DictionarySerializer>
i assume the above is a string called xml, then with
XDocument.Parse(xml)
.Descendants("key")
.Where(x => (string)x.Value == "key1")
.FirstOrDefault().NextNode.ToString()
I can get the string `<value>CONTENT1</value>` But i simply cannot get my head around how to get the value of the value node to to say. I am afrad it is super simple, and i just are stuck in a coffein loop :-)
|
If you want to get all keys and values from the XML from all 1000 elemnts. You can use:
Dictionary<string, string> elements = new Dictionary<string, string>();
xml.Root.Elements().ToList().ForEach(xmlElement =>
{
elements.Add(xmlElement.Descendants("key").First().Value,
xmlElement.Descendants("value").First().Value);
});
So, the elements dictionary will contain all of your 1000 nodes.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, xml"
}
|
Raspberry Pi GPIO input voltage Limit
I am doing a project in which I have a component that outputs a 5 Volt signal. Since the Pi is only able to handle 3.3 V I connected the signal to a voltage divider. I used a 4.7 kiloOhm and a 2.2 kiloOhm resistor.
5V * 4700Ω/(4700Ω+2200Ω)= 3.4 V
Can the Pi handle that current or do I have to reduce it even further?
|
You will still be **exceeding** the maximum voltage of the GPIO (admittedly not by much).
There is no allowance for tolerances; ±5% for resistors, ±2.5% for external power. Good design always makes allowance for worst case values.
There is also **NO NEED** ; GPIO will be low if <0.8V; high if >2.2V so I suggest you design for 2.3V
The ACTUAL threshold for GPIO is not specified; my tests indicate 1.25V, although there is some variation between individual Pi; 1.3V is probably the threshold, but a higher voltage gives a greater noise margin.
See Electrical Specifications of GPIO
|
stackexchange-raspberrypi
|
{
"answer_score": 2,
"question_score": 4,
"tags": "gpio, voltage"
}
|
How to place a JavaScript variable value in HTML input tag's value?
$( window ).on( "load", function(){
var token_val= document.getElementsByName("token")[0].value;
var real_data = "<input type='hidden' name='token' value='NEED VLAUE OF token_val HERE'>";
$('form').append(real_data);
});
This my code. I need to set value on input tag as variable token_val 's value.
|
$( window ).on( "load", function(){
var token_val= document.getElementsByName("token")[0].value;
var real_data = "<input type='hidden' name='token' value='" + token_val + "'>";
$('form').append(real_data);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, simple html dom"
}
|
Local ffmpeg output to S3 Bucket
Heres my setup; \- I have a local PC running ffmpeg with output configured to h.264 and aac \- and S3 bucket created at AWS
what i need to do is, use ffmpeg [local] output to upload files directly to s3 bucket. PS: Planing to use that s3 bucket with cloudfront to allow 1 [one] user to stream a live event with about setup.
i could not find a way to specify output location as s3 bucket [with key]. any ideas as to how to do it? Thanks
|
You can:
1. Mount the S3 bucket using S3FS FUSE and then you output directly to it.
How to Mount S3 Bucket on CentOS/RHEL and Ubuntu using S3FS
2. Segment the media for HTTP streaming and upload each segment and playlists using the S3 API and a script of your choice.
I'd go with 1 for a live stream.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 7,
"tags": "amazon web services, amazon s3, ffmpeg, video streaming, live streaming"
}
|
How do you execute directive code after rendering?
I'm trying to build a directive that runs after a nested `ng-repeat` has completed rendering. Here's what I've tried (fiddle):
The HTML:
<div ng-app="MyApp" ng-controller="MyCtrl">
<ul my-directive>
<li ng-repeat="animal in animals">{{animal}}</li>
</ul>
</div>
And the JavaScript:
angular.module("MyApp", [])
.directive("myDirective", function () {
return function(scope, element, attrs) {
alert(element.find("li").length); // 0
};
});
function MyCtrl($scope) {
$scope.animals = ["Dog", "Cat", "Elephant"];
}
The linking function in my custom directive runs before all of the `<li>` elements have been rendered (and `0` is alerted). How do I run code after the `ng-repeat` has completed rendering?
|
You could move the directive inside ng-repeat, <
<div ng-app="MyApp" ng-controller="MyCtrl">
<ul>
<li ng-repeat="animal in animals" my-directive>{{animal}}</li>
</ul>
</div>
Or have a look at < which is related to your question.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "javascript, angularjs, angularjs ng repeat"
}
|
How to close gdb (or other frames) on emacs?
I'm learning about emacs (using version 2.3 on Ubuntu 10.10), and I'm having some trouble with the frames. When I run gdb, for example, I have to get my mouse and click "File->Close" to close the gdb frame. What's the easiest way to close a frame from keyboard? By the way, is there a summary for this keyboard shortcuts?
|
I think you refer to killing the gdb buffer rather than closing a frame (which in Emacs refers to a window). To kill the buffer you are in type `C-x k`.
To get a descriptions of a certain command you can use `C-h k`. So for File - Close you can type `C-h k` and click File - Close. Emacs will then show a description about that function. You can use the same approach to show a description for `C-x k` by typing `C-h k C-x k`.
You can also go the other way (from a function to a command). Say that you find out that some key has to do with killing buffers and you want to know what other things you can kill and the commands this. Then you could type `C-h f` to get descriptions of functions. So, for instance, type `C-h f` and write 'kill' then press `Tab` to show the functions starting with 'kill'. Choose any function, such as `kill-sentence` and Emacs will show a description of it and what key it is bound to.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 2,
"tags": "emacs"
}
|
Is value of NSString a NSInteger value in iOS
I am interesting of determine if text in NSString is int value or not.
For example :
NSString value = @"something";
int i = value.intValue;
// i -> 0
So i is 0 and it don't give me information if text is real int value.
Second problem is if string is int alike :
NSString vaue = @"10.10.21.32"
int i = value.intValue;
// i -> 10
How to determinate if text is real int value ?
Marko
|
Use `NSNumberFormatter`, with `lenient` set to false and `allowsFloats` set to false.
NSNumberFormatter *intFormat = [NSNumberFormatter alloc] init];
intFormat.lenient = false;
intFormat.allowsFloats = false;
NSNumber *myNumber = [intFormat numberFromString:value];
int finalValue;
if (myNumber) { // was able to parse OK
finalValue = [myNumber intValue];
} else {
// handle invalid strings here
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, xcode, nsstring, int, type conversion"
}
|
I am trying to find derivative $f$
> I want to find the derivative of $f: [1, \infty] \to \mathbb{R}$ defined by formula $$f(x) = \int_0^{x^4} e^{t^2} dt$$
* * *
Here is what I have done:
* * *
$F(b) = \int_0^b e^{t^2} dt$ and knowing that $f(x) = F(x^4)$
So I take
We want $\frac d{dx} f(x) = \frac d{dx}F(x^4) * \frac d{dx} x^4 = 4x^3 * e^{{(x^4)}^2} = 4x^3 e{^x}^8$
Where $F'(x^4) = e^{{x^4}^2}$ since $F'(x^4) = f'(x^4)$
> Is since $F'(x^4) = f'(x^4)$ correct logic for that step?
|
Put $F(z)=\int_0^z e^{t^2}\, dt$ and remark that $f(x)=F(x^4)$. Hence $$ Df(x) = DF(x^4) Dx^4 = 4x^3 e^{(x^4)^2} = 4x^3 e^{x^8}. $$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": -2,
"tags": "calculus, integration, derivatives"
}
|
CSS - overflow hidden for an entire <li>
I'm outputting a list of `<li>` elements and I want to apply `overflow:hidden` on my `<ul>` so if any `<li>` doesn't fit it will be hidden **completely** , not only part of it.
Here is my list:
<ul style="height: 500px; overflow:hidden;">
<li>Some big text goes here</li>
<li>Some big text goes here</li>
<li>Some big text goes here</li>
<li>Some big text goes here</li>
</ul>
is it possible to do it with pure CSS+HTML?
|
It would only work with two requirements ( _in pure CSS_ )..
1. The `li` elements do not wrap their contents ( _use`white-space:nowrap;`_)
2. The `height` of the `ul` is a multiple of the `line-height` of the `li`
**demo** <
* * *
Alternatively you could write some javascript to detect the overflow and hide the elements that need to..
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "html, css, html lists, overflow"
}
|
Static array in struct on heap or stack?
Let's say you have a static array as an attribute of a `struct`
struct example {
char array [5];
};
struct example* exp = (struct example*)malloc(sizeof(struct example));
...initialize and so on...
Now is the static array in the struct considered to be on the heap or stack? In addition is it any more efficient to have an array with specified size in the struct vs a dynamically allocated array, i.e. a pointer that will point to the dynamic memory once you allocate it, attribute in terms of time to allocate? Lastily if it is on the stack does the stack eliminate the variable right when the struct is freed?
|
You are using the malloc function to allocate a memory.
So, using malloc function to allocate a memory for any variable, or a structure, it will allocate a memory in heap only. You declaring a variable "a", this is the member of structure. So, in here you are not allocating a memory. You just declare a structure. After that you allocating a memory using malloc, in here only the memory will be allocated in the heap.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "c, struct, dynamic arrays"
}
|
Javascript related input-button text change
I have product name(in paragraph), text form and button. The products have id's as follows p1,p2... The input types have id's as follows i1,i2...After typing something in the form and clicking submit I want this to change the default product text. I have the following function which works only for one set(paragraph,form and button). The problem is that this product function works only for p1,i1 I want it to fork for p1,i1,p2,i2 and etc.
function product(id){
var userInput = document.getElementById("i1").value;
document.getElementById("p1").innerHTML = userInput;
}
The function call is as follows:
<button type='button' onclick='product()'>Name product</button>
|
what you need is to pass the index to the function:
function product(id) {
var userInput = document.getElementById("i"+id).value;
document.getElementById("p"+id).innerHTML = userInput;
}
your html would look like:
<button type='button' onclick='product(1)'>Name product</button>
hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, html, events, onclick, buttonclick"
}
|
MySql takes a long time optimizing a join-less query
We have a simple query that looks like:
SELECT a,b,c,d FROM table WHERE a=1 and b IN ('aaa', 'bbb', 'ccc', ...)
No joins at all, 5000 contsant values in the IN clause.
Now, this query takes 1-20 seconds to run on a very strong (16 core) server. The table has an index on (a,b), and we also tried reversing the index to (b,a). The server has tons of memory, and nobody is writing to this table - just 5 processes running selects like I described above.
We did some profiling and saw that some queries spend 3.5 seconds in "JOIN::optimize" (.\sql_select.cc 977). I remind you, the queries do not use joins at all.
What could be the cause for this large time spent optimizing joins on a join-less table?
Here is the result of EXPLAIN SELECT:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table range IX_A_B IX_A_B 65 \N 5000 Using where
|
Our DBA found this as a reported bug.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 2,
"tags": "sql, mysql, optimization, join, query optimization"
}
|
How to determine if two vectors form a basis?
> Let $T:\Bbb R^2\to \Bbb R^2$ be a linear transformation such that $T (1,1)=(9,2)$ and $T(2,-3)=(4,-1)$.
>
> A) Determine if the vectors $(1,1)$ and $(2,-3)$ form a basis.
> B) Calculate $T(x,y)$.
I need help with these, please I'm stuck, don't even know how to start them...
|
**Hint**
$\\{(1,1),(2,-3)\\}$ is a basis if and only if the vectors are linearly independent (note that the vector space is two-dimensional). Are they linearly independent?
To compute $T(x,y)$ use that $$(1,0)=\frac 35(1,1)+\frac 15(2,-3),$$ $$(0,1)=\frac 25(1,1)-\frac 15(2,-3)$$ and $$(x,y)=x(1,0)+y(0,1).$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, linear transformations"
}
|
Seeking explanation to Java built in Object class
Object a[] = new Object[2];
a[0] = "asd";
a[1] = 1;
I am seeking an explanation to how this is possible in Java. I did look at the implementation of Object and I must ask for some help to understand it.
Creating a variable that can hold any type in e.g. Python is built-in but in Java we need the Object class.
What is it in the implementation of Object that allows it to have any type, and please whats the explanation?
|
Let's go step by step:
* `Object` is the root of all **reference types** in Java. Anything that is a _reference_ , is also `instanceof Object`!
* "Obviously", `a[0] = "asd";` assigns a **String**. Strings are Objects by default.
* and finally, `a[1] = 1;` leads to **auto-boxing**. You are assigning an **Integer** object to that array slot, not a **primitive** int value of 1.
And of course, covariance is also worth mentioning here.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "java"
}
|
How to resume file download in Python?
I am using python 2.7 requests module to download a binary file using the following code, how to make this code "auto-resume" the download from partially downloaded file.
r = requests.get(self.fileurl, stream=True, verify=False, allow_redirects=True)
if r.status_code == 200:
CHUNK_SIZE = 8192
bytes_read = 0
with open(FileSave, 'wb') as f:
itrcount=1
for chunk in r.iter_content(CHUNK_SIZE):
itrcount=itrcount+1
f.write(chunk)
bytes_read += len(chunk)
total_per = 100 * float(bytes_read)/float(long(audioSize)+long(videoSize))
self.progress_updates.emit('%d\n%s' % (total_per, 'Download Progress : ' + self.size_human(itrcount*CHUNK_SIZE) + '/' + Total_Size))
r.close()
I would prefer to use only `requests` module to achieve this if possible.
|
If the web server supports the range request then you can add the Range header to your request:
Range: bytes=StartPos-StopPos
You will receive the part between StartPos and StopPos. If dont know the StopPos just use:
Range: bytes=StartPos-
So your code would be:
def resume_download(fileurl, resume_byte_pos):
resume_header = {'Range': 'bytes=%d-' % resume_byte_pos}
return requests.get(fileurl, headers=resume_header, stream=True, verify=False, allow_redirects=True)
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 27,
"tags": "python, python 2.7, python requests"
}
|
How do I find the volume cut off of the unit ball by the plane ax+by+cz = d?
How do I find the volume cut off of the unit ball by the plane ax+by+cz = d?
I know that there's a double integral somewhere here, but I just don't understand how to attack this problem. Any guidance would be appreciated!
|
By symmetry of the unit ball (centered at $(0,0,0)$ I suppose), you may as well rotated the plane until it is parallel to the $xy$-plane. This can be done by first computing the distance $\lambda$ from $(0,0,0)$ to the plane and then we have the point set $$ CAP=\\{(x,y,z)\mid z\geq \lambda,\ y^2\leq 1-z^2,x^2\leq 1-y^2-z^2\\} $$ One fourth of this _spherical cap_ has $x,y\geq 0$ and its volume can be calculated as $$ \frac14 CAP=\int_\lambda^1 \int_0^{\sqrt{1-z^2}}\int_{0}^{\sqrt{1-y^2-z^2}}1\ dx\ dy\ dz $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "integration, general topology, multivariable calculus"
}
|
Codeblocks automatically closes on Ubuntu 15.10 x64
I have codeblocks installed it is now randomly closing while im coding. It closes automatically. How to fix it?
|
I did have same problem few weeks ago, and solution was reinstalling codeblocks.
sudo apt-get autoremove --purge codeblocks
sudo apt-get install codeblocks
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ubuntu gnome, code blocks"
}
|
Cannot run block in pl/sql getting ora-06550 and pls-00103
I am trying to make anonymous blocks to update esri's oracle versioned views. The code runs fine when I execute it from pl/sql developer without the begin/end. But as soon as I add the begin/end I get errors.
begin
call sde.version_util.set_current_version ('ARCFM8.vtemp');
call sde.version_user_ddl.edit_version ('ARCFM8.vtemp', 1);
update arcfm8.t_conductormarker_vw set CEAREFERENCEDRAWING = 'my fisrt multiversion view update'
where OBJECTID = 3;
call sde.version_user_ddl.edit_version ('ARCFM8.vtemp', 2);
end;
;
sde.version_user_ddl.edit_version ('ARCFM8.vtemp', 1);
update arcfm8.t_conductormarker_vw set CEAREFERENCEDRAWING = 'my fisrt multiversion view update' where OBJECTID = 3;
sde.version_user_ddl.edit_version ('ARCFM8.vtemp', 2);
end;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sql, oracle, plsql, plsqldeveloper"
}
|
How to send the content of v-file-input?
My component is something like this:
<template>
<div>
<v-file-input accept="image/*" v-model="image"></v-file-input>
<button @click="uploadImage">Upload</button>
</div>
</template>
<script>
export default {
data(){
return {
image: null
}
},
methods: {
async uploadImage(){
await this.$axios.put('url', {image: this.image})
}
}
}
</script>
If I click the button and send the request, the request payload is `{image: {}}`. Why? How to send the content of `this.image`?
|
You should probably use a `POST` rather than a `PUT`. But your code is working: if you `console.log(this.image)`, you'll see the file, same goes for your Vue devtools in your browser.
I'm not sure how to see it in the network tab but this is properly sent to the given backend. I guess you just need a proper backend here.
This question may be useful here: How to see form data with enctype = "multipart/form-data" in Chrome debugger
Here is an MDN page talking about `multipart/form-data` objects even if there is no solution on how to see the actual payload neither: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "vue.js, nuxt.js, vuetify.js"
}
|
Is it possible to remove spaces from existing images?
I have changed my WordPress blog theme but now in older posts images are not working. I have used images names with space `:/` and it is not working now in this theme. I can see the name like `something%20icon.png`. Can I fix it somehow? Not manually all image.
Update: I have find out that problem is that old images that are not working are in root/images (new one are in wp-content\upload...). If I tried url of some image, website.com/images/image.jpg it will open main website not an image. There are images in directory.
|
You can test flowing code
$img_space = 'something icon.png';
$img_without_space = preg_replace('/\s+/', '', $im);
echo $image;
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "images"
}
|
Is Affected Rows of Insert statement always 1?
By affected rows, I mean the statement runs successfully, ie. no syntax error or duplicate primary key, etc.
Is it meaningless to check the return value of ExecuteNonQuery()?
SqlCommand cmd= new SqlCommand("INSERT INTO.. ", connection);
if(cmd.ExecuteNonQuery()!=1)
throw new Exception();
|
From MSDN.aspx):
> For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
So no, the number can be different than 1, especially if multiple rows are being inserted with the statement.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql server, database"
}
|
Converting a Mixed SUBSET-SUM Problem To All-Positive Case
Let's say we have a SUBSET-SUM problem with list {$x_1,x_2,x_3,...x_N$} and weight $W$, with some of $x_i<0$. Is there a known way, in polynomial time, to convert this problem into an equivalent problem, but with all $x_i \geq 0$? And if there aren't any, is it possible for there to be such an algorithm?
|
Both variants are NP-complete, so such a reduction surely exists: the definition of NP-completeness guarantees it.
If you want an explicit reduction, you can reduce one to the other (reduce to 3SAT using Cook's theorem, then reduce 3SAT to the other using its NP-completeness). The resulting reduction will be ugly, though, so I suspect this might not be what you're looking for.
If you want a simple and natural reduction, I'm not sure how to achieve it.
|
stackexchange-cs
|
{
"answer_score": 2,
"question_score": 1,
"tags": "subset sum, polynomial time reductions"
}
|
Maximization with constraints
How can I find $\lambda_H$ and $\lambda_T$ such that $$\max_{0 \leq \lambda_H , \ \lambda_T \ \leq 1 }\left\\{\frac{4.6575342 \times 10^{-4}}{2.1722965 \times 10^{-4} + \lambda_H},\frac{1.0958904 \times 10^{-2}}{3.4311896 \times 10^{-4}+\lambda_T}\right\\}<1?$$
Is this problem equivalent to finding $x$ and $y$ such that $$\min_{0 \ \leq \ x , \ y \ \ \leq \ 1}\\{.4664048+(2147.0588450)x,0.0313096+(91.2500009)y\\} \geq 1?$$
|
Each of the functions is convex, their max is then convex, so the solution of the maximization lies at one the corners: (0,0), (0,1), (1,0) and (1,1). It should be (0,0).
What is not clear is the $<1$. Is it a constraint? If so it should be written as a constraint.
If you want to impose the value is $<1$ then it is just a matter of increasing the variables from zero until the point you reach 1 or one of them hits one.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "calculus, optimization, research"
}
|
Why a vector of column names can't be used to filter rows in data.table?
Suppose I have the following data `dt` and a vector of column names `cols`
dt <- data.table(id = letters[1:10], amount = 1:10, id2 = c(rep('a',5),rep('b',5)))
cols <- 'id'
Can someone help me to understand why this approach not works
dt[cols=='a']
but this one works?
dt[get(cols)=='a']
Both approachs shouldn't return the same thing in `vec`?
|
We could `eval`uate on a `sym`bol
dt[eval(as.name(cols)) == 'a']
id amount id2
1: a 1 a
Or specify the `.SDcols`
dt[dt[, .SD[[1]] == 'a', .SDcols = cols]]
id amount id2
1: a 1 a
Or directly subset `.SD` if there is a single column
dt[dt[, .SD[[cols]] == 'a']]
id amount id2
1: a 1 a
* * *
The preferred method would be through `.SDcols` as `get` can sometimes have env issues, while `eval` (not so recommended by the community)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "r, data.table"
}
|
What are the major differences between solr modules
I am looking into Solr search for my site and am seeing two equally well-used modules.
* Apache Solr Search (lots of contrib around this)
* Search API Solr Search, built on Search API
Why would I pick one over the other?
|
I would recommend using Search Api Solr. Search Api Solr is a little bit more complex; however, it is more powerful. In addition there are many sub-modules that allow you to extended the search funcionality.
You should consider reading the article Battleplan for Search & Solr in Drupal 8.
According to this post.
> The two maintainers of Search API and Apache Solr have meet in person and have determined a way forward for advanced searches with Drupal and they both have agreed that Search API is it.
|
stackexchange-drupal
|
{
"answer_score": 2,
"question_score": 4,
"tags": "7, search"
}
|
android how to know if i have location available
i've made a listener that checks is the GPS status is changed.. i want the listener to check if the phone is able get location at all, if now throw gps, then throw cellolar cell.. how can i add it to my listener ?
my listener:
locMgr.addGpsStatusListener(new GpsStatus.Listener()
{
public void onGpsStatusChanged(int event)
{
switch(event)
{
case GpsStatus.GPS_EVENT_STARTED:
locationStatus.setText("Location is On");
break ;
case GpsStatus.GPS_EVENT_STOPPED:
locationStatus.setText("Location is Off");
break ;
}
}
}) ;
|
Write a class
public class MyLocationListener implements LocationListener {
/**
* This function handles location change event if location is found
*/
public void onLocationChanged(Location loc) {...
Now, whenever you'll get some GPS location, it'll come inside `onLocationChanged()` method.
Do not forget to add the following permissions in your manifest-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Also make sure you are adding both the location listeners GPS as well as Network like-
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, gps, location"
}
|
Radgrid add new record data checking
In a Radgrid, how do I keep the add new record open when someone clicks the save button and I check to make sure the data is all in the correct format or valid? I want the add new record to stay open after I tell them the data is not valid and also keep the values they have already entered.
|
in the edit template of the Grid, you can always use the Validators. The edit form will not post if the validators don't pass.
You can take a look at the following demo:
<
When you add a new record - notice that UnitPrice is a required field. if you don't enter that the update button wont fire the postback.
Hope this is useful.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "telerik, radgrid"
}
|
Can I use with statement with MySQLdb.Connection object?
I wonder if I can use the context manager `with` with the `Connection` object, and write code like this:
with MySQLdb.connect(...) as conn:
do_something()
Will the `conn` object be closed automatically after the block like with a `file` object ?
Thanks.
|
MySQLdb does not support the context manager protocol. Roll your own, or use oursql instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 9,
"tags": "python, mysql python"
}
|
Couple of slangs I've heard when watching anime
In one of the animes I've watched recently (can't recall the title), I heard words like "" (not sure if this is how it's spelt in katakana since I only heard the word, but as for how it's pronounced in English, it would most probably sound like cheeeeesee) and "" (English pronunciation : wotto).
Judging from context, the former means "hello" and the latter, "whoops". And there is also "" (uwaa) which probably means "yikes" (I'm guessing, in a bad way, something like "") in English.
So the questions that arises are, since I am only translating based on context, I am not sure if they mean what I think they meant. Can anyone correct/ advice on this?
Secondly, are these words even used in real life (I have only heard them on anime) ?
|
>
If it sounded like and it was said in a scene where one would say "Hello!", it would almost have to be:
**** **** , etc.
It is an informal and slangy "Hi!" that comes from **** **** **** **** , etc.
Naturally, this has nothing to do with cheese.
>
If this was uttered where you would expect to hear "Whoops!", then it would be:
(emphatic version of above)
It is an interjection uttered when you are surprised by something happening all of a sudden or when something catches your attention.
Finally,
>
You heard this one right. It is an exclamation used in all kinds of situations.
You mentioned "Yikes!" and that would be one meaning of it. We use it upon seeing/hearing something we like as well. It is an all-purpose exclamation.
> are these words even used in real life?
Yes, of course. All three are actively used among us native speakers in real life. You would, however, need to understand that is only used by certain (young) speakers in casual situations.
|
stackexchange-japanese
|
{
"answer_score": 12,
"question_score": 3,
"tags": "slang, casual"
}
|
I'm trying to effectively "Index if" - copy a list over with certain criteria
I have a column of data, and a marker next to it. Think:
ID#1 -- A
ID#2 -- B
ID#3 -- A
I'm trying to move over only the ID numbers with the marker A - so my final result is
ID#1
ID#3
This is very easy to do with VBA - Filter the range, copy, paste. I'm trying to find a non-VBA solution to this problem. I've been trying various array formulas - Index(range,sumproduct(row*criteria)), but I can't quite get it working. How would I get this to work?
Computational elegancy is a significant factor - the sheet I'm dealing with should be a database due to it's size, but the powers that be have nixed that idea.
|
Use:
=IFERROR(INDEX($A$1:$A$8,SMALL(IF($B$1:$B$8="A",ROW($B$1:$B$8),999999),ROW(A1))),"")
Small will return the IDs with "A" for each row (smallest to largest)
A1:A8 change it to correspond your ID column
B1:B8 change it to correspond your A column
Keep $ for fixed references
press `Ctrl`+`Shift`+`Enter` instead of `Enter` it is an array formula
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 4,
"tags": "microsoft excel"
}
|
Calculate a certain determinant as a limit – is this valid in an arbitrary field?
Let $\mathbb{K}$ be a field, and $a,b,x_1,...,x_n\in \mathbb{K}$, we pose :
$$\Delta_n=\text{det} \left(\,\begin{bmatrix}x_1&a&\dots &a\\\ b&x_2& \ddots & \vdots\\\ \vdots&\ddots&\ddots& a\\\b&\dots&b& x_n\end{bmatrix}\,\right)$$
if $a\neq b$: $\Delta_n=\frac{b P(a)-a P(b)}{b-a}$, with $P(x)=\prod_i(x_i-x)$.
My problem is to calculate $\Delta_n$ in the case where $a=b$:
If $\mathbb{K}=\mathbb{R}$: the function $x\to\frac{x P(a)-a P(x)}{x-a}$, is continuous in $\mathbb{R}$, then : $$ \Delta_n=\lim_{x\to a}\frac{x P(a)-a P(x)}{x-a}=\lim_{x\to a}\frac{Q(x)-Q(a)}{x-a}=Q'(a) $$ with $Q(x)=x P(a)-a P(x)$ and $Q'(x)=P(a)-a P'(x)=\prod_i(x_i-a)+a\sum_i\prod_{j\neq i}(x_i-a)$.
_**Question:**_
Can we say that this method is true for any field $\mathbb{K}$?
|
Let $\Bbb K$ be a (commutative) field and fix $x_1, \ldots, x_n \in \Bbb K$. Denote the determinant with $$ \Delta(a, b)= \begin{vmatrix}x_1&a&\dots &a\\\ b&x_2& \ddots & \vdots\\\ \vdots&\ddots&\ddots& a\\\b&\dots&b& x_n\end{vmatrix} $$ for $a, b \in \Bbb K$, and let $P \in \Bbb K[x]$ be the polynomial $P(x) = (x_1-x) \ldots (x_n-x)$.
Then $$ (b-a)\Delta(a, b) = bP(a)-aP(b) = (b-a)P(a) - a (P(b)-P(a)) \\\ = (b-a) (P(a) - a Q(a, b)) $$ with $Q(a, b) = \frac{P(b)-P(a)}{b-a}$ in $\Bbb K[a, b]$. It follows that $$ \Delta(a, b) = P(a) - a Q(a, b) $$ in $\Bbb K[a, b]$, and therefore $$ \Delta(a, a) = P(a) - a Q(a, a) = P(a) - a P'(a) $$ where $P'$ is the formal derivative of $P$, see in particular Correspondence to analytic derivative.
This confirms your result $$ \Delta(a, a) = P(a) - a P'(a) = \prod_i(x_i-a)+a\sum_i\prod_{j\neq i}(x_i-a) $$ since the formal derivative in $\Bbb K[x]$ satisfies the usual sum and product rules for derivatives.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, field theory, determinant"
}
|
Find the scalar value and calculate perpendicular vector
Stuck on this problem for my class for a bit, I'm not sure exactly how to solve it. If someone could point me in the right direction I would really appreciate it.
What I have so far
> Given the points: A = ( 3, -4, 2) B = (-1, -3, 5)
and the vector:
> n = 2i + 5j - k
>
> Find the displacement vector of AB = (-4, 1, 3)
>
> Calculate the dot product (scalar product) OA . n = -16
>
> Let THETA be the angle between the vectors OA and n. THETA is greater than 90 degrees.
Now here is where I'm stuck.
> The vector OA is to be expressed as a sum OA = kn + b, where k is a scalar and b is a vector perpendicular to n. Determine the value of k in this expression.
>
> Using your answer from the last question, calculate the vector b.
I know the answer is staring me in the face but I'm feeling very math-illiterate.
|
Consider the plane with normal $\mathbf n$ and containing the point $A$. The equation of this plane, as you have worked out earlier, is $$\mathbf r\cdot\mathbf n=-16$$ The asked-for decomposition requires the perpendicular component to reach from the origin to a point on this plane - in other words, $k\mathbf n\cdot\mathbf n=-16$. Solving, we get $30k=-16$ and hence $k=-\frac8{15}$. Then $$\mathbf b=\vec{OA}-k\mathbf n=(3,-4,2)+\tfrac8{15}(2,5,-1)=(\tfrac{61}{15},-\tfrac43,\tfrac{22}{15})$$ and we can verify that $\mathbf b\cdot\mathbf n=0$, i.e. they are perpendicular as stipulated in the question.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 2,
"tags": "vectors"
}
|
Make overflow automatically go down every few seconds
I want that scroll would automatically go down a little bit every few seconds and that would expose more text. Is it possible to do that? By overflow I mean this: <
|
You can use a timer that relaunches itself it there is anything left to do:
function scroll() {
$('#x').animate({ scrollTop: '+=5px' }, 100, function() {
if($('#x table').height() - this.scrollTop - $('#x').height() > 0)
setTimeout(scroll, 500);
});
}
scroll();
And an updated example: <
Note that I added `id="x"` to your HTML to make it easier to reference the `<div>`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, html, css"
}
|
editor component like RichEdit that supports embedding photos?
can anyone suggest an editor component like RichEdit that supports embedding photos in a delphi app? RichEdit doesn't seem to support this.
am not considering embedding MS Word since not everyone would have that.
than you for your help!
|
I recomend TRichView <
I did work with WPTools for long time, but recently I found TRichView a lot more simple to use.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -1,
"tags": "delphi, richedit"
}
|
R: tm package reading in Newsgroups data
The lines of code below return the following error:
">"object 'readNewsgroup' not found
library(tm)
setwd("C:/Users/DanRoDuq/Downloads/20news-bydate-train")
sci.electr.train=Corpus(DirSource("sci.electronics")
,readerControl=list(reader=readNewsgroup,language="en_US"))
I got the data from: < and downloaded the file called 20news-bydate.tar.gz
When I replace readNewsgroup by readPlain, the code runs, but the instructions I'm following tell me to use the readNewsGroup setting. Should I maybe be loading another library?
|
There is no longer a reader called `readNewsgroup` in the current `tm`-Version (0.6). With `getReaders()` you get all available readers for your Version.
Download the same Version as the instructions you are following and there should be a `readNewsgroup` reader.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "r, tm, newsgroup"
}
|
Why and when do we need to normalize weights in Reinforcement Learning?
I recently came across this SO question, wherein the poster was asked to normalize their weights while using a function approximator with SARSA. I don't remember having to normalize any weights while using a DQN and so therefore would like to when and why is this method needed.
|
The kind of divergence that the other question experienced is a common problem with deep RL and temporal difference methods (Q-learning, SARSA, or any Actor Critic).
The weight normalisation would not be needed if the asker of the question you linked had used some kind of protection against divergence, such as using a separate target network. The normalisation may have worked for them as an alternative.
DQN already has experience replay and separate target network to help with this. If you do get runaway feedback causing diverging values, you already have some hyperparameters you can change to try and fix it - size of minibatch, size of replay table, number of updates between copying to target network.
So, in short, you don't really need weight normalisation in Deep RL. You might want to use it for regularisation though.
|
stackexchange-ai
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reinforcement learning, weights, weight normalization"
}
|
translate Ruby regex to php/perl regex
I have made this regex, which works fine in Ruby:
/(1?[[\(\s\.-]]\d{3}\)?[\s\.-]\d{3}[\s\.-]\d{4}(\z[^\d])?)/
It's for extracting phone numbers from text document but now I'm using the same expression in PHP, using `preg_match_all`. Now the same expression gives me an empty array.
I don't understand why this is happening
What do I need to change about this expression to make it work in PHP?
|
You have a strange error in your Regexp. I think it's partially luck it's working on Rubular:
(1?[[\(\s\.-]]\d{3}\)?[\s\.-]\d{3}[\s\.-]\d{4}(\z[^\d])?)
^ ^
Why are those brackets there two times?
See here for a working version where I just removed those. Works fine with PHP now:
<
(1?[\(\s\.-]\d{3}\)?[\s\.-]\d{3}[\s\.-]\d{4}(\z[^\d])?)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, ruby, regex, preg match all"
}
|
The type of array in the line
I am new to programming, and the following line confused me:
> switch_block_conn[from_side][to_side][from_track].nelem = 0
Is this line actually describing an array? What is it doing?
|
From the syntax in the given code sample, assuming it is valid code, it is implied that:
* `switch_block_conn` is a 3-d array. You can infer this from the 3 array index operations.
* The individual elements in `switch_block_conn` are structs. You can infer this from the `.` operator used.
* Those structs have (among potentially other members), an `nelem` member. You can infer this from the name given after the `.`.
* The `nelem` member is a numeric or pointer type (specific size and type unknown from this sample). You can infer this from the assignment of 0 to that member.
Note that most of these conclusions can be drawn only in C and not C++ due to operator overloading in C++.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c"
}
|
Friend Referal Script
I want to know how to write a script that connect to different mail servers and load the list of friends, something like that is found on facebook and other sites.
Mainly, I want to connect to hotmail, gmail and yahoo.
|
What you are looking for is contact API's.
<
<
<
You can find more, you just have to search the terms `something contact api` and you should get a whole slue of information. If you want to find a script for PHP add php to those terms.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, api, contacts, friend"
}
|
C# WPF. Как открыть нужное окно приложения в зависимости от размера рабочего стола
Здравствуйте. Есть приложение на WPF. Хочу добавить два главных окна с различными XAML разметками. Теперь мне нужно запускать приложение в зависимости от размера рабочего стола компьютера/ноутбука.
Как определить ширину и высоту рабочего стола я знаю, делается примерно так:
int Width = SystemInformation.PrimaryMonitorSize.Width;
int Height = SystemInformation.PrimaryMonitorSize.Height;
А вот как реализовать запуск нужного главного окна приложения я не знаю. Возможно ли такое вообще сделать или нет?
|
Да, можно.
Откройте `App.xaml` и уберите установку свойства `StartupUri`.
Затем откройте `App.xaml.cs` и добавьте в него метод:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
...
}
Вместо многоточия просто проверьте свои условия, создайте экземпляр нужного окна и покажите его:
Window window = (условие) ? new Window1() : new Window2();
window.Show();
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "c#, wpf"
}
|
Divide verb in Cobol
I have this odd output in the remainder part of the DIVIDE verb in COBOL. The goal is just to divide 213.20 by 10 then save-off the quotient to another variable as well as the remainder. I was expecting in the remainder part to have value of 3.2 but it just gave me 0. Please enlighten me.
See code snippet below:
WORKING-STORAGE SECTION.
01 VAR-A PIC S9(09)V99 COMP-3 VALUE 213.20
01 VAR-B PIC S9(09)V99 COMP-3 VALUE 10.00
01 VAR-C PIC S9(09)V99 COMP-3 VALUE 0.
01 VAR-D PIC S9V99 COMP-3 VALUE 0.
PROCEDURE DIVISION.
MAIN-PARAGRAPH.
DIVIDE VAR-A
BY VAR-B
GIVING VAR-C
REMAINDER VAR-D.
DISPLAY 'VAR-A: 'VAR-A.
DISPLAY 'VAR-B: 'VAR-B.
DISPLAY 'VAR-C: 'VAR-C.
DISPLAY 'VAR-D: 'VAR-D.
********************************************
RESULTS:
VAR-A: 00000021320
VAR-B: 00000001000
VAR-C: 00000002132
VAR-D: 000
|
The problem is that you have defined the receiving variable `VAR-C` with 2 digits after the decimal. I think you wanted integer division, so try defining it as follows:
01 VAR-C PIC S9(09) COMP-3.
Now `VAR-C` can only hold whole numbers (eg. 21) and the remainder (`VAR-D`) will contain the residual (eg. 3.20)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "cobol"
}
|
Polling Amazon SQS Queue with Ruby
The Amazon SDK for Ruby changes frequently, the current version of the `aws-sdk` Ruby gem is 2.0.29. The old method of polling Amazon SQS messages is no longer valid
# polling SQS Queue
queue.poll do |msg|
puts "Got message: #{msg.body}"
end
What is the correct method now for the version 2.0 of the AWS SDK for Ruby?
|
The version 2 SDK does not implement queue polling yet. It is on the SDK backlog as a feature request: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "amazon web services, amazon sqs, aws sdk"
}
|
Excel - For Loop
Sub Macro11()
'
' Macro11 Macro
'
'
Calculate
Range("B46:CRZ46").Select
Selection.Copy
Sheets("Sheet1").Select
Range("B:B").Select
Cells(Range("B:B").End(xlUp).Row + 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
End Sub
What the following Macro does, is refresh the page (which creates a new data set), copy the data set from `("B46:CRZ46")` and paste it in `"Sheet1"`. Now, I want the pasting to go down a row every time (which I tried with `.End(xlUp)` however I am not using it correctly and it just copies and pastes on the same row.
What could I change or add to for the code to function well?
|
You can assign values directly without needing to copy/paste:
Dim rng As Range
Calculate
Set rng = Activesheet.Range("B46:CRZ46")
Sheets("Sheet1").Cells(Rows.Count, "B").End(xlUp) _
.Offset(1, 0).Resize(rng.rows.count, rng.columns.count).Value = rng.Value
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "excel, vba"
}
|
App Engine datastore does not support operator OR
I am trying to query the google datastore for something like (with pm --> persistanceManager):
String filters = "( field == 'value' || field == 'anotherValue' )";
Query query = pm.newQuery(myType.class, filters);
When I execute - I am getting back: **App Engine datastore does not support operator OR**.
What's the best approach in people experience for this kind of queries?
Any help appreciated!
|
Perform multiple queries. The Datastore, like all other databases, isn't able to efficiently execute disjunctions. Unlike other databases, it exposes this difficulty to the user, to make it clear that what you're doing isn't efficient. Your only solution is to execute multiple queries - one for each or - and combine them.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 4,
"tags": "java, google app engine, google cloud datastore, jdoql"
}
|
Why is stylesheets and scripts separate from app in rails directory structure
I never understood why the stylesheets and scripts are outside the `/app` folder in ruby on rails. Is there benefits of housing them in the `/public` folder away from the `/app`?
Thank! Matt
|
In production environment, `/app` is served by Ruby appserver, i.e mongrel, thin, unicorn, etc, while `/public` is served by a webserver that is better in serving static content, i.e nginx. Sometimes you would also want to decouple `/public` to be served by a CDN, i.e Amazon S3. Decoupling this two directory provides better deployment arrangement in production environment.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ruby on rails, directory structure"
}
|
How do you turn off G.SKill RGB lights on AsRock motherboard?
Before finalizing an order that would include
* RAM: G.Skill Trident Z RGB
* MB: AsRock Taichi X399
What will the options be for me to turn off RGB lights? Searching, I read mainly topics about "Asus Aura". Is there an equivalent software for AsRock? Are there other ways?
|
Have you tried using the Gskill RGB software? I haven't tried it because I have an ASUS motherboard, let me know if it works. <
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "memory, motherboard, rgb"
}
|
How to create an interface/form in django where the user can use tools such as bold and italicize before submitting (similar to tools in google docs)
I am making a django website where a user inputs an essay. I want to the user to be able to use tools in order to "prettify" their essay by changing font, color, and other elements, and use tools such as bold and italics.
For example, if you see the interface where you can ask a question in stack overflow, you can see formatting information on the top.
Stack Overflow Create Question Tools
|
basically you can use django-ckeditor in your admin. select your field and customize it, for example code:
class ArticleAdmin(admin.ModelAdmin):
form = ArticleModelForm
content = forms.CharField(widget=CKEditorUploadingWidget())
prepopulated_fields = {'slug': ('title',), }
class Meta:
model = Article
admin.site.register(Article, ArticleAdmin)
admin.site.register(ArticleComment)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, django"
}
|
Build go-ethereum source code
I wanted to build go-ethereum source code in my local side and test it in geth. I have followed up the instructions in the github go-ethereum as it is. However, I have got fail with some errors when I try command to build as below.
go-ethereum> **go install -v github.com/ethereum/go-ethereum/cmd/geth**
Is there any ways to build go-ethereum source code on either windows or ubuntu? I have tested it in both windows10 and Ubuntu18.04 with go version 1.13.4.
|
Those instructions work for me on Ubuntu 18.04. I'm assuming it's something to do with your Go installation (or a missing/out-of-date C compiler?).
Another, `make`-based, method (which again works for me on Ubuntu) is the following:
* `git clone
* Install the latest version of Go
* `sudo apt-get install -y build-essential`
* `cd go-ethereum`
* `make geth`
|
stackexchange-ethereum
|
{
"answer_score": 1,
"question_score": 2,
"tags": "go ethereum, geth debugging"
}
|
Implementing Simulated Annealing
I think I understand the basic concept of simulated annealing. It's basically adding random solutions to cover a better area of the search space at the beginning then slowly reducing the randomness as the algorithm continues running.
I'm a little confused on how I would implement this into my genetic algorithm.
Can anyone give me a simple explanation of what I need to do and clarify that my understand of how simulated annealing works is correct?
|
When constructing a new generation of individuals in a genetic algorithm, there are three random aspects to it:
1. Matching parent individuals to parent individuals, with preference according to their proportional fitness,
2. Choosing the crossover point, and,
3. Mutating the offspring.
There's not much you can do about the second one, since that's typically a uniform random distribution. You _could_ conceivably try to add some random factor to the roulette wheel as you're selecting your parent individuals, and then slowly decrease that random function. But that goes against the spirit of the genetic algorithm and (more importantly) I don't think it will do much good. I think it would hurt, actually.
That leaves the third factor-- change the mutation rate from high mutation to low mutation as the generations go by.
It's really not any more complicated than that.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "artificial intelligence, genetic algorithm, simulated annealing"
}
|
Making a 2D very simple running game with jumps. Same class?
Hey I'm making a very simple Running Jumping game for my Java 1 class. The character is gonna run and jump over oncoming rocks. Should the rock and the running Boy be in the same class or separate?
import javax.swing.*;
import java.awt.*;
import java.awt.Dimension;
public class Boy extends JPanel {
JLabel Boy1;
ImageIcon Boy;
public Boy () {
setLayout(null);
setBackground (Color.white);
Boy = new ImageIcon ("/Users/a/Documents/workspace/JumpyBoy/src/Boy.png");
Boy1 = new JLabel (Boy, SwingConstants.CENTER);
Boy1.setBounds(80, 300, 130, 500);
add (Boy1);
}
}
|
@niiraj874u is correct. You want 2 classes. One for the boy and one for the rock.
Generally speaking, different nouns should become different classes.
Each noun, a boy and a rock in this case, will have different actions (functions) to perform: the boy will jump, the rock will roll (I guess). And these functions should be encapsulated into the separate classes depending on which object does which action.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, image, class, jpanel, 2d"
}
|
Is there a difference between "In" and "Out" peer connections?
On bitcoin-qt, some peers are called "Out" and some are "In". Is there any difference besides who initiated the connection?
|
No, connection directionality doesn't affect peer behavior in Bitcoin P2P at all. The same rules for relaying inventory, and punishments for misbehavior apply to both. The software will avoid making outgoing connections to peers in close proximity in the IP address space to one another, but this does not apply to incoming connections where many connections from even the same IP address are allowed.
|
stackexchange-bitcoin
|
{
"answer_score": 2,
"question_score": 2,
"tags": "bitcoin core, peers"
}
|
GTK and CSS : Rounded buttons
I am trying to create a rounded button by calling a external CSS file in my C++ application.
I manage to get a round button but some rectangular border remains and I cannot find how to get rid of that border.
Content of CSS file :
GtkButton {
-GtkWidget-focus-line-width: 1px;
border-width: 1px;
border-radius: 30px;
background-image: -gtk-gradient (linear,
left top,
left bottom,
from (@win_bg),
color-stop (0.5, @win_dark),
to (@win_bg));
}
PS : I left out the color definitions to keep it shorter.
|
I am running Debian Wheezy (currently testing), after installing the gtk unico engine (apt-get install gtk3-engines-unico) and modifying my css it worked (rectangular borders are gone)
GtkButton {
engine: unico;
-GtkWidget-focus-line-width: 1px;
border-width: 1px;
border-radius: 30px;
background-image: -gtk-gradient (linear,
left top,
left bottom,
from (@win_bg),
color-stop (0.5, @win_dark),
to (@win_bg));
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "c++, css, gtk"
}
|
Expectation of Geometric Random Variable Simulation
I have the following code for simulating a geometric random variable where $X \sim \text{Geometric}(p)$, $0 \leq p \leq 1$, and pmf is $p(n) = (1 - p)^np$:
> 1. Set $X = 0$.
> 2. Generate $U \sim \text{Uniform}(0,1)$.
> 3. If $U \leq (1-p)$ set $X = (X + 1)$ and return to (2).
> 4. Else return $X$,
>
Obviously this is an inefficient approach to say generating one with, $\lfloor \text{ln}(U) / \text{ln}(1 - p)\rfloor$, since a small $p$ rarely goes through multiple iterations.
**My question:** With a simulation in R, I can calculate an estimated number of times we will loop through for a $p$. But I would like to have an actual equation to which I can calculate the expected number for any arbitrary $p$ to compare with more efficient algorithms.
How do I go about calculating this? Obviously, $E(U)=.5$, do we need to condition this on $1−p$?
|
We are just simulating geometric distribution that starts from $0$.
When we simulate $U ~\sim \operatorname{Uniform}(0,1)$ and compare the value with $1-p$, it is equivalent to tossing a coin with probability of tail being $1-p$ where we view probability of obtaining a head as the success event. Note that we have $Pr(U \leq 1-p) = 1-p$.
The corresponding mean is $\frac{1-p}{p}$.
Edit:
The expected number of rounds that is required is $\frac{1-p}{p}+1=\frac1p$
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 1,
"tags": "distributions, simulation"
}
|
How to filter Power BI table using list of keywords (in a column in other table)
I have a big data table with a column called Account Name. In another table ( _Accounts_ ) I have a column of Account Keywords that contains parts of full account names. I want to filter the big data by column 'Account Name' using the list of keywords in the 'Acount Keywords' list.
I've created a new measure in the big data table called 'Filter Accounts' with the following DAX:
FILTER ACCOUNTS = contains(Accounts,Accounts[Account Keyword],Big_Data[Account Name])
But the "contains" function works on exact matches. I want it to return true if the 'Account Keyword' is found within any part of the 'Account Name' field. I also want it to ignore case.
The DAX statement results in TRUE only for exact matches. How do I modify my DAX to achieve the desired non-exact matches?
|
DAX has two functions for text contains matching, `CONTAINSSTRING` and `CONTAINSSTRINGEXACT`, where the latter is case-sensitive but the former is not.
You can find how many keywords match an `Account Name` by writing a calculated column like this on the `Big_Data` table:
Keyword Matches =
COUNTROWS (
FILTER (
Accounts,
CONTAINSSTRING ( Big_Data[Account Name], Accounts[Account Keyword] )
)
)
To get a `TRUE` or `FALSE` output instead of a count, simply append `> 0` to see if the count is a positive value.
Match Exists =
COUNTROWS (
FILTER (
Accounts,
CONTAINSSTRING ( Big_Data[Account Name], Accounts[Account Keyword] )
)
) > 0
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "powerbi, dax"
}
|
vmap automatically puts '<,'> infront of excommands
I'm trying to write a copy/paste function for visual mode vim. Copy reads all the lines highlighted.
` vmap cc :execute Copy()<CR> ` turns into ` '<,'>:execute Copy()<CR> `
which results in ` E481: No range allowed `
How can I get vmap not to insert '<,'> when going into ex mode?
|
You can use `C-u` to clear command line.
vmap cc :<C-u>execute Copy()<CR>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "vim"
}
|
apoc.export.csv.query runs without completing
I'm trying to execute a csv export using the APOC procedure library, specifically, the procedure CALL apoc.export.csv.query
The procedure runs forever even with a simple query, for example:
CALL apoc.export.csv.query("match (m:Movie) where m.name='Matrix' return m.name","results.csv",{})
The Neo4j version is 3.2.1 and the corresponding APOC version is apoc-3.2.0.3.
Is this a bug or syntax error?
|
If you are running the query from the browser that may indeed be a **visualization bug** (browser unable to show you the result of the procedure ... which does actually finish in fact). You do get the result in the file though, correct ? Try the same command-line with the cypher-shell and you should get a result immediately.
I have logged an issue for something similar to that but I haven't checked yet if it has been resolved in 3.2.2.
Hope this helps, Regards, Tom
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "neo4j, cypher"
}
|
Is it possible to search all databases in a SQL Server for a specific view? If yes how?
I am trying to find a specific view. I know it exists on a specific SQL Server but I don't know under which Database. If I use Information_Schema it would only search within the current Database.
SELECT *
FROM INFORMATION_SCHEMA.Views v
WHERE v.Table_Name LIKE '%vwViewName%'
Is it possible to search all databases in a SQL Server instance for a specific view? If yes, then how?
|
You can use `sp_msforeachdb` to check `sys.views` across all databases:
DECLARE @views TABLE (ViewName NVARCHAR(4000))
DECLARE @ViewName NVARCHAR(4000) = 'ViewName'
DECLARE @query NVARCHAR(4000) = 'SELECT ''?'' + ''.'' + s.name + ''.'' + v.name from [?].sys.views v inner join sys.schemas s on v.schema_id=s.schema_id WHERE v.name LIKE ''%' + @ViewName + '%'''
INSERT INTO @views (ViewName)
EXEC sp_msforeachdb @query
SELECT *
FROM @views
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, sql server, view, information schema"
}
|
If $c > a > 0$ and $a − b + c = 0$, find the largest root of $ax^2 + bx + c = 0$.
> If $c > a > 0$ and $a − b + c = 0$, find the largest root of $ax^2 + bx + c = 0$.
Edit: The key says that the larger root is $-a-b+c$. Is there something wrong with the key?
|
You have: $$ax^2+bx+c=0$$ When you put $x=-1$, you get: $$a-b+c=0$$ Roots are: $$\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$ Substitute $b=a+c$ in it: $$\frac{-(a+c)\pm\sqrt{(a+c)^2-4ac}}{2a}$$ $$=\frac{-(a+c)\pm\sqrt{(a-c)^2}}{2a}$$ Solving, you get roots as $-\frac ca$ and $-1$, out of which, $-1$ will be greater,
because: $$c>a>0 \implies \frac ca>1$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "algebra precalculus"
}
|
visual basic 2010 -- alternate of Alt+Tab
I want to:
1. set "Hello!" on the clipboard
2. alt tab to last active window (e.g. notepad, etc)
3. paste what's on the clipboard
The way I have it implemented works, but not flawlessly; it works most of the times, other times, it simply won't do step 2. I've tried other events such as "Click", "MouseUp" and as you can see below, "MouseClick". Is there any alternate way of implementing the alt+tab? Frustrated and need your help. Thanks!
* * *
I have "System.Threading" imported. sample code:
Private Sub try1_click(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles try1.MouseClick
Clipboard.Clear() 'clears the clipboard
Clipboard.SetText("Hello!")
SendKeys.Send("%{Tab}")
Thread.Sleep(500)
SendKeys.SendWait("+{Insert}")
SendKeys.Send("{Enter}")
End Sub
|
First store the process name of the current active window to activate it later, you can store it in a dictionary or a list or tuple or anything else.
Then use **AppActivate** to activate the desired window that you want instead trying to send tab keys to try to return to the last active window.
#Region " App Activate "
' [ App Activate ]
'
' // By Elektro H@cker
'
' Examples :
'
' App_Activate("notepad")
' App_Activate("notepad.exe")
Private Sub App_Activate(ByVal ProcessName As String)
ProcessName = If(ProcessName.ToLower.EndsWith(".exe"), _
ProcessName.Substring(0, ProcessName.LastIndexOf(".")), _
ProcessName)
AppActivate(Process.GetProcessesByName(ProcessName).FirstOrDefault.Id)
End Sub
#End Region
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": ".net, vb.net, process"
}
|
If closest parent has a certain class then do something
I am iterating through jQuery objects and trying to use <
$(".lists .list .lineone").each(function(index) {
var text = $(this).text();
if (text == "John Smith") {
$(this).closest(".list").addClass("hidden");
};
if (text == "John Smith" && !(this).closest(".list").hasClass(".hidden")) {
counter++;
};
});
I am getting an error that hasClass() doesn't exist? Why is this?
I am trying to check in the 2nd if statement that the current element it's closest parent element called `.list` if it also has the class `.hidden` and if so add to the counter.
|
To expand to nikhil's comment, this should be the code
$(".lists .list .lineone").each(function(index) {
var text = $(this).text();
if (text == "John Smith") {
$(this).closest(".list").addClass("hidden");
};
if (text == "John Smith" && !$(this).closest(".list").hasClass(".hidden")) {
counter++;
};
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "jquery"
}
|
Infinispan Warning: org.jgroups.conf.XmlConfigurator: version is missing in the configuration file
at my company I am currently upgrading from Wildfly 19 to Wildfly 20. As a result I hab to upgrade the version of our Infinispan Cache from 9.x to 10.x. When I start my application I'm now getting multiple lines of warnings that always say:
`WARN [org.jgroups.conf.XmlConfigurator] (MSC service thread 1-1) version is missing in the configuration file`
My DefaultCacheManager gets initialized like this:
`EmbeddedCacheManager infManager = new DefaultCacheManager(new GlobalConfigurationBuilder().build());`
So Infinispan would use its default jgroups configuration file.
How can I avoid that warnings? Is there something wrong with the default configuration file? Do I have to provide a custom one, although I'm only using local caches? Or is it a completly different problem?
Thanks in advance for everyone who can help me.
|
JGroups (which is used for clustering in Infinispan and Wildfy) introduced a version attribute in the configuration files, with release 4.2.2.Final (see <
Infinispan 10/11 still uses JGroups 4.2.1.Final and so the default configuration files shipped don't have the version attribute.
IMO, it is safe to ignore since I don't expect any significant (API) changes between 4.2.1.Final and 4.2.4.Final (for the record, Wildfly 20 is using JGroups 4.2.4.Final).
If you want to remove the warning, you can copy the default configuration files from Infinispan (or create your own) and add the missing version attribute.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, wildfly, cluster computing, infinispan, jgroups"
}
|
Is my butane soldering iron's tip dead? (pic)
I've read the other posts on iron cleaning technique and I'm pretty sure I left it dirty often enough that it's toast, it seems the iron coating on the tip has flaked off completely; since I've got nothing to lose I'll attack it with a file in a second and see if I can get another small job out of it. $15 lesson learned.
The real question is why the plating up near the catalyst is flaking off and the whole tip is bending. Does this indicate I'm using too much heat?
 soldering iron tip you will ruin it!
You are running the iron much too hot, turn it all the way down so the catalyst is only just glowing, if that's too cold turn it up slowly!!!
To get your tip back use tip tinner or a soft wire brush, such as brass to avoid damaging the tip.
Again, NEVER, EVER get a file anywhere near a non-shitty soldering iron.
|
stackexchange-electronics
|
{
"answer_score": 10,
"question_score": 5,
"tags": "soldering"
}
|
Get start & end timestamp for month from Month and Year
I have following data:
Array
(
[month] => 07
[year] => 2014
)
I want start & end timestamp of july 2014 using above array.
|
Used functions: < <
<?php
$array = array('Month' => 07, 'Year' => 2014);
$daysCount = cal_days_in_month(CAL_GREGORIAN, $array['Month'], $array['Year']); //obtain month days count
$firstDay = mktime(0, 0, 0, $array['Month'], 1, $array['Year']); //obtain timestamp of specified month first day
$lastDay = mktime(0, 0, 0, $array['Month'], $daysCount, $array['Year']); //obtain timestamp of specified month last day
echo 'First: '.$firstDay.' Last: '.$lastDay;
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
Julia types with abstract type and definied type
How to make type with one abstract and one definied field
Like this:
abstract AbstractType
type type1 <: AbstractType
x
y
end
type type2 <: AbstractType
w
z
end
type MyType{T<:AbstractType}
a::T
b::Int64
end
a = MyType(type1(1,2))
I tried with some constructors but it didnt work as well.
|
It's not clear what you're trying to do. The reason your last statement isn't working has less to do with mixed types and more to do with the fact that you're trying to instantiate your type while missing an input argument.
If you want to be able to instantiate with a default value for b, define an appropriate wrapper constructor:
abstract AbstractType
type type1 <: AbstractType; x; y; end
type type2 <: AbstractType; w; z; end
type MyType{T<:AbstractType}; a::T; b::Int64; end
MyType{T<:AbstractType}(t::T) = MyType(t,0); # wrapper
julia> a = MyType(type1(1,2))
MyType{type1}(type1(1, 2), 0)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "types, julia, abstract"
}
|
Periodicity of events
For example, we have event that will go every 3 month. Event have DateStart, DataEnd and Periodicity.
Help me to write method that return true/false if event will go at specific date.
public bool MonthPeriodicityChecker (DateTime start, DateTime end, DateTime dateCheck, int periodicity)
{
}
For example, record have:
start = 02/23/2012 22:00:00;
end = 12/31/2012 23:30:00;
periodicity = 3;
Method must return true when current month = February, May, August, November.
Thanks.
|
The code is pretty simple:
var someDate = DateTime.Now; // could be any date set some other way
if(someDate > end) return false;
var checkDate = start;
while(checkDate < end)
{
if(checkDate.Month == someDate.Month && checkDate.Year == someDate.Year)
return true;
checkDate = checkDate.AddMonths(periodicity);
}
return false;
All you're doing is making sure `someDate` isn't past `end` and that the difference in months between the `start` and `someDate` is divisible evenly by the periodicity.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -5,
"tags": "c#"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.