INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Do I have to have the actual instructions on a cloning potion to make one?
I'm trying to get the rocket boots, which are apparently in the room in the desert castle that has a chest too high to reach.
I read something online where a guy made clones of himself and then climbed them to get to the chest. I don't have the actual instructions on how to make the cloning potion, but can I still brew it? I don't want to waste candies on something that might not even work.
Also, is there another, easier way to get to the chest? If so, that would _really_ help. | the concept of the clone is a good idea but it takes too much cloning potions. Instead use a summoning tribe spear. It is the same concept but it is faster and it doesn't cost anything | stackexchange-gaming | {
"answer_score": 0,
"question_score": 0,
"tags": "candy box 2"
} |
ObjectiveC - determine block return type at compile time
Would it be possible to determine the return type of a declared block, at compile time? The compiler is doing it, by inferring the type based on the return statements within the block. Is this result available to the programmer too?
For example:
^{
return [NSArray array];
}
is translated by the compiler to
^NSArray*(){
return [NSArray array];
}
What I'm trying to achieve is a macro similar to `__typeof__`, but that returns the block return type. For example a macro like `DECLARE_BLOCK(myBlock, ^{return [NSArray array];})` would expand as `NSArray* (^myBlock)() = ^{...}`.
I'd be able to use that macro to allow flexible blocks to be declared, something similar to the `auto` construct in `C++11`. | There is a nice and simple way to obtain the return type: `__typeof__(^{...}())` \- simulate the call of the block.
The solution is not mine, I discovered it on a pull request submitted for the Kiwi framework (< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "objective c, objective c blocks"
} |
Regular expression to match string not containing " " "?
Input:
<img alt="sample" src="/blabla.jpg" /><script type="text/javascript"
src="/blabla.js" /><script type="text/javascript"> var link =
"/pdf/sample.pdf"; </script>
Output:
"/blabla.jpg", "/blabla.js", "/pdf/sample.pdf" etc.
I want to select by file source extension(jpg, pdf, png etc) in all string(html output). How can I make this? Help please
EDIT : My regex pattern is: `" \".+?(\.js|\.jpg)\" "`. But doesn't work correctly. Output is: `"alt="sample" src="/blabla.jpg""`. I want to `"/blabla.jpg"` | "[^"]*?\.(?:jpg|pdf|js)"
Try this.See demo.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "asp.net, regex, match"
} |
Poker how many ways to make 4 of a kind
In this link it say there 13 X 48 = 624 ways to make 4 of a kind from card deck
Where does the 48 come from?
I can get 4! = 24 but I cannot get the 48 | The 48 refers to the fifth card, it's a five-hand poker right? Any other card will do after the four. Perhaps you will find the following product less confusing
$$\binom{13}{1} \binom{4}{4} \binom{48}{1}$$
where we choose the card in 13 ways, choose the four of a kind in 1 way and the fifth card in 48 ways. | stackexchange-stats | {
"answer_score": 5,
"question_score": 3,
"tags": "combinatorics, games"
} |
react-router v4 + electron - Does a timeline exist where they play nice together?
I'm trying to use react-router v4 inside an electron app.
Issue number one: electron loads the initial page as `file:///path/to/project/index.html`, react-router expects the initial page to be "/" and as such doesn't match it and renders nothing.
My initial solution to this was this little nasty piece of code to redirect to the right page on app start:
{window.location.href.endsWith('index.html') && <Redirect to="/" />}
This works perfectly until webpack-dev-server pops up to ruin the party - as soon as I make a single change to the code and webpack reloads the page to show the latest changes, it tries to load the new `file:///` route, erroring out and showing a blank page.
Anyone ever dealt with this? Are we just doomed to an endless loop of manual electron restarting? | In case anyone ever stumbles upon this, I "solved" the issue using MemoryRouter instead. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs, webpack, react router, electron"
} |
How to set a mouse to a particular cell in all worksheets?
I would like to set cursor/mouse pointer to cell `AL2` but my program can only make this on the active worksheet
Dim a As Worksheet
For Each Sheet In ThisWorkbook.Sheets
Range("AL2").Select
Next Sheet
Could anyone explains why the code does not do what I would like to have? | Is this what you are trying?
Dim aSheet As Worksheet
For Each aSheet In ThisWorkbook.Sheets
aSheet.Activate
Range("AL2").Select
Next Sheet
Having said that, one should always avoid using `.Select` and `.Activate`
Why do you want to select a cell? What exactly are you trying to do? | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "excel, vba"
} |
Change a SKPhysicsBody's body shape
I don't want to change ANYTHING other than the body that defines the shape of a SKPhysicsBody. How do I do this?
I can't seem to find where I can change this.
Or even commentary on how to change it.
Yes, I know this has to be done carefully, so that it avoids all possible new collisions, overlaps, etc. But putting that aside, how do I change the body of an SKPhysicsBody? | You can manually create a custom shape for a physics body using `CGMutablePath`, then pass it into the `SKPhysicsBody` constructor.
For example:
let path = CGMutablePath()
path.move(to: CGPoint(.....))
path.addLine(to: CGPoint(.....))
let customPhysicsBody = SKPhysicsBody(edgeChainFrom: path) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "sprite kit, physics, skphysicsbody"
} |
Make dummy variable for categorical data, based on ID column with duplicate values in python
I have the following pandas dataframe:
ID value
0 1 A
1 1 B
2 1 C
3 2 B
4 10 C
5 4 C
6 4 A
I want to make dummy variables for the values in the column 'value', for each value in the column 'ID'. So I want it this:
ID A B C
0 1 1 1 1
1 2 0 1 0
2 10 0 0 1
3 4 1 0 1
How can I do this in python? | Use `crosstab` with limit counts to `1` by `DataFrame.clip`:
df1 = (pd.crosstab(df['ID'], df['value'])
.clip(upper=1)
.reset_index()
.rename_axis(None, axis=1))
print (df1)
ID A B C
0 1 1 1 1
1 2 0 1 0
2 4 1 0 1
3 10 0 0 1 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas"
} |
WCF Config element: baseAddressPrefixFilters
I have read the documentation for this element but still fail to understand what its purpose is. Here is a sample of how I've seen it used in examples:
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
I want to understand what this does that the base addresses in a service node doesn't do. I don't understand what this element is actually used for. | A WCF service host will only allow a single base address per scheme (HTTP in this case). Now if you deploy a WCF service on an IIS configured with multiple base addresses, for example < and < you will see an error. Using the baseAddressPrefixFilters you can filter one of the two base addresses and your service will run just fine. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": "wcf, configuration files"
} |
How many arguments does a function take?
How can i get a lambda list specification of a some function parameters, or at least a number of arguments it takes?
For example:
(defun a (a b) )
(get-arg-list #'a) ;-> '(a b) | Common Lisp provides the function `FUNCTION-LAMBDA-EXPRESSION` which may be able to recover the source expression, which then includes the lambda list.
LispWorks has defined a function `FUNCTION-LAMBDA-LIST` which returns the arglist.
Many other implementations have some form of `ARGLIST` function in some internal package.
Many Common Lisp users use SLIME, a very clever editor extension for the GNU Emacs editor. It has a backend for Common Lisp called SWANK. The SWANK sources provide all kinds of interfaces to the various Common Lisp implementations, including getting the arglist of functions. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "lisp, common lisp"
} |
Change backgroundcolor of PushButton (hyperref package)
I would like to create a pushbutton and change its background color. Is this feasible ? And how ?
Here's my MWE:
\documentclass[a4paper, 12pt]{article}
\usepackage{xcolor}
\usepackage{hyperref}
\begin{document}
\begin{Form}
\PushButton[
name=additem,
borderwidth=0.5pt,
bordercolor=blue,
backgroundcolor=red % why doesn't this work ?
]{\textcolor{blue}{Add an item}}
\end{Form}
\end{document}
 and by omitting leading dot, you could take the following regular expression.
const
string = "Vl.55.16b25.3d.42b50.59b30.90.24b35.3d.56.67b70.Tv.54b30.Vl.41b35.Tv.Bd.71b50.3d.99b20.03b50.Tv.73b50.Vl.05b25.12b40.Bd.Tv.82b25.",
result = string.match(/[^.].*?b\d\d(?=\.(3d|\D\D|$))/g);
console.log(result); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
send typing notification in MSBOT framework in node.js
I have developed a bot in Bot framework. Once user responds to the bot and bot is processing it, i need to show the typing indicator to the user in the meanwhile for every 2 seconds . It should be working across all conversations of the chat. | Easy as pie. Node.js bots send a typing indicator to the user by executing `session.SendTyping();`
If you want to see what this looks like in the framework, you can find the code here Also, Microsoft has a documentation page that talks specifically about this. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "node.js, botframework"
} |
Form to update multiple items of a database at the same time
I am trying to create a page that will show the items in a table and all fields for each of the items. The purpose is to give the user the possibility to update the item's details online.
I have around 14 fields in my table and was planning on doing it like the below. Would it make sense? Or would there be a more efficient way to do this?
<form>
(query all items in table)
while (...) {
<span class="details">NAME: </span>
<input name="name" value="<?php echo $info['name']; ?>">
<span class="details">CATEGORY: </span>
<input name="category" value="<?php echo $info['category']; ?>"
...
... and so on 12 more times
}
<button to submit the form>
</form>
And then, I would like to update in the database ONLY those fields that have been updated by the user. Should I check one by one each field? Or is there an easier way to do this?
Thanks! | I am currently using this code for disabling all fields that not changed:
<script>
$(function() {
$('.input').change(function() {
$(this).addClass('changed');
});
$('input[type=submit]').click(function(){
$('form').find('.input:not(.changed)').attr("disabled", "disabled");
});
});
</script>
I added 'input' class to all form element (select, textarea, input, etc), then, the script watching them if they changed then it adds another class named 'changed', and later, when the submit button clicked, the script disables all element that not changed. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, html, database, forms"
} |
What to do when question and answers get mass-upvoted with no reason?
I answered a not-so-interesting question on Stack Overflow giving just a short example rather than a complete answer. Since yesterday the question was upvoted 44 times and my answer 55 times!
Even if I'm happy with the reputation I don't think this is normal. Should I do something or can I do something, maybe like flagging the question? | Due to the reputation cap, you can only get 200 reputation per day so it's not like those upvotes are _severely_ affecting your reputation. If you really feel so bad about getting it all from one answer, go answer some other questions and get upvotes that don't count. That way you can pretend that you got reputation from those answers and the other one just filled in the rest. Kind of like what I'm doing right now. I've already hit the reputation cap here on meta for the day, but I'm still answering anyways. :)
Really there's nothing to be worried about. Some questions just attract a lot of views, especially when someone like Jon Skeet answers them. Lots of views sometimes equates to lots of upvotes on unexpecting answers. | stackexchange-meta | {
"answer_score": 4,
"question_score": 3,
"tags": "discussion, up votes"
} |
Ruby's && operator with regards to arrays
I'm porting Amp's DiffLib implementation to C# and stumbled upon this very line (#114):
@b2j[@a[i,1]] && @b2j[@a[i,1]].each do |j|
Now, I got everything else ported and most tests seem to pass but I still do not understand what is this `&&` here for. I assume it is something along those lines in C#:
if(b2j.ContainsKey(a[i]))
{
foreach(var j in b2j[a[i]])
But still not particularly sure about that. | It says that if `@b2j[@a[i,1]]` is not `nil` and not `false`, then continue and do an iteration with `each` it. It is used to control the flow of the program in this case. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, ruby, porting"
} |
RxJava. How do I make the Observable timer run in the background?
I need to make sure that after pressing one button, the other is not available for 15 minutes. To do this, I use a method like this:
disposableTimer = Observable.timer(15,TimeUnit.MINUTES)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(aLong -> {
buttonSimpleAct.setEnabled(true);
});
This works well when the program is active, but I need this timer to work even when the program is closed. That is, if the first button was pressed, the application was closed and returned after 15 minutes, the second button should already be active.
Are there any ways to make the Observable work in the background, or alternatives to this? | What I'd do is save (in a persistent manner) the timestamp for when the button should be re-enabled and restart the timer with the remaining time when the app comes back.
// when the first button is clicked:
long reenableAfter = System.currentTimeMillis() + 15 * 60 * 1000L;
save(reenableAfter);
disposableTimer = Observable.timer(15 ,TimeUnit.MINUTES, AndroidSchedulers.mainThread())
.subscribe(aLong -> buttonSimpleAct.setEnabled(true));
// when the app starts
long reenableAfter = load();
disposableTimer = Observable.timer(reenableAfter - System.currentTimeMillis(),
TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe(aLong -> buttonSimpleAct.setEnabled(true)); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, android, timer, background, rx java"
} |
How can I reorient the axes of an object?
I spent some time in Unity yesterday trying to fire a sphere from a horizontal cylinder (like a ball from a cannon). I was using Vector3.forward, but the sphere kept coming out the top of the cylinder rather than the front. Someone suggested using Vector3.up instead, and sure enough it worked!
The cylinder is vertical by default. So, it appears that when I rotated the cylinder by 90 degrees to lay it flat, the local axes remained the same. The relative front of the cylinder remained at the same point, so when I fired the sphere it shot out the new "top", not what looked to me like the "front". If I had happened to be facing the other way, I would have had to fire at Vector3.down instead.
How can I reorient/reset the axes of an object so that they match my expectations? (And if I can't, how can I tell by looking which way an object is oriented?) | Click on the object in the scene, and look at the Rotation values in the Inspector. This will tell you which way the object is oriented in absolute terms.
If the orientation does not match your expected axis (for example, 90 degrees off, or using an unintuitive axis for a given direction), you cannot change the axis of the object itself. Instead, you can use a "parent transform" as follows:
Create an empty GameObject as a parent of your object, and align its transform with your model's expected axis. Now use the parent transform to reference and manipulate the child object. | stackexchange-gamedev | {
"answer_score": 5,
"question_score": 3,
"tags": "unity, orientation, visualization"
} |
error on calling signalR server method from a controller method
i cant call a server method from a hub trough controller. i am currently getting this error because of the authorize attribute from the controller:
'AuthorizeAttribute' is an ambiguous reference between 'System.Web.Mvc.AuthorizeAttribute' and 'Microsoft.AspNet.SignalR.AuthorizeAttribute'
any idea why is this happening or what is the proper way of calling signalR methods from controller actions??
here is my set up
[Authorize]
public class UserController : BaseController
{
public ActionResult doSomething()
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
hubContext.Clients.All.BroadcastLogin(myusernm);
return View();
}
} | If you have `using System.Web.Mvc;` and `using Microsoft.AspNet.SignalR;` at the top of your file then it will not know which `AuthorizeAttribute` to use.
Change `[Authorize]` to `[System.Web.Mvc.AuthorizeAttribute]` or use a using alias directive. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, asp.net mvc 4, signalr, signalr hub"
} |
gumby framework CSS framework
I need to develop a easy web site, I usually use bootstrap CSS framework, but this I want to use Gumbyn which allow me to 16 columns instead of 12.
I was wondering if :
* Can I change the green color easily?
* How can I use a fixed layout instead of a fluid one?
* is it compatible with all browser?
Thanks | Yes, you can change the green. Just add a second style sheet and make sure to include it after gumby, then add rules for your colors. And if you remove the @media rules from gumby it will be a fixed layout. I am sure it is compatible. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, css frameworks, gumby framework"
} |
Calling GDAL (programs) from Python
Could someone navigate me for using/calling GDAL stand-alone programs from Python? I have GDAL 2.3.2 and Python 3.7. When I call gdal from python I can access to a limited number of functions including gdal.Warp() and gdal.Translate(). I can not however access 'gdal_edit' which I am currently interested to use. In the Git page of this function I did not find any information regarding access to this function either! | gdal_edit is itself a python script - you should be able to find it located within your GDAL installation.
To access it from Python, you can use the subprocess library to call the script. e.g.
import subprocess as sp
#locate your gdal_edit script
gdaledit = r"C:\Program Files\GDAL\gdal_edit.py"
#input data
srcdata = 'abc.tif'
cmd = [gdaledit, '-a_srs', 'EPSG:4326', '-tr', '150', srcdata]
sp.check_call(cmd, shell=True)
You use the `shell=True` argument so that Python can effectively run the script from the command line. Without it, you will get an error. | stackexchange-gis | {
"answer_score": 5,
"question_score": 1,
"tags": "python, gdal, editing"
} |
Copying text file
How to copy the text file through vb6 code.
Having Source filename like clock.fin, time.mis, date.fin, so on...,
Having Destination Filename are saving in stroutput.
Stroutput as a string.
I want to give as clock.txt, time.txt, date.txt through code.
FileCopy App.Path & "\Temp\" & Name, App.Path & "\Temp\" & strOutput.txt
Getting error as Invalid qulifier in stroutput.txt | Well, for one thing, the `.txt` part should be in quotes since it is a string literal. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "vb6"
} |
RewriteRule with optional params
I have been trying for several hours to modify a URL by including optional parameters
My rewriting rules do not work
It consists of an ID, a slug and the two optional parameters are "-season- {number} -" and "-episode -" {number} "
I think the problem is that the slug sometimes contains a dash at the end.
RewriteRule ^serie-([0-9]+)(-([a-z0-9/-]))? serie.php?id=$1&sl=$2 [L]
RewriteRule ^serie-([0-9]+)-([a-z0-9/-])-saison-([0-9]+)-episode-([0-9]+)$ /serie.php?id=$1&sl=$2&esid=S$3-E$4 [L]
I want this result:
serie-1-the-strain
and with optional params:
serie-1-the-strain-saison-17-episode-259
Thanks or your help! | You should update the `RewriteRule` as:
RewriteRule ^serie-([0-9]+)-([a-z0-9/-]+)-saison-([0-9]+)-episode-([0-9]+)$ /serie.php?id=$1&sl=$2&esid=S$3-E$4 [L]
RewriteRule ^serie-([0-9]+)(-([a-z0-9/-]+))? serie.php?id=$1&sl=$3 [L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": ".htaccess, mod rewrite, url rewriting"
} |
Insert image so that it fills the rest of the page while not fall below a minimum size
I'm trying to make a command that adds images to page in a way that fill the rest of the page. I'm using code from How to define a figure size so that it consumes the rest of a page? and it works. But I noticed that sometimes the image will be very small when there is little space left, so I wanted to make it conditional - if there is more than 1/3 of the page left, fit the image, otherwise just put the bigger image on the next page - but I can't get the if to work. I'm new with LaTeX, can you help me make it work?
Here's the code:
\newcommand\measurepage{\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}
\newcommand{\imgFill}[1]{\begin{center}
\ifnum \measurepage<0.3*\textheigth \includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{#1}
\else \includegraphics[height=\measurepage,width=\textwidth,keepaspectratio]{#1} \fi
\end{center}
} | I've solved it. As Ulrike Fischer said, I should have used ifdim instead of ifnum (like I said, I'm new at this). Also, I had a typo (heigth instead of height)
So, If anyone needs this, working code:
\newcommand\measurepage{\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}
\newcommand{\imgFill}[1]{\begin{center}
\ifdim \measurepage<0.3\textheight \includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{#1}
\else \includegraphics[height=\measurepage,width=\textwidth,keepaspectratio]{#1} \fi
\end{center}
} | stackexchange-tex | {
"answer_score": 1,
"question_score": 2,
"tags": "graphics, scaling, fit, fill"
} |
ffmpeg complex filter - multiple crops on black background
We are attempting to process a video file by cropping it into several pieces and arranging it on a black background which is exactly 1920x1080. The following command runs but it never completes and we have to kill the process.
Is there something wrong with how we're trying to do this?
ffmpeg -i in.mov -y -filter_complex "\
color=s=1920x1080:c=black[bg];\
[0:v]crop=w=1920:h=ih:x=0:y=0[crop1];\
[0:v]crop=w=iw-1920:h=ih:x=1920:y=0[crop2];\
[bg][crop1]overlay=x=0:y=0[out1];\
[out1][crop2]overlay=x=0:y=h[final]" \
-map [final] out.mov | The `color` base has no duration set, and so runs indefinitely. The overlay filter by default terminates when the longer input ends. Here, it doesn't. So, let's correct that.
ffmpeg -i in.mov -y -filter_complex "\
color=s=1920x1080:c=black[bg];\
[0:v]crop=w=1920:h=ih:x=0:y=0[crop1];\
[0:v]crop=w=iw-1920:h=ih:x=1920:y=0[crop2];\
[bg][crop1]overlay=x=0:y=0:shortest=1[out1];\
[out1][crop2]overlay=x=0:y=h[final]" \
-map [final] out.mov | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ffmpeg, fluent ffmpeg"
} |
Is there any java library for converting document from pdf to html?
Open source implementation will be preferred. | Obviously, it isn't an easy task, PDF formatting is much richer than HTML's one (plus you must extract images and link them, etc.).
Simple text extraction is much simpler (although not trivial...).
I see in the sidebar of your question a similar question: Converting PDF to HTML with Python which points to a library (poppler, which is apparently written in C++, perhaps can be accessed with JNI/JNA) and to a related question which offers even more answers. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 6,
"tags": "java, html, pdf"
} |
How to reach to previous to previous component in angular
Suppose ,I have three routes `A->B->C` ,I go to B from A ,and then to C from B
Now I want to move to A directly From C. Is this possible ? | You can try with `Location` Class in `angular/common` . It has method historyGo()
Example if you want to go to previous to previous component
import {
Location
} from "@angular/common"
class A {
constructor(private location: Location) {}
goBackTo() {
this.historyGo(-1)
}
}
As per docs
> Position of the target page in the history relative to the current page. A negative value moves backwards, a positive value moves forwards, e.g. location.historyGo(2) moves forward two pages and location.historyGo(-2) moves back two pages
Also you can look at this answer | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, angular"
} |
Securing WordPress Blog Installation
Besides having secure passwords for my blog user and database connections, what should I do to make sure my WordPress installation is secure on my Linux shared server? | I think the best suggestions are well explained in the official "Hardening Wordpress" document:
<
At the end, those are the same suggestions for every application out there:
* Keep it updated.
* Use good passwords
* Reduce what information your are presenting (versions, server info, etc).
If you want to improve security with obscurity (not only thought it, but as an addtional measure), this document gives some ideas:
| stackexchange-serverfault | {
"answer_score": 6,
"question_score": 7,
"tags": "linux, apache 2.2, security"
} |
Styled alert box without a JS library
I would like to display an alert on my web site. I could use a library like jQuery, but currently, the site does not use one, and I don't think it is a good idea to add a library just for the sole purpose of an alert box.
Is there any way of styling the alert box, or is there a pure js alternative to something like jQuery modal dialog? | > Is there any way of styling the alert box
No, it is browser chrome and you can't touch it.
> or is there a pure js alternative to something like jQuery modal dialog?
jQuery doesn't have a modal dialog. jQuery UI does.
There is no pure JS alternative — you are dealing in presentation, so you need CSS.
jQuery UI is pure JS + CSS, and anything you can do with it, you can do by writing the JS and CSS yourself. Look at their code if you want an example. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript"
} |
How to override search in Magento?
My user should be able to use the search box to search by some attribute (numeric) it works.
But I'd like to my customer to be able to search using separator.
Example:
search by : 12345678 = works great
search by : 12-34-56-78 = doesn't work
Which will the best way to override magento search to parse/rewrite/modify this behavior?
Thank you | If you actually want to override the default search (OOP override, that is) Refer to my earlier answer.
Otherwise @Anton's answer may be enough for you to use the default search which is always preferable. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "search, magento, customization"
} |
Static class in C++
In the header I declared
#ifndef SOUND_CORE
#define SOUND_CORE
static SoundEngine soundEngine;
...
but the constructor for SoundEngine gets called multiple times, how is it possible, when it's declared as global static
I call it as
#include "SoundCore.h"
and use it directly
soundEngine.foo()
thank you | I would use `extern` instead of static. That's what `extern` is for.
In the header:
extern SoundEngine soundEngine;
In an accompanying source file:
SoundEngine soundEngine;
This will create one translation unit with the instance, and including the header will allow you to use it everywhere in your code.
// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp
int foo()
{
hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line
int main()
{
foo();
} | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "c++, class, static"
} |
Can we concatenate two properties in Hibernate HQL query?
Lets say I have one table with two columns `firstname` and `lastname` with String datatype. Normally I write my hql query like
"select firstname,lastname from contact"
Can I write a hql query which concatenates both property ?
Maybe something like `"select firstname+lastname as fullname from Contact"` | select concat(c.firstname, c.lastname) as fullname from Contact c
or, if you want a separator:
select concat(c.firstname, ' ', c.lastname) as fullname from Contact c
See the documentation. | stackexchange-stackoverflow | {
"answer_score": 53,
"question_score": 26,
"tags": "hibernate"
} |
How to share an AWS NLB between two EKS Services?
We have a cross AZ deployment in an EKS cluster inside an AWS region where every AZ is independent, meaning that components do not talk to other components that are not in the same AZ.
We are using Contour as our ingress and have different Daemon Sets, one for each AZ. As a result, we also have different Services defined for every Daemon Set.
When deploying the Services to EKS, two different NLBs are created.
We would like to have only one NLB that will be shared between the Services.
The question is: can it be achieved and if it can then how? | Yes, you should be able to do this, by using an appropriate _selector_ in your `Service`.
In each `DaemonSet` that you use, you have set the _label_ in the Pod-`template` for the pods.
E.g.
template:
metadata:
labels:
app: contour
az: az-1
and
template:
metadata:
labels:
app: contour
az: az-2
Now, in your Loadbalancer Service, you need to use a _selector_ that matches the Pods on both your DaemonSets, e.g. `app: contour`
Example Service
apiVersion: v1
kind: Service
metadata:
name: my-service
annotation:
service.beta.kubernetes.io/aws-load-balancer-type: nlb
spec:
selector:
app: contour # this needs to match the Pods in all your DaemonSets
ports:
- protocol: TCP
port: 80
type: LoadBalancer | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "amazon eks, heptio contour"
} |
GROUP BY having MAX date
I have problem when executing this code:
SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
FROM tblpm GROUP BY control_number
HAVING control_number=n.control_number)
Basically, I want to return the most recent date for each control number. The query above returns correct output but it takes 37secs. before the output was shown.
Is there any other sql clause or command that can execute faster than the query above? | Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a _correlated subquery_ , and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated); | stackexchange-stackoverflow | {
"answer_score": 170,
"question_score": 81,
"tags": "mysql, sql, optimization, greatest n per group"
} |
Get folder hierarchy with Google Drive API [C# / .NET]
I am looking for an elegant way to get the folder hierarchy, beginning with my root folder, using the C# Google Drive API V3.
Currently, you can get the root folder and its parents by
var getRequest = driveService.Files.Get("root");
getRequest.Fields = "parents";
var file = getRequest.Execute();
but I am looking for a way to get the children, not the parents, so I can recursively go down the file structure. Setting `getRequest.Fields = 'children'` is not a valid field option. | recursively fetching children is a very time consuming way to fetch the full hierarchy. Much better is to run a query to fetch all folders in a single GET (well it might take more than one if you have more than 1,000 folders) and then traverse their parent properties to build up the hierarchy in memory. Bear in mind that (afaik) there is nothing that prevents a folder hierarchy being cyclic, thus folder1 owns folder2 owns folder3 owns folder1, so whichever strategy you follow, check that you aren't in a loop.
If you're new to GDrive, it's important to realise early on that Folders are simply labels, rather than containers. So cyclic relationships and files with multiple parents is quite normal. They were originally called Collections, but got renamed to Folders to appease those members of the community that couldn't get their head around labels. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "c#, .net, visual studio, c# 4.0, google drive api"
} |
How do we perform installation testing of a native Android app on different devices
We have one Android app which is live as well. So far we have some device in the company (around 3-4) and we have tested the app (installation and full functionality) over them and all working fine. But there are so many crashes reported by the users along with the device and os details and we are not able to get a solution that we can cover maximum devices so at least app crash not encounter by end user.
Can some one help us in this ? or let us know the services or tools (paid or free) so at a time we can test out app on real device and get the report so we be sure and mitigate the app crashes? | There are several apps that support testing such as:
1. SauceLabs
2. AWS Device Farm
3. Xamarin Test Cloud
4. BrowserStack
5. Perfecto mobile
6. Test Object
7. Bugsnag
Bugsnag has modules to test mobile applications in both iOS and Android. Plus it specializes in crash reporting, which may make your troubleshooting easier. SauceLabs or AWS Device Farm is cost effective solutions. Appium has integration with Test Object to spy the objects for the app under test. | stackexchange-sqa | {
"answer_score": 3,
"question_score": 1,
"tags": "android, mobile, installation"
} |
How can I link one drupal View field (an image) to a QuickTab?
Im trying to link each image field of my view to a quicktab that I created. This is my view
> , I even tried to put it as an external link, but it never recognize it as a link.
>  to land to the page that I wanted.
5. Finally I did create the basic pages inserting in each one the Quicktabs that I needed.
And voilá! that was all :D
Thanks | stackexchange-drupal | {
"answer_score": 0,
"question_score": 0,
"tags": "views, 7, navigation, blocks"
} |
Verifying if string S is equal to string T backwards
For example, if I first enter `testing` and then that same word backwards, which is `gnitset`, it should print that the statement is true. I'm not sure what's wrong with my program since I just started with the _strrev_ function and strings in general.
#include <stdio.h>
int main()
{
char wordS[101], wordT[101];
scanf("%s", wordS);
scanf("%s", wordT);
if (wordS == strrev(wordT)){
printf("true");
}
else printf("false");
return 0;
} | `wordS == strrev(wordT)` compares pointers but not the string. Use `strcmp` instead.
if (strcmp (wordS ,strrev(wordT)) == 0) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c, arrays, string"
} |
How to split a string based on number of white space
I am trying to achieve this using the String.split function in Java but doesn't seem to find an elegant solution. The number of blank space between each character or word is fixed.
String original = "H E L L O W O R L D"
String finalWord = original.split();
System.out.println(finalWord);
HELLO WORLD
Basically, the number of white space between each alphabet is fixed e.g. 2 and the number of white space between word is also fixed e.g. 4.
How can I achieve that using Java?
**H** (space)(space) **E** (space)(space) **L** (space)(space) **L** (space)(space) **O** (space)(space)(space)(space) **W** (space)(space) **O** (space)(space) **R** (space)(space) **L** (space)(space) **D**
into
HELLO(space)WORLD
Hope it's understandable! | original.replaceAll("\\s{4,}", " ").replaceAll("\\s{2,}", "").trim()
The first will replace 4+ spaces with a space and the second will replace 2+ spaces with no spaces. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "java, string, split, delimiter"
} |
How to make Postgres character field sortable by number
I have the following postgressql table:
CREATE TABLE businesses
(
id serial NOT NULL,
town character varying(200) NOT NULL,
name character varying(200) NOT NULL,
employees character varying(200) NOT NULL,
offices character varying(200) NOT NULL,
CONSTRAINT businesses_pkey PRIMARY KEY (id)
)
I need to sort by number of employees. Unfortunately I realized that the table is of type character , which appears to be a string. Is there a way to modify the table without destroying it, to turn the employees field into something sortable by number? | Use this query to change the type of the column:
ALTER TABLE businesses ALTER employees TYPE numeric USING cast(employees as numeric);
You can find details here : < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "postgresql"
} |
I keep seeing "myApp.controllers" or "myApp.modules" in Angular JS. What does this mean?
I keep seeing code similar to the following:
angular.module('app.controllers')
I've seen this in some tutorials. I don't understand the significance of the `.controllers` in the module name. I've looked but can't find any information.
When I go into my console and try to access it I get nothing
So I guess my question(s) are:
1. What is the significance of the `.controllers` in `.module("app.controllers")`?
2. Are there other such suffixes that I should be aware of? | There is no significance. You can call your modules what you like. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, angularjs"
} |
How to insert to Combobox into Tablewidget
QComboBox *combo1 = new QComboBox(this);
QStringList list;
list <<"TRUE"<<"FALSE";
combo1 = new QComboBox(this);
combo1->addItems(list);
for(int i=0;i<ui->tableWidget->rowCount();i++){
if(a[i]==true){
combo1->setCurrentIndex(0);
ui->tableWidget->setCellWidget(i,2,combo1);
}
else{
combo1->setCurrentIndex(1);
ui->tableWidget->setCellWidget(i,2,combo1);
}
}
my source code. last cell change combobox. but Except last cell, All cell not combobox, i want all cell change combobox | **Try**
combo1 = new QComboBox(ui->tableWidget); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, qt"
} |
Can MPlayer flip a video horizontally?
I know VLC can do it but that stopped working :(
Can Gnome MPV do it? Can MPlayer do it?
It makes learning Tai Chi from videos soo much easier. | Strictly speaking you are after the 'mirror' function of MPlayer and perhaps the easiest way to accomplish this is by using the excellent MPlayer gui: SMPlayer.
Simply follow this trail after opening SMPlayer:
Video --> Mirror_image
to flip the video 180% horizontally, or more correctly: 'mirror'! Screenshot below on my own system:
 to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9)) | Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9)) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "javascript, function, loops"
} |
Joomla: How to set user group access permission for article post?
I got several user groups with special rights and categories.
**Example:** Classes: A, B, C. Teachers: A, B, C.
Now if "Teacher A" creates an article within his categorie (A) via frontpage he's able to select a permissionlevel for this article (Group A, B, C access).
Is it possible to hide this "access level selection" and give an automatic access level, in this case "access level a", when posting into categorie a?
Thanks for any usefull help! :) | I've done something similar in the past on a client project. I ended up creating a template override for the edit layout by copying components/com_content/views/form/tmpl/edit.php to templates/mytemplate/html/com_content/form/edit.php. Then, I moved the fields around and hid the regular access level selection container. Then, I performed some logic to get the logged in user to determine what access level they should be selecting, and set that in a hidden field right before the closing form tag, so that when it got submitted, the form would take that value. The field I used looked like this:
<input type="hidden" name="jform[access]" value="YOUR_GROUP_ACCESS_ID" />
So, as Dmitry said, it does take a little bit of work, but it's not too difficult. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "joomla, permissions, submit, categories, article"
} |
Global Methods In MVC4
I have a method that will need to be called by various controllers and various actions. Where is the correct place to put this method and how would i call it from other controllers. Cant seem to find anything by searching, so if someone could point me in the right direction i would appreciate it.
Thanks | Sounds like a job for a base controller:
public class BaseController : Controller
{
// Do your common stuff here...
}
Then inherit `BaseController`:
public class MyController : BaseController
{
// Your code goes here...
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c#, asp.net, asp.net mvc, asp.net mvc 4"
} |
Consulta em banco com acentuação na tabela
Sei que e meio absurdo, mais infelizmente me deparei com uma situação que não sei como contornar
A empresa tem um sistema que grava em baco ACCSSES e algumas tabelas tema acentuação e caracteres especiais Ex: Código - Ação - Preço
E instalei um programa que converte o banco para MYSQL e envia para o meu servidor uma vez por dia, e atualiza o banco
Porem as tabelas tambem sobem com os caracteres especiais.
E preciso realizar as consultas com estes caracteres so que da pau na hora de realizar, existe alguma forma de contornar isso ?
SELECT * FROM Campanhas ORDER BY Código ASC | Use o acento invertido:
SELECT * FROM Campanhas ORDER BY `Código` ASC
Eu pessoalmente acho uma péssima ideia usar acentos em nomes de colunas, isso sempre terá chances de causar algum problema no momento de enviar as "instruções" para o servidor, seria mais interessante revisar e mudar tudo para sem acento:
Código => codigo
Ação => acao
Preço => preco | stackexchange-pt_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
} |
opencv array more than 255
I'm dealing with CvMat in opencv of type CV_8U.
I'm basically adding arrays (and resultant addition is expected to be more than 255).
It looks like the CvMat array doesn't store values more than 255 (values more than 10,000-20,000). I don't want an overflow to occur.
Is there any way I can do that using a opencv data-structure? | CV_8U means each variable is between 0 and 255 (8bit unsigned integer). CV_16U will give you 0 to 65535 Is that all you were looking for? | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, c, opencv"
} |
If String Is Contained By Brackets, Remove Them
I'm trying to write a function that will take input, check to see if it has "[" as the first char and "]" as the last and remove them if it does. The string may have more brackets in them, if that's the case then I need to print an error statement. Everywhere I've looked, I've seen examples of how to do this if it were just the two brackets, but I need to check if there are any more as well, and that's where I'm getting confused.
I've seen examples of using `regex`, and I know that if I can find a string with just the two brackets on the outside, I can use `substring` to trim it, but I can't figure out how to check the string for the instances of brackets without remvoing all of them.
Help would be greatly appreciated. Thanks. | if(str.chatAt(0) == '[' && str.charAt(str.length()-1) == ']') //str.matches("\\[.*\\]")
{
str = str.substring(1, str.length() - 1);
}
if(str.contains("[") || str.contains("]")) //str.matches(".*[\\[\\]].*")
{
//throw your error
}
Posted potential regex solutions beside the if statements. Warning: Not the greatest at regex, so they may not be correct.
as @Ingo pointed out in the comments, `str.charAt(0)` will fail on empty string. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "java"
} |
Is it possible to use handlebars inside handlebars path?
I have an object like this:
`{ "var1": "x", "var2": { "x": "y": "z": } }`
I want something like `{{var2.{{var1}} }}` | The lookup built-in helper (Under "The lookup helper" section) can handle this.
var obj = {
"var1": "z",
"var2":
{
"x": 'x value',
"y": 'y value',
"z": 'z value'
}
}
var output = Handlebars.compile('{{lookup var2 var1}}')(obj)
// output would be 'z value' in this case
It basically allows you to "lookup" property (`var1`) in object (`var2`) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, handlebars.js, mustache"
} |
How to format an email address line (with name) with PHP?
I'm trying to generate email messages. The recipient's email address and name are specified by a user. What is the correct way to do this with PHP:
$to_header = "To: $name <$email>" # incorrect!
I already use a decent method for validating the email addressess (let's not go to that now...), but how do I properly encode $name with eg. QP when needed? For example, if the recipient is called "Foo Bär", I should produce (eg.) something like:
To: =?utf-8?Q?Foo_B=C3=A4r?= <[email protected]>
**Update:** Earlier I wasn't using a ready-made mailer such as PHPMailer for other reasons (we already had an external queue system). Anyway, now I'm ending up using SwiftMailer. Thanks for all the answers! | I've used `iconv_mime_encode` to encode the Subject -header. I presume the same could be used for encoding the name in the To -header as well.
I do, however, as others have, recommend using an existing library or package to handle the encoding for you.
I've used Mail mime available from PEAR. Not perhaps the best out there, but as an alternative to the other ones suggested.
var_dump(
iconv_set_encoding('output_encoding', 'UTF-8'),
iconv_set_encoding('internal_encoding', 'UTF-8'),
iconv_set_encoding('input_encoding', 'UTF-8'),
iconv_mime_encode('To', 'Bäråör Zückefém') . " <[email protected]>"
); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, email"
} |
Entity Framework OfType()
Let's assume I have a parent entity "Firm" and a handful of child entities that inherit from Firm. Assuming the children are named "RedFirm", "GreenFirm", and "BlueFirm", what is the proper way to query the Firm collection if I want to retrieve only RedFirm and GreenFirm instances?
I know I can do `context.Firms.OfType(RedFirm)`, but that only returns the RedFirm instances. Is there anyway to pass a collection of types into OfType or something similar to that? I suppose this can be done through a union but I would think that would be less efficient. | context.Firms.Where(x => x is RedFirm || x is GreenFirm); | stackexchange-stackoverflow | {
"answer_score": 24,
"question_score": 13,
"tags": "c#, entity framework"
} |
Assigning to a dynamically created vector
How do I assign to a dynamically created vector?
master<-c("bob","ed","frank")
d<-seq(1:10)
for (i in 1:length(master)){
assign(master[i], d )
}
eval(parse(text=master[2]))[2] # I can access the data
# but how can I assign to it THIS RETURNS AN ERROR #######################
eval(parse(text=master[2]))[2]<- 900 | OK. I'll post this code but only because I was asked to:
> eval(parse(text=paste0( master[2], "[2]<- 900" ) ) )
> ed
[1] 1 900 3 4 5 6 7 8 9 10
It's generally considered bad practice to use such a method. You need to build the expression" `ed[2] < 100`. Using `paste0` lets you evaluate master[2] as `'ed'` which is then concatenated with the rest of the characters before passing to `parse` for convert to a language object. This would be more in keeping with what is considered better practice:
master<-c("bob","ed","frank")
d<-seq(1:10)
mlist <- setNames( lapply(seq_along(master), function(x) {d} ), master)
So changing the second value of the second item with `<-`:
> mlist[[2]][2] <- 900
> mlist[['ed']]
[1] 1 900 3 4 5 6 7 8 9 10 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r"
} |
What is the name of the maximum training level setting?
Does anyone know the console command to change the default setting for the maximum amount of training levels in Oblivion?
I'm attempting to alter it, and the `setgs` console command works, but using the setting `iTrainingNumAllowedPerLevel` (the setting's name in Skyrim) does not. I know it exists, because I've used it before. | It appears the value is called `ITrainingSkills`, as said in this discussion on UESP.
From the NexusMods Forum it seems the command to change it, is:
setgamesetting itrainingskills, (number) | stackexchange-gaming | {
"answer_score": 3,
"question_score": 3,
"tags": "the elder scrolls iv oblivion"
} |
polynomial regression in python from scratch
I was doing this polynomial regression:
for i in np.arange(1, len(coeff)):
line += coeff[i] * x_pts ** i
I am aware of the concept but I don't understand why they are doing this step, can somebody explain, please. | This code is just saying
y=a_n*x^n + a_(n-1)*x^(n-1) +...+ a_1*x^(1)
Although I'm not sure why exponent = 0 is not included.
Edit: OP should have included more code (and as text in the body of the question, not as an image). Anyway, the original code is:
line = coeff[0]
for i in np.arange(1, len(coeff)):
line += coeff[i] * x_pts ** i
so we can see line is initialized as coeff[0], which is actually a constant not a coefficient. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "python, regression"
} |
Facebook and Twitter official buttons: over-ride CSS to display inline and float right?
I'm trying to use the official Facebook and Twitter buttons together.
I'd like to float them both right, inline with a third button, so that all three are arranged neatly and on one line, in the top right-hand corner of the UI.
I'd like the ordering as follows: Twitter button, Facebook button, third element.
This is proving surprisingly difficult, despite quite a lot of StackOverflow hunting and Googling. I've set up a JSFiddle here to show the problem: <
How can I over-ride the CSS styles so that all three elements are in the top right-hand corner of the HTML display? | Here you go. jsFiddle I guess you'll understand :) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "css, twitter, facebook like"
} |
SQL code to count only duplicates where all instances of the duplicate are null
I have a large data set with duplicate reference numbers (reference duplications range from 0 to 37 times). I want to count the number of references only where all instances are null in two columns. So using the table below, the code should return 1 because only Reference Code 3 has all null values, and the duplicates should only be counted once.
I would be grateful for any help.
!Table showing test data | This involves two steps: (1) isolate all the distinct pairs of values that only have null; (2) count each one once. One way to express this in a query is:
SELECT COUNT(*) FROM
(
SELECT refnum FROM #ref
GROUP BY refnum
HAVING MIN(colA) IS NULL
AND MIN(colB) IS NULL;
) AS x; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql, sql server"
} |
Past continuous and simple past
Yesterday Sue was walking along the road when she met James. He ......... (go) to the station to catch a train and he was carrying a bag. They stopped to talk for a few minutes.
Which one is correct , to say (was going) or (went) or **both** and **why** ? | "Was going," because, even though these sentences report something that happened in the past, when Sue meets James, as the first sentences tells, he has yet to arrive at the station. If he went to the station to catch a train, that would mean he went there, and presumably caught a train, _before_ she met him. I don't think that's the intended meaning.
If, for some reason, it is, instead of "went," it should be "had gone."
> He had gone to the station to catch a train.
We would want to know about his recent activities before Sue met him, and the past perfect conveys that much better than the simple past. | stackexchange-ell | {
"answer_score": 1,
"question_score": 0,
"tags": "past simple, past continuous"
} |
Prove For each integer $n \ge 1$ $\sum_{i=1}^{n} i^2=\frac{n(n+1)(2n+1)}{6}$
Did I do this correctly?
(basis) $\sum_{i=1}^{1} i^2=\frac{1(1+1)(2(1)+1)}{6}$ thus both sides are equal to 1.
(induction) Fixed $n$ and $k$ to be natural numbers. Assume $n=k$, then
$\sum_{i=1}^{k+1}i^2= \frac{k(k+1)(2k+1)}{6} + (k+1)^2$ by induction hypothesis.
$=\frac{k(k+1)(2k+1)+6(k+1)^2}{6}$
$=\frac{(k+1)(k(2k+1)+6(k+1))}{6}$
$=\frac{(k+1)(2k^2+7k+6))}{6}$
$=\frac{(k+1)(2k+3)(k+2))}{6}$
Eroge, the statement is true for the natural number n whenever it is true for any natural number less than n. | I would write your last sum in terms of $k+1$. What i mean is, if you assume when $n=k$ that
$$\sum_{i=1}^ki^2=\frac{k(k+1)(2k+1)}{6}$$
then your last sum, which you have written as
$$\sum_{i=1}^{k+1}i^2=\frac{(k+1)(2k+3)(k+2)}{6}$$
I would write as
$$\sum_{i=1}^{k+1}i^2=\frac{(k+1)[(k+1)+1][2(k+1)+1]}{6}$$
Because you are trying to show that the formula is valid for $n=k+1$, which is much more obvious at first glance. But your proof looks correct. Just my two cents... | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "proof verification"
} |
How to make search bar in asp.net which fetch record from database according to user input in asp.net?
I want to make search field where user enter his required data, and if data is available is DB then it fetch that data and display it. if not then give error message. using asp.net. Any Idea? or visual studio 2010 have any component like that? I am new to asp.net. | ASP.net Data access tutorials would be a good place to start | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, sql server, visual studio"
} |
Is there any difference between using/not using "astype(np.float)" for narray?
I'm going to import the txt file which contains Numbers only, for some coding practice.
Noticed that i can get the same result with either code_1 or code_2:
code_1 = np.array(pd.read_csv('e:/data.txt', sep='\t', header=None)).astype(np.float)
code_2 = np.array(pd.read_csv('e:/data.txt', sep='\t', header=None))
So I wonder if there is any difference between using or not using `.astype(np.float)`? please tell me if there is an similar question. thx a lot. | `DataFrame.astype()` method is used to cast a pandas object to a specified `dtype`. `astype()` function also provides the capability to convert any suitable existing column to categorical type.
The `DataFrame.astype()` function comes very handy when we want to case a particular column data type to another data type.
In your case, the file is loaded as a `DataFrame`. The numbers will be loaded as integers or floats depending on the numbers. The `astype(np.float)` method converts the numbers to floats. On the other hand if the numbers are already of float type, then as you saw there will not be any difference between the two. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, numpy, user defined types, numpy ndarray"
} |
css media query doesn't work on Sony Xperia Z smartphone
I need your help, I face a problem with my css media query code.
I just wrote the following css media code
@media (max-width: 900px) {
#content {
width: 100%;
margin: auto;
}
#recent_activities .act {
width: 94%;
padding: 3% 10px;
background-color: #FFF;
text-align: left;
margin-bottom: 10px;
margin-left: 0px;
height: inherit;
}
#header_container
{
display: none;
}
#footer {
width: 94%;
margin: auto;
padding: 3% 0px;
text-align: center;
}
}
my problem is that the code works perfectly on the computer screen when I re-size the browser window but unfortunately it does not work on my smart-phone (Xperia Z). | Just put the following meta tag in the `<head>`:
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
hope that helps. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "css, media queries"
} |
SQL removing duplicates in a certain column
Good afternoon all!
Had a question regarding the removal of duplicates in one column and making it remove the whole row. I will provide an example in a screenshot in Excel as to not provide proprietary info.

FROM SomeTable
group by Prov, Clinic,Address
having count(*)>1
SELECT Prov, Clinic,Address, countrows = count(*)
INTO [holdkey]
FROM SomeTable
GROUP BY Prov, Clinic,Address
HAVING count(*) > 1
SELECT DISTINCT sometable.*
INTO holdingtable
FROM sometable, holdkey
WHERE sometable.Prov = holdkey.Prov
AND sometable.Clinic = holdkey.Clinic
AND sometable.Address = holdkey.Address
SELECT Prov, Clinic,Address, count(*)
FROM holdingtable
group by Prov, Clinic,Address
having count(*)>1
DELETE sometable
FROM sometable, holdkey
WHERE sometable.Prov = holdkey.Prov
AND sometable.Clinic = holdkey.Clinic
AND sometable.Address = holdkey.Address
INSERT sometable SELECT * FROM holdingtable | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 1,
"tags": "sql, sql server, database"
} |
Lebesgue integral over discrete set
Let $X=\\{x_1,x_2,\ldots\\}$, and for any $A\subseteq X$ let $$\mu(A)=\sum_{x_n\in A}2^{-n}$$ Suppose $f$ is given by $f(x_n)=1/n!$. Find $$\int_X fd\mu$$
I tried to estimate from below by simple functions $s_k$ where $s_k(x_n)=1/n!$ for $n=1,2,\ldots,k$ and $s_k(x_n)=0$ otherwise. Then $\int_Xs_kd\mu=\sum_{i=1}^k2^{-i}/i!$.
I'm quite sure that $\int_Xfd\mu=\sum_{i=1}^\infty 2^{-i}/i!$. But since there could be other simple functions that are $\leq f$, how can I prove it rigorously? | Your sequence $\\{s_k\\}$ converges to $f$ monotonically. The monotone convergence theorem gives you the value of the integral. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "real analysis, measure theory, lebesgue integral"
} |
Run two commands with a crontab
I have a quick question. I need to add a cron to my debain crontab using an automated shell script and I need the cron to do two things:
1. cd into /etc/application
2. run the command "scrapy crawl"
> crontab -l | { /bin/cat; /bin/echo "* 3 * * * cd /etc/application"; } | crontab -
How do I get it to also run the scrapy crawl command? | You can have multiple commands in a single crontab line. Just separate them with semicolons:
crontab -l | { /bin/cat; /bin/echo "* 3 * * * cd /etc/application ; scrapy crawl"; } | crontab - | stackexchange-stackoverflow | {
"answer_score": 17,
"question_score": 12,
"tags": "shell, cron, debian, cd"
} |
Does upgrading the Sacred Chime affect miracle damage and healing effectiveness?
I know that miracle damage is affected by faith, but does upgrading the sacred chime also increase the damage of miracles and the effectiveness of healing miracles? The item status says it inflicts lightning and dark damage and this stat is increased by upgrading the chime, but does this mean the actual miracle damage or the damage done by its melee attack? Do any of those stats have an effect on healing miracles? | Yes, upgrading your charm affects the potency of miracles. This means that the **damage** of miracles such as Lightning Spear increase and the **healing** of miracles such as Heal also increases.
It's more effective to upgrade your charm than it is to add 1 point into Faith. Upgrading your charm once will add 20-40 damage to your Lightning Spear which is significantly more than adding 1 point into Faith.
In short; upgrade your charm to increase miracle potency
(Upgrading your charm also increases the melee attack if you are so inclined to bonk someone over the head with it)
To reflect the queries in the comments, I have tested the healing and it does increase the amount healed. | stackexchange-gaming | {
"answer_score": 1,
"question_score": 3,
"tags": "dark souls 2"
} |
Alternative for QUnit
What is the best alternative for QUnit unit test frameworks, also easy for understanding for an end user to learn. | You could give Jasmine a try. See these references for some comparison between QUnit and Jasmine:
* qUnit vs Jasmine - stackoverflow.com
* Choosing between qUnit and Jasmine - effectif.com
Easy for an end user to understand - what is that end user supposed to do? Write tests? Look at the results and decide if the product is stable enough? Unit tests are usually for the team, not for the end user (unless the end user is a technical guy/girl and can appreciate the value of unit tests) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "frameworks, qunit"
} |
How to get resource bundle value based on values received from managed bean?
I am looking for the possibility if I can get resourcbundle values based on values received from managed bean. It may be useful in datatable, datagrid, and also with other components where values are rendered.
I tried with this code:
<h:outputText value="#{resourceBundle['myBean.myMsg']}" />
But it didnt work. My outputText was not able to fetch the value from resourcebundle. Result was like:
???myBean.myMsg | If you getting `???myBean.myMsg` that means that it could not find _myBean.myMsg_ string in your resource file...
I guess you want to use the key inside the myBean.myMsg (and not the string _myBean.myMsg_ )?
In that case just remove the `''` that surrounds it
<h:outputText value="#{resourceBundle[myBean.myMsg]}" />
Otherwise it will be used as a string and not as EL expression | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "jsf, xhtml, facelets, resourcebundle"
} |
Set focus to window based on ID using win32com.client's AppActivate
I've tried the following, but focus isn't returned to the program that had focus when the script was run:
import win32com.client
import win32gui
current = win32gui.GetForegroundWindow()
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')
shell.AppActivate(str(current)) | It turns out that `win32gui.GetForegroundWindow()` returns the window handle and not the process ID.
`win32process.GetWindowThreadProcessId(hwnd)` can be used to get the thread ID and process ID from the handle.
import win32com.client
import win32gui
import win32process
hwnd = win32gui.GetForegroundWindow()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')
shell.AppActivate(pid) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, win32com"
} |
how to grep for specific time period in a log
We work with log files that have line entries that start with a date/time format such as this:
20150408 13:29:28 <rest of text>
What would I need to do in order to `grep` for a date range?
Say like all lines that start at `20150408 13:29:28` and end at `20150408 17:55:02`?
Would `grep` be the tool for the job or would something else be better like `sed`? | Certanly task can be done by `sed`
sed '/20150408 13:29:28/,/20150408 17:55:02/! d' log_files
but if lines did not have exact `20150408 13:29:28` script will print nothing and if its did not have exact `20150408 17:55:02` file will print every lines till the end. So the better is use date compare by script:
limit1=$(date -d "20150408 13:29:28" +"%s")
limit2=$(date -d "20150408 17:55:02" +"%s")
while read -r logdate logtime logline
do
logsec=$(date -d "$logdate $logtime" +"%s")
if [ $limit1 -le $logsec -a $limit2 -ge $logsec ]
then
echo $logdate $logtime $logline
fi
done < log_files | stackexchange-unix | {
"answer_score": 4,
"question_score": 5,
"tags": "linux, sed, grep, logs"
} |
set onMarkerClickListener along with title, but either one of them shows up. How to show both?
I'm using this line to generate a title for the marker-
mMap.addMarker(new MarkerOptions().position(latLng).title("Last location"));
Then if I set onMarkerClickListener
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "Clicked on marker", Toast.LENGTH_SHORT).show();
return true;
}
Marker title wouldn't show. I need to show both, toast and marker title; how to do that, if it is possible? | Add a line `marker.showInfoWindow();` inside the onMarkerClick method. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, android fragments, android mapview, android maps v2, android maps"
} |
The indefinite article - which sentence is correct?
> There is a big and comfortable bed in my room.
or
> There is a big and a comfortable bed in my room. | The former is correct, as big and comfortable are adjectives of bed.
> There is a big, long, green and comfortable bed.
In the second sentence, the word _a_ denotes a new item in your list.
> There is a bed, a chair, a sofa, and a window in the room.
Combining these ideas you'd get something like:
> There is a brown bed, a purple chair, and a big and comfortable bed in the room.
Often the 'and' is omitted though when chaining adjectives:
> There is a brown bed, a purple chair, and a big comfortable bed in the room. | stackexchange-ell | {
"answer_score": 3,
"question_score": 2,
"tags": "grammar"
} |
Bash Script multi conditional fails
In this Bash Shell script I like to check if the length of the string is zero. In that case the script should echo an error message and exit.
dbname="ssss"
dbuser=""
if [ -z "$dbname"]
then
echo "DB name is not specified!"
exit
fi
if [ -z "$dbuser"]
then
echo "DB user is not specified!"
exit
fi
If dbname is "" it works as expected. But if it has some value and I was expecting to see it exit at the next conditional, I get this error message:
Script.sh: line 4: [: missing `]'
DB user is not specified!
Why the error message? | [ -z "$dbuser"]
should be
[ -z "$dbuser" ]
# note: ------^ | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "bash, shell"
} |
Sacar MIN y MAX con php
Requiero sacar el mínimo de un campo en MySQL que hago SUM() al mismo con PHP, por ejemplo: Mi campo se llama carne, utilizo SUM() para sumar toda esa columna, hasta ahí todo bien obtengo la sumatoria de toda la columna, ahora bien como puedo sacar el mínimo de esa misma columna o campo. Quisiera poder obtener ese resultado y colocarlo en campo | Sería de la siguiente forma, tomando en cuenta que el tipo de dato de tu columna es DOUBLE:
SELECT MIN(carne) AS minimo, SUM(carne) AS sum FROM tabla
El resultado será algo similar a:
minimo | suma
---------------------
1.23456 | 14.845172
En una respuesta comentaste que te arroja 0 en el MIN, posiblemente hay un campo con 0. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
} |
Linking to external HTML pages in MediaWiki
I have been generating HTML documentation for my C++ code using Doxygen. Where I work, we have a MediaWiki page where we write documentation for a lot of our applications. Since this documentation is auto-generated and is already in a nice clean HTML format, it doesn't make sense to rewrite it to put it on the wiki. All I really need is to be able to put a link on the wiki to the auto-generated HTML.
I have been having a lot of trouble figuring out how to simply put a link to an HTML file in the wiki. It seems like it should be such a simple thing to do, but after doing some digging it really is not very straightforward. I don't even know where to put the file for it to be visible to the wiki server... I'm completely lost.
Does anyone know how to do this? | It turns out UNC links will work to access HTML files from the Wiki. The files just need to be stored in a location that the Wiki server can see such as a shared drive.
On a side note, in our Wiki, the links only work on internet explorer for some reason. I figured I would at least mention this in case someone else is trying to get this to work on a different browser and running into issues. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "html, hyperlink, mediawiki, doxygen, mediawiki api"
} |
Can a port be bound when the process has terminated?
Given: a process binds to a port on Linux, and that process is then terminated with either TERM or KILL signals. Is there anyway that the port could still be bound, or will the kernel clean up and guarantee the port will be unbound. | If the original process spawns child processes, it's possible for the child processes to keep the socket open past the parent process exit. If the parent process is the only process with the socket open, it should clean up upon termination. An existing process will close all open file descriptors, which includes all its sockets.
Once a close is initiated, the socket may still be in TIME_WAIT state. TCP attempts to guarantee delivery of all data being transmitted. When a socket is closed, it goes into TIME_WAIT to fulfil this guarantee. There are multiple variables that may require some time if they're TCP sockets such as to finish handshaking or whether the sockets were configured with SO_LINGER option.
Here's a link that explains TIME_WAIT from the Unix Socket FAQ: < | stackexchange-superuser | {
"answer_score": 1,
"question_score": 2,
"tags": "linux, networking, unix"
} |
Points, Vectors, and Planes Oh My! (Finding parallel vectors and intersecting vectors)
I'm quite stumped on the following problem: Consider the planes 4x + 1y + 1z = 1 and 4x + 1z = 0. (A) Find the unique point P on the y-axis which is on both planes. (_ _, __ , __)
(B) Find a unit vector u with positive first coordinate that is parallel to both planes **__ _I + __ _** _J + **_**_K
(C) Use the vectors found in parts (A) and (B) to find a vector equation for the line of intersection of the two planes r(t) = **__ _I + __ _** _J + **_**_K
Work thus far: I've figured out (A) is (0,1,0) Now, I know that the dot product of <4,1,1> and **u** will = 0, as well as the dot product between <4,0,1> and **u**... I'm quite stumped. Can anyone help me out by giving me hints? I'd prefer that the entire solution isn't given yet, so I can work through it. I'll respond as quickly as I can.
Thank you,
Landon | (B) Write $\mathbf{u}=(a,b,c)$. You want $(4,1,1)\cdot (a,b,c) = 0$, so that means $4a+b+c=0$. You also want $(4,0,1)\cdot(a,b,c)=0$< so that means $4a+c=0$. This tells you that you must have $b=0$, and $c=-4a$. So the general form of vectors that are parallel to both planes is $(a,0,-4a)$. Since you want it to be a _unit_ vector, you want $a^2 + 0^2 + (-4a)^2 = 1$, or $17a^2=1$. This gives you the absolute value of $a$ by solving for $a$, from which you can find one with positive first coordinate.
(C) Now that you have a point in both, and a direction parallel to both, that point and direction will give you a line that is common to both planes, giving (C). | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "multivariable calculus, vector spaces"
} |
Idiom/Phrase/Proverb to describe a scenario where a person who saved me from a bad habit has now fallen into the the same habit
I am facing a dilemma. Someone I know once (long time back) helped me get into a good habit, and abandon the accompanying bad habit, and now they have fallen into the same trap as me. I want to let them know of this, but I can't find the proper way to do this. I am looking for a proverb, idiom, phrase, or a historical reference which I could use to subtly remind that person of that fact.
Being direct might get me a quicker response, but I am afraid beginning from that might make the person less receptive to my advice. I am looking for something that I can use to get the other person thinking before I finally approach this topic.
Something suggestive, yet powerful.
Any help would be greatly appreciated. | 2 sentences that comes to my mind are:
> Physician, heal yourself! 1
and
> The shoemaker's children go barefoot 2
Both are referring to people who are able to help others, but have problems help themselves. Although the situation is a bit other, because in your case the person that have helped you got the same problem not in the same time, but afterwards.
**Disclaimer** while in first case I'm sure it has the same meaning as in my languange, in second case in Polish the saying is referring to the shoemaker going barefoot himself. | stackexchange-english | {
"answer_score": 4,
"question_score": 3,
"tags": "phrases, proverbs, idiom requests"
} |
Clear SQL database
I want to remove all entered data into my SQL database. I am using Python to handle all of the SQL statements from the program - however I did not make a backup of the clean database, and I want to clear all the records and reset primary IDs etc without affecting the structure of the database so it is ready to ship with my code.
I am using Python and SQLiteStudio.
Thanks. | In SQLiteStudio's SQL editor execute this command:
DELETE FROM table_name;
If you have multiple tables then the command is:
DELETE FROM table_name_1, table_name_2,...;
Instead of `table_name` you put the name of your table(s). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, sql, records, sqlitestudio"
} |
Custom registration field to SQL database
I have created new columns in a SQL table called `wp_users`. Those fields are "giodo", "handel" and "regulamin".
What I want to do is to add '1' to each column when a user registers and selects corresponding checkboxes.
I added checkboxes to the form using form_register and then I added those checkboxes to user data with this (here is an example for only one of them):
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register ($user_id) {
if ( isset( $_POST['giodo'] ) )
update_user_meta($user_id, 'giodo', $_POST['giodo']);
}
Can I somehow add their values to the database? | > I have created new colums in a SQL table 'wp_users'. Those fields are "giodo", "handel" and "regulamin".
Don't add columns to Core tables. There is no guarantee that these won't be destroyed or corrupted on next update. What you should be using is _user meta_ , and in fact that appears to be what you are actually using:
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register ($user_id) {
if ( isset( $_POST['giodo'] ) )
update_user_meta($user_id, 'giodo', $_POST['giodo']);
}
So the question is a bit confusing.
Your code _should have already_ inserted data into the database, just not where you are trying to put it. Your code should have inserted the data into the `$wpdb->usermeta` table and can be retrieved using `get_user_meta()`. That is what I would suggest. Abandon the attempt to add columns to a Core table and use the user meta API, which is what it was built for. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, users, actions, forms, user registration"
} |
Python: How to show matplotlib in flask
I'm very new to Flask and Matplotlib. I'd like to be able to show a simple chart I generated in some html, but I'm having a very hard time figuring out how. Here is my Python code:
from flask import Flask, render_template
import numpy as np
import pandas
import matplotlib.pyplot as plt
app = Flask(__name__)
variables = pandas.read_csv('C:\\path\\to\\variable.csv')
price =variables['price']
@app.route('/test')
def chartTest():
lnprice=np.log(price)
plt.plot(lnprice)
return render_template('untitled1.html', name = plt.show())
if __name__ == '__main__':
app.run(debug = True)
And here is my HTML:
<!doctype html>
<html>
<body>
<h1>Price Chart</h1>
<p>{{ name }}</p>
<img src={{ name }} alt="Chart" height="42" width="42">
</body>
</html> | You can generate the image on-the-fly in Flask URL route handler:
import io
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
xs = range(100)
ys = [random.randint(1, 50) for x in xs]
axis.plot(xs, ys)
return fig
Then you need to include the image in your HTML template:
<img src="/plot.png" alt="my plot"> | stackexchange-stackoverflow | {
"answer_score": 96,
"question_score": 58,
"tags": "python, matplotlib, flask"
} |
Two questions about Dirichlet's theorem on arithmetic progressions
Dirichlet's Theorem on arithmetic progressions states that there are infinitely many primes of the form
$$an+b$$
Being $a$ and $b$ coprimes.
1. Very elemental question: Can we say that this Theorem:
$$an-b$$
is equivalent to Dirichlet's one? I supose it is, as it would be the same as $a(n-1)+(n-b)$, but I would like to get sure, as I am not used to work with this kind of formulae
2. For which functions $f(n)$ can we say that there are infinitely many primes of the form
$$a[f(n)]+b$$ ? For example, $a2^n+b$ or $a(5n)+b$
Thank you! | 1. Yes, Dirichlet's theorem is equivalent to the statement that there are infinitely primes of the form $an - b$ for any relatively prime $a$ and $b$.
2. The short answer is that we don't know. Other than Dirichlet's theorem, there isn't another known family of functions with similar properties. There are many conjectures. For instance, it is thought that $x^2 + 1$ should be prime infinitely often. More generally, it is thought that any "reasonable" quadratic polynomial should be prime infinitely often (where "reasonable" is analogous to $a,b$ being relatively prime in the linear case). One such grand conjecture is Schinzel's Hypothesis. | stackexchange-math | {
"answer_score": 4,
"question_score": 4,
"tags": "number theory, elementary number theory, prime numbers"
} |
How do I pass all other attributes in props - ReactJS
const Label = (props) => {
return <label className={"card-label"} {...props.attributes}>{props.children}</label>;
};
If I try to access the attributes in other functions. I'm getting errors and unable to proceed
<Label attributes={style:{margin:"10px"}}>Select Tip %</Label>
Does anyone know the answer? How do I pass all other attributes of any component with props? | You should put your attributes value into attributes prop as an object:
return <Label className={"card-label"} attributes={{style:{}}}>Select Tip %</Label>;
A more readable way is to extract attributes from props directly:
const Label = ({ attributes, children }) => {
return <label className={"card-label"} {...attributes}>{children}</label>;
}; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "reactjs, react component"
} |
Output datestring in specified format
I have seen a lot of posts about parsing strings into dates, but not such definitive answers about the other direction, dates into strings of the desired format.
I have a Javascript `Date` (which I made from `Date(unixtimestamp)`) and I want a string that looks like `'YYYY-MM-DD HH:MM'`. Sure, I could get year, month, day, hour, and min and manually make the string with the dashes and colon, but that's multiple lines where I wonder if a single line of someone else's code will do.
Any thoughts? | Date.toISOString returns almost what you want.
var d= new Date();
var s= d.toISOString();
/* returned value: (String) 2014-07-28T18:26:46.550Z */
You can tinker with the return in the same line of code-
var d= new Date();
var s= d.toISOString().replace('T', ' ').slice(0, 16);
/* returned value: (String) 2014-07-28 18:26 */
or even:
(new Date(1406571989450)).toISOString().replace('T', ' ').slice(0, 16);
/* returned value: (String) 2014-07-28 18:26 */ | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, string, date"
} |
Query not using the index
I have a query.
`SELECT id_id FROM videos_member ORDER BY date_id DESC LIMIT 0,30`
Here is the table
CREATE TABLE IF NOT EXISTS `videos` (
`id_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`date_id` int(11) NOT NULL,
PRIMARY KEY (`id_id`),
KEY `date_id` (`date_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
I keep getting this
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE videos ALL NULL NULL NULL NULL 342 Using filesort
Why isn't is using the index? | The table contains (or at least MySQL thinks it contains) 342 rows. This is tiny and likely fits into a single block of physical storage, which means it can be read in a single read operation. Using the index would require at least two read operations. So MySQL might be smart here and realize that reading the whole table at once is just more efficient than reading the index and then using it to access the table.
In other words if you insert more rows into the table the plan might change to using index. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql"
} |
Help! jquery-UI datepicker function onChangeMonthYear() the parameter of "month" no leading zero
$('.selector').datepicker({
onChangeMonthYear: function(year, month, inst) { ... }
});
I just want the month parameter with leading zero!
thank you very much! | Since you're dealing with only a 2 digit scenario you can do take a simple check approach:
$('.selector').datepicker({
onChangeMonthYear: function(year, month, inst) {
if(month < 10) month = "0"+month;
otherFunc(year, month, inst);
}
});
You can try it in the context of your overall question here. It has to be a string to have the leading `0`, but that's ok in your case since you're using it as a selector.
* * *
A more general approach for reuse would be to create a small function:
function leftPad(num) {
return (num < 10) ? '0' + num : num;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, user interface, datepicker"
} |
Convergence of conditional expectations given convergence of random variables
Say $X_n$ is an $\mathcal{F}_n$-adapted sequence of random variables converging to $X_{\infty}$ in $L^1$. Clearly, fixed $n\leq m$ one has $E[X_m\mid \mathcal{F}_n] \to E[X_{\infty}\mid \mathcal{F}_n]$ in $L^1$. What's the easiest way to prove this? I know that $E[X_{\infty}\mid \mathcal{F}_n]\in L^1$ but I can't use the dominated convergence because I don't have P-a.s. convergence of the random variables, nor monotone convergence because I don't have non-negativity. | This amounts to saying that the mapping $X \mapsto E[X|\mathcal{G}]$ is continuous for the $L^1$ norm (here $\mathcal{G}$ is any sub-$\sigma$-field.)
The mapping is clearly linear and satisfies $$\lVert E[X|\mathcal{G}]\rVert_{L^1}= E\left|E[X|\mathcal{G}]\right|\leq E\left[E[|X||\mathcal{G}]\right]=E|X|=\lVert X\rVert_{L^1}.$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability theory, convergence divergence, conditional expectation"
} |
Возможно ли изменить стили для другого элемента при условии?
К примеру у меня есть элемент с классом `.my-class1`, а также динамичным классом `.my-class1-2`(элемент тот же, класс то появляется, то исчезает при каком-то условии(у меня это открытие и скрытие меню при нажатии на бургер)). Также есть отдельный элемент с классом `.my-class2` Знаю что отсутствие класса можно задать через псевдокласс `:not` Возник вопрос, возможно ли изменить стили для элемента с классом `.my-class2` только если элемент с классом `.my-class1` не содержит класса `.my-class1-2`, тоесть `.my-class1:not(.my-class1-2)` | вы можете задать такое условие только если `.my-class2` находится ВНУТРИ `.my-class1:not(.my-class1-2)` либо ПОСЛЕ него (сам или в контейнере). В общем, один из вариантов:
.my-class1:not(.my-class1-2) .my-class2
.my-class1:not(.my-class1-2) + .my-class2
.my-class1:not(.my-class1-2) ~ .my-class2
.my-class1:not(.my-class1-2) + %element% .my-class2
.my-class1:not(.my-class1-2) ~ %element .my-class2 | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css"
} |
Packetizing a video using libav libraries
I am trying to make a video streaming server and client applications which uses the libav libraries.
What I want the server to do is to simply read the video frame-by-frame and put the frames into packets and then send them to the client. Of course the client must be able to read the frame from the packet.
How can I do this? Are there any tutorials available?
I'm using an Ubuntu 11.04 machine. | I am working on the same problem now. Something you may want to try to look at is live555 livemedia library. <
You can use that library to stream mp3, h264 video, mpeg, etc. And it uses UDP and RTSP so it is very convenient for real time delivery of video. the FFPlay application included with ffmpeg (which is the whole set that includes libavformat among others) can play RTSP streams. you do something like
avformat_open_input(&pFormatCtx, "rtsp://192.168.1.1/someFile.264", NULL, &optss)
You can change the streaming RTSP examples to plugin your encoder output (maybe something like x264) to send content live as soon as you encode it. (look at the FAQ (
If you have pre-recorded video it is much simpler, you just give the video files and it will do the work for you. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c++, libav"
} |
Choosing CPU configuration for small NAS
I am going to build an small 4 disks NAS server with FreeNAS/ZFS. I've read that due to ZFS performance 8GB is the recommended amount of RAM for the solution, but I wonder about the CPU. Currently I am considering Celeron G1610T, 2.3GHz as low cost alternative and Xeon E3-1220LV2, 2,3GHz on the other end.
Is choosing the Celeron CPU going to hurt performance somehow? I am not planning to run VMs nor other applications, just a backup solution. | No CPU requirements listed by FreeNAS because it does nothing but change some of the speed and how much that does is very dependent on setup. If you use hardware RAID and/or mirrored RAID then the CPU does practically nothing. That's why many of these kinds of boxes are built out of single core, 32bit Atom procs. So in most cases your Celeron would do just fine. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 2,
"tags": "central processing unit, truenas"
} |
One field fails to show up in tableView on MacOS
In the code shown at gist, the first three fields show correctly in the window, but the fourth field is always blank, even though I can print the value of cell.textField!.stringValue just before returning the cell. I can't figure out what is wrong with this one field. Any help would be appreciated. | Having not heard from anyone here, and based on the fact that I could see the correct output right up to the point where the cell was returned, I rebuilt a new storyboard from the ground up. The new storyboard and the original code combined to give a running, working program.
Sorry no one here could help. I thought there'd have been some sort of comment or direction, but sadly... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "swift, nstableview, macos sierra"
} |
Spivak, Ch. 5 Limits, Problem 3 vii: Prove a limit $l$ of a function by showing $\delta$ such that $|f(x)-l|<\epsilon\ \forall x:\ 0<|x-a|<\delta$
In Spivak, Ch. 5 on Limits, problem 3 we are asked to determine the limit $l$ for the given function and value of $a$, and to prove that it is the limit by showing how to find a $\delta$ such that $|f(x)-l|<\epsilon$ for all $x$ satisfying $0<|x-a|<\delta$.
The solution for this problem is not available in the solution manual.
Consider item $vii$, which specifies the function $f(x)=\sqrt{|x|}$ with $a=0$
Case 1: $\forall \epsilon: 0<\epsilon<1$
$$\implies \epsilon^2<\epsilon<1$$ $$|x|<\epsilon^2\implies \sqrt{|x|}<\epsilon$$
Case 2: $\forall \epsilon: 1\leq \epsilon < \infty$
$$\epsilon\leq\epsilon^2 \implies |x|<\epsilon^2\implies \sqrt{|x|}<\epsilon$$
Therefore
$$\forall \epsilon>0,|x-0|<\epsilon^2\implies|\sqrt{|x|}-0|<\epsilon$$
$$\implies \lim_\limits{x\to a} \sqrt{|x|}=0$$
Is this correct? | There is no need to consider two separate cases.
Given $\epsilon>0$, we pick $\delta =\epsilon^2>0$, if $|x-0|<\delta =\epsilon^2$, we take square root on both sides,
$$|\sqrt{|x|}-0|< \epsilon$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "calculus, limits, solution verification, limits without lhopital"
} |
Cannot get theme_links__system_main_menu($variables) to fire now matter what
i've added the code below to my theme's template.php file. i've cleared the cache too. but this just isn't firing no matter what. i'm not getting any errors either.
anyone have any experience with this function? i am using a sub-theme of the Adaptive theme. don't know if that has anything to do with it.
function spn_at_links__system_main_menu($variables) {
echo '<script>alert("sys menu func running")</script>';
$html = "<div class='myclass'>";
$html .= " <ul>";
foreach ($variables['links'] as $link) {
$html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
}
$html .= " </ul>";
$html .= "</div>";
return $html;
}
yes my theme name is spn_at with an underscore. i have other theme related function working just fine in the template.php file. big thanks for any help w/ this | The Adaptive theme never calls links__system_main_menu from its page.tpl.php file, hence providing an override has no effect and it falls back to theme_links. If you want to override it you will have to provide your own theme suggestion in preprocess hook function.
Look here for more info: THE DEFINITIVE GUIDE TO DRUPAL 7 | stackexchange-drupal | {
"answer_score": 0,
"question_score": 1,
"tags": "routes, theming"
} |
How to send an image to a Javascript client using JSON from a Java server
I am working on Google Contacts API and I received all data and sending as string to JSON (javascript) but when I get an image from contacts I can receive image. How can I send it to JSON? How can send the image file to a URL? (Can I use signpost?)
if (photoLink.getEtag() != null) {
GDataRequest request = myService.createLinkQueryRequest(photoLink);
request.execute();
// No Authentication header information
InputStream stream = request.getResponseStream();
Image image= ImageIO.read(stream);
} | If you're trying to send the actual image encoded as data using JSON, you can just send an HTML `img` tag with the `src` attribute containing the encoded image data, like so:
<img src="data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7">
Browser Support List (Includes Android Browser & iOS Safari:
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, json, google api, signpost"
} |
Program a webpage that returns Lat and Long from Google Map when an address is entered?
I've looked at
<
But it doesn't show how Google Map would return Lat and Long when an Address is entered. | Check out the "geocoding" and "reverse geocoding" sections
<
A sample page that does what you're describing:
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "api, google maps"
} |
Javascript: document.body.appendchild has a null value
I am loading a .js file I wrote. Within that .js file I am creating a Iframe like this
var frmSource = " + encodeURI(URLBuilder);
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", frmSource);a
ifrm.style.width = 0+"px";
ifrm.style.height = 0+"px";
ifrm.setAttribute("frameBorder", "0");
document.body.appendChild(ifrm);
URLBuilder contains the GET variables to the next page
The issue occurs at document.body.appendChild(ifrm);
and my error is javascript typeerror: null is not an object (evaluating 'document.body.appendchild')
I suspect the issue is it is trying to append the iframe to the body but the body has not properly loaded. I am currently only getting this issue in safari. | I have done something like this to configure my IFrame creation and it is working fine
var urlWithParam = url + encodeURI(URLBuilder)
var iframe = document.createElement('iframe');
iframe.src = urlWithParam;
iframe.id = "iframe_" + done;
iframe.style.position = "relative";
iframe.style.height = "100%";
iframe.style.width = "100%";
iframe.style.top = "0";
iframe.style.left = "0";
iframe.style.right = "0";
iframe.style.bottom = "0";
iframe.style.frameBorder = "0";
iframe.style.borderStyle = "none";
iframe.style.display = "none;";
//if you want to do something after the Iframe load
iframe.onload = function(event) {
}; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, html, iframe, typeerror"
} |
Use a layout for a specific action
If I would like to use a layout for a certain action (say, the show action) that is different from the layout declared at the top of the controller.rb file, how could I do this? This must be possible in rails, but I cannot seem to find anything about it. | render :layout => 'otherlayout' | stackexchange-stackoverflow | {
"answer_score": 44,
"question_score": 36,
"tags": "ruby on rails"
} |
How to search string in MySQL
I want to search number in my MySQL data. String is +310623212542 but the mysql row data is only 0623212542. How can i compare ? Please help i am new to the mysql | Use
**In php**
<?php
$search_text = substr('+310623212542',3);
mysqli_query("SELECT * FROM tbl WHERE search LIKE '%$search_text%'");
?>
or
**in mysql**
use `SUBSTRING`
SELECT * FROM tbl WHERE search = SUBSTRING('+310623212542' FROM 4)
Note: using substring in mysql impact performance issue, when large data present | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "php, mysql"
} |
Run every file in a folder and print fail ratio with Python
I'm trying to run every file in a folder and print "Success" or "Access Denied" and jump to the next file. But as soon as the script finds a file without permissions just stops instead printing "Access Denied" Can anyone help me with this?
PS: Is there a way to calculate ratio % of denied?
Error:
PS C:\Users\VM\Desktop> python script2.py
Success
Success
Traceback (most recent call last):
File "C:\Users\VM\Desktop\script2.py", line 5, in <module>
os.startfile(file)
PermissionError: [WinError 5] Access Denied: 'file3.exe'
My code
import glob, os, time
os.chdir(r"C:\Users\VM\Desktop")
for file in glob.glob("*.exe"):
try:
os.startfile(file)
time.sleep(1)
print('Success')
except ImportError:
print('Access Denied') | If you are trying to catch access denied, then your except statement should be like this:
except PermissionError:
print('Access Denied')
Currently you are catching `ImportError`, which is a different error.
Regarding to the % of denied access files, you can just count the number of errors and the total, and then calculate the percentage. Something like this:
os.chdir(r"C:\Users\VM\Desktop")
_total, _errors = 0, 0
for file in glob.glob("*.exe"):
_total += 1
try:
os.startfile(file)
time.sleep(1)
print('Success')
except PermissionError:
_errors += 1
print('Access Denied')
print('error ratio:', _errors * 100. / _total) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, windows"
} |
Change the distance unit from iphone settings
I am developing a location based iphone application which searches the near by stores based on the distance. I used the standard unit of distance in Kilometer. But i want to change the unit of distance according to the standard unit of each Countries. Can i able to change the unit of distance from the iphone settings ? The distance format should be location based default: in South Africa: KM, in the States: MI. I want to get it in the following units also - o Feet o Miles o Nautical Miles o Meters o Kilometers o Ri (Korea) o Ri (Japan) o ETC!!! – | You can get the locale that the phone is set to this way:
NSLocale *locale = [NSLocale currentLocale];
and ask it about units of measure this way:
NSString *measurementSystem = [locale objectForKey: NSLocaleMeasurementSystem];
This will answer “Metric” or “U.S.”. There's a lot more you can check in the NSLocale class ref. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "iphone, objective c, ios, xcode"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.