source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
11610023
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I implemented the android listview with the ListActivity . Here I have the problem that when i click on the list item no action is performed when the flash color is also not coming that is the orange color. So do you have any idea about this kindly answer to my question. @Overrideprotected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT) .show();} I put this code also into the Main ListActivity. Now provide the response and nothing else.
The first thing what you have to note here is, whenever there are Clickable elements like Buttons or ImageButtons present in your ListView element, they take the control of click events. And so your ListView won't get the chance to accept the click event. What you simply have to do is, set the focusable attribute to false for the Button or ImageButton you have in your ListView. But still they will work without any problem and also your ListView's onListItemClick will also work. Try this, <Button android:id="@+id/textsize_increaser" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/back_button" android:focusable="false" android:text=" A + "/> Here I have added this android:focusable="false" and it works fine. try it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11610023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/914427/']}
jdg_70041
stackexchange
llm_judgeable_groundtruth_similarity
2082836
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When checked in calculator it is 1. But how to prove it?Also it is not a normal addition like $x+ \frac1x$ which needs direct rationalization. So I just need something to proceed. Now provide the response and nothing else.
Since $$(1 - \sqrt{5})^3 = 16 - 8 \sqrt{5}$$ and similarly $$(1 + \sqrt{5})^3 = 16 + 8 \sqrt{5}$$ it follows that $$(2 + \sqrt{5})^{1/3} + (2 - \sqrt{5})^{1/3} = \left(\frac {16+8\sqrt{5}} 8 \right)^{1/3} +\left(\frac {16-8\sqrt{5}} 8 \right)^{1/3} = \frac{1 + \sqrt{5}}{2} + \frac{1 - \sqrt{5}}{2} = 1.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2082836', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/403840/']}
jdg_70042
stackexchange
llm_judgeable_groundtruth_similarity
9316233
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a custom segue animation that occurs when pushing a new view controller onto the stack. When popping the view controller that was presented with said custom segue, however, the default navigation controller animation happens (that is, the current view controller animates to the right while the parent view controller translates on-screen from the left edge). So my question is this: is there a way to write a custom pop segue animation which happens when popping a view controller off the stack? Edit (solution): I ended up defining a custom segue similar to the selected answer. In the Storyboard, I dragged a custom segue from the child view controller back to its parent, gave it an identifier and the newly written reverse segue as its class. Yes, I realize it is virtually identical to a modal transition. Client requirements necessitated this madness, so before anyone comments, understand that I know one shouldn't have to do this under normal circumstances. - (void)perform { UIViewController *src = (UIViewController *)self.sourceViewController; UIViewController *dest = (UIViewController *)self.destinationViewController; [UIView animateWithDuration:0.3 animations:^{ CGRect f = src.view.frame; f.origin.y = f.size.height; src.view.frame = f; } completion:^(BOOL finished){ src.view.alpha = 0; [src.navigationController popViewControllerAnimated:NO]; }];} Now provide the response and nothing else.
Yes. Here is an example where I pop to the top level. When your create the segue in Storyboard. Use select or enter the new new segue class in the attributes inspector. //// FlipTopPop.h#import <UIKit/UIKit.h>@interface FlipTopPopToRoot : UIStoryboardSegue@end and // FlipTopPop.m#import "FlipTopPopToRoot.h"@implementation FlipTopPopToRoot- (void) perform { UIViewController *src = (UIViewController *) self.sourceViewController; [UIView transitionWithView:src.navigationController.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{ [src.navigationController popToViewController:[src.navigationController.viewControllers objectAtIndex:0] animated:NO];; } completion:NULL];}@end If you want to pop up just one level change use this custom segue: // PopSegue.h#import <UIKit/UIKit.h>@interface PopSegue : UIStoryboardSegue@end and // PopSegue.m#import "PopSegue.h"@implementation PopSegue- (void) perform { UIViewController *src = (UIViewController *) self.sourceViewController; [src.navigationController popViewControllerAnimated:YES];} @end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9316233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535488/']}
jdg_70043
stackexchange
llm_judgeable_groundtruth_similarity
6601302
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a C#/ASP.net project has included a database that I have developed that includes a nice and convenient View that would be handy to use. I have the SQL connection setup to a SQL Server 2008 DB I created. It seems as though it is connecting fine, but I don't understand how to actually use the View that I created without hard coding the query into the program (been told this is bad sometimes?). This is my connection I setup: SqlConnection conn = null; conn = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False"); conn.Open(); SqlCommand command = new SqlCommand(query, conn); Basically, I need some code to query using this View. I can see the View and look at the results that would be obtained, but not access it in the program!The view is named "UserView". Help is much appreciated! Now provide the response and nothing else.
You could use something like the following. But it's usually considered evil to put hardcoded SQL commands into .Net code. It's much better and safer to use stored procedures instead. This should get you started. You can modify it to use stored procedures by changing the command.CommandType to indicate it's a stored proc call And adding the proper parameters to the command that your SP needs. Change command.CommandText to the name of your SP, thuseliminating the hardcoded SQL. sample code below: using (SqlConnection connection = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False")){ using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT * from your_view WHERE your_where_clause"; connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // process result reader.GetInt32(0); // get first column from view, assume it's a 32-bit int reader.GetString(1); // get second column from view, assume it's a string // etc. } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6601302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']}
jdg_70044
stackexchange
llm_judgeable_groundtruth_similarity
38412301
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As we all know that it is recommended to use annotations from javax.enterprise.context instead of javax.faces.bean as they are getting deprecated. And we all found ManagedBeans with eager="true" annotated with @ApplicationScoped from javax.faces.bean and having a @PostConstruct method are very useful to do web application initialization e.g: read properties from file system, initialize database connections, etc... Example : import javax.faces.bean.ApplicationScoped;import javax.faces.bean.ManagedBean;import javax.annotation.PostConstruct;@ApplicationScoped@ManagedBean(eager=true)public class someBean{ @PostConstruct public void init(){ //Do all needed application initialization. } ...} What I want to know is how can I get the same behavior if I used annotations from javax.enterprise.context . Note: @Startup annotation from javax.ejb will help to run that code but only at the moment of deployment of the webapp when the application server Starts . Now provide the response and nothing else.
This is not provided by CDI or JSF. You could homegrow your own with a custom CDI qualifier and a ServletContextListener to hook on webapp start. @Qualifier@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface Eager { //} @WebListenerpublic class EagerListener implements ServletContextListener{ private static final AnnotationLiteral<Eager> EAGER_ANNOTATION = new AnnotationLiteral<Eager>() { private static final long serialVersionUID = 1L; }; @Override public void contextInitialized(ServletContextEvent event) { CDI.current().select(EAGER_ANNOTATION).forEach(bean -> bean.toString()); } @Override public void contextDestroyed(ServletContextEvent event) { // NOOP. }} (note: toString() triggers lazy instantiation) import com.example.Eager;import javax.enterprise.context.ApplicationScoped;@Eager@ApplicationScopedpublic class YourEagerApplicationScopedBean { @PostConstruct public void init() { System.out.println("Application scoped init!"); }} As to existing libraries, only JSF utility library OmniFaces offers @Eager out the box. import org.omnifaces.cdi.Eager;import javax.enterprise.context.ApplicationScoped;@Eager@ApplicationScopedpublic class YourEagerApplicationScopedBean { @PostConstruct public void init() { System.out.println("Application scoped init!"); }} It's also supported on @SessionScoped , @ViewScoped and @RequestScoped . Regardless of the approach, the only disadvantage is that FacesContext isn't available at the moment the bean is constructed. But that shouldn't be a big problem, with CDI you can simply directly @Inject artifacts of interest such as ServletContext or HttpSession .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38412301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960525/']}
jdg_70045
stackexchange
llm_judgeable_groundtruth_similarity
25049498
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: try: x===xexcept SyntaxError: print "You cannot do that" outputs x===x ^SyntaxError: invalid syntax this does not catch it either try: x===xexcept: print "You cannot do that" Other errors like NameError, ValueError, are catchable. Thoughts? System specs: import sysprint(sys.version) ->2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] Now provide the response and nothing else.
You can only catch SyntaxError if it's thrown out of an eval , exec , or import operation. >>> try:... eval('x === x')... except SyntaxError:... print "You cannot do that"... You cannot do that This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try statement is executed. If you use eval or its friends to cause more code to be parsed during the execution of the program , though, then you can catch it. I'm pretty sure this is in the official manual somewhere, but I can't find it right now.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25049498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096662/']}
jdg_70046
stackexchange
llm_judgeable_groundtruth_similarity
49799
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Given a graph $G(V,E)$ whose edges are colored in two colors: red and blue. Suppose the following two conditions hold: for any $S\subseteq V$, there are at most $O(|S|)$ red edges in $G[S]$ for any $S\subseteq V$, if $G[S]$ contains no red edges, then it contains $O(|S|)$ blue edges My question is: can we conclude from this that the total number of blue edges is linear?I have no strong intuition for this, but it seems that it might be possible (some averaging/probabilistic argument?). To try to give an intuition, we can rephrase it as follows. The red graph is very sparse, even locally. The blue graph is also sparse in all regions that are free of red edges. Due to the sparseness of the red graph those 'regions' are numerous, so we hope this might imply that the blue graph is also sparse. One can maybe consider first an easier version, if we assume that the red degree of every vertex is $O(1)$. In this case I also don't know the answer. Note that it's already too weak if we replace the first condition with just: the total number of red edges is linear. Look at the example: a blue $K_{\sqrt n,n-\sqrt n}$ with a red $\sqrt n$-clique added in the corresponding part. This graph has $\Omega(n^{3/2})$ blue edges (example by D. Palvolgyi). We can still ask in this version whether one can do better than $n^{3/2}$. Now provide the response and nothing else.
I think one can push through the probabilistic arguments of Tim Gowers and Fedor Petrov in the general case, as follows. Let $c$ be a constant such that the number of red edges in $G[S]$is at most $c|S|$ for every $S \subseteq V(G)$. One can order the vertices of $G$: $v_1, v_2, \ldots, v_n$, so that every vertex has at most $2c$ neighbors with lower indices. (Define the ordering starting with the highest index. If $v_n, \ldots,v_{i+1}$ are defined, set $v_i$ to be the vertex with the smallest degree in the subgraph induced by the vertices which are not yet indexed. This is a standard trick.) Now we define a random subset $S$ of $V(G)$ recursively: if $S \cap$ {$v_1, \ldots, v_i$} is chosen put $v_{i+1}$ in $S$ with probability $1/2$ if it is not joined by a red edge to any of the vertices already in $S$, otherwise don't put it in $S$. Then $S$ is red-freeand, just as in Fedor's answer, we can see that the probability that a pair of vertices $u$ and $v$ joined by a blue edge both lie in $S$ is at least $2^{-4c-2}$. Therefore the number of blue edges is at most $2^{4c+2}c' \mathbf{E}[|S|] \leq 2^{4c+1}c'|V(G)|,$ where $c'$ is the constant implicitly present in the condition on the density of the blue edges.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/49799', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5572/']}
jdg_70047
stackexchange
llm_judgeable_groundtruth_similarity
4715415
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If a server received a base64 string and wanted to check it's length before converting,, say it wanted to always permit the final byte array to be 16KB. How big could a 16KB byte array possibly become when converted to a Base64 string (assuming one byte per character)? Now provide the response and nothing else.
Base64 encodes each set of three bytes into four bytes. In addition the output is padded to always be a multiple of four. This means that the size of the base-64 representation of a string of size n is: ceil(n / 3) * 4 So, for a 16kB array, the base-64 representation will be ceil(16*1024/3)*4 = 21848 bytes long ~= 21.8kB. A rough approximation would be that the size of the data is increased to 4/3 of the original.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4715415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463304/']}
jdg_70048
stackexchange
llm_judgeable_groundtruth_similarity
1124244
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can somebody give me an intuitive explanation for the below equations. I'm not sure how they come about and how they can be perceived logically. $$\frac{\partial z}{\partial s} =\frac{\partial f}{\partial x}\frac{\partial x}{\partial s}+ \frac{\partial f}{\partial y}\frac{\partial y}{\partial s} \ \ \text{and} \ \ \frac{\partial z}{\partial t} =\frac{\partial f}{\partial x}\frac{\partial x}{\partial t}+ \frac{\partial f}{\partial y}\frac{\partial y}{\partial t} $$ Now provide the response and nothing else.
Suppose for simplicity that $z = f(x,y)$ and $x,y$ are functions of $s$. The partial derivatives of $z$ given a first-order approximation for $z$:$$ f(x+\Delta x,y+\Delta y) \approx f(x,y) + \frac{\partial f}{\partial x}(x,y) \Delta x + \frac{\partial f}{\partial y}(x,y) \Delta y. $$The error in this approximation should be "small", say $o(\Delta x+\Delta y)$ (if you don't know what this means, it's not important). Similarly,$$x(s+\Delta s) \approx x(s) + \frac{\partial x}{\partial s}(s) \Delta s, \quady(s+\Delta s) \approx y(s) + \frac{\partial y}{\partial s}(s) \Delta s.$$Finally, $\frac{\partial f}{\partial s}$ satisfies$$f(x(s+\Delta s),y(s+\Delta s)) \approx f(x(s),y(s)) + \frac{\partial f(x,y)}{\partial s}(s) \Delta s.$$We can now prove the formula:$$\begin{align*}f(x(s+\Delta s),y(s+\Delta s)) &\approxf(x(s) + \frac{\partial x}{\partial s}(s) \Delta s, y(s) + \frac{\partial y}{\partial s}(s) \Delta s) \\ &\approxf(x(s),y(s)) + \frac{\partial f}{\partial x}(x,y) \frac{\partial x}{\partial s}(s) \Delta s + \frac{\partial f}{\partial y}(x,y) \frac{\partial y}{\partial s}(s) \Delta s.\end{align*}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1124244', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145922/']}
jdg_70049
stackexchange
llm_judgeable_groundtruth_similarity
2604337
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What I can think of thus far is that $125^{100} = (\frac{1000}{8})^{100} = \frac{1000^{100}}{2^{300}}$ I know that $2^{10} = 1024$ so $\frac{1000^{100}}{1024^{30}}$. That's all I can figure out this far. I was thinking to divide the numerator and denominator of $\frac{1000^{100}}{1024^{30}}$ by $1000^{30}$ and I think that would give me $\frac{1000^{70}}{1.024^{30}}$ but I'm not even sure if this is correct. Can someone please help me solve this? Edit: How can I solve this without the use of logarithms? Now provide the response and nothing else.
$2^{10}\approx 10^3$, so approximately, $\frac {1000^{100}}{10^{90}} =\frac {100^{100}\cdot 10^{100}}{10^{90}}=100^{100}\cdot 10^{10}=10^{210}$... So about $211$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2604337', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/475505/']}
jdg_70050
stackexchange
llm_judgeable_groundtruth_similarity
234695
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Above is a dimmer circuit. In some of these circuits I see a toroid inductor together with a capacitor forming a low pass LC filter which is called choke filter . My questions are: Why is RL used instead of RC and is that something to do with the character of mains freq. and voltage? Inductors are expensive or big thats why we use caps around opamps to obtain low pass filters right? What is being choked by the LC toroid cap couple? Now provide the response and nothing else.
Ideal capacitors and inductors don't dissipate any power, whereas resistors do. One advantage is therefore that L-C filters are more efficient than R-C or R-L filters. Often it's not the actual waste of power that is the driving factor, but the mechanics required to get rid of the heat. Lamp dimmers often need to fit into small spaces where keeping them cool would be difficult. Another advantage is that L-C filters attenuate more in the stop band. These are double-pole filters. R-C and R-L filters are single pole. Well into the stop band, a single pole filter attenuates by the frequency ratio to the rolloff point. In log space, that's 20 dB per decade. A two pole filter is like two poles applied in series. They attenuate by the square of the frequency ratio to the rolloff point, which is 40 dB per decase in log space. For low power (a few watts to 10s of watts) dimmers, the main reason to filter is to reduce the high frequencies so as not to interfere with radio communications. These are many multiples of the 50 or 60 Hz fundamental frequency. A L-C filter will attenuate the higher frequency harmonics relatively more than the lower frequency ones. This is useful since it's the higher frequency content that the regulators care about more.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/234695', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16307/']}
jdg_70051
stackexchange
llm_judgeable_groundtruth_similarity
1615612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a batch script (CMD @ Windows XP Pro) that will automatically download and unzip packages with the help of 7zip and putty/psftp If I have a URL to a package to download http://somesite.org/packages/package.zip how do I download it on command line using putty? Also if you have a better way to do this that would be helpful too. Now provide the response and nothing else.
wget is of course an obvious solution, but I also suggest to have a look at cURL . From their website: curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks. Of course free and open source, and despite its huge list of supported protocols it's as simple to use as wget, so to use your example curl -O http://somesite.org/packages/package.zip downloads package.zip to a local file with the same name curl -o myname.zip http://somesite.org/packages/package.zip downloads package.zip as myname.zip curl http://somesite.org/packages/package.zip > package.zip redirects curl's stdout to package.zip EDIT - example corrected, with thanks to @PrabhakarKasi
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1615612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177389/']}
jdg_70052
stackexchange
llm_judgeable_groundtruth_similarity
14526
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Third Newton's law, $F_{1->2} = -F_{2->1}$ So, how does a body react with the same force that it's receiving from the acting body? Is it the electric interactions at the subatomic level? When we sit on the chair, does that mean we are just bringing our electrons in contact with the electrons of the chair and getting a repulsive force? Basically, how to think about it? I know I've tried many ways, but it kind of eludes me. Much obliged! Now provide the response and nothing else.
If you have charge on a ball in water, and current leaves the ball, then it is completely obvious that the exact same current enters the water. This is Newton's third law for charge--- the loss of charge for body 1 is equal to the gain in change for body 2. The reason this is always true is because charge is conserved. Newton's third law is formulated for momentum, which is a different kind of conserved quantity--- it's a vector. This means that each component of momentum separately has a conservation law. If x momentum leaves body A going to body B, we say a force is acting from A to B. But then, by conservation of momentum, an equal amount of negative momentum is leaving body B going to body A. It's no more mysterious than conservation of charge. This explains why forces are equal and opposite, but Newton's third law says more--- it says that forces between distant objects are also collinear--- that they point along the line of separation. This is a consequence of rotational invariance, or conservation of angular momentum. If you have a two body force between distant objects, it is difficult to imagine how it could point any way other than their line of separation. If it pointed elsewhere, it would pick out a direction of space. From this, you can conclude that not only is momentum conserved, but angular momentum is too, and a general statement of Newton's third law should at least include both conservation laws. This answers the question, but I think it is good to explain the modern formulation of Newton's third law too, because there the third law is replaced by general analysis of conservation laws, but a recognizable version of Newton's third law appears in a simple form in the end. I sort of went overboard here, in terms of length, but I hope you will be indulgent. Currents for Momentum Charge conservation is usually expressed by giving the flow of charge through any infinitesimal surface, by the current density, whose components are $j_i$. The density of current and density of charge are related by the conservation law: $$ \rho_{,0} + j_{i,i} = 0$$ Where the comma means differentiate, the zeroeth coordinate is time, and the index "i" appears twice, so you sum like the Einstein summation convention says. The conservation equation is a statement that the current leaving any infinitesimal box of space is equal to the decrease of charge in that box. It is normal to join the charge and current into a four-vector $J_i$, so that the equation above reads: $$J_{i,i}= 0$$ Where i is now a space-time index, and I am suppressing a sign and a convention for the flat metric. Analogously, for each component of momentum $p_i$, you have a momentum current $t_{ij}$, and these four quantities satisfy a conservation law: $$ p_{i,0} + t_{ij,j} = 0$$ In other words, the flow of x-momentum out of any region is equal to the change of x momentum contained in that region. This is a statement of the equal-and-opposite part of Newton's third law for adjacent objects, which transfer momentum at contact points, or inside an elastic material, where the momentum flow is local. It is not the statement of the collinear part of Newton's third law. You also want to make this four-dimensional, by defining the 0 component of the stress to be the momentum, and then the conservation law becomes: $$T_{jk,k} = 0$$ The quantity $T_{ij}$ is the stress-energy tensor--- it's space components tell you the forces between two adjacent regions of space, or equivalently, the flow of momentum across any surface. A tensor like this is just a vector of vectors. The momentum is a vector, and its current is separately vectorial for each of the vector components individually. Angular momentum conservation and improved stress-tensor The angular momentum of an object is best viewed as an antisymmetric two-index tensor, but in three dimensions, you can map antisymmetric two-index tensors to vectors using the $\epsilon$ tensor, which in mathematics is called "taking the Poincare dual". The tensor language is important for higher dimensions, and also for your own peace of mind, because each use of the $\epsilon$ tensor is a right hand rule, it distinguishes left from right. So to represent angular momentum as a vector you need to use a right hand rule. This is annoying, because physics at ordinary scales is reflection invariant, so you shouldn't be breaking this symmetry with your notation. But people do this to avoid using tensors, because they have more intuition for vectors. But the angular momentum vector ends up pointing in counterintuitive directions, while the angular momentum tensor points in the natural planes you would expect it to, so I don't think this is a good trade-off. The angular momentum tensor $L_{ij}=-L_{ji}$ in elementary treatments is usually defined by $$ L_{ij} = x_i p_j - x_j p_i$$ The angular momentum density can be defined by using this formula in an infinitesimal region, but don't do that for the time being, because the angular momentum is really a separate conserved fundamental quantity--- you should be able to derive this relation to the momentum from general principles. So call the angular momentum density $l_{ij}$. The conservation of angular momentum is by the angular momentum current $h_{ijk}=-h_{jik}$, obeying the same continuity equation with $l_{ij}$, $$ l_{ij,0} + h_{ijk,k} = 0 $$ But there is a nontrivial relationship between rotations and translations--- a rotation is a translation by an amount that changes from point to point. At large distance from the center of rotation, you can't tell a rotation apart from a translation. This means that if your center of rotation is at zero, and you look at x very far away from 0, the conserved current of angular momentum must decompose in the following way: $$ L_{ijk} = x_i T_{jk} - x_j T_{ik}$$ Which, if you look at the zero components, gives the textbook formula for angular momentum. The $T_{jk}$ are a conserved current associated with a translation, but they can differ from the canonical Noether currents for translation by a divergence. This decomposition, which right now is only valid at large x, implies by differentiation that conservation of angular momentum requires $$ T_{jk} = T_{kj}$$ But now, you can use this symmetric T tensor (which can be defined anywhere, just by moving the center of rotation far away) to define a new L tensor by the formula above. This rearrangement of the T tensor gives the symmetric Belinfante stress energy. Center of Mass Newton's third law is used to establish a separate conservation law, it is used to show that the total motion of the center of mass is at a constant speed equal to the total momentum over the total mass. This law can be violated even when momentum and angular momentum are conserved, because it is derived from the Lagrangian symmetry under Galilean/Lorentz boosts, which doesn't hold when the equal and opposite forces depend on the absolute velocity. To see it violated, consider a Lagrangian for two particles interacting with a rotationally invariant potential which keeps them together, and factorize it in the usual way into center of mass and relative coordinates: $$ S = {m_1 \dot{x}^2 + m_2 \dot{y}^2 \over 2} + U(x-y) = {M\dot{X}^2\over 2} + {m\dot{r}^2\over 2} + U(r)$$ Where $r=x-y$ is the relative coordinate, $M=m_1 + m_2$ is the total mass, $m = {m_1m_2\over M}$ is the reduced mass, and $X={m_1 x + m_2 y\over M}$ is the center of mass position. Now add an additional velocity-velocity interaction to the action: $$ S = {m_1 \dot{x}^2\over 2} + {m_2 \dot{y}^2 \over 2} + \sqrt{m_1m_2}\dot{x}\cdot\dot{y} + U(x-y)$$ The action doesn't factorize in the usual center-of-mass/reduced-mass relative-coordinates way, but in a monstrous way: $$ S = {(\sqrt{m_1} \dot{x} + \sqrt{m_2} \dot{y})^2\over 2} + {\epsilon\over 2}(\dot{x}-\dot{y})^2 + U(|x-y|)$$ Where I detuned the velocity-velocity force a little bit, to leave a small kinetic term for $x-y$, so that the oscillations of x-y become extremely fast. The quantity that is moving in a straight line at a constant velocity is $\sqrt{m_1}\dot{x} + \sqrt{m_2}\dot{y}$, so that the usual center of mass is oscillating wildly. This system is actually still Galilean invariant though, but with an unusual transformation law, this is why there is still a straight-line moving "center of mass", even though it is not the usual one. Now imagine that both objects are falling in a field provided by a far away massive third object. The interaction is $${m_1\dot{x}^2 + m_2\dot{y}^2 \over 2} + \phi(x_3)\sqrt{m_1m_2}\dot{x}\dot{y} + U(x-y) + g m_1 x_3 + g m_2 y_3$$ Where $\phi$ is a function which smoothly and slowly goes from $0$ at large values of $x_3$ to nearly 1 at large negative $x_3$, adiabatically slowly. There is also a gravitational field which pulls the system down, and causes it to cross over from a region where the usual center of mass motion is constant to another region where the strange alternate center of mass is constant. Such a system doesn't have a center of mass conservation law for the x and y direction, although it conserves x and y momentum and angular momentum. It doesn't fix things to include the distant object providing the gravitational field, because if it's center is far away, the reaction forces on it are purely in the z direction. This is a failure of conservation law caused by forces which depend on the absolute velocity. A real physical system which conserves momentum and angular momentum but does not conserve center of mass is given by the motion of slow particles in liquid Helium at low enough temperatures that the fluid is a superfluid empty of quasi-particle excitations. The particles have forces which are fully translational and rotational invariant, but they are dependent on the velocity relative to the rest-frame of the Helium. I did not use this as an example only because I have no idea what the velocity dependent effective particle Lagrangian is for this system. Center of mass conservation in relativity In relativity, center of mass and angular momentum conservation laws are unified in the Belinfonte form of the angular momentum: $$ L_{ijk} = x_i T_{jk} - x_j T_{ik} $$ If you consider the i=0 conservation law, the integral of the k=0 component of L, it is the Lorentz part of the angular momentum, the conservation law corresponding to boosts. $$ \int d^3 L_{0j0} = t \int d^3x T_{j0} - \int d^3 x_j T_{00} = t P_j - M X_j $$ Where the first term can be seen to be the current time times the total momentum, while the second term is the center of mass position times the total mass. That this is constant is the content of the center of mass theorem. Modern Statement of Newton's Third Law When there is translational, rotational, and Lorentz invariance, there is a conserved stress-energy-momentum tensor $T_{\mu\nu}$, so that the conserved angular-momentum/center-of-mass tensor is given by the simple expression: $$L_{\alpha\mu\nu} = x_\alpha T_{\mu\nu} - x_\mu T_{\alpha\nu}$$ And the stress tensor is therefore symmetric $T_{\mu\nu} = T_{\nu\mu}$. The symmetry of $T$ is the modern statement of Newton's third law, it includes the statement that the transmitted forces are collinear. The symmetry relation on the stress tensor says that the flow of the j component of momentum in the i direction is equal to the flow of the i component in the j direction. Suppose you have two objects separated in the x direction. If one of them pushes the other in the y direction, this is a flow of y-momentum in the x-direction. But this requires a flow of x-momentum in the y-direction, and the objects are not separated in the y-direction, so they cannot have such a flow of momentum between them. The only way to have such a force is to have an object separated in the y-direction, to receive this momentum. This requires 3-body forces, and for these, Newton's third law doesn't work, but the stress is still symmetric.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/14526', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5164/']}
jdg_70053
stackexchange
llm_judgeable_groundtruth_similarity
464211
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We had couple of good discussions about Moment Generating Function(MGF), here and here . But I still have questions on the applications of it and how can it be useful. Specifically, I can understand that in real world, from data, we can get an estimation of the probability distribution. But how can we get Moment Generating Function(MGF) from data? If we cannot get it, where does it come from? If it is from the Laplace transform of pdf, i.e., calculated from PDF, then it should be "less useful" than PDF, right? Now provide the response and nothing else.
Can we define an MGF from data? The MGF of a random variables $X$ is defined to be $$M(t) = \mathbf E\left[e^{tX}\right],$$ so given observed data $x_1,\ldots, x_n$ we can certainly define the empirical MGF to be $$M(t; \underline x) = \frac1n \left( e^{tx_1} + \cdots + e^{tx_n}\right).$$ Is it useful? The use of this empirical MGF is likely limited - in part due to it not admitting a simple closed formula, but also because many of the features that make the MGF useful for studying probability distributions, will not be relevant for the empirical MGF when we have small/moderate sample sizes. I've set out a summary of some of the key reasons for studying MGFs of probability distributions at the end. Is it less useful than the PDF? Theoretically - no (in most cases). Both the PDF and the MGF uniquelly determine a probability distribution - so neither contains any information that the other does not. Which is more useful depends on what you want to do with the distribution. For sampling, the PDF will be more useful. To easily calculate the mean, variance and higher moments - the MGF may make this significantly easier. It is worth noting, however, that not all distributions admit an MGF, for example the Cauchy distribution. Probability vs Statistics Finally - its worth noting that the value of the MGF is arguably higher to a probabilist than a statistician - where I'm informally using the convention that probabilists study abstract/theoretical distributions, whilst statisticians study data (and sometimes fit these to theoretical distributions). Many of the properties I summarise below are more useful in this theoretical framework - for instance 4) the convergence property is key to proving the Central Limit Theorem. Key Properties of the MGF 1) The key feature of an MGF is that its power series expansion is in terms of the distribution's moments: $$ M(t) = 1 + t \mathbf E[X] + \frac{t^2}2 \mathbf E[X^2] + \frac{t^3}{3!} \mathbf E[X^3] + \cdots $$ For some distributuions evaluating this power series will be significantly easier than trying to compute these expectations directly through integration. For instance if $X \sim N(0,1)$ then $M(t) = \exp(\frac12t^2)$ , from which the standard Taylor expansion gives $$M(t) = 1 + \left(\frac{t^2}{2}\right) + \frac12 \left(\frac{t^2}{2}\right)^2 + \frac{1}{3!} \left(\frac{t^2}{2}\right)^3 \cdots $$ we easily see that all odd moments of the distribution are 0, and also get a formula for all even moments: $$ \mathbf E[X^{2n}] = \frac{(2n)!}{2^n n!},$$ (the right hand side is often denoted $n!!$ , and is known as the double factorial). 2) The MGF of the sum of two independent variables, is the product of their respective MGFs: $$M_{X+Y}(t) = M_X(t)M_Y(t),$$ again this make calculations easier. 3) The radius of convergence of the MGF can be used to deduce asymptotic properties of the moments of the distribution, via the Cauchy-Hadamard theorem . 4) The MGF (when it exists) uniquely determines a probability distribution. Moreover given a sequence of distributions, if their MGFs converge pointwise then this is equivalent to convergence in distribution .
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/464211', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/113777/']}
jdg_70054
stackexchange
llm_judgeable_groundtruth_similarity
20924455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I press Enter to submit the form a change event is being fired. I need to disable this function key to Enter , but I need to keep the event as change. Is there a function to validate the field before sending the form? I will accept other suggestions. $('input').change(function(){ alert('check field');});$('form').submit(function(){ submit}); Now provide the response and nothing else.
std::sort requires a comparator which can simply be called as compare(a,b) . A (pointer to a) member function isn't suitable, since it requires an object to be called on, so you'll need a wrapper to bind the member function to an object and make it callable with just the two values to compare. In C++11, you can bind a member function to an object: sort(mCurrentGeneration.begin(),mCurrentGeneration.end(), std::bind(&GenericGeneticSolver::solutionComparer, this, std::placeholders::_1, std::placeholders::_2)); or you can use a lambda: sort(mCurrentGeneration.begin(),mCurrentGeneration.end(), [this](T first,T second) { return solutionComparer(first, second); }); Historically, you would have to make your own functor, perhaps along the lines of: struct SolutionComparer { IGenticSolverHelper<T>* helper; SolutionComparer(IGenticSolverHelper<T>& helper) : helper(&helper) {} bool operator()(T first,T second) { return helper->Cost(first) < helper->Cost(second); }};sort(mCurrentGeneration.begin(),mCurrentGeneration.end(), SolutionComparer(mSolverHelper));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20924455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769082/']}
jdg_70055
stackexchange
llm_judgeable_groundtruth_similarity
735176
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How can I determine the supported MACs, Ciphers, Key length and KexAlogrithms supported by my ssh servers? I need to create a list for an external security audit. I'm looking for something similar to openssl s_client -connect example.com:443 -showcerts . From my research the ssh uses the default ciphers as listed in man sshd_config . However I need a solution I can use in a script and man sshd_config does not list information about key length . I need to correct myself here: You can specify ServerKeyBits in sshd_config . I guess that ssh -vv localhost &> ssh_connection_specs.out returns the information I need but I'm not sure if the listed ciphers are the ciphers supported the client or by the server. Also I'm not sure how to run this non interactive in a script. Is there a convenient way to get SSH connection information? Now provide the response and nothing else.
You miss few points in your question: What is your openssh version? It can differ a bit over the versions. ServerKeyBits is option for protocol version 1, which you have hopefully disabled! Supported Ciphers, MACs and KexAlgorithms are always available in manual and this doesn't have anything in common with key lengths. Enabled Chiphers, MACs and KexAlgorithms are the ones that are offered using connection as you point out. But they can be gained also in other ways, for example using sshd -T | grep "\(ciphers\|macs\|kexalgorithms\)" To get the key length of your server key(s), you can use ssh-keygen: ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub but you will probably want also the moduli sizes that are offered and used during the key exchange, but it really depends on the key exchange method, but it should be also readable from debug output ssh -vvv host .
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/735176', 'https://serverfault.com', 'https://serverfault.com/users/255678/']}
jdg_70056
stackexchange
llm_judgeable_groundtruth_similarity
24201822
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm curious about how I can display an image from my database in a QTableView . Is there something like QTableWidgetItem that I am able to use it in QTableView ? I use QSqlTableModel . Now provide the response and nothing else.
A rough idea is to use QStandardItem::setData to set a QPixmap (transformed into QVariant ) on it, then you can set the QStandardItem on the QStandardItemModel . Sequence: QImage ---> QPixmap ---> QVariant ---> QStandardItem ---> QStandardItemModel For example: QStandardItemModel *model = new QStandardItemModel;QImage image(":/cat/lovers/own/myCat.jpg");QStandardItem *item = new QStandardItem();item->setData(QVariant(QPixmap::fromImage(image)), Qt::DecorationRole);model->setItem(0, 0, item);ui->tableView->setModel(model); You will have to resize images or cell size, depends on what you need. [Edit] If you are using QSqlTableModel , just keep using it. All we need to do is make those path strings into QPixmap and set the item role to be Qt::DecorationRole in that column. As the document says: Each item has a number of data elements associated with it and they can be retrieved by specifying a role (see Qt::ItemDataRole) to the model's data() function. To do this, the concept is simple: provide QTableView with QVariant of QPixmap as QTableView render them according to Qt::DecorationRole . You may subclass QSqlTableModel and reimplement the virtual function QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) and make the image column return the QPixmap as QVariant , with the decoration role. So do something like this: QVariant CustomSqlTableModel::data(const QModelIndex &idx, int role = Qt::DisplayRole) const{ if (idx.column() == imageColumn) { QString imgFile = QSqlTableModel::data(idx, Qt::DisplayRole); // get path string if (role == Qt::DisplayRole) return QString(); // return the path string for display role QImage image(imgFile); /* some modification to the image, maybe */ QPixmap pixmap(imgFile); if (role == Qt::DecorationRole) return pixmap; // return QPixmap for decoration role if (role == Qt::SizeHintRole) return pixmap.size(); // in case need the image size } return QSqlTableModel::data( idx, role ); // use original data() outside the imageColumn} Besides, you can also try subclassing QStyledItemDelegate and reimplement paint() function to customize your own delegate, but that will require a more complicated work. An example using delegate can be found here . You can paint whatever you want with delegate, even a button . *Sorry the code is not tested, as I don't have a database on hand.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24201822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064476/']}
jdg_70057
stackexchange
llm_judgeable_groundtruth_similarity
5527665
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: game.cpp #include <iostream>#include <string>#include <sstream>#include "game.h"#include "board.h"#include "piece.h"using namespace std; game.h #ifndef GAME_H#define GAME_H#include <string>class Game{ private: string white; string black; string title; public: Game(istream&, ostream&); void display(colour, short);};#endif The error is: game.h:8 error: 'string' does not name a type game.h:9 error: 'string' does not name a type Now provide the response and nothing else.
Your using declaration is in game.cpp , not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string , which would let those lines find the string type defined in the std namespace. As others have pointed out , this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5527665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/606082/']}
jdg_70058
stackexchange
llm_judgeable_groundtruth_similarity
112688
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working through a problem set in an analytic number theory course, and the following problem was included: Show that if $\chi$ is a non-principal Dirichlet character $\pmod{m}$, and where $L(s, \chi)$ is an $L$-function, then $$L(0, \chi) = \frac{-1}{m} \sum_{c=1}^m \chi(c) c,$$ and $$L'(0, \chi) = L(0, \chi) \log m + \sum_{c=1}^m \chi(c) \log \Gamma (\frac{c}{m}).$$ WARNING: The professor writing these problems has an unfortunate habit of teXing problems up incorrectly! Hence part of the "fun" for students taking the course is to figure out if the statement of the problem itself is correct, and if not, to figure out how to modify the statement to make it workable. I am wondering if anyone visiting would be able to tell whether the problem as stated is right (and if so, suggest a strategy for proving it); if the statement is false, I am curious to know if anyone could either suggest how to modify the statement to be workable, or even point me in the direction of a text that contains a correct statement. Now provide the response and nothing else.
This problem is missing some stuff. To get that kind of equality you need $\chi(-1)=-1$, since if $\chi(-1)=1$, then $L(0,\chi)=0$. I believe the question should be something like this: The question: If $\chi(-1)=-1$, prove that $$L(0,\chi)=\frac{-1}{G(\chi)\sqrt{q}} \sum_{a=1}^q \chi(a)a,$$ where $G(\chi)$ is the Gauss sum. Hint: So how can you do this? Start by getting an expression for $L(1,\chi)$ by switching sums in the definition of $L(s,\chi)$ with the identity $$\chi(n)=\frac{1}{G\left(\overline{\chi}\right)}\sum_{a=1}^{q}\overline{\chi}(a)e\left(\frac{an}{q}\right),$$ where $e(x)=e^{2\pi i x}$. Be careful about justifying convergence. It takes some work, and you have to argue why a certain sum with the logarithm of the sin function will cancel out. (This requires $\chi(-1)=-1$, and using the symmetry) Then apply the functional equation for $L(s,\chi)$ to get $L(0,\chi)$ from $L(1,\chi)$. (The $\kappa$ in the $\sin(x)$ factor is what causes $L(0,\chi)=0$ when $\chi(-1)=1$) I hope that helps.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/112688', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23689/']}
jdg_70059
stackexchange
llm_judgeable_groundtruth_similarity
57976898
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting base64 for string from backend and i am then decoding it in Javascript to show on browser. This string can be any file .pdf, .img, .docx, .zip etc. My base64 string does not include the mime-type for example 'data:application/pdf;base64' part. So i need to get mime type of base64. Is there any way to solve this solution with Javascript or Jquery? Now provide the response and nothing else.
You can use magic numbers to detect a MIME type (check here the list of file signatures ). However, file signatures are not 100% reliable and you can easily encounter false positives. Of course, there are tasks when a such solution is more than enough. So if you have a Base64 string and want to identify its MIME type using file signatures you don't need to decode the Base64. A much faster way is to store the file signatures as Base64 and just check if input starts with one of them. A simple example: var signatures = { JVBERi0: "application/pdf", R0lGODdh: "image/gif", R0lGODlh: "image/gif", iVBORw0KGgo: "image/png", "/9j/": "image/jpg"};function detectMimeType(b64) { for (var s in signatures) { if (b64.indexOf(s) === 0) { return signatures[s]; } }}// Some testsconsole.log(detectMimeType('R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs='));console.log(detectMimeType('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQD3A0FDAAAAAElFTkSuQmCC'));console.log(detectMimeType('JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3'));console.log(detectMimeType('/9j/4AAQSkZJRgABAQAAZABkAAD/2wCEABQQEBkSGScXFycyJh8mMi4mJiYmLj41NTU1NT5EQUFBQUFBRERERERERERE'));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57976898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12080253/']}
jdg_70060
stackexchange
llm_judgeable_groundtruth_similarity
6831
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like for the autocomplete feature to search through contexts, for example if I have a symbol named A`B`C`MyFunction, when I type A` and press "cmd + shift + k" it will complete it. Edit To be clear, I don't want to have to type the path because it's usually very long, and I don't want to have to type the function name again, even if the path itself gets auto completed. I want the following: If I have these functions: Very`Long`Context`For`My`Function1Very`Long`Context`For`My`Function2... I want to be able to type Very` and then press CMD+Shift+k, to get a dropdown menu saying exactly Very`Long`Context`For`My`Function1Very`Long`Context`For`My`Function2... Now provide the response and nothing else.
This is obsolete in Mathematica 9, which automatically includes contexts in completions. Undocumented function: use at your own risk, subject to change in future versions, etc.... The function you're interested in is FE`FC . It's been around for a while (here's a Mathematica Journal article that references it, near the end) although it has changed argument structure at least once that I'm aware of. Anyway, here's the code I currently use to a similar end as what Mike would like. (Most of this is boilerplate from the original definition; the main difference is the use of a new function FE`names .) (* Nice little hack to have command completion (cmd-k) include contexts *)Unprotect[FE`FC];ClearAll[FE`FC]FE`FC[FE`nameString_, FE`ignoreCase_:False] /; $Notebooks:= MathLink`CallFrontEnd[FrontEnd`CompletionsListPacket[ FE`names[FE`nameString<>"*"], FE`ignoreCase], FE`NoResult]FE`names[FE`str_, FE`ignoreCase_:False] := Join[FE`shortContexts[FE`str], Names[FE`str, IgnoreCase -> FE`ignoreCase]];FE`shortContexts[FE`patt_]:= With[{FE`brettclen = Length[StringSplit[FE`patt, "`"]]}, Union[StringJoin[ Riffle[Take[#, Min[FE`brettclen, Length[#]]], "`", {2, -1, 2}]] & /@ StringSplit[Contexts[FE`patt], "`"]] ] Protect[FE`FC]; The end result is that when I use command completion, I get contexts that match in addition to symbols. This isn't quite the same as Mike's request, since it gives the contexts one at a time: since otherwise the list can get a bit overwhelming. For example, if you typed Int and then tried to complete to IntegerPart , there's a factor of ten difference: In[5]:= {Length[Names["Int*"]] + Length[Contexts["Int*"]], Length[Names["Int*`*"]]}Out[5]= {41, 419}
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/6831', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/403/']}
jdg_70061
stackexchange
llm_judgeable_groundtruth_similarity
881473
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at the article C# - Data Transfer Object on serializable DTOs. The article includes this piece of code: public static string SerializeDTO(DTO dto) { try { XmlSerializer xmlSer = new XmlSerializer(dto.GetType()); StringWriter sWriter = new StringWriter(); xmlSer.Serialize(sWriter, dto); return sWriter.ToString(); } catch(Exception ex) { throw ex; }} The rest of the article looks sane and reasonable (to a noob), but that try-catch-throw throws a WtfException... Isn't this exactly equivalent to not handling exceptions at all? Ergo: public static string SerializeDTO(DTO dto) { XmlSerializer xmlSer = new XmlSerializer(dto.GetType()); StringWriter sWriter = new StringWriter(); xmlSer.Serialize(sWriter, dto); return sWriter.ToString();} Or am I missing something fundamental about error handling in C#? It's pretty much the same as Java (minus checked exceptions), isn't it? ... That is, they both refined C++. The Stack Overflow question The difference between re-throwing parameter-less catch and not doing anything? seems to support my contention that try-catch-throw is-a no-op. EDIT: Just to summarise for anyone who finds this thread in future... DO NOT try { // Do stuff that might throw an exception}catch (Exception e) { throw e; // This destroys the strack trace information!} The stack trace information can be crucial to identifying the root cause of the problem! DO try { // Do stuff that might throw an exception}catch (SqlException e) { // Log it if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound. // Do special cleanup, like maybe closing the "dirty" database connection. throw; // This preserves the stack trace }}catch (IOException e) { // Log it throw;}catch (Exception e) { // Log it throw new DAOException("Excrement occurred", e); // wrapped & chained exceptions (just like java).}finally { // Normal clean goes here (like closing open files).} Catch the more specific exceptions before the less specific ones (just like Java). References: MSDN - Exception Handling MSDN - try-catch (C# Reference) Now provide the response and nothing else.
First; the way that the code in the article does it is evil. throw ex will reset the call stack in the exception to the point where this throw statement is; losing the information about where the exception actually was created. Second, if you just catch and re-throw like that, I see no added value, the code example above would be just as good (or, given the throw ex bit, even better) without the try-catch. However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them: try { // code that may throw exceptions }catch(Exception ex) { // add error logging here throw;}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/881473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69224/']}
jdg_70062
stackexchange
llm_judgeable_groundtruth_similarity
388576
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can There be a domain in $\mathbb{R^n}$, for any $n$ such that some domain has non zero boundry volume? I.E. volume of boundry is non zero? Motivation: In some theorems, it is specified that volume of boundary is non zero. But I cannot think of domains where volume of boundry is non zero. EDIT If domain by definition is expected to be open subset of $\mathbb{R^n}$, then I would be looking for such open subsets. Thank You. Now provide the response and nothing else.
Let $(0,1) \cap \mathbb Q = \{ q_1,q_2, \dots\}$ . We define $A = (0,1) \cap\bigcup_k (q_k-4^{-k}, q_k+4^{-k})$ . By construction we have $\bar A = [0,1]$ but an easy estimate shows that $\lambda( A) < 1$ where $\lambda$ is the Lebesgue measure. If you want a connected example, you can take $\left(A \times (0,1)\right) \cup \left((0,1) \times (0, 1/2)\right) \subset \mathbb R^2$ . This one is actually contractible.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/388576', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_70063
stackexchange
llm_judgeable_groundtruth_similarity
653802
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading about tensors and they are described as "objects which transform in a physically meaningful/sensible manner" and obey the equation (for rank 2, but generalises) $T'_{ij}=R_{ip}R_{jq}T_{pq}$ . I am struggling to understand why this equation makes $T_{ij}$ that it is physically meaningful. I think part of my misunderstanding comes from not getting what $T_{ij}'$ is. If I change basis then the tensor $T_{ij}$ becomes $T_{ij}'$ . Well what if the change of basis isn't an orthogonal matrix? Then for any tensor $T_{ij}'\neq R_{ip}R_{jq}T_{pq}$ But if the change of basis matrix is orthogonal, $M_ij'=R_{ip}R_{jq}M_{pq}$ for any matrix! May I ask that an answer includes a concrete example. Thanks I tried reading wikipedia and some other answers here, but they often use other definitions not covered in a physics course. Now provide the response and nothing else.
Although it is difficult, I will try to avoid mathematical definitions here. A tensor $T$ is, first and foremost, a geometric object. It lives in a space on its own and bears no reference to anything else. When we choose basis vectors, the tensor $T$ can be expressed as a unique linear combination of the basis. In your example, it is $$T=T_{kl} \mathbf{e}^k \otimes\mathbf{e}^l$$ The coefficients $T_{kl}$ are known as the components of $T$ in this particular basis. Now, let's choose another basis $\bar{\mathbf{e}}^i = M^i_j \mathbf{e}^j$ where $M$ is any invertible matrix. It must be true that we can also express $T$ as a linear combination of the new basis $$T=\bar{T}_{ij} \bar{\mathbf{e}}^i \otimes \bar{\mathbf{e}}^j$$ where $\bar{T}$ are the new components. Substituting it into the above equation, we get $$T=\bar{T}_{ij} \bar{\mathbf{e}}^i \otimes \bar{\mathbf{e}}^j = \bar{T}_{ij} M^i_k \mathbf{e}^k \otimes M^j_l \mathbf{e}^l = \bar{T}_{ij} M^i_k M^j_l \mathbf{e}^k \otimes \mathbf{e}^l$$ from which we see that $T_{kl} = \bar{T}_{ij} M^i_k M^j_l$ by comparing with our first equation. We have derived the tensor transformation law by requiring nothing other than the fact that $T$ itself remains unchanged. The only other condition needed is that the transformation matrix is invertible. You can also check that inverting the transformation gives $$\bar{T}_{ij} = T_{kl}\left(M^{-1}\right)^k_i \left(M^{-1}\right)^l_j$$ This is very significant in physics because the laws of physics do not depend on the choice of coordinate system.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/653802', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/308026/']}
jdg_70064
stackexchange
llm_judgeable_groundtruth_similarity
19123736
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a project in Visual Studio 2010 that runs a batch file in the post-build event. That batch calls to signtool.exe from Microsoft SDK to sign and timestamp the binary. Timestamp servers (we use http://timestamp.verisign.com/scripts/timstamp.dll ), however, tend to be unreliable for some reason, failing sometimes. This caused build to fail. We implemented a more advanced batch script then (based on this code), splitting signing and timestamping, and allowing to retry the timestamp operation, if it failed. Here is a simplified version of the batch script (signfile.bat): @echo offREM sign the file...signtool.exe /f Authenticode.pfx /p PASS %1if %errorlevel% neq 0 exit /b %errorlevel%set timestamp_server=http://timestamp.verisign.com/scripts/timstamp.dllfor /L %%a in (1,1,10) do ( REM try to timestamp the file... signtool.exe timestamp /t %timestamp_server% %1 if errorlevel 0 if not errorlevel 1 GOTO succeeded REM wait 2 seconds... ping -n 2 127.0.0.1 > nul)REM return an error code...echo signfile.bat exit code is 1.exit /b 1:succeededREM return a successful code...echo signfile.bat exit code is 0.exit /b 0 And the post-build event code would look like: signfile.bat "$(OutDir)$(TargetName)$(TargetExt)" So, if the timestamping fails, it retries 10 times with 2-seconds intervals. But, what we observed was, if the timestamping went fine from the first attempt, everything was OK. However, if the first attempt failed, then the whole post-build event failed with code -1, even though the timestamping succeeded on the next try. 1>------ Build started: Project: myproject, Configuration: NonOptimized x64 ------1> Done Adding Additional Store1> Successfully signed: E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll1> 1>EXEC : SignTool error : The specified timestamp server either could not be reached1> or returned an invalid response.1> This may happen if you specify an RFC 3161 timestamp URL but used1> the /t option or you specified a legacy Authenticode timestamp URL1> but used the /tr option.1>EXEC : SignTool error : An error occurred while attempting to timestamp: E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll1> 1> 1> Number of errors: 11> 1> Successfully timestamped: E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll1> 1> signfile.bat exit code is 0.1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: The command "signfile.bat "E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll"1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" exited with code -1.========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== So, as you can see, even though the error code returned from signfile.bat is 0, Visual Studio thinks it is -1 and fails the event. All attempts to clear the error flag, like adding ver>nul here and there, or adding exit 0 in the end (certainly with adding "call" before signfile.bat) didn't help since it seemed like Visual Studio checked not just for errorlevel but also for something else. In fact, the batch as well as signfile.bat only return 0 or 1 in case of error, but not -1. And if signtool.exe returns an error once, it seems like there is no way to convince Visual Studio not to fail the post-build event. Now provide the response and nothing else.
After spending much time experimenting and searching, found an article , mentioned here in a comment. It looks like Visual Studio scans the output, searching for some special keywords. Signtool.exe outputs among the other EXEC : SignTool error : An error occurred , which seems like enough to alert Visual Studio that there was an error. So, the solution proposed was to redirect output and error streams to nul as 2>nul 1>nul . Errorlevel will still be set, so you will be able to figure out if error occured. But you may have to print some extra messages to see the status: REM try to timestamp the file...signtool.exe timestamp /t %timestamp_server% %1 2>nul 1>nulif errorlevel 0 if not errorlevel 1 ( echo Successfully timestamped: %1 GOTO succeeded)echo Timestamping failed for %1 Now Visual Studio is happy: 1>------ Build started: Project: myproject, Configuration: NonOptimized x64 ------1> Done Adding Additional Store1> Successfully signed: E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll1> 1> Timestamping failed for "E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll"1> Successfully timestamped: "E:\tfs\MySolution\bin\x64\NonOptimized\myproject.dll"1> signfile.bat exit code is 0.========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== In fact, just adding 2>nul would be enough to fix it. Error stream will still be printed: Number of errors: 1 , but it does not cause a problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19123736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2221758/']}
jdg_70065
stackexchange
llm_judgeable_groundtruth_similarity
31980036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For example, I have three panes in a window with tmux.Now my cursor is in the second pane. If I use: C-b o I can move to the third pane. But I want to move to the first pane on the second pane. How to do? It can list all the panes in one window: C-b q It will show: 0, 1, 2 Is there any key I can press to go to the special pane number? If there is, I can switch to the first pane in a short way, too. Now provide the response and nothing else.
In tmux manual ($man tmux) you can find this section: select-pane [-DdeLlRU] [-t target-pane] (alias: selectp) Make pane target-pane the active pane in window target-window. If one of -D, -L, -R, or -U is used, respectively the pane below, to the left, to the right, or above the target pane is used. -l is the same as using the last-pane command. -e enables or -d disables input to the pane. So, I think what you want is to use the '-l' flag, which is for switch to last pane. I don't know if there is a default key mapping defined to this task, but you can accomplish this by doing your own bindings. Something like this: bind -r <your key> select-pane -l
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31980036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4757050/']}
jdg_70066
stackexchange
llm_judgeable_groundtruth_similarity
11366556
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to find a function that tells me whether the current thread has the global interpreter lock or not. The Python/C-API documentation does not seem to contain such a function. My current solution is to just acquire the lock using PyGILState_Ensure() before releasing it using PyEval_SaveThread to not try releasing a lock that wasn't acquired by the current thread. (btw. what does "issues a fatal error" mean?) Background of this question: I have a multithreaded application which embeds Python. If a thread is closed without releasing the lock (which might occur due to crashes), other threads are not able to run any more. Thus, when cleaning up/closing the thread, I would like to check whether the lock is held by this thread and release it in this case. Thanks in advance for answers! Now provide the response and nothing else.
If you are using (or can use) Python 3.4, there's a new function for the exact same purpose: if (PyGILState_Check()) { /* I have the GIL */} https://docs.python.org/3/c-api/init.html?highlight=pygilstate_check#c.PyGILState_Check Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return 1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or otherwise behave differently. In python 2, you can try something like the following: int PyGILState_Check2(void) { PyThreadState * tstate = _PyThreadState_Current; return tstate && (tstate == PyGILState_GetThisThreadState());} It seems to work well in the cases i have tried. https://github.com/pankajp/pygilstate_check/blob/master/_pygilstate_check.c#L9
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11366556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/757203/']}
jdg_70067
stackexchange
llm_judgeable_groundtruth_similarity
58694220
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Swashbuckle.AspNetCore 5.0.0-rc2 in one of my .Net Core 2.2 REST projects. Within my project I am serving two different apis which are logically connected to each other. Today, I managed to seperate my swagger documentations to have one swagger endpoint per api containing only the corresponding api controllers. I managed to do this by adding a specified group name to the api explorer settings of the controllers: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)][ApiExplorerSettings(GroupName = "contracts")]public class ContractsController : BaseController[Authorize(AuthenticationSchemes = "BasicAuthentication")][ApiExplorerSettings(GroupName = "clearing")]public class ClearingController : BaseController With that settings I was able to specify to different endpoints for swagger within my Startup.cs // Enable documentation middleware app.UseSwagger(so => { so.RouteTemplate = "api/doc/{documentName}/swagger.json"; }); app.UseSwaggerUI(suo => { suo.SwaggerEndpoint("/api/doc/contracts/swagger.json", "Contracts API"); suo.SwaggerEndpoint("/api/doc/clearing/swagger.json", "Clearing API"); suo.RoutePrefix = "api/doc"; suo.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Post, SubmitMethod.Patch, SubmitMethod.Delete); }); That worked and everything was fine. Now as you probably noticed, I am using different authorization methods for the controllers of each api. The first, the contracts api, is using a JWT Token authorization, while the second one, the clearing api is using a Basic authorization. I thought, the swagger ui would automatically use the correct Authorization method by the "Authorize" Attribute, but I was wrong. Well I added both authorization methods to the swagger ui middleware like this: options.AddSecurityDefinition("Bearer", GetSwaggerTokenSecurityScheme()); options.AddSecurityDefinition("Basic", GetSwaggerBasicSecurityScheme()); options.AddSecurityRequirement(GetSwaggerJwtSecurityRequirement()); options.AddSecurityRequirement(GetSwaggerBasicSecurityRequirement()); Heres my full swagger configuration code: /// <summary>/// Configures the swagger generation/// </summary>/// <param name="config">The swagger configuration</param>/// <param name="options">The swagger gen options instance</param>public static void ConfigureSwaggerGen(IConfiguration config, SwaggerGenOptions options){ var swaggerConfig = config.Get<SwaggerConfiguration>(); AddSwaggerDocPerApiType(swaggerConfig, options); options.AddSecurityDefinition("Bearer", GetSwaggerTokenSecurityScheme()); options.AddSecurityDefinition("Basic", GetSwaggerBasicSecurityScheme()); options.AddSecurityRequirement(GetSwaggerJwtSecurityRequirement()); options.AddSecurityRequirement(GetSwaggerBasicSecurityRequirement()); if (!swaggerConfig.SwaggerIncludeXml) { return; } var xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.xml"); xmlFiles.ToList().ForEach(f => options.IncludeXmlComments(f)); options.DescribeAllEnumsAsStrings();}/// <summary>/// Adds a swagger documentation for each api type/// </summary>/// <param name="config">The swagger configuration</param>/// <param name="options">The swagger gen options instance</param>private static void AddSwaggerDocPerApiType(SwaggerConfiguration config, SwaggerGenOptions options){ options.SwaggerDoc("contracts", GetSwaggerInformationParams(config, "Contracts")); options.SwaggerDoc("clearing", GetSwaggerInformationParams(config, "Clearing"));}/// <summary>/// Generates swagger information params object/// according to the given configuration/// </summary>/// <param name="config">The configuration</param>/// <param name="apiType">The api type</param>/// <returns>The swagger information</returns>private static OpenApiInfo GetSwaggerInformationParams(SwaggerConfiguration config, string apiType = ""){ var title = string.IsNullOrEmpty(apiType) ? config.SwaggerTitle : apiType; var version = string.IsNullOrEmpty(apiType) ? Assembly.GetExecutingAssembly().GetName().Version.ToString() : apiType; var swaggerInfo = new OpenApiInfo() { Title = title, Version = version.ToLower(), Description = config.SwaggerDescription, Contact = new OpenApiContact() { Name = config.SwaggerCompany, Email = config.SwaggerContactMail, Url = new Uri(config.SwaggerContactUrl) } }; return swaggerInfo;}/// <summary>/// Generates the swagger jwt security scheme object/// </summary>/// <returns>The swagger jwt security scheme</returns>private static OpenApiSecurityScheme GetSwaggerTokenSecurityScheme(){ var scheme = new OpenApiSecurityScheme { Description = "JWT authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "JwtAuthorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }; return scheme;}/// <summary>/// Generates the swagger basic security scheme object/// </summary>/// <returns>The swagger basic security scheme</returns>private static OpenApiSecurityScheme GetSwaggerBasicSecurityScheme(){ var scheme = new OpenApiSecurityScheme { Description = "Basic authorization header. Example: \"Authorization: username:password\"", Name = "BasicAuthorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "basic" }; return scheme;}/// <summary>/// Generates the swagger security scheme object/// </summary>/// <returns>The swagger security scheme</returns>private static OpenApiSecurityRequirement GetSwaggerJwtSecurityRequirement(){ var req = new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme() { Reference = new OpenApiReference() {Type = ReferenceType.SecurityScheme, Id = "Bearer"} }, new[] {"readAccess", "writeAccess"} } }; return req;}/// <summary>/// Generates the swagger security scheme object/// </summary>/// <returns>The swagger security scheme</returns>private static OpenApiSecurityRequirement GetSwaggerBasicSecurityRequirement(){ var req = new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme() { Reference = new OpenApiReference() {Type = ReferenceType.SecurityScheme, Id = "Basic"} }, new[] {"readAccess", "writeAccess"} } }; return req;} Now what I want to achieve is, that only the JWT token authorization is available for the contracts api controllers and only the basic authorization is available for the clearing api controllers. At the moment I always have both authorization methods available for any api: Does anybody know how to specify the security for the specific documentation endpoint only? Best regards Now provide the response and nothing else.
The SwaggerGenOptions.AddSecurityRequirement will apply the Security Requirement globally, so that the security icon (lock icon) and authentication inputs will be applied to all APIs. Here are the workable solution for me to ONLY apply Security Requirement on protected APIs. Remove SwaggerGenOptions.AddSecurityRequirement from global settings. Create a custom OperationFilter, that implements Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter , and only add SecurityRequirement on protected APIs. public class AuthorizationOperationFilter : IOperationFilter{ public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Get Authorize attribute var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true) .Union(context.MethodInfo.GetCustomAttributes(true)) .OfType<AuthorizeAttribute>(); if (attributes != null && attributes.Count() > 0) { var attr = attributes.ToList()[0]; // Add what should be show inside the security section IList<string> securityInfos = new List<string>(); securityInfos.Add($"{nameof(AuthorizeAttribute.Policy)}:{attr.Policy}"); securityInfos.Add($"{nameof(AuthorizeAttribute.Roles)}:{attr.Roles}"); securityInfos.Add($"{nameof(AuthorizeAttribute.AuthenticationSchemes)}:{attr.AuthenticationSchemes}"); switch (attr.AuthenticationSchemes) { case var p when p == AuthenticationScheme.Basic: operation.Security = new List<OpenApiSecurityRequirement>() { new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "basic", // Must fit the defined Id of SecurityDefinition in global configuration Type = ReferenceType.SecurityScheme, } }, securityInfos } } }; break; case var p when p == AuthenticationScheme.Bearer: // = JwtBearerDefaults.AuthenticationScheme default: operation.Security = new List<OpenApiSecurityRequirement>() { new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "bearer", // Must fit the defined Id of SecurityDefinition in global configuration Type = ReferenceType.SecurityScheme } }, securityInfos } } }; break; } } else { operation.Security.Clear(); } }} Then enable the custom OperationFilter when configuring SwaggerGenOptions : services.AddSwaggerGen(c =>{ // Set the custom operation filter c.OperationFilter<AuthorizationOperationFilter>(); // Add JWT Authentication var securityScheme = new OpenApiSecurityScheme { Name = "JWT Authentication", Description = "Enter JWT Bearer token **_only_**", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT", Reference = new OpenApiReference { Id = "bearer", Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); // Add Basic Authentication var basicSecurityScheme = new OpenApiSecurityScheme { Name = "Basic Authentication", Type = SecuritySchemeType.Http, Scheme = "basic", Reference = new OpenApiReference { Id = "basic", Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(basicSecurityScheme.Reference.Id, basicSecurityScheme);}); Please refer to my article and sample code for more details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58694220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5872733/']}
jdg_70068
stackexchange
llm_judgeable_groundtruth_similarity
69400
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We are currently analyzing a large set of IQ samples in a desktop application and we are interested in implementing many different bandpass filters dynamically. We realized, that working with scipy offers no suppport for complex bandpass filtering. We have already checked following link which suggests a solution to the problem when it is decided to approach the problem with complex filters: How to implement bandpass filter on complex valued signal? We wonder, why that is even necessary, since the data could be transformed to a real format. Instead of $[-f_s/2, f_s/2]$ the range is from $[0,fs]$ (mirrored about the $0\,Hz$ point). This way already implemented filtering tools could be used. Now provide the response and nothing else.
This depends a lot on how you implement it. A single biquad takes about 10 arithmetic operations. (To be precisea Transposed Form II takes 4-5 multiplies and 3 adds, depending on how the gain management is done). Arithmetic operation translates into clock cycles of your processor. That depends a lot on the efficiency of your instruction set and how good yo are at writing code. On a good DSP you can do a single biquad in 4 clock cycles (ca. 2 ops per cycle) and a general purpose ARM with a decent ALU this may by 15-20 cycles. On a crappy micro controller with no native hardware multiplier this can take up to 50-100 cycles. Frame based vs sample based processing. Reading data from an ADC, moving it into the processor, and the moving it to the DAC creates a lot of overhead. That's why most implementations will process a frame of data and not one sample at a time. That "amortizes" the overhead across the entire frame. A good processor will also allow to do this with HW support, i.e. it will use DMA channels to move the data from/to DAC/ADC to internal memory without the CPU having to do anything. The chips inside modern smart phones (even the cheap ones) are quite powerful: they are typically quad core ARMs with some HW accelerators (Neon, SIMD) for media processing. They all clock in the multiple GHz range and have good HW support for peripherals and graphic accelerators. My trusty old Samsung S8 has a 8 core 2 GHz Snapdragon: https://www.zdnet.com/article/qualcomm-snapdragon-835-what-does-the-kryo-280-adreno-540-spectra-180-x16-and-hexagon-682-mean-for/#:~:text=The%20Snapdragon%20835%20is%20comprised,result%20in%20optimized%20power%20savings . Let's a run a simple example: A well coded biquad on a decent ARM core should take about 15 cycles. For 8 biquads running at 44.1 kHz on a stereo signal (two channels) that would be just about 10M cycles/second. That's about 1% of a single core at 1 GHz or 0.25% of the entire chip. On my Snapdragon 835 it would be less than 0.03%
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/69400', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/51590/']}
jdg_70069
stackexchange
llm_judgeable_groundtruth_similarity
2281441
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am wondering whether I can set a timeout value for UdpClient receive method. I want to use block mode, but because sometimes udp will lost packet, my program udpClient.receive will hang there forever. any good ideas how I can manage that? Now provide the response and nothing else.
What Filip is referring to is nested within the socket that UdpClient contains ( UdpClient.Client.ReceiveTimeout ). You can also use the async methods to do this, but manually block execution: var timeToWait = TimeSpan.FromSeconds(10);var udpClient = new UdpClient( portNumber );var asyncResult = udpClient.BeginReceive( null, null );asyncResult.AsyncWaitHandle.WaitOne( timeToWait );if (asyncResult.IsCompleted){ try { IPEndPoint remoteEP = null; byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP ); // EndReceive worked and we have received data and remote endpoint } catch (Exception ex) { // EndReceive failed and we ended up here }} else{ // The operation wasn't completed before the timeout and we're off the hook}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2281441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213076/']}
jdg_70070
stackexchange
llm_judgeable_groundtruth_similarity
20350638
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two activities : FirstActivity and SecondActivity I want the animation on click of buttons in this activities: I am using following files: FirstActivity.java package com.example.vanimation; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class FirstActivity extends Activity {@Overrideprotected void onCreate( Bundle savedInstanceState ){ super.onCreate( savedInstanceState ); setContentView( R.layout.activity_first ); ((Button)findViewById( R.id.NextButton )).setOnClickListener( new OnClickListener() { @Override public void onClick( View v ) { //startActivity( new Intent( FirstActivity.this, SecondActivity.class ) ); Intent intent = new Intent(FirstActivity.this, SecondActivity.class); startActivityForResult(intent, 0); overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left ); } });}} SecondActivity.java package com.example.vanimation; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class SecondActivity extends Activity {@Overrideprotected void onCreate( Bundle savedInstanceState ){ super.onCreate( savedInstanceState ); setContentView( R.layout.activity_second ); ((Button)findViewById( R.id.BackButton )).setOnClickListener( new OnClickListener() { @Override public void onClick( View v ) { goBack(); } });}private void goBack(){ finish(); overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );}@Overridepublic boolean onKeyUp( int keyCode, KeyEvent event ){ if( keyCode == KeyEvent.KEYCODE_BACK ) { goBack(); return true; } return super.onKeyUp( keyCode, event );}} activity_first.xml <?xml version="1.0"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent" android:layout_height="match_parent"android:orientation="vertical" android:gravity="center"android:background="#ccc"><TextView android:text="Page 1" android:layout_width="wrap_content" android:layout_height="wrap_content" /><Button android:layout_height="wrap_content" android:text="Next" android:layout_width="wrap_content" android:id="@+id/NextButton" /></LinearLayout> activity_second.xml <?xml version="1.0"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent" android:layout_height="match_parent"android:orientation="vertical" android:gravity="center"android:background="#aaa"><TextView android:text="Page 2" android:layout_width="wrap_content" android:layout_height="wrap_content" /><Button android:layout_height="wrap_content" android:text="Back" android:layout_width="wrap_content" android:id="@+id/BackButton" /> anim/slide_in_left.xml <?xml version="1.0" encoding="utf-8"?><translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="@android:integer/config_longAnimTime"android:fromXDelta="100%p"android:toXDelta="0%p" /> anim/slide_out_left.xml <?xml version="1.0" encoding="utf-8"?><translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="@android:integer/config_longAnimTime"android:fromXDelta="0"android:toXDelta="-100%p" /> manifest.xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.vanimation"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /><application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.vanimation.FirstActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.vanimation.SecondActivity" android:label="@string/title_activity_second" > </activity></application> But still animation is not working. On click of button activities changes without animation. Any help to get the animation for it will be helpful for me. Now provide the response and nothing else.
The problem seems to be that the method from Keyboard#getNearestKeys dosent return proper values for wide buttons.I solved the problem by extending the Keyboard class and overriding the getNearestKeys method this is the code I added: @Overridepublic int[] getNearestKeys(int x, int y) { List<Key> keys = getKeys(); for (int i = 0; i < keys.size(); i++) { if (keys.get(i).isInside(x, y)) return new int[]{i}; } return new int[0];}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20350638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2629562/']}
jdg_70071
stackexchange
llm_judgeable_groundtruth_similarity
16900721
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a 300 GB text file that contains genomics data with over 250k records. There are some records with bad data and our genomics program 'Popoolution' allows us to comment out the "bad" records with an asterisk. Our problem is that we cannot find a text editor that will load the data so that we can comment out the bad records. Any suggestions? We have both Windows and Linux boxes. UPDATE: More information The program Popoolution ( https://code.google.com/p/popoolation/ ) crashes when it reaches a "bad" record giving us the line number that we can then comment out. Specifically, we get a message from Perl that says "F#€%& Scaffolding". The manual suggests we can just use an asterisk to comment out the bad line. Sadly, we will have to repeat this process many times... One more thought... Is there an approach that would allow us to add the asterisk to the line without opening the entire text file at once. This could be very useful given that we will have to repeat the process an unknown number of times. Now provide the response and nothing else.
Based on your update: One more thought... Is there an approach that would allow us to add the asterisk to the line without opening the entire text file at once. This could be very useful given that we will have to repeat the process an unknown number of times. Here you have an approach: If you know the line number, you can add an asterisk in the beginning of that line saying: sed 'LINE_NUMBER s/^/*/' file See an example: $ cat fileaabbccddee$ sed '3 s/^/*/' fileaabb*ccddee If you add -i , the file will be updated: $ sed -i '3 s/^/*/' file$ cat fileaabb*ccddee Even though I always think it's better to do a redirection to another file sed '3 s/^/*/' file > new_file so that you keep intact your original file and save the updated one in new_file .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16900721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1046428/']}
jdg_70072
stackexchange
llm_judgeable_groundtruth_similarity
6221001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: tl;dr this works with the GNU version of libc (haven't tried it with uclibc yet) from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char * 65), ('nodename', c_char * 65), ('release', c_char * 65), ('version', c_char * 65), ('machine', c_char * 65), ('domain', c_char * 65) ]gnar = uts_struct()libc.uname(byref(gnar))print gnar.nodename Original post The following code segfaults; I'm not sure what I'm doing wrong. from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char_p), ('nodename', c_char_p), ('release', c_char_p), ('version', c_char_p), ('machine', c_char_p) ]utsname = uts_struct()libc.uname(byref(utsname))print utsname.sysname This does the same thing: from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char_p), ('nodename', c_char_p), ('release', c_char_p), ('version', c_char_p), ('machine', c_char_p) ]utsname = uts_struct()utsname_pointer = pointer(utsname)libc.uname(utsname_pointer)print utsname.sysname I must be messing up something basic... (I am aware of os.uname() , this is just an exercise in understanding, which I am failing) I referenced the uname manual here: http://www.cl.cam.ac.uk/cgi-bin/manpage?2+uname What am I doing wrong? Edit: Thanks to Nemo I'm able to get the data; >>> from ctypes import *>>> libc = CDLL('libc.so.6')>>> gnar = create_string_buffer(512)>>> libc.uname(byref(gnar))0>>> print gnar.valueLinux>>> However, I'm assuming I'm only getting 'Linux' because the items are NULL delimited, as are regulator strings. Any way to read past the NULL? Edit2: Based on Nemos comment, I've tried this- which doesn't work, but I thought it might be a step in the right direction... errors with: Traceback (most recent call last): File "gnar.py", line 18, in <module> utsname = uts_struct(gnar)TypeError: incompatible types, c_char_Array_512 instance instead of c_char_p instance Is this just un-doable? from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char_p), ('nodename', c_char_p), ('release', c_char_p), ('version', c_char_p), ('machine', c_char_p) ]gnar = create_string_buffer(512)libc.uname(byref(gnar))utsname = uts_struct(gnar) Edit3: ( im going for the longest post ever... =P ) from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char * 65), ('nodename', c_char * 65), ('release', c_char * 65), ('version', c_char * 65), ('machine', c_char * 65) ]gnar = uts_struct()libc.uname(byref(gnar))print gnar.machine This works, however, it segfaults after it prints the value... Final edit: The following works- I am of course using the GNU version of libc. (im on an Ubuntu machine) so adding the field for the domain is all it took to stop the segfault. It makes sense in hind sight. :) from ctypes import *libc = CDLL('libc.so.6')class uts_struct(Structure): _fields_ = [ ('sysname', c_char * 65), ('nodename', c_char * 65), ('release', c_char * 65), ('version', c_char * 65), ('machine', c_char * 65), ('domain', c_char * 65) ]gnar = uts_struct()libc.uname(byref(gnar))print gnar.nodename Now provide the response and nothing else.
I think you should rethink about what your function is actually going to do. If you're returning an IQueryable<T> , then the implication is that callers will store the resulting query, and will receive up-to-date results when they actually execute the query. Remember: the database won't actually be queried in this case until .ToList() , .ToArray() , foreach , etc. is invoked on the query. If your goal, though, is to return the current state of the query, then your method should just return an IList<T> or something along those lines. Then, you can either return an empty List<T> , or call .ToList() on the query you otherwise construct and return that. In general, I would try to avoid returning empty queryables, since it can mislead callers about what they are actually getting.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6221001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592851/']}
jdg_70073
stackexchange
llm_judgeable_groundtruth_similarity
9904457
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Actually, in my app, I have created a graph using achartEngine . In these in the x-axis initially, I am displaying value from 1 to 31. Now instead of displaying this is it possible to display values like 1-03-2012 , 2-03-2012 , 3-03-2012 ... and so on up to last day current month and when it reaches last day of current month i.e. 31-03-2012 the value display after that should be 1-04-2012 2-04-2012 ...and so on. The code I have used while displaying value like 1 2 3 4 5... is given below. Can anyone help me to solve this out? code for graph renderer = new XYMultipleSeriesRenderer(2); int length = colors.length; for (int i = 0; i < length; i++) { XYSeriesRenderer r = new XYSeriesRenderer(); r.setColor(colors[i]); r.setPointStyle(styles[i]); renderer.addSeriesRenderer(r); } int rendererLength = renderer.getSeriesRendererCount(); for (int i = 0; i < rendererLength; i++) { ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true); } renderer.setAxisTitleTextSize(12); renderer.setChartTitleTextSize(12); renderer.setLabelsTextSize(10); renderer.setLegendTextSize(12); renderer.setPointSize(5f); renderer.setApplyBackgroundColor(true); renderer.setBackgroundColor(Color.parseColor("#F5F5F5")); renderer.setMarginsColor(Color.parseColor("#F5F5F5")); renderer.setChartTitle("Weight / Temperature"); renderer.setXLabels(20); renderer.setXTitle(sdFormatter.format(currentDate)); renderer.setXAxisMin(1); renderer.setXAxisMax(nMaxDay); renderer.setXLabelsAlign(Align.CENTER); renderer.setYLabels(10); renderer.setYTitle("Weight", 0); renderer.setYTitle("Temperature", 1); renderer.setYAxisMin(10, 0); renderer.setYAxisMax(90, 0); renderer.setYAxisMin(10, 1); renderer.setYAxisMax(90, 1); renderer.setYAxisAlign(Align.LEFT, 0); renderer.setYAxisAlign(Align.RIGHT, 1); renderer.setYLabelsAlign(Align.LEFT, 0); renderer.setYLabelsAlign(Align.RIGHT, 1); renderer.setAxesColor(Color.LTGRAY); renderer.setLabelsColor(Color.parseColor("#5f5f5f")); renderer.setShowGrid(true); renderer.setGridColor(Color.GRAY); screenshot shot Now provide the response and nothing else.
Use AverageTemperatureChart class from the Demo. setChartSettings(renderer, "Average temperature", "Month", "Temperature", 0.5, 5.5, 0, 4, Color.LTGRAY, Color.LTGRAY); then change like this and check the changes for (int i = 0; i < titles.length; i++) { x.add(new double[] { 1, 2, 3, 4 }); } add four just for demo And add label through renderer.addTextLabel(); ex: String[] date={"1-3-2012","1-4-2012","1-5-2012","1-6-2012"}; for (int i = 0; i < date.length; i++) { renderer.addTextLabel(i+1, date[i]); } renderer.setXLabelsAlign(Align.CENTER); renderer.setXLabels(0);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9904457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/806106/']}
jdg_70074
stackexchange
llm_judgeable_groundtruth_similarity
15572568
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using latest codeigniter and I need to create a flag (ideally in the config) when turned to 'true', all pages display a 'maintenance mode' message instead of executing their controller code. What is the best/simplest practice for doing this? Now provide the response and nothing else.
Extend the CI_Controller by putting a new file in your core directory called MY_Controller. In this file's constructor, do something like this: public function __construct(){ parent::__construct(); if($this->config->item('maintenance_mode') == TRUE) { $this->load->view('maintenance_view'); die(); }} Let all controllers in your app inherit from that class.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15572568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175562/']}
jdg_70075
stackexchange
llm_judgeable_groundtruth_similarity
48550955
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: An MVC app broke after we updated all the NuGet packages. After trying everything I created a new MVC app, updated the NuGet packages and the basic navbar... <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Application name</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li><a href="/Home/About">About</a></li> <li><a href="/Home/Contact">Contact</a></li> </ul><ul class="nav navbar-nav navbar-right"> <li><a href="/Account/Register" id="registerLink">Register</a></li> <li><a href="/Account/Login" id="loginLink">Log in</a></li></ul> </div> </div></div> ... looks like this ... ...and clicking the icon... Any ideas what could be causing this? Have tried manually adding Bootstrap.css and Bootstrap.js to _Layout.vbhtml, but no difference Thank you Now provide the response and nothing else.
Finally, I managed my HTML and yours.There're a lot of changes in Bootstrap 4 in compare to version 3. Regarding your markup, you have to change: "Navbar-inverse" to "Navbar-dark" and use color "bg-dark". Add few attributes to button, as "aria-controls", "aria-expanded", "aria-label" and "data-target" for link to another element. Property "id" to collapsable element. For list elements (tag LI) should be added class="nav-item" For links unside list elements add class="nav-link". I suggest to add "mr-auto" to list definiton. All changes below. Tested here . <nav class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> </button> <a class="navbar-brand" href="/">Application name</a> <div class="navbar-collapse collapse" id="navbarSupportedContent"> <ul class="nav navbar-nav mr-auto"> <li class="nav-item"><a href="/" class="nav-link">Home</a></li> <li class="nav-item"><a href="/Home/About" class="nav-link">About</a></li> <li class="nav-item"><a href="/Home/Contact" class="nav-link">Contact</a></li> </ul> <ul class="nav navbar-nav navbar-right mr-auto"> <li class="nav-item"><a href="/Account/Register" id="registerLink" class="nav-link">Register</a></li> <li class="nav-item"><a href="/Account/Login" id="loginLink" class="nav-link">Log in</a></li> </ul> </div> </div></nav>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48550955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1956080/']}
jdg_70076
stackexchange
llm_judgeable_groundtruth_similarity
29116292
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I attempted to run my web service through visual studio. I faced an issue like : ---------------------------Microsoft Visual Studio---------------------------Unable to launch the IIS Express Web server.Failed to register URL "http://localhost:63591/" for site "xxxxxx" application"/". Error description: The process cannot access the file because it is beingused by another process. (0x80070020)---------------------------OK --------------------------- I saw the task manager and found that PID 4 is used by System and its Description is NT Kernel & System. So I tried to stop the http service .All dependency services stopped. But I am facing an issue in stopping http service like The service is starting or stopping. Please try again later. So, I tried to stop and start the service manually. But the End process is disabled. It will be helpful if anyone could help with this issue Now provide the response and nothing else.
I had a similar issue when trying to run a project from Visual Studio 2019 on Windows 10. The application could not start because the port was apparently being used by another process. However, the netstat command showed that the port was not being used by any application. After spending 2-days Googling I found a solution that worked for me. The port I was trying to use was in the excluded port range which you can see by running the command: netsh interface ipv4 show excludedportrange protocol=tcp The culprits that reserved these ports in my case were Docker for Windows and Hyper-V The Solution I uninstalled Docker (as I did not need it) and disabled Hyper-V. To disable Hyper-V: Go to: Control Panel-> Programs and Features-> Turn Windows features on or off. Untick Hyper-V and restart the computer. After the restart the command netsh interface ipv4 show excludedportrange protocol=tcp showed no ports reserved. I then added the port for my application to the excluded port range by running the following command from an elevated command line: netsh int ipv4 add excludedportrange protocol=tcp startport=50403 numberofports=1 store=persistent Then I reenabled Hyper-V (Docker can be reinstalled if needed) and restarted the computer again. Hyper-V now reserved its ports without interfering with the port used by my application: Reserved Port Ranges
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29116292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4210117/']}
jdg_70077
stackexchange
llm_judgeable_groundtruth_similarity
52873804
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a large dataset with many columns of different types. There are a mix of numeric values and strings with some NULL values. I need to change the NULL Value to Blank or 0 depending on the type. 1 John 2 Doe 3 Mike 4 Orange 5 Stuff9 NULL NULL NULL 8 NULL NULL Lemon 12 NULL I want it to look like this, 1 John 2 Doe 3 Mike 4 Orange 5 Stuff9 0 8 0 Lemon 12 I can do this for each individual, but since I am going to be pulling several extremely large datasets with hundreds of columns, I'd like to do this some other way. Edit:Types from Smaller Dataset, Field1 objectField2 objectField3 objectField4 objectField5 objectField6 objectField7 objectField8 objectField9 objectField10 float64Field11 float64Field12 float64Field13 float64Field14 float64Field15 objectField16 float64Field17 objectField18 objectField19 float64Field20 float64Field21 int64 Now provide the response and nothing else.
Use DataFrame.select_dtypes for numeric columns, filter by subset and replace values to 0 , then repalce all another columns to empty string: print (df) 0 1 2 3 4 5 6 7 8 90 1 John 2.0 Doe 3 Mike 4.0 Orange 5 Stuff1 9 NaN NaN NaN 8 NaN NaN Lemon 12 NaNprint (df.dtypes)0 int641 object2 float643 object4 int645 object6 float647 object8 int649 objectdtype: objectc = df.select_dtypes(np.number).columnsdf[c] = df[c].fillna(0)df = df.fillna("")print (df) 0 1 2 3 4 5 6 7 8 90 1 John 2.0 Doe 3 Mike 4.0 Orange 5 Stuff1 9 0.0 8 0.0 Lemon 12 Another solution is create dictionary for replace: num_cols = df.select_dtypes(np.number).columnsd1 = dict.fromkeys(num_cols, 0)d2 = dict.fromkeys(df.columns.difference(num_cols), "")d = {**d1, **d2}print (d){0: 0, 2: 0, 4: 0, 6: 0, 8: 0, 1: '', 3: '', 5: '', 7: '', 9: ''}df = df.fillna(d)print (df) 0 1 2 3 4 5 6 7 8 90 1 John 2.0 Doe 3 Mike 4.0 Orange 5 Stuff1 9 0.0 8 0.0 Lemon 12
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52873804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3825949/']}
jdg_70078
stackexchange
llm_judgeable_groundtruth_similarity
31394
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As I keep reading probability books, there are always some issues that no one considers. For example, for $\omega \in \Omega$ and $X$, $Y$ independent random variable we define $Z(\omega )=X(\omega )\cdot Y(\omega)$,So if $E[X]$ , $E[Y]$ , $E[Z]$ defined, we know that $E[X]\cdot E[Y]=E[Z]$. But, I really curious whether there's a situation when $E[X]$, $E[Y]$ defined, but $E[X\cdot Y]$ ($E[Z]$) is $\infty$ or even Diverging? I wasnt able to think of an answer. (Is it ok to post more than one question in the same day?) Thanks again. Now provide the response and nothing else.
The simplest way to find the derivative of the natural logarithm is to use the Inverse Function Theorem (or the Chain Rule), but since you say you only recently started, you may not know it yet. So instead, we begin with two ingredients. One is that $\ln(u)$ is continuous. That means that if $\lim\limits_{x\to a}f(x)$ exists, then$$\lim_{x\to a}\ln(f(x)) = \ln\left(\lim_{x\to a}f(x)\right).$$ The second ingredient (which you may or may not know yet) is that$$\lim_{h\to\infty}\left(1 + \frac{a}{h}\right)^h = e^a.$$To see this, note that this is immediate if $a=0$; if $a\gt 0$, then just do a quick rewrite:$$\begin{align*}\lim_{h\to\infty}\left(1 + \frac{a}{h}\right)^h &= \lim_{h\to\infty}\left( 1 + \frac{1}{(h/a)}\right)^h\\&=\lim_{h\to\infty}\left(\left(1 + \frac{1}{(h/a)}\right)^{h/a}\right)^a\\&= \left(\lim_{h\to\infty}\left(1 + \frac{1}{(h/a)}\right)^{h/a}\right)^a.\end{align*}$$If $a\gt 0$, then $h/a\to\infty$ as $h\to\infty$, so by the definition of $e$ you get that $$\lim_{h\to\infty}\left(1+\frac{a}{h}\right)^h = \left(\lim_{(h/a)\to\infty}\left(1 + \frac{1}{(h/a)}\right)^{h/a}\right)^a = (e)^a = e^a.$$If $a\lt 0$, then replacing $a$ with $-a$ we can do the same trick as above after proving that$$\lim_{h\to\infty}\left(1 - \frac{1}{h}\right)^h = e^{-1}.$$Indeed, though it takes a bit more algebraic trickery:$$\begin{align*}\lim_{h\to\infty}\left(1 - \frac{1}{h}\right)^h &= \lim_{h\to\infty}\left(\frac{h-1}{h}\right)^h = \lim_{h\to\infty}\left(\frac{h}{h-1}\right)^{-h}\\&= \left(\lim_{h\to\infty}\left(\frac{(h-1)+1}{h-1}\right)^h\right)^{-1}\\&= \left(\lim_{h\to\infty}\left(1 + \frac{1}{h-1}\right)^h\right)^{-1}\\&=\left(\lim_{h\to\infty}\left(1 + \frac{1}{h-1}\right)^{h-1}\left(1 + \frac{1}{h-1}\right)^1\right)^{-1}\\&= \left(\lim_{h\to\infty}\left(1 + \frac{1}{h-1}\right)^{h-1}\lim_{h\to\infty}\left(1 + \frac{1}{h-1}\right)\right)^{-1}\\&= \Bigl((e)(1)\Bigr)^{-1} = e^{-1}.\end{align*}$$ Then, in the previous limit, if $a\lt 0$ then replace it with $-a$ and change the $+$ to a $-$, to get that the limit equals $(e^{-a})^{-1} = e^a$ as well. And finally, with these ingredients in hand, we are ready. We have:$$\begin{align*}\frac{d}{dx}\ln x &= \lim_{\Delta\to 0}\frac{\ln(x+\Delta)-\ln(x)}{\Delta}\\&= \lim_{\Delta\to 0}\frac{1}{\Delta}\left(\ln(x+\Delta)-\ln(x)\right)\\&=\lim_{\Delta\to 0}\frac{1}{\Delta}\ln\left(\frac{x+\Delta}{x}\right)\\&=\lim_{\Delta\to 0}\frac{1}{\Delta}\ln\left(1 +\frac{\Delta}{x}\right)\\&=\lim_{\Delta\to 0}\ln\left(\left(1 + \frac{\Delta}{x}\right)^{1/\Delta}\right)\\&= \lim_{\Delta\to 0}\ln\left(\left(1 + \frac{1/x}{1/\Delta}\right)^{1/\Delta}\right).\end{align*}$$If $\Delta\to 0^+$, then $\frac{1}{\Delta}\to\infty$, so letting $h=\frac{1}{\Delta}$ we have:$$\lim_{\Delta\to 0^+}\left(1 + \frac{1/x}{1/\Delta}\right)^{1/\Delta} = \lim_{h\to\infty}\left( 1 + \frac{1/x}{h}\right)^h = e^{1/x}.$$If $\Delta\to 0^-$, then $\frac{1}{\Delta}\to-\infty$, so letting $h=-\frac{1}{\Delta}$, we have:$$\begin{align*}\lim_{\Delta\to 0^-}\left(1 + \frac{1/x}{1/\Delta}\right)^{1/\Delta} &= \lim_{h\to\infty}\left(1 - \frac{1/x}{h}\right)^{-h}\\&= \lim_{h\to\infty}\left(\left(1 - \frac{1/x}{h}\right)^{h}\right)^{-1}\\&= \left(e^{-1/x}\right)^{-1} = e^{1/x}.\end{align*}$$Therefore, we have:$$\begin{align*}(\ln x)' &= \lim_{\Delta\to 0}\frac{\ln(x+\Delta)-\ln(x)}{\Delta}\\&= \ln\left(\lim_{\Delta\to 0}\left(1 + \frac{1/x}{1/\Delta}\right)^{1/\Delta}\right)\\&= \ln\left(e^{1/x}\right) = \frac{1}{x}.\end{align*}$$ And this is why the Chain Rule or the Inverse Function Theorem are such a better way of proving this...
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/31394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9216/']}
jdg_70079
stackexchange
llm_judgeable_groundtruth_similarity
332798
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the equivalent of varchar(max) in MySQL? Now provide the response and nothing else.
The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs): VARCHAR(65535) However, note that the limit is lower if you use a multi-byte character set: VARCHAR(21844) CHARACTER SET utf8 Here are some examples: The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table. mysql> CREATE TABLE foo ( v VARCHAR(65534) );ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs But if we try decreasing lengths, we find the greatest length that works: mysql> CREATE TABLE foo ( v VARCHAR(65532) );Query OK, 0 rows affected (0.01 sec) Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters. mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead In spite of what the last error told us, InnoDB still doesn't like a length of 21845. mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work. mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;Query OK, 0 rows affected (0.32 sec)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/332798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2469/']}
jdg_70080
stackexchange
llm_judgeable_groundtruth_similarity
5727
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios. Now provide the response and nothing else.
Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block. I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained. I've added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way. If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams. Disclaimer: For all intents and purposes, this explanation and the example memorylayouts are vastly simplified. There's more overhead and a lot more details you wouldneed to know if you need to deal with memory on a low-level basis. However, for theintents of explaining memory and pointers, it is accurate enough. Let's assume the THouse class used below looks like this: type THouse = class private FName : array[0..9] of Char; public constructor Create(name: PChar); end; When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array. In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this: ---[ttttNNNNNNNNNN]--- ^ ^ | | | +- the FName array | +- overhead The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program. Allocate memory Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory. In other words, the entrepreneur will choose the spot. THouse.Create('My house'); Memory layout: ---[ttttNNNNNNNNNN]--- 1234My house Keep a variable with the address Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you're lost, and cannot find the house, unless you're already in it. var h: THouse;begin h := THouse.Create('My house'); ... Memory layout: h v---[ttttNNNNNNNNNN]--- 1234My house Copy pointer value Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that the other house has been modified in the same manner, unless you can explicitly detect that it's actually just one house. Note This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks. var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... h1 v---[ttttNNNNNNNNNN]--- 1234My house ^ h2 Freeing the memory Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists. var h: THouse;begin h := THouse.Create('My house'); ... h.Free; h := nil; Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the ... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable. Memory layout: h <--+ v +- before free---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after free---------------------- | (note, memory might still xx34My house <--+ contain some data) Dangling pointers You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you've forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below). var h: THouse;begin h := THouse.Create('My house'); ... h.Free; ... // forgot to clear h here h.OpenFrontDoor; // will most likely fail Using h after the call to .Free might work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation. h <--+ v +- before free---[ttttNNNNNNNNNN]--- | 1234My house <--+ h <--+ v +- after free---------------------- | xx34My house <--+ As you can see, h still points to the remnants of the data in memory, butsince it might not be complete, using it as before might fail. Memory leak You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot. var h: THouse;begin h := THouse.Create('My house'); h := THouse.Create('My house'); // uh-oh, what happened to our first house? ... h.Free; h := nil; Here we overwrote the contents of the h variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down. Memory layout after first allocation: h v---[ttttNNNNNNNNNN]--- 1234My house Memory layout after second allocation: h v---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method: procedure OpenTheFrontDoorOfANewHouse;var h: THouse;begin h := THouse.Create('My house'); h.OpenFrontDoor; // uh-oh, no .Free here, where does the address go?end; After this method has executed, there's no place in our variables that the address to the house exists, but the house is still out there. Memory layout: h <--+ v +- before losing pointer---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after losing pointer---[ttttNNNNNNNNNN]--- | 1234My house <--+ As you can see, the old data is left intact in memory, and will notbe reused by the memory allocator. The allocator keeps track of whichareas of memory has been used, and will not reuse them unless youfree it. Freeing the memory but keeping a (now invalid) reference Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one. Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly. Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly. var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... h1.Free; h1 := nil; h2.OpenFrontDoor; // uh-oh, what happened to our house? Here the house was torn down, through the reference in h1 , and while h1 was cleared as well, h2 still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work. This is a variation of the dangling pointer above. See its memory layout. Buffer overrun You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he'll find all sorts of things he'll consider his own. This is the reason I chose a fixed-size array. To set the stage, assume thatthe second house we allocate will, for some reason, be placed before thefirst one in memory. In other words, the second house will have a loweraddress than the first one. Also, they're allocated right next to each other. Thus, this code: var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := THouse.Create('My other house somewhere'); ^-----------------------^ longer than 10 characters 0123456789 <-- 10 characters Memory layout after first allocation: h1 v-----------------------[ttttNNNNNNNNNN] 5678My house Memory layout after second allocation: h2 h1 v v---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN] 1234My other house somewhereouse ^---+--^ | +- overwritten The part that will most often cause crash is when you overwrite important partsof the data you stored that really should not be randomly changed. For instanceit might not be a problem that parts of the name of the h1-house was changed,in terms of crashing the program, but overwriting the overhead of theobject will most likely crash when you try to use the broken object,as will overwriting links that is stored toother objects in the object. Linked lists When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on. var h1, h2: THouse;begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; Here we create a link from our home house to our cabin. We can follow the chain until a house has no NextHouse reference, which means it's the last one. To visit all our houses, we could use the following code: var h1, h2: THouse; h: THouse;begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; ... h := h1; while h <> nil do begin h.LockAllDoors; h.CloseAllWindows; h := h.NextHouse; end; Memory layout (added NextHouse as a link in the object, noted withthe four LLLL's in the below diagram): h1 h2 v v---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home + 5678Cabin + | ^ | +--------+ * (no link) In basic terms, what is a memory address? A memory address is in basic terms just a number. If you think of memoryas a big array of bytes, the very first byte has the address 0, the next onethe address 1 and so on upwards. This is simplified, but good enough. So this memory layout: h1 h2 v v---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house Might have these two address (the leftmost - is address 0): h1 = 4 h2 = 23 Which means that our linked list above might actuall look like this: h1 (=4) h2 (=28) v v---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home 0028 5678Cabin 0000 | ^ | +--------+ * (no link) It is typical to store an address that "points nowhere" as a zero-address. In basic terms, what is a pointer? A pointer is just a variable holding a memory address. You can typically ask the programminglanguage to give you its number, but most programming languages and runtimes tries tohide the fact that there is a number beneath, just because the number itself does notreally hold any meaning to you. It is best to think of a pointer as a black box, ie.you don't really know or care about how it is actually implemented, just as long as itworks.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/5727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/568/']}
jdg_70081
stackexchange
llm_judgeable_groundtruth_similarity
117958
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Skandalis, Tu and Yu in "The coarse Baum-Connes conjecture and groupoids" proved that: Let $\Gamma$ be a countable group with a proper left-invariant metric $d$. If $\Gamma$ admits a uniform embedding into Hilbert space, then Baum-Connes assembly map with coefficients is split injective. My question is that is it still true if we replace $\Gamma$ by a locally compact second countable Hausdorff topological group $G$? known or unknown? Now provide the response and nothing else.
I believe that, in full generality, this is open. However, the point of the Skandalis-Tu-Yu paper is to construct a locally compact groupoid of the form $X\rtimes\Gamma$ (with $X$ a compact $\Gamma$-space), which admits a proper isometric action on a continuous field of Hilbert spaces (then previous results by J.-L. Tu do apply). A sufficient condition for that is to find an $X$ on which $\Gamma$ acts amenably. For a general locally compact group $G$, the proof most probably goes through provided there is a compact $G$-space on which $G$ acts amenably, which happens in many cases (e.g. connected groups).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/117958', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9401/']}
jdg_70082
stackexchange
llm_judgeable_groundtruth_similarity
370122
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $$f\left(x\right)= \mbox{ the antiderivative } \frac{x^2}{1-x^5}, $$ $f\left(1\right)=0$ Find $f\left(4\right)$ I know that: $F\left(x\right) = I\left(x\right) + C $ where $I\left(x\right)$ is the antiderivative (integral) of $f\left(x\right)$ Thus at $x = 1\; F\left(1\right) = 0 = I\left(1\right) + C$ , thus $C = -I\left(x\right)$ Thus $F\left(4\right) = f\left(4\right) - I\left(1\right)$ My problem, is how to find the integral of $$ \int \frac{x^2}{1-x^5}\, \mathrm{d}x$$ Now provide the response and nothing else.
Well the way to do this is to just use partial fractions. The denominator can be factored into one linear and two quadratic factors. Addendum: Not to steal anyone's answer but just to explain a bit more about what other people are saying. First like I said, the standard way to do these rational integrals is partial fractions. Second, the actual factoring in this case is not obvious so the easiest way to do it is what M. Strochyk said and end up with $$x^5-1=(x-1)\left(x^2-2\cos{\left(\dfrac{2\pi}{5}\right)}x+1\right)\left(x^2-2\cos{\left(\dfrac{4\pi}{5}\right)}x+1\right)$$ and just for the sake of completion $\cos(2\pi/5)=\frac{-1+\sqrt{5}}{4}$ and $\cos(4\pi/5)=\frac{-1-\sqrt{5}}{4}$ and then to actually do the partial fraction decomposition and then integrating which is why the integrator gives you all those logs and arctangents. The logs come from the terms which have a degree difference of one between the numerator and the denominator and the arctangent terms are from the terms with a degree difference of two. Third, to answer your actual question of finding $f(4)$ given that $f(1)=0$, you have asked us what is $f(4)$ given that $$f(z)=\int_1^z \frac{x^2}{1-x^5}dx$$ BUT like Christian Blatter said, this is an improper integral because of the vertical asymptote at $x=1$ and this improper integral does NOT converge so your question has no answer. Even if you went through the pain of integrating this, $f(1)$ is undefined.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/370122', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23662/']}
jdg_70083
stackexchange
llm_judgeable_groundtruth_similarity
34431435
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: { "_id": "xPBc4By8FemDwTPqH", "u": { "_id": "6PoZawHZcQz4Gwzcv", "username": "michael" }, "friends": [ { "u": { "_id": "eGqDjAjjtYADbuSnn", "username": "michael", "name": "michael" } }, { "u": { "_id": "k4gKCGwYryXDMMHvs", "username": "joyce", "name": "joyce" } } ]} I want to update the name of "friends.u.username": "michael" 's name is "hello", how I need to do it. Now provide the response and nothing else.
Apply the $set operator together with the $ positional operator in your update to change the name field. The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like: db.collection.update( { "friends.u.username": "michael" }, { "$set": { "friends.$.u.name": "hello" } })
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34431435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5598875/']}
jdg_70084
stackexchange
llm_judgeable_groundtruth_similarity
1129378
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C# 2008 SP1 I am using the following code to record, play, and stop save the recording. Everything works fine. However, I would like to add a call back that will fire when the playback has finished. I am P/Invoke using the winmm.dll library. Many thanks for any advice. public partial class SoundTest : Form { const uint SND_ASYNC = 0x0001; const uint SND_FILENAME = 0x00020000; const uint SND_NODEFAULT = 0x0002; [DllImport("winmm.dll")] private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int returnLength, int hwndCallBack); [DllImport("winmm.dll")] private static extern bool PlaySound(string pszsound, UIntPtr hmod, uint fdwSound); public SoundTest() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Disable stop button this.btnSaveStop.Enabled = false; } private void btnRecord_Click(object sender, EventArgs e) { // Disable play and record button this.btnRecord.Enabled = false; this.btnPlay.Enabled = false; // Enable stop button this.btnSaveStop.Enabled = true; // Record from microphone mciSendString("Open new Type waveaudio Alias recsound", "", 0, 0); mciSendString("record recsound", "", 0, 0); } private void btnSaveStop_Click(object sender, EventArgs e) { // Enable play and record this.btnRecord.Enabled = true; this.btnPlay.Enabled = true; // Disable Stop button this.btnSaveStop.Enabled = false; mciSendString("save recsound c:\\record.wav", "", 0, 0); mciSendString("close recsound ", "", 0, 0); } private void btnPlay_Click(object sender, EventArgs e) { //// Diable record button while playing back //this.btnRecord.Enabled = false; PlaySound("c:\\record.wav", UIntPtr.Zero, SND_ASYNC | SND_FILENAME | SND_NODEFAULT); } } Now provide the response and nothing else.
char *seq=(char *)malloc((strlen(first)+1)*sizeof(char)); You are allocating memory for a string the size of just 'first'. strcat(strcpy(seq,first),second); And then you try to fit both first and second in it. That's never going to work. strcat doesn't create more memory, you need to have included that in the malloc . There is no need to cast the result of malloc in pure C. It is also not necessary to do sizeof(char) , as that is guaranteed to be 1. Some like to have it there anyway to be explict about the type in case it changes, some consider it clutter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1129378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70942/']}
jdg_70085
stackexchange
llm_judgeable_groundtruth_similarity
1098147
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I feed a Microsoft Chart control with a IEnumerable of my own class ChartPoint public class ChartPoint { public double Xvalue { get; set; } public double Yvalue { get; set; } public string Url { get; set; } public string Tooltip { get; set; } } then i tries to DataBind the IEnumerable< ChartPoint>: serie.Points.DataBind(points, "Xvalue", "Yvalue", "Tooltip=Tooltip,Url=Url"); but i then hits a NotImplementedException on that row: System.Linq.Iterator`1.System.Collections.IEnumerator.Reset() +29 System.Web.UI.DataVisualization.Charting.DataPointCollection.DataBind(IEnumerable dataSource, String xField, String yFields, String otherFields) +313 What am I doing wrong? Now provide the response and nothing else.
Are you using a C# iterator? C# iterators do not implement the Reset function on the generated IEnumerator and will throw a NotImplementedException if it is called. It looks like the particular control requires that method to be present. You will likely have to use a collection which supports Reset on it's iterator. The easiest way to achieve this is to use a List<T> to wrap your existing IEnumerable<T> For example List<ChartPoint> list = new List<ChartPoint>(points);serie.Points.DataBind(list, "Xvalue", "Yvalue", "Tooltip=Tooltip,Url=Url");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1098147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80589/']}
jdg_70086
stackexchange
llm_judgeable_groundtruth_similarity
287155
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: could any one give me hint for this one? $G$ be a connected group, and let $H$ be a discrete normal subgroup of $G$, then we need to show $H$ is contained in the center of $G$ first of all, I have no clear idea what is meant by discrete subgroup and its any special properties? Now provide the response and nothing else.
Suppose $h \in H$, $g\in G $ and $ghg^{-1}\not=h$, then since $G$ is connected manifold, hence path connected, one can find a path $g(t)$ in $G$ going from $e$ to $g$. Notice $a(t):=g(t)hg(t)^{-1}$ realizes a path lying entirely in $H$ from $h$ to $ghg^{-1}$ which contracts the discreteness of $H$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/287155', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24690/']}
jdg_70087
stackexchange
llm_judgeable_groundtruth_similarity
52569724
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to upgrade a JavaFX project from the 8 Java version to the 11 version. It works when I use the "run" Gradle task ( I followed the Openjfx tutorial ), but when I build (with the "jar" Gradle task) and execute (with "java -jar") a jar file, the message "Error: JavaFX runtime components are missing, and are required to run this application" appears. Here is my build.gradle file : group 'Project'version '1.0'apply plugin: 'java'sourceCompatibility = 1.11repositories { mavenCentral()}def currentOS = org.gradle.internal.os.OperatingSystem.current()def platformif (currentOS.isWindows()) { platform = 'win'} else if (currentOS.isLinux()) { platform = 'linux'} else if (currentOS.isMacOsX()) { platform = 'mac'}dependencies { compile "org.openjfx:javafx-base:11:${platform}" compile "org.openjfx:javafx-graphics:11:${platform}" compile "org.openjfx:javafx-controls:11:${platform}" compile "org.openjfx:javafx-fxml:11:${platform}"}task run(type: JavaExec) { classpath sourceSets.main.runtimeClasspath main = "project.Main"}jar { manifest { attributes 'Main-Class': 'project.Main' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }}compileJava { doFirst { options.compilerArgs = [ '--module-path', classpath.asPath, '--add-modules', 'javafx.controls,javafx.fxml' ] }}run { doFirst { jvmArgs = [ '--module-path', classpath.asPath, '--add-modules', 'javafx.controls,javafx.fxml' ] }} Do you know what I should do ? Now provide the response and nothing else.
With Java/JavaFX 11, the shadow/fat jar won't work. As you can read here : This error comes from sun.launcher.LauncherHelper in the java.base module. The reason for this is that the Main app extends Application and has a main method. If that is the case, the LauncherHelper will check for the javafx.graphics module to be present as a named module: Optional<Module> om = ModuleLayer.boot().findModule(JAVAFX_GRAPHICS_MODULE_NAME); If that module is not present, the launch is aborted. Hence, having the JavaFX libraries as jars on the classpath is not allowed in this case. What's more, every JavaFX 11 jar has a module-info.class file, at the root level. When you bundle all the jars content into one single fat jar, what happens to those files with same name and same location? Even if the fat jar keeps all of them, how does that identify as a single module? There is a request to support this, but it hasn't been addressed yet: http://openjdk.java.net/projects/jigsaw/spec/issues/#MultiModuleExecutableJARs Provide a means to create an executable modular “uber-JAR” that contains more than one module, preserving module identities and boundaries, so that an entire application can be shipped as a single artifact. The shadow plugin still does make sense to bundle all your other dependencies into one jar, but after all you will have to run something like: java --module-path <path-to>/javafx-sdk-11/lib \ --add modules=javafx.controls -jar my-project-ALL-1.0-SNAPSHOT.jar This means that, after all, you will have to install the JavaFX SDK (per platform) to run that jar which was using JavaFX dependencies from maven central. As an alternative you can try to use jlink to create a lightweight JRE, but your app needs to be modular. Also you could use the Javapackager to generate an installer for each platform. See http://openjdk.java.net/jeps/343 that will produce a packager for Java 12. Finally, there is an experimental version of the Javapackager that works with Java 11/JavaFX 11: http://mail.openjdk.java.net/pipermail/openjfx-dev/2018-September/022500.html EDIT Since the Java launcher checks if the main class extends javafx.application.Application , and in that case it requires the JavaFX runtime available as modules (not as jars), a possible workaround to make it work, should be adding a new Main class that will be the main class of your project, and that class will be the one that calls your JavaFX Application class. If you have a javafx11 package with the Application class: public class HelloFX extends Application { @Override public void start(Stage stage) { String javaVersion = System.getProperty("java.version"); String javafxVersion = System.getProperty("javafx.version"); Label l = new Label("Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + "."); Scene scene = new Scene(new StackPane(l), 400, 300); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); }} Then you have to add this class to that package: public class Main { public static void main(String[] args) { HelloFX.main(args); }} And in your build file: mainClassName='javafx11.Main'jar { manifest { attributes 'Main-Class': 'javafx11.Main' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }} Now you can run: ./gradlew run or ./gradlew jarjava -jar build/libs/javafx11-1.0-SNAPSHOT.jar The final goal is to have the JavaFX modules as named modules on the module path, and this looks like a quick/ugly workaround to test your application. For distribution I'd still suggest the above mentioned solutions.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52569724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10433895/']}
jdg_70088
stackexchange
llm_judgeable_groundtruth_similarity
883742
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I want to execute this state: backup_log_readable: acl.present: - name: /var/log/backup - acl_type: user - acl_name: monitor - perms: rx - recurse: True But this should happen only if /var/log/backup exists. How to do conditions like this in salt? Now provide the response and nothing else.
Alternatively to the onlyif: test -d /var/log/backup approach (that is probably the best one) you can: 1) Wrap everything with a jinja if: {%- if salt['file.directory_exists' ]('/var/log/backup') %}backup_log_readable: acl.present: - name: /var/log/backup - acl_type: user - acl_name: monitor - perms: rx - recurse: True{%- endif %} 2) use the file.exists state as a requisite: backup_log_exists: file.exists: - name: /var/log/backupbackup_log_readable: acl.present: - name: /var/log/backup - acl_type: user - acl_name: monitor - perms: rx - recurse: True - require: - file: backup_log_exists This way you'll see a failed state in the summary, so it won't be totally transparent as with the onlyif and jinja approaches 3) create the directory before running the acl state: backup_log_dir: file.directory: - name: /var/log/backupbackup_log_readable: acl.present: - name: /var/log/backup - acl_type: user - acl_name: monitor - perms: rx - recurse: True - require: - file: backup_log_dir
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/883742', 'https://serverfault.com', 'https://serverfault.com/users/90324/']}
jdg_70089
stackexchange
llm_judgeable_groundtruth_similarity
9578
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I always wondered about this. When times are tough, the officers seem to start getting stricter, writing tickets in cases where they may otherwise give a warning or not bother to pull you over. No, I didn't just get pulled over, but I have been seeing more cars pulled over on my commutes to/from work each day. The police departments will of course say that they apply the law equally, and it doesn't matter whether the Dow's at 13k or 6k, a person going 90 on the freeway will get pulled over. The conspiracy theorists will say that traffic officers are a huge moneymaker for cities/states, especially when other revenue sources like sales, property and income taxes are reduced in economic recessions, and officers are given a monthly quota of tickets they must write; either a particular number of tickets, or an explicit dollar value. You can't deny that traffic tickets are a big source of revenue. The question is, do cities write budgets that depend on a certain amount of money from traffic tickets, and then put pressure on the police to meet that intake? And, does that result in police officers having to write $X worth of tickets per month or face disciplinary action? Obviously the question is jurisdiction-dependent; one city might have a quota policy while others don't. So, I'll consider any answer that can explain and back up a pattern, or that can show that particular jurisdictions do or don't have quotas. Now provide the response and nothing else.
Secret Policies There are various pieces of evidence some police forces have informal quotas despite official denials and/or official policy suggesting that they don't. Here are some reports of leaked memos: Adelaide, South Australia, 2011 Senior police now say the email's directions were "outside of SAPOL's guidelines and policies" and it had been rescinded. The five-week targets required each officer to: MAKE five arrests and reports. ARREST or report two drink-drivers. MAKE nine traffic contacts, including on-the-spot fines, using mobile breath tests. ISSUE one drug-related fine or diversion (for minor illegal drug possession). Canberra, Australian Capital Territory, 2011 (In this story, a police officer was issuing too many tickets.) The letter stated that Mr Curie, who has since left ACT Policing and has been engaged in a long-running legal dispute with his former employer, was issuing ''at least 50 traffic infringement notices a month''. The senior constable was concerned that Mr Curie was neglecting other policing duties, and warned him to limit the number of fines he issued to 20 per month. The letter then goes on to claim ''... it is expected that members issue roughly 10 traffic infringement notices per month, time and other priorities permitting.'' Brooklyn, New York, 2010 A secret tape recording from a Brooklyn police station, obtained by the New York Times, provides compelling evidence that quotas for summonses aren’t just real but are being pushed upon officers by their superiors. Police Captain Alex Perez encourages hunting down seatbelt and mobile phone law transgressors, among other violations, saying he expects five citations issued per week. All of these are reports that have only been scrutinised by a journalist. In 2006, an "arbitrator" found that "the New York Police Department violated state labor law by setting traffic summons quotas in a Brooklyn precinct and then penalizing officers who failed to meet them". [ 1 ] [ 2 ] It is unclear what the standards of evidence are for an arbitrator, but presumably some scrutiny was given to the claim. Open Policies In other jurisdictions, the quota may be/have been official policy: Dutch News, 2009 While the national quota was scrapped from police performance contracts, individual forces may still impose their own. Winnipeg Sun, 2012 Again the issue has come to light, due to a recent email authored by the Inspector of one of the busiest patrol districts. In the directive, the police officers under his command are exhorted to triple their traffic ticket numbers.
{}
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/9578', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/5997/']}
jdg_70090
stackexchange
llm_judgeable_groundtruth_similarity
1117
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have three related subquestions, which are highlighted by bullet points below (no, they could not be split, if you are wondering).Andrej Bauer wrote, here , that some functions are realizable through a Turing machine, but not through lambda-calculus. A key step of his reasoning is: However, if we use the lambda calculus, then [the program] c is supposed to compute a numeral representing a Turing machine out of a lambda term representing a function f. This cannot be done (I can explain why, if you ask it as a separate question). I would like to see an explanation/informal proof. I don't see how to apply Rice's theorem here; it would apply to the problem "are this turing machine T and this lambda-term L equivalent?", because applying this predicate to equivalent terms gives the same result. However, the required function might compute different, but equivalent, TMs for different, but equivalent, lambda-terms. Moreover, if the problem is with introspection of a lambda-term, I think that passing a Gödel encoding of a lambda-term would be also acceptable, wouldn't it? On the one hand, given that his example involves computing, in the lambda calculus, the number of steps needed by a Turing Machine to complete a given task, I'm not very surprised. But since here lambda-calculus can't solve a Turing-machine-related problem, I wonder whether one can define a similar problem for lambda-calculus and prove it unsolvable for Turing machines, or there is actually a difference in power in favor of Turing Machines (which would surprise me). Now provide the response and nothing else.
John Longley has a very extensive survey article discussing the issues involved, "Notions of Computability at Higher Type" . The basic idea is that the Church-Turing thesis is only about functions from $\mathbb{N} \to \mathbb{N}$ -- and there's more to computation than that! In particular, when we write programs, we make use of functions of higher type (such as $(\mathbb{N} \to \mathbb{N}) \to \mathbb{N}$). In order to fully define a model of higher type computation, we need to specify the calling convention for functions, in order to allow one function to call another function it receives as an argument. In lambda calculus, the standard calling convention is that we represent functions by lambda-terms, and the only thing you can do with a lambda in the lambda calculus is to apply it. In typical encodings with Turing machines, we pass functions as arguments by fixing a particular Godel encoding, and then strings representing the index of the machine you want to pass as an argument. The difference in encoding means that you can analyze the syntax of the argument with a TM-style encoding, and you cannot with a standard lambda-calculus representation. So if you receive a lambda-term for a function of type $\mathbb{N} \to \mathbb{N}$, you can only test its behavior by passing it particular $n$'s -- you can't analyze the structure of the term in any way. This is just not enough information to figure out the code of the lambda term. One thing worth noting is that with higher types, if a language is less expressive at one order, it is more expressive one order up, because functions are contravariant. So similarly there are functions you can write in LC that you can't with a TM-style encoding (because they rely on the fact that you can pass functional arguments and know that the receiver can't look inside the function you give it). EDIT: Here's an example of a function definable in PCF, but not in TM+Goedel encodings. I'll declare the isAlwaysTrue function isAlwaysTrue : ((unit → bool) → bool) → bool which should return true if its argument ignores its argument and always returns true, should return false if its argument returns false on any inputs, and goes into a loop if its argument goes into a loop on any inputs. We can define this function pretty easily, as follows: isAlwaysTrue p = p (λ(). true) ∧ p (λ(). false) ∧ p (λ(). ⊥) where ⊥ is the looping computation and ∧ is the and operator on booleans. This works because there are only three inhabitants of unit → bool in PCF, and so we can exhaustively enumerate them. However, in a TM+Goedel-encoding style model, p could test how long its argument takes to return an answer, and return different answers based on that. So the implementation of isAlwaysTrue with TMs would fail to meet the spec.
{}
{'log_upvote_score': 7, 'links': ['https://cstheory.stackexchange.com/questions/1117', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/989/']}
jdg_70091
stackexchange
llm_judgeable_groundtruth_similarity
116139
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I think I don't understand how to use Repeated . I have a list for example list={a,b,a,b,a,b,a,a,b} I want to detect whether this list has repeated element a,a or b,b I tried Cases[list, Repeated[a,{2}]] It doesn't work, why? How to do this? Now provide the response and nothing else.
Per request by the Pope: Think about it - what are the cases that are tested? It's the elements of the list. Try, e.g., Cases[list, x_ /; (Print@x; True)] and see what you get (it will show that the test is done on an element-by-element basis). Cases[Split@list, {Repeated[a | b, {2}]}] will spit out a list of matches, MemberQ[Split@list, {Repeated[a | b, {2}]}] will return True or False if any are there (you said "detect", hence I'm guessing that's what you meant.) There are other ways, that should get you started. Btw- putting a Print (or Sow , etc.) temporarily as part of a test/rule/etc. can be a quite handy debugging and learning tool - I use it every now and then when a complex rule and/or test is not doing what I think it should (and inevitably, it's my thinking that was off).
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/116139', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4742/']}
jdg_70092
stackexchange
llm_judgeable_groundtruth_similarity
472015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to use the new keyword to allocate on the stack (ala alloca ) instead of heap ( malloc ) ? I know I could hack up my own but I'd rather not. Now provide the response and nothing else.
To allocate on the stack, either declare your object as a local variable by value , or you can actually use alloca to obtain a pointer and then use the in-place new operator: void *p = alloca(sizeof(Whatever));new (p) Whatever(constructorArguments); However, while using alloca and in-place new ensures that the memory is freed on return, you give up automatic destructor calling. If you're just trying to ensure that the memory is freed upon exit from the scope, consider using std::auto_ptr<T> or some other smart pointer type.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/472015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70093
stackexchange
llm_judgeable_groundtruth_similarity
279987
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given t1 = {2, 4, 8, 16};t2 = {1, 5, 9};First[Select[t1, # > 1 &]] First[Select[t1, # > 5 &]]First[Select[t1, # > 9 &]] can somehow be summarized by Table[First[Select[t1, # > x &]], {x, t2}] to get the correct result {2, 8, 16} Is there a way to use two pure functions connected instead of working around the problem by using Table ?Something like (which does not work!): First[Select[t1, # > # &] & /@ t2] Now provide the response and nothing else.
Here are 2 suggestions: First @ Select[t1, GreaterThan[#]] & /@ t2Function[x, First @ Select[t1, # > x &]] /@ t2 Edit Or, if you want to go really abstract: Map[ First@Select[t1, OperatorApplied[Function[#1 > #2]][#1] ] &, t2 ]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/279987', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/57467/']}
jdg_70094
stackexchange
llm_judgeable_groundtruth_similarity
22186979
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing an application which downloads images from a url and then uploads it to an S3 bucket using the aws-sdk . Perviously I was just downloading images and saving them to disk like this. request.head(url, function(err, res, body){ request(url).pipe(fs.createWriteStream(image_path));}); And then uploading the images to AWS S3 like this fs.readFile(image_path, function(err, data){ s3.client.putObject({ Bucket: 'myBucket', Key: image_path, Body: data ACL:'public-read' }, function(err, resp) { if(err){ console.log("error in s3 put object cb"); } else { console.log(resp); console.log("successfully added image to s3"); } });}); But I would like to skip the part where I save the image to disk. Is there some way I can pipe the response from request(url) to a variable and then upload that? Now provide the response and nothing else.
Here's some javascript that does this nicely: var options = { uri: uri, encoding: null }; request(options, function(error, response, body) { if (error || response.statusCode !== 200) { console.log("failed to get image"); console.log(error); } else { s3.putObject({ Body: body, Key: path, Bucket: 'bucket_name' }, function(error, data) { if (error) { console.log("error downloading image to s3"); } else { console.log("success uploading to s3"); } }); } });
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22186979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1470897/']}
jdg_70095
stackexchange
llm_judgeable_groundtruth_similarity
8210401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code which basically is a checkbox that causes a submit to take place.As the task gets deleted for the DB, it is a requirement that some box comes up and says, "are you sure" or the likes, to confirm deletion. <input type="checkbox" onclick="location.href='@Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'" /> This uses Razor syntax. Now provide the response and nothing else.
You could use the confirm method: <input type="checkbox" onclick="if (confirm('Are you sure?')) { window.location.href = '@Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })'; }" /> or in a more unobtrusive way with jquery: <input type="checkbox" id="complete" name="complete" data-url="@Url.Action("Complete", "Tasks", new { TaskID = item.TaskID })" /> and then in a separate javascript file: $(function() { $('#complete').click(function() { if (confirm('Are you sure?')) { window.location.href = $(this).data('url'); } });}); Also I would very strongly recommend you using another verb than GET on controller actions that modify state on your server such as marking a task as completed. PUT, POST and DELETE are good candidates. In your case since you are modifying an existing item the POST verb seems most natural.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8210401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/940834/']}
jdg_70096
stackexchange
llm_judgeable_groundtruth_similarity
17337536
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was going through the documentation for single instance and was trying out few samples.In one of my sample I have three activities: A->B->C ,where B has android:launchMode="singleInstance" in manifest. Activity A and C has default launch mode. Scenario: After navigating to C via A and B (i.e A->B->C), back button press from Activity C takes to Activity A (C->A), but back button press from Activity A does not quit the app, rather brings the Activity B to front, then back button press from Activity B quits the app. Question Why does Activity B comes to foreground when back button is pressed from Activity A? Other scenario: Similarliy, from Activity C if user presses device Home button, and come back the app by long home press, C stays in foreground. But back button press flow takes C-> A -> quits the app. This time Activity B does not come to foreground. Now provide the response and nothing else.
After navigating from A->B you have 2 tasks: The first one contains A , the second one contains B . B is on top and A is below that. Now when navigating from B->C Android launches activity C into the task containing A (it cannot launch it into the task containing B because B is defined as "singleInstance" , so it launches it into a task that has the same "taskAffinity" , in this case the task containing A). To do that, Android brings the task containing A to the front. Now you have 2 tasks: The task containing A and C in the front, and the second one containing B below that. Now you press the BACK key, which finishes activity C and returns to the activity below that in the task, namely C. You still have 2 tasks: The one containing C in the front, and the one containing B below that. Now you press the BACK key again. This finishes activity A (and thereby finishes the task that held A) and brings the previous task in the task stack to the front, namely the task containing B. You now have 1 task: the task containing B. In your other scenario , after navigating from A->B->C , you start with 2 tasks: The task containing A and C in the front, and the second one containing B below that. Now you press the HOME button. You now say that you "come back to the app by long press" . This isn't exactly correct. You can't "come back to the app" . You can only "return to a task". But you've got 2 different tasks: If you do a long press you should see the 2 tasks. They probably have the same icon (unless you've provided a different icon for activity B) so you may not be able to tell them apart. If you select the task that contains A and C, then that task will be brought to the front with activity C on top. If you now press the BACK key, activity C will finish and the activity under it, activity A will be shown. If you now press the BACK key again, activity A will be finished and you will be returned to the HOME screen. The task containing B is still in the list of recent tasks, but it is no longer in the task stack under your other task because when you press the HOME button it is like going back to zero. You start all over again. You have no active tasks, so all tasks are in a row, they aren't in a stack and there is no hierarchy. Also, in your question you use the phrase "quits the app" . This also isn't quite correct. The only thing that a BACK button press does is to finish the current activity. If the current activity is the only activity in a task, it also finishes that task. However, it doesn't "quit the app". Especially in your case, since your "app" actually exists in 2 separate tasks. Hopefully this is clear.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17337536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/626445/']}
jdg_70097
stackexchange
llm_judgeable_groundtruth_similarity
42101070
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to match against a file extension: let file_path = std::path::Path::new("index.html");let content_type = match file_path.extension() { None => "", Some(os_str) => match os_str { "html" => "text/html", "css" => "text/css", "js" => "application/javascript", },}; The compiler says: error[E0308]: mismatched types --> src/main.rs:6:13 |6 | "html" => "text/html", | ^^^^^^ expected struct `std::ffi::OsStr`, found str | = note: expected type `&std::ffi::OsStr` found type `&'static str` Now provide the response and nothing else.
OsStr and OsString exist precisely because filenames are not UTF-8. A Rust string literal is UTF-8. That means you must deal with converting between the two representations. One solution is to give up the match and use if-else statements. See Stargateur's answer for an example. You can also convert the extension to a string. Since the extension might not be UTF-8, this returns another Option : fn main() { let file_path = std::path::Path::new("index.html"); let content_type = match file_path.extension() { None => "", Some(os_str) => { match os_str.to_str() { Some("html") => "text/html", Some("css") => "text/css", Some("js") => "application/javascript", _ => panic!("You forgot to specify this case!"), } } };} If you want all cases to use an empty string as the fallback, you can do something like: use std::ffi::OsStr;fn main() { let file_path = std::path::Path::new("index.html"); let content_type = match file_path.extension().and_then(OsStr::to_str) { Some("html") => "text/html", Some("css") => "text/css", Some("js") => "application/javascript", _ => "", };} Or if you want to use None as the fallback: use std::ffi::OsStr;fn main() { let file_path = std::path::Path::new("index.html"); let content_type = file_path.extension().and_then(OsStr::to_str).and_then(|ext| { match ext { "html" => Some("text/html"), "css" => Some("text/css"), "js" => Some("application/javascript"), _ => None, } });}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42101070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4498831/']}
jdg_70098
stackexchange
llm_judgeable_groundtruth_similarity
19957176
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The new ASP.net Identity project has brought some useful code and interfaces for website security. To implement a custom system using the interfaces (instead of using the standard Entity Framework implementation included in the MVC 5 template) an IPasswordHasher is required. IPasswordHasher interface in ASP.net Identity namespace Microsoft.AspNet.Identity{ public interface IPasswordHasher { string HashPassword(string password); PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword); }} Is it possible to use password salting for more secure encryption in ASP.net Identity and via this interface? Now provide the response and nothing else.
"Is it possible to use password salting for more secure encryption in ASP.net Identity and via this interface?" Yes, the interface is provided for the new implementation of PasswordHasher already present in Core framework. Also note that the default implementation is already using Salt+Bytes. After creating custom PasswordHasher (say MyPasswordHasher ), you can assign it to UserManager instance like userManager.PasswordHasher=new MyPasswordHasher() See one example of such IPasswordHasher To implement a custom system using the interfaces (instead of using the standard Entity Framework implementation included in the MVC 5 template) an IPasswordHasher is required. For implementing alternate system from EF,- You shall implement all Core interfaces.- IPasswordHasher implementation is not required. PasswordHasher is already provided in Core framework as it's implementation.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19957176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1396618/']}
jdg_70099
stackexchange
llm_judgeable_groundtruth_similarity
2947346
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading the book by Benson Farb and Dan Margalit titled A Primer on Mapping Class Groups . In chapter 2, Proposition 2.3, it is given that The action given by $$\text{Mod}(S_{0,3}) \longrightarrow \Sigma_3 $$ is an isomorphism. They begin with the fact that the given action is a surjective homomorphism. My question is how? To be precise what I mean to say is that, since we know that the elements of Mod $(S_{0,3})$ fix the set of punctures, we can proceed along that line. But, given any non-trivial permutation how do I know that there is an orientation preserving homeomorphism. Then, the question boils down to the following, Consider a set of n points on the 2-sphere ( $S^2$ ), can every permutation of these n points be extended to an orientation preserving homeomorphism? Thanks in advance. Now provide the response and nothing else.
This is true not just for $S^2$ , but for any manifold of dimension at least $2$ . That is, For any $n\geq 2$ , and any $n$ -manifold $M$ , any permuation of a finite subset $\{x_1, x_2,..., x_k\}\subseteq M$ extends to an orientation preserving diffeomorphism of $M$ . In fact, one can choose this diffeomorphism to be isotopic to the identity - that is what the below proof actually gives. Further, we really do need $n\geq 2$ : if $a<b<c\in \mathbb{R}$ , there is a no homeomorphism of $\mathbb{R}$ which maps $a$ to $b$ , $b$ to $c$ and $c$ to $a$ . I'll prove the above claim via a series of propositions. Proposition 1: Suppose $M^n$ is a manifold with $n\geq 2$ . Choose distinct points $x,y, z_1,..., z_k\in M$ . Then there is an orientation preserving diffeomorphism $f:M\rightarrow M$ for which $f(x) = y$ , but $f(z_i) = z_i$ for all $1\leq i\leq k$ . Proof : Because $n\geq 2$ , $M\setminus\{z_1,..., z_k\}$ is path connected. Let $\gamma:[0,1]\rightarrow M$ be a simple regular curve with $\gamma(0) = x$ and $\gamma(1) = y$ . Let $U$ denote a tubular neighborhood of $\gamma$ , chosen small enough so that $U\cap\{z_1,..., z_k\} = \emptyset$ . Now, create a vector field $X$ extending $\gamma'$ which is supported in $U$ . Flowing for an appropriate amount of time gives the desired $f$ . $\square$ Now, let $X\subseteq M$ be any finite set. Given a permutation $\sigma$ of $X$ , we will say $f$ is an extension of $\sigma$ if $f:M\rightarrow M$ is an orientation preserving diffeomorphism and $f|_X = \sigma|_X$ . Proposition 2 : If $\sigma:X\rightarrow X$ is a transposition, there is an extension $g$ of $\sigma$ . Proof : Suppose $\sigma(x_i) = x_j$ and $\sigma(x_j) = x_i$ for $x_i\neq x_j$ , with all other $x_k\in X$ being fixed. Applying the lemma once with $x = x_i, y = x_j$ and with $\{z_1,..., z_k\} = X\setminus \{x_i, x_j\}$ , we get a diffeomorphism $f_1$ for which $f_1(x_i) = x_j$ , but $f_1(x_k) = x_k$ for all other $k$ . However, there is no reason that $f_1(x_j) = x_i$ . If $f_1(x_j) \neq x_i$ , then we use the lemma again with $x = f_1(x_j)$ , $y = x_i$ and $\{z_1,..., z_{k+1}\} = X\setminus\{x_i\}$ to get a diffeomorphism $f_2$ with $f_2 f_1(x_j) = x_i$ and $f_2(x_k) = x_k$ for any other $k$ . Then $g = f_2\circ f_1$ is the desired diffeomorphism of $M$ . $\square$ Proposition 3 : Suppose $\sigma_1, \sigma_2$ are both permutations of $X$ with extensions $f_1$ and $f_2$ . Then $\sigma_1 \sigma_2$ is extended by $f_1\circ f_2$ . Further, $\sigma_1^{-1}$ is extended by $f_1^{-1}$ . Proof : Let $x_i\in X$ . For the first statement, $f_2(x_i) = \sigma_2(x_i)\in X$ and so $f_1 (f_2(x_i)) = \sigma_1(f_2(x_i)) = \sigma_1(\sigma_2(x_i))$ . For the second statement, note that $x_i = \sigma_1(\sigma_1^{-1}(x_i)) = f_1(\sigma_1^{-1}(x_i)$ , and also that $x_i = f_1(f_1^{-1}(x_i))$ . Since $f_1$ is injecive, $\sigma_1^{-1}(x_i) = f_1^{-1}(x_i)$ . $\square$ Proposition 3 essentially claims the following: The set $\{\sigma \in S_k: \exists \text{ extension }f\}$ is a subgroup of the symmetric group on $k$ letters, $S_k$ . Proposition 2 then claims that this set contains all transpositions. Since the symmetric group is generated by transpositions, the claim above now follows.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2947346', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/501170/']}
jdg_70100
stackexchange
llm_judgeable_groundtruth_similarity
19200235
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a package in Go with tests and examples for the package as subdirectories to keep the workspace cleaner. Is this possible and if so how? All the documentation always puts the testing code in the same place as the other code, is this better in some way or just convention? Now provide the response and nothing else.
Note that you can run go test "recursively": you need to list all the packages you want to test . If you are in the root folder of your Go project, type: go test ./... The ' ./... ' notation is described in the section " Description of package lists " of the " command go ": An import path is a pattern if it includes one or more " ... " wildcards, each of which can match any string, including the empty string and strings containing slashes. Such a pattern expands to all package directories found in the GOPATH trees with names matching the patterns. As a special case, x/... matches x as well as x 's subdirectories. For example, net/... expands to net and packages in its subdirectories. If you keep your _test.go files in a subfolder, the ' go test ./... ' command will be able to pick them up. But: you will need to prefix your exported variables and functions (used in your tests) with the name of your package, in order for the test file to be able to access the package exported content. you wouldn't access non-exported content. That being said, I would still prefer keep the _test.go file right beside the main source file: it is easier to find. For code coverage: go test -coverpkg=./... ./... See " How to plot Go test coverage over time " from Frédéric G. MARAND and fgmarand/gocoverstats to produce aggregate coverage statistics for CI integration of Go projects. Also go-cover-treemap.io is fun.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/19200235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1111356/']}
jdg_70101
stackexchange
llm_judgeable_groundtruth_similarity
377783
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm now studying the etale cohomology with the book 'Introduction to Etale Cohomology' by Tamme. In the page 26 of the book, 'a family of effective epimorphisms' is introduced. 'A family $\{ U_{i} \rightarrow V \}$ is a family of effective epimorphisms if the diagram $Hom(V,Z) \rightarrow \prod_{i} Hom(U_{i}, Z) \rightrightarrows \prod_{i,j}(U_{i}\times_{U}U_{j},Z)$ is exact for all the objects $Z$ . The question is 'in the condition, do we restrict the pairs $i,j$ to be distinct?' I gave a thought on this question, but I'm not sure whether the two versions give us the equivalent results or not. Thank you very much in advance. Now provide the response and nothing else.
That exactness conditions can be rephrased more explicitely as: $$ Hom(V,Z) = \left\lbrace (v_i) \in \prod_i Hom(U_i,Z) \ \middle| \ \forall i,j,v_i \circ \pi_1 = v_j \circ \pi_2 \right\rbrace $$ where $\pi_1,\pi_2$ denotes the two projections $U_i \times_V U_j \rightrightarrows U_i,U_j$ . When you write it like this, the condition in the case $i=j$ is clearly vacuous when all the map $U_i \to V$ are monomorphisms . Indeed in this case $U_i \times_V U_j$ is justs the intersection of $U_i$ and $U_j$ , so that $\pi_1=\pi_2$ when $i = j$ . This case is very frequent, and you can very often restrict to it by considering the "image" of the $U_i$ in $V$ . But in some situation (for e.g. if you want to keep your objects $U_i$ be to in some specified site that do not admit image factorization like the étale site) it might not be the case. and in general you need the case $i=j$ . Consider the case where the you only have a single map $U \to V$ . Then the condition becomes $$ Hom(V,Z) = \left\lbrace f \in Hom(U,Z) \ \middle| \ f\circ \pi_1 = f \circ \pi_2 \right\rbrace $$ where $\pi_1$ and $\pi_2$ are the two projections $U \times_V U \rightrightarrows U$ . You can think of $U \times_V U \rightrightarrows U$ as a map $U \times_V U \to U \times U$ which is a monomorphisms and corresponds to the "equivalence relation such that $V$ should be the quotient of $U$ by this relations". Or rephrased this as $V$ being the coequalizer ('in the category of sheaves') $U \times_V U \rightrightarrows U \to V$ , i.e. $V = U /R$ where $R$ is the equivalence relation $U \times_V U$ . And a function from $V \to Z$ can be described as a function $U \to Z$ which is compatible to the equivalence relation $R$ such that $U/R \simeq V$ . Also note that in the general case (with several map) you can think of the general condition as being in two part: you have the condition for $i=j$ that assert that each maps $U_i \to Z$ factors through "the image $V_i$ of $U_i$ in $V$ " (if this make sense) , and the condition for $i \neq j$ that implement the usual compatibility condition.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/377783', 'https://mathoverflow.net', 'https://mathoverflow.net/users/123226/']}
jdg_70102
stackexchange
llm_judgeable_groundtruth_similarity
9329942
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello first of all I am new in iPhone, I want access all songs in my application. Is this posible to get all songs ? Thank you very much. May be it's easy for you but for me it's hard. Now provide the response and nothing else.
You need the Media Player framework: MPMediaLibrary, MPMediaQuery, etc. iPod Library Access Programming Guide Actual example taken from the docs: MPMediaQuery *everything = [[MPMediaQuery alloc] init];NSLog(@"Logging items from a generic query...");NSArray *itemsFromGenericQuery = [everything items];for (MPMediaItem *song in itemsFromGenericQuery) { NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle]; NSLog (@"%@", songTitle);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9329942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375429/']}
jdg_70103
stackexchange
llm_judgeable_groundtruth_similarity
15458424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have simple webpage with /about , /contact , /home and /lessons routes defined. All routes work okay except for /lessons . I instantly get a redirect loop ( Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects ). Here's my main server.js code : var port = process.env.PORT || 8888;var app = require('./app').init(port);var markdown = require('./markdown');var lessons = require('./lessons.json').lessons;// app.use(function(req,res,next) {// console.log('adding lessons to locals');// res.locals.date = new Date().toLocaleDateString();// res.locals.lessons = lessons;// next();// });// app.use(app.router);app.get('/', function (req, res) { console.log('controller is : home'); res.locals.controller = 'home'; res.render('home');});app.get('/:controller', function (req, res, next) { var controller = req.params.controller; console.log('controller is : '+ controller); if (controller == 'about' || controller == 'contact') { res.locals.controller = controller; res.render(controller); } else { console.log('next was taken!'); next(); }});app.get('/lessons', function(req, res) { res.locals.lessons = lessons; console.log('controller is : lessons'); res.render('lessons');});app.get('/lessons/:lesson', function(req, res) { console.log('controller is : lesson'); res.locals.controller = 'lessons'; res.send('gimmie the lesson');});/* The 404 Route (ALWAYS Keep this as the last route) */app.get('/*', function (req, res) { console.log('got 404 request to ' + req.url); res.render('404');}); and here's the app.js file which is used for server initialization: var express = require('express');var slashes = require('connect-slashes');exports.init = function (port) { var app = express(); app.use(express.static(__dirname + '/public')); // add middleware to remove trailing slash in urls app.use(slashes(false)); app.set('views', __dirname + '/views') app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.logger()); app.enable("jsonp callback"); if ('development' == app.get('env')) { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.use(express.logger({ format: ':method :url' })); } if ('production' == app.get('env')) { app.use(express.errorHandler()); } app.use(function (err, req, res, next) { console.log('Oops, something went wrong'); res.render('500.ejs', { locals: { error: err }, status: 500 }); }); app.listen(port); console.log("Listening on port %d in %s mode", port, app.settings.env); return app;} I have tried debugging the app with node-inspector but it's useless since the app doesn't seem to go into any of the app.get s to try to match. It immidiately gives me the error when I try to access localhost:8888/lessons EDIT: I think I have found the root of the problem : My /public dir has a lessons folder My /views dir has a lessons.ejs view When I change /public/lessons into /public/lessons11 for example, the problem is resolved. Can someone explain to me what's express flow in the original scenario that causes the redirect loop ? also, what can I do to resolve it ? Thanks Now provide the response and nothing else.
This happens: a request for /lessons comes in; the static middleware sees the public/lessons folder and assumes that's what the intended target is; because it's a folder, it will generate a redirect to /lessons/ (see below); static middleware picks that request up again, but notices there's no index.html in that folder, and hands it off to the next middleware ( connect-slashes ); the connect-slashes middleware removes the trailing slash and issues a redirect to /lessons ; the whole loop starts again; You can prevent the static middleware from adding a trailing slash, which will fix your redirect loop I think: app.use(express.static(__dirname + '/public', { redirect : false }));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15458424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/599912/']}
jdg_70104
stackexchange
llm_judgeable_groundtruth_similarity
15972040
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to show a formatted date in the section header of a table view.. I used the following code.but its throwing an exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath dateSectionIdentifier not found in entity <NSSQLEntity Expense id=1>' . guess the exception is coming when adding a sort descriptor. NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithCapacity:20];NSSortDescriptor *mainSortDescriptor = [[NSSortDescriptor alloc] initWithKey:dateSectionIdentifier ascending:NO];[sortDescriptors addObject:mainSortDescriptor];[fetchRequest setSortDescriptors:sortDescriptors]; //Expense.h NSString *dateSectionIdentifier; //Expense.m @dynamic dateSectionIdentifier-(NSString *)dateSectionIdentifier{[self willAccessValueForKey:@"dateSectionIdentifier"];NSString *tempDate = [self primitiveDateSectionIdentifier];[self didAccessValueForKey:@"dateSectionIdentifier"];if(!tempDate){ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"d MMMM yyyy"]; tempDate = [dateFormatter stringFromDate:[self date]]; [self setPrimitiveDateSectionIdentifier:tempDate]; [dateFormatter release];}return tempDate;} Now provide the response and nothing else.
The title of your question indicates that "dateSectionIdentifier" is a transient property. You cannot use a transient property in a sort descriptor (or in a predicate) of a Core Data fetch request if SQLite is used as store type. That is a documented restriction, only persistent properties can be used. See Persistent Store Types and Behaviors in the "Core Data Programming Guide"for more information.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15972040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/949988/']}
jdg_70105
stackexchange
llm_judgeable_groundtruth_similarity
49046847
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using asp.net + Autofac. I'm trying to load a custom JSON configuration file, and either create/instance an IConfiguration instance based on that, or at least include my file into whatever IConfiguration asp.net builds by default. My problem is that asp.net seems to override the dependency registration for IConfiguration. I can't seem to register my own IConfiguration object - the DI container will always resolve this to some instance that seems to have been generated by the asp.net library itself. And I'm not sure how I can get asp.net to at least load my custom config file additionally - i.e. if there is any way to get a hold of the ConfigurationBuilder it uses, and add my own file before it is building the IConfiguration object. I've tried the following: public class Startup{ public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { this.Configuration = new ConfigurationBuilder() .SetBasePath(path) .AddJsonFile("somefile.json") .Build(); } public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. services .AddMvc() .AddControllersAsServices(); var builder = new ContainerBuilder(); builder.Register(x => this.Configuration).As<IConfiguration>(); builder.Populate(services); var container = builder.Build(); // This will return another IConfiguration instance then the one I registered; // namely One that contains 1 provider, a MemoryConfigurationProvider var xxx = container.Resolve<IConfiguration>(); return new AutofacServiceProvider(container); }} How can I get asp.net to load my custom JSON config file as well? Now provide the response and nothing else.
You can do this by using the Options pattern: On ASP.NET Core 2, register the config file on Program.cs public class Program{ public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // custom config file .AddJsonFile("myappconfig.json", optional: false, reloadOnChange: false) .Build(); BuildWebHost(args, configuration).Run(); } public static IWebHost BuildWebHost(string[] args, IConfiguration config) => WebHost.CreateDefaultBuilder(args) .UseConfiguration(config) .UseStartup<Startup>() .Build();} Create a class that matches with your config file: public class MyAppConfig{ public string SomeConfig { get; set; } public int NumberConfig { get; set; }} Register it on ConfigureServices public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.Configure<MyAppConfig>(Configuration);} Then, just access it in your Controller: [Route("api/[controller]")]public class ValuesController : Controller{ private readonly MyAppConfig _appConfig; public ValuesController(IOptions<MyAppConfig> optionsAccessor) { if (optionsAccessor == null) throw new ArgumentNullException(nameof(optionsAccessor)); _appConfig = optionsAccessor.Value; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return _appConfig.SomeConfig; }} If you are not in ASP.NET Core 2 yet, the process is almost the same. You just need to add the custom config file on Startup.cs . The rest is basically the same.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49046847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3437979/']}
jdg_70106
stackexchange
llm_judgeable_groundtruth_similarity
33106520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using gradle as the JavaFX plugin.Everything works perfectly even after building and runnig the excecutable at distribution/ , except with one class: CloseableHttpClient For several purposes I create the following object like this: CloseableHttpClient client = HttpClients.createDefault(); Running the program in the IDE is no problem, everything works fine. But if I build and try to run the .exe-File I get the following Throwable -StackTrace: java.lang.NoClassDefFoundError: Could not initialize class org.apache.http.conn.ssl.SSLConnectionSocketFactory at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:955) at org.apache.http.impl.client.HttpClients.createDefault(HttpClients.java:58) at ch.itcb.tools.lom.util.JsonSimpleUtil.http(JsonSimpleUtil.java:29)... I really don't understand that. How can it be that just this class doesn't get found, but all my other classes do? My build.gradle file: apply plugin: 'java'apply plugin: 'eclipse'apply from: 'javafx.plugin'sourceCompatibility = 1.8version = '0.1'jar { manifest { attributes 'Implementation-Title': 'LogoffManager', 'Implementation-Version': version }}repositories { mavenCentral()}dependencies { compile fileTree(dir: 'lib', include: ['*.jar']) compile 'ch.qos.logback:logback-classic:1.1.3' compile 'org.apache.httpcomponents:httpclient:4.5.1' compile 'com.googlecode.json-simple:json-simple:1.1' compile group: 'commons-collections', name: 'commons-collections', version: '3.2' testCompile group: 'junit', name: 'junit', version: '4.+'}test { systemProperties 'property': 'value'}uploadArchives { repositories { flatDir { dirs 'repos' } }} Please write a comment if you need more information. Thx. Now provide the response and nothing else.
it's a good question, which I came across just now while researching examples of the many ways Java developers can end up with class path fun :-) I started with a minimal version of your build.gradle (including only what's directly relevant), specifically: plugins { id 'java'}sourceCompatibility = 1.8repositories { mavenCentral()}jar { manifest { attributes 'Main-Class': 'com.oliverlockwood.Main' }}dependencies { compile 'org.apache.httpcomponents:httpclient:4.5.1'} My 'Main' class, in this context, uses your code example, i.e.: package com.oliverlockwood;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;public class Main { public static void main(String[] args) { CloseableHttpClient client = HttpClients.createDefault(); }} At this stage, I can run gradle clean build followed by java -jar build/libs/33106520.jar (my project was named after this StackOverflow question) and I see this: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/impl/client/HttpClients at com.oliverlockwood.Main.main(Main.java:8)Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.client.HttpClients at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) This is subtly different from your error, but before we dig and reproduce that, let me emphasise something: both this error and the one you're seeing are caused at runtime when the classloader is unable to find a class that it needs. There's quite a good blog post here with some more details about the difference between compile-time classpath and runtime classpaths. If I run gradle dependencies I can see the runtime dependencies for my project: runtime - Runtime classpath for source set 'main'.\--- org.apache.httpcomponents:httpclient:4.5.1 +--- org.apache.httpcomponents:httpcore:4.4.3 +--- commons-logging:commons-logging:1.2 \--- commons-codec:commons-codec:1.9 I added these manually one-by-one to my runtime classpath. (For the record, this isn't generally considered good practice; but for the sake of the experiment, I copied these jars to my build/libs folder and ran with java -cp build/libs/33106520.jar:build/libs/* com.oliverlockwood.Main . Interestingly enough, this wasn't able to reproduce your exact problem. To recap: Without org.apache.httpcomponents:httpclient available at runtime, then we fail because the HttpClients jar is not found. With org.apache.httpcomponents:httpclient:4.5.1 available at runtime, then your problem does not manifest - and I note that the class your build fails to find ( org.apache.http.conn.ssl.SSLConnectionSocketFactory ) is part of this same Apache library , which is very suspicious indeed. My suspicion is then that your runtime classpath contains a different version of the Apache httpclient library. Since there's a whole lotta versions out there, I'm not going to test every single combination, so I will instead leave you with the following advice. If you want to fully understand the root cause of your issue, then identify exactly which jars (including their versions) are present in your error-case runtime classpath, including any jars that are packaged inside yours if you're creating a fat jar (more on this in point 3). It'd be great if you shared these details here; root cause analysis usually helps everyone to understand better :-) Where possible, avoid using dependencies in the manner of compile fileTree(dir: 'lib', include: ['*.jar']) . Managed dependencies based on a repository such as Maven or JCenter are much easier to work with consistently than dependencies in a random directory. If these are internal libraries that you don't want to publish to an open-source artifact repository, then it may be worth setting up a local Nexus instance or similar. Consider producing a "fat jar" instead of a "thin jar" - this means that all runtime dependencies are packaged in the jar that you build. There's a good Shadow plugin for Gradle that I'd recommend - with this in place in my build.gradle , and running gradle clean shadow , I was able to run java -jar just fine without needing to manually add anything to my classpath.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33106520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2594161/']}
jdg_70107
stackexchange
llm_judgeable_groundtruth_similarity
27644361
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I throw CHECKED exceptions from inside Java 8 streams/lambdas? In other words, I want to make code like this compile: public List<Class> getClasses() throws ClassNotFoundException { List<Class> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String") .map(className -> Class.forName(className)) .collect(Collectors.toList()); return classes; } This code does not compile, since the Class.forName() method above throws ClassNotFoundException , which is checked. Please note I do NOT want to wrap the checked exception inside a runtime exception and throw the wrapped unchecked exception instead. I want to throw the checked exception itself , and without adding ugly try / catches to the stream. Now provide the response and nothing else.
This LambdaExceptionUtil helper class lets you use any checked exceptions in Java streams, like this: Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String") .map(rethrowFunction(Class::forName)) .collect(Collectors.toList()); Note Class::forName throws ClassNotFoundException , which is checked . The stream itself also throws ClassNotFoundException , and NOT some wrapping unchecked exception. public final class LambdaExceptionUtil {@FunctionalInterfacepublic interface Consumer_WithExceptions<T, E extends Exception> { void accept(T t) throws E; }@FunctionalInterfacepublic interface BiConsumer_WithExceptions<T, U, E extends Exception> { void accept(T t, U u) throws E; }@FunctionalInterfacepublic interface Function_WithExceptions<T, R, E extends Exception> { R apply(T t) throws E; }@FunctionalInterfacepublic interface Supplier_WithExceptions<T, E extends Exception> { T get() throws E; }@FunctionalInterfacepublic interface Runnable_WithExceptions<E extends Exception> { void run() throws E; }/** .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println)); */public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E { return t -> { try { consumer.accept(t); } catch (Exception exception) { throwAsUnchecked(exception); } }; }public static <T, U, E extends Exception> BiConsumer<T, U> rethrowBiConsumer(BiConsumer_WithExceptions<T, U, E> biConsumer) throws E { return (t, u) -> { try { biConsumer.accept(t, u); } catch (Exception exception) { throwAsUnchecked(exception); } }; }/** .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName)) */public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E { return t -> { try { return function.apply(t); } catch (Exception exception) { throwAsUnchecked(exception); return null; } }; }/** rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), */public static <T, E extends Exception> Supplier<T> rethrowSupplier(Supplier_WithExceptions<T, E> function) throws E { return () -> { try { return function.get(); } catch (Exception exception) { throwAsUnchecked(exception); return null; } }; }/** uncheck(() -> Class.forName("xxx")); */public static void uncheck(Runnable_WithExceptions t) { try { t.run(); } catch (Exception exception) { throwAsUnchecked(exception); } }/** uncheck(() -> Class.forName("xxx")); */public static <R, E extends Exception> R uncheck(Supplier_WithExceptions<R, E> supplier) { try { return supplier.get(); } catch (Exception exception) { throwAsUnchecked(exception); return null; } }/** uncheck(Class::forName, "xxx"); */public static <T, R, E extends Exception> R uncheck(Function_WithExceptions<T, R, E> function, T t) { try { return function.apply(t); } catch (Exception exception) { throwAsUnchecked(exception); return null; } }@SuppressWarnings ("unchecked")private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }} Many other examples on how to use it (after statically importing LambdaExceptionUtil ): @Testpublic void test_Consumer_with_checked_exceptions() throws IllegalAccessException { Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String") .forEach(rethrowConsumer(className -> System.out.println(Class.forName(className)))); Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String") .forEach(rethrowConsumer(System.out::println)); }@Testpublic void test_Function_with_checked_exceptions() throws ClassNotFoundException { List<Class> classes1 = Stream.of("Object", "Integer", "String") .map(rethrowFunction(className -> Class.forName("java.lang." + className))) .collect(Collectors.toList()); List<Class> classes2 = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String") .map(rethrowFunction(Class::forName)) .collect(Collectors.toList()); }@Testpublic void test_Supplier_with_checked_exceptions() throws ClassNotFoundException { Collector.of( rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), StringJoiner::add, StringJoiner::merge, StringJoiner::toString); }@Test public void test_uncheck_exception_thrown_by_method() { Class clazz1 = uncheck(() -> Class.forName("java.lang.String")); Class clazz2 = uncheck(Class::forName, "java.lang.String"); }@Test (expected = ClassNotFoundException.class)public void test_if_correct_exception_is_still_thrown_by_method() { Class clazz3 = uncheck(Class::forName, "INVALID"); } UPDATE as of Nov 2015 The code has been improved with the help of @PaoloC, please check his answer below and upvote it . He helped solve the last problem: Now the compiler will ask you to add throw clauses and everything's as if you could throw checked exceptions natively on Java 8 streams. NOTE 1 The rethrow methods of the LambdaExceptionUtil class above may be used without fear, and are OK to use in any situation . NOTE 2: The uncheck methods of the LambdaExceptionUtil class above are bonus methods, and may be safely removed them from the class if you don't want to use them. If you do used them, do it with care, and not before understanding the following use cases, advantages/disadvantages and limitations: • You may use the uncheck methods if you are calling a method which literally can never throw the exception that it declares. For example: new String(byteArr, "UTF-8") throws UnsupportedEncodingException, but UTF-8 is guaranteed by the Java spec to always be present. Here, the throws declaration is a nuisance and any solution to silence it with minimal boilerplate is welcome: String text = uncheck(() -> new String(byteArr, "UTF-8")); • You may use the uncheck methods if you are implementing a strict interface where you don't have the option for adding a throws declaration, and yet throwing an exception is entirely appropriate. Wrapping an exception just to gain the privilege of throwing it results in a stacktrace with spurious exceptions which contribute no information about what actually went wrong. A good example is Runnable.run(), which does not throw any checked exceptions. • In any case, if you decide to use the uncheck methods,be aware of these 2 consequences of throwing CHECKED exceptions without a throws clause: 1) The calling-code won't be able to catch it by name (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement). It will bubble and probably be caught in the main program loop by some "catch Exception" or "catch Throwable", which may be what you want anyway. 2) It violates the principle of least surprise: it will no longer be enough to catch RuntimeException to be able to guarantee catching all possible exceptions. For this reason, I believe this should not be done in framework code, but only in business code that you completely control. References: http://www.philandstuff.com/2012/04/28/sneakily-throwing-checked-exceptions.html http://www.mail-archive.com/[email protected]/msg05984.html Project Lombok annotation: @SneakyThrows Brian Goetz opinion (against) here: How can I throw CHECKED exceptions from inside Java 8 streams? https://softwareengineering.stackexchange.com/questions/225931/workaround-for-java-checked-exceptions?newreg=ddf0dd15e8174af8ba52e091cf85688e *
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/27644361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3411681/']}
jdg_70108
stackexchange
llm_judgeable_groundtruth_similarity
7300497
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've seen in some applications the layout shifts when soft keyboard is shown. This is certainly not adjustPan because the whole layout (probably inner layout) shifts, not only the current EditText . This is for instance in Evernote login screen. Can you advice how this made? Now provide the response and nothing else.
Here's a solution that works like the Evernote login screen: First, define a class that will be your special LinearLayout like this: public class MyLayout extends LinearLayout {public MyLayout(Context context, AttributeSet attrs) { super(context, attrs);}public MyLayout(Context context) { super(context);}private OnSoftKeyboardListener onSoftKeyboardListener;@Overrideprotected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { if (onSoftKeyboardListener != null) { final int newSpec = MeasureSpec.getSize(heightMeasureSpec); final int oldSpec = getMeasuredHeight(); if (oldSpec > newSpec){ onSoftKeyboardListener.onShown(); } else { onSoftKeyboardListener.onHidden(); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec);}public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) { this.onSoftKeyboardListener = listener;}public interface OnSoftKeyboardListener { public void onShown(); public void onHidden();}} This layout listens to measure changes, and if new measurements are < than the old ones, that means part of the screen is eaten by soft keyboard. Though, for it to work, in your manifest you need to set android:windowSoftInputMode="adjustResize" so the content will be resized and not just shifted. And the whole system works as follows:You have your layout: <MyLayout id="layout"> <SomeImage id="image"/> <SomeText> <SomeInput></MyLayout> It's like evernotes login screen.Then, in your activity: ((MyLayout)findViewById(R.id.layout)).setOnSoftKeyboardListener(new OnSoftKeyboardListener() { @Override public void onShown() { findViewById(R.id.image).setVisibility(View.GONE); } @Override public void onHidden() { findViewById(R.id.image).setVisibility(View.VISIBLE); } }); Then go to manifest.xml and set android:windowSoftInputMode="adjustResize" What will happen, is when soft keyboard is shown, it'll hide the image and will resize the rest of content. (You can actually see how text is resized in Evernote) Image hide is, of course, one of the many things you can do. But you must be careful, since different layout changes will also call onMeasure. Of course it's a dirty variant. You need to check for orientation changes, and the right time when actually take the measurements, and maybe some more logic when comparing the new specs with the old ones. But i think this is the only way to do it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7300497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397991/']}
jdg_70109
stackexchange
llm_judgeable_groundtruth_similarity
110369
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am reviewing the book Biochemistry Concepts and Connections by Appling, Cahill, and Mathews and I cannot understand why they divide by the hydrogen concentration by $10^{-7}$ . Why not just leave it at the antilog(-8.1) over $\pu{1 M}$ like the other concentrations? I literally have see nothing else on the internet like this. Now provide the response and nothing else.
The textbook is precisely correct.The equilibrium constant $K$ which the logarithm is taken of is dimensionless , and includes activities or fugacities , and not concentrations and pressures.In practice this is achieved by using standard states which refer to the pure materials: standard concentration $c^⦵$ and standard pressure $p^⦵$ .One must be very fastidious with units when finding the equilibrium constant.For example, the reaction $$\ce{aA + bB <=> cC + dD}$$ equilibrium constant $K_c$ is exactly $$K_c = \frac{([\ce{C}]/c^⦵)^c\cdot ([\ce{D}]/c^⦵)^d}{([\ce{A}]/c^⦵)^a\cdot ([\ce{B}]/c^⦵)^b}$$ For pure water in its standard state $c^⦵ = [\ce{H+}] = \pu{1e-7 M}$ .It also correlates with so-called biological standard state of $\mathrm{pH} = 7$ .You probably haven't seen it before because many authors use sloppy notations omitting mentioning standard states since they can often be cancelled out.In this case those cannot be cancelled out, and must be written explicitly. In fact, your own textbook contains extensive explanation [1, p. 91]: For chemical reactions the standard state for solutes is defined as $\pu{1 M}$ ; however, in living cells the concentration of $[\ce{H+}]$ is roughly $10^{-7}~\mathrm M$ , much lower than the standard value of $\pu{1 M}$ . It is therefore appropriate to define the reference concentration of $\ce{H+}$ in biochemical reactions relative to the $\ce{H+}$ concentration found in the living state (i.e., $10^{-7}~\mathrm M$ ), rather than the value $\pu{1 M}$ defined by the chemical standard state. Recall that when a solute in a dilute solution has a concentration of $\pu{1 M}$ , the activity of that solute is unity. For the biochemical standard state we define the activity of $\ce{H+}$ to be unity when $[\ce{H+}] = 10^{-7}~\mathrm M$ . [...] The mass action expression $Q$ is unitless. We strip the units from each concentration term in $Q$ by dividing each by its proper standard concentration (e.g., $\pu{1 M}$ for all solutes except $\ce{H+}$ ; $10^{-7}~\mathrm M$ for $\ce{H+}$ ; $\pu{1 bar}$ for gases, etc.). Refrences Appling, D. R.; Anthony-Cahill, S. J.; Mathews, C. K. Biochemistry: Concepts and Connections (Global Edition); Pearson: Boston , 2015 . ISBN 978-1-292-11210-7.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/110369', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/75312/']}
jdg_70110
stackexchange
llm_judgeable_groundtruth_similarity
21825
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find the probability of getting 8 trials in a row correct in a block of 25 trials, you have 8 total blocks (of 25 trials) to get 8 trials correct in a row. The probability of getting any trial correct based on guessing is 1/3, after getting 8 in a row correct the blocks will end (so getting more than 8 in a row correct is technically not possible). How would I go about finding the probability of this occurring? I've been thinking along the lines of using (1/3)^8 as the probability of getting 8 in a row correct, there are 17 possible chances to get 8 in a row in a block of 25 trials, if I multiply 17 possibilities * 8 blocks I get 136, would 1-(1-(1/3)^8)^136 give me the likelihood of getting 8 in a row correct in this situation or am I missing something fundamental here? Now provide the response and nothing else.
By keeping track of things you can get an exact formula . Let $p=1/3$ be the probability of success and $k=8$ be the number of successes in a row you want to count. These are fixed for the problem. Variable values are $m$, the number of trials left in the block; and $j$, the number of successive successes already observed. Let the chance of eventually achieving $k$ successes in a row before $m$ trials are exhausted be written $f_{p,k}(j,m)$. We seek $f_{1/3,8}(0,25)$. Suppose we have just seen our $j^\text{th}$ success in a row with $m\gt0$ trials to go. The next trial is either a success, with probability $p$--in which case $j$ is increased to $j+1$--; or else it is a failure, with probability $1-p$--in which case $j$ is reset to $0$. In either case, $m$ decreases by $1$. Whence $$f_{p,k}(j,m) = p f_{p,k}(j+1,m-1) + (1-p)f_{p,k}(0,m-1).$$ As starting conditions we have the obvious results $f_{p,k}(k,m)=1$ for $m \ge 0$ ( i.e. , we have already seen $k$ in a row) and $f_{p,k}(j,m)=0$ for $k-j \gt m$ ( i.e. , there aren't enough trials left to get $k$ in a row). It is now fast and straightforward (using dynamic programming or, because this problem's parameters are so small, recursion) to compute $$f_{p,8}(0,25) = 18p^8 - 17p^9 - 45p^{16} + 81p^{17}-36p^{18}.$$ When $p=1/3$ this yields $80897 / 43046721 \approx 0.0018793$. Relatively fast R code to simulate this is hits8 <- function() { x <- rbinom(26, 1, 1/3) # 25 Binomial trials x[1] <- 0 # ... and a 0 to get started with `diff` if(sum(x) >= 8) { # Are there at least 8 successes? max(diff(cumsum(x), lag=8)) >= 8 # Are there 8 successes in a row anywhere? } else { FALSE # Not enough successes for 8 in a row }}set.seed(17)mean(replicate(10^5, hits8())) After 3 seconds of calculation, the output is $0.00213$. Although this looks high, it's only 1.7 standard errors off. I ran another $10^6$ iterations, yielding $0.001867$: only $0.3$ standard errors less than expected. (As a double-check, because an earlier version of this code had a subtle bug, I also ran 400,000 iterations in Mathematica, obtaining an estimate of $0.0018475$.) This result is less than one-tenth the estimate of $1-(1-(1/3)^8)^{136} \approx 0.0205$ in the question. But perhaps I have not fully understood it: another interpretation of "you have 8 total blocks ... to get 8 trials correct in a row" is that the answer being sought equals $1 - (1 - f_{1/3,8}(0,25))^8) = 0.0149358...$.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/21825', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/8789/']}
jdg_70111
stackexchange
llm_judgeable_groundtruth_similarity
4208929
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This problem confuses me, Can we use Leibniz rule here? But in the chapter Leibniz rule was not introduced. Is it possible to find the derivative using simple concepts. The actual problem is to evaluate the integral $\int_{0}^\infty e^{-y^2-(9/y)^2} dy$ using differential equations. Now provide the response and nothing else.
This is the correct first step in evaluating $\int_0^\infty e^{-y^2-(9/y)^2}\,\mathrm{d}y$ . To justify the swapping of the order of integration and differentiation (differentiation inside the integral), we can use Fubini and FTC: $$\begin{align}\frac{\mathrm{d}}{\mathrm{d}x}\int_0^\infty e^{-y^2-x^2/y^2}\,\mathrm{d}y&=\frac{\mathrm{d}}{\mathrm{d}x}\int_0^\infty\int_x^\infty\frac{2t}{y^2}e^{-y^2-t^2/y^2}\,\mathrm{d}t\,\mathrm{d}y\tag{1a}\\&=\frac{\mathrm{d}}{\mathrm{d}x}\int_x^\infty\int_0^\infty\frac{2t}{y^2}e^{-y^2-t^2/y^2}\,\mathrm{d}y\,\mathrm{d}t\tag{1b}\\&=-\int_0^\infty\frac{2x}{y^2}e^{-y^2-x^2/y^2}\,\mathrm{d}y\tag{1c}\end{align}$$ Explanation: $\text{(1a)}$ : $\int_x^\infty\frac{2t}{y^2}e^{-t^2/y^2}\,\mathrm{d}t=e^{-x^2/y^2}$ $\phantom{\text{(1a):}}$ here we are writing a function $\phantom{\text{(1a):}}$ as the integral of its derivative $\text{(1b)}$ : Fubini-Tonelli $\text{(1c)}$ : Fundamental Theorem of Calculus Hint 1: For the next step, you might want to complete the square in the exponents $$f(x)=\int_0^\infty e^{-y^2-x^2/y^2}\,\mathrm{d}y=e^{-2x}\int_0^\infty e^{-(y-x/y)^2}\,\mathrm{d}y\tag2$$ and from $(1)$ $$-\frac12f'(x)=\int_0^\infty\frac{x}{y^2}\,e^{-y^2-x^2/y^2}\,\mathrm{d}y=e^{-2x}\int_0^\infty\frac{x}{y^2}e^{-(y-x/y)^2}\,\mathrm{d}y\tag3$$ then consider the substitution $u=y-x/y$ . Hint 2: Another approach to the next step was suggested by Sangchul Lee: note that $$\begin{align}\frac{\mathrm{d}}{\mathrm{d}x}\int_0^\infty e^{-y^2-x^2/y^2}\,\mathrm{d}y&=-\int_0^\infty\frac{2x}{y^2}e^{-y^2-x^2/y^2}\,\mathrm{d}y\tag{4a}\\&=-2\int_0^\infty e^{-y^2-x^2/y^2}\,\mathrm{d}y\tag{4b}\\\end{align}$$ Explanation: $\text{(4a)}$ : $(1)$ allows us to differentiate inside the integral $\text{(4b)}$ : substitute $y\mapsto x/y$ and $(4)$ says that $f'(x)=-2f(x)$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4208929', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/701541/']}
jdg_70112
stackexchange
llm_judgeable_groundtruth_similarity
4682915
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need a simple way to set a shortcut for menu items. But this don´t work with shortcut, just with click: <MenuItem Header="Editar"> <MenuItem Header="Procurar" Name="MenuProcurar" InputGestureText="Ctrl+F" Click="MenuProcurar_Click"> <MenuItem.ToolTip> <ToolTip> Procurar </ToolTip> </MenuItem.ToolTip> </MenuItem></MenuItem> I am using WPF 4.0 Now provide the response and nothing else.
You need to use KeyBindings (and CommandBindings if you (re)use RoutedCommands such as those found in the ApplicationCommands class ) for that in the controls where the shortcuts should work. e.g. <Window.CommandBindings> <CommandBinding Command="New" Executed="CommandBinding_Executed" /></Window.CommandBindings><Window.InputBindings> <KeyBinding Key="N" Modifiers="Control" Command="New"/></Window.InputBindings> For custom RoutedCommands : static class CustomCommands{ public static RoutedCommand DoStuff = new RoutedCommand();} usage: <Window ... xmlns:local="clr-namespace:MyNamespace"> <Window.CommandBindings> <CommandBinding Command="local:CustomCommands.DoStuff" Executed="DoStuff_Executed" /> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="D" Modifiers="Control" Command="local:CustomCommands.DoStuff"/> </Window.InputBindings> ...</Window> (It is often more convenient to implement the ICommand interface rather than using RoutedCommands . You can have a constructor which takes delegates for Execute and CanExecute to easily create commands which do different things, such implementations are often called DelegateCommand or RelayCommand . This way you do not need CommandBindings .)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4682915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97082/']}
jdg_70113
stackexchange
llm_judgeable_groundtruth_similarity
35235
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we are in the field of desktop applications which need to store their data in a database. How do I store the password for this database avoiding the most obvious mistakes, which are: 1) hard coding the database password inside the code (cited as #21 coding horror under „Hard-coded passwords“ inside http://www.codinghorror.com/blog/2009/01/top-25-most-dangerous-programming-mistakes.html ) 2) encrypting the password of the database and storing it in a file, you would shift the problem to: „where do I store the password which encrypts the database's password?“ 3) using a remote database server and an n-tier architecture where the program doesn't directly access the database but authenticates with another layer which grants each operation and forwards it to the database layer. Everything is encrypted through ssl and authentication is done via a digital certificate (so effectively using public key cryptography). Number 3 is actually a solution but it doesn't apply to desktop applications which need to work offline! Someone on another similar question answered that to „give untrusted users trusted access to a system“ is unfeasible that's why DRM never worked, however he didn't cite a proved study or a proved theorem. Notice the same problem happens if we want to encrypt the database: where do I store the password with which I encrypt a database in a desktop application? Can anybody shed some insight?Thank you NOTE: this same problem is discussed in CWE-259: Use of Hard-coded Password but no definitive solution is explained Now provide the response and nothing else.
Any secret key that you embed in a program can be recovered by a person who has full access to that program, the best you can do is make it time consuming to do so. But let's say you could make the secret totally unrecoverable by analysing the binary. The user could perform dynamic analysis by running the program while monitoring it's memory and wait for the key to be constructed. OK let's say you have managed to use a key without ever building it completely in memory somehow. The key still has to be used for something, and the user could examine that mechanism and use the anti-forensic key in the same way. Let's say the mechanism for constructing and using the key is totally obfuscated beyond recovery. The key still has to depart your program in order to be useful outside it. I could just masquerade as a database waiting for my secret key to be passed to me, I wouldn't have to analyse your program at all. Any form of encryption you use would have to be readable by my database software, which I am also in complete control of regarding keypairs and such. But I have written my own database format which is loaded into the same program as the key which you can't read. So your program is completely locked down and everything happens inside. Except it doesn't - you will load dynamic libraries which I could edit thereby changing the behavior of your program. Ultimately there is nothing that runs on my machine that I do not have final control over. This is not something you can avoid.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/35235', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/24688/']}
jdg_70114
stackexchange
llm_judgeable_groundtruth_similarity
50971123
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a pandas series features that has the following values ( features.values ) array([array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), ..., array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0]), array([0, 0, 0, ..., 0, 0, 0])], dtype=object) Now I really want this to be recognized as matrix, but if I do >>> features.values.shape(10000,) rather than (10000, 3000) which is what I would expect. How can I get this to be recognized as 2d rather than a 1d array with arrays as values. Also why does it not automatically detect it as a 2d array? Now provide the response and nothing else.
In response your comment question, let's compare 2 ways of creating an array First make an array from a list of arrays (all same length): In [302]: arr = np.array([np.arange(3), np.arange(1,4), np.arange(10,13)])In [303]: arrOut[303]: array([[ 0, 1, 2], [ 1, 2, 3], [10, 11, 12]]) The result is a 2d array of numbers. If instead we make an object dtype array, and fill it with arrays: In [304]: arr = np.empty(3,object)In [305]: arr[:] = [np.arange(3), np.arange(1,4), np.arange(10,13)]In [306]: arrOut[306]: array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])], dtype=object) Notice that this display is like yours. This is, by design a 1d array. Like a list it contains pointers to arrays elsewhere in memory. Notice that it requires an extra construction step. The default behavior of np.array is to create a multidimensional array where it can. It takes extra effort to get around that. Likewise it takes some extra effort to undo that - to create the 2d numeric array. Simply calling np.array on it does not change the structure. In [307]: np.array(arr)Out[307]: array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])], dtype=object) stack does change it to 2d. stack treats it as a list of arrays, which it joins on a new axis. In [308]: np.stack(arr)Out[308]: array([[ 0, 1, 2], [ 1, 2, 3], [10, 11, 12]])
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50971123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6656387/']}
jdg_70115
stackexchange
llm_judgeable_groundtruth_similarity
80268
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Are there any empirical studies justifying the use of the one standard error rule in favour of parsimony? Obviously it depends on the data-generation process of the data, but anything which analyses a large corpus of datasets would be a very interesting read. The "one standard error rule" is applied when selecting models through cross-validation (or more generally through any randomization-based procedure). Assume we consider models $M_\tau$ indexed by a complexity parameter $\tau\in\mathbb{R}$, such that $M_\tau$ is "more complex" than $M_{\tau'}$ exactly when $\tau>\tau'$. Assume further that we assess the quality of a model $M$ by some randomization process, e.g., cross-validation. Let $q(M)$ denote the "average" quality of $M$, e.g., the mean out-of-bag prediction error across many cross-validation runs. We wish to minimize this quantity. However, since our quality measure comes from some randomization procedure, it comes with variability. Let $s(M)$ denote the standard error of the quality of $M$ across the randomization runs, e.g., the standard deviation of the out-of-bag prediction error of $M$ over cross-validation runs. Then we choose the model $M_\tau$, where $\tau$ is the smallest $\tau$ such that $$q(M_\tau)\leq q(M_{\tau'})+s(M_{\tau'}),$$ where $\tau'$ indexes the (on average) best model, $q(M_{\tau'})=\min_\tau q(M_\tau)$. That is, we choose the simplest model (the smallest $\tau$) which is no more than one standard error worse than the best model $M_{\tau'}$ in the randomization procedure. I have found this "one standard error rule" referred to in the following places, but never with any explicit justification: Page 80 in Classification and Regression Trees by Breiman, Friedman, Stone & Olshen (1984) Page 415 in Estimating the Number of Clusters in a Data Set via the Gap Statistic by Tibshirani, Walther & Hastie ( JRSS B , 2001) (referencing Breiman et al.) Pages 61 and 244 in Elements of Statistical Learning by Hastie, Tibshirani & Friedman (2009) Page 13 in Statistical Learning with Sparsity by Hastie, Tibshirani & Wainwright (2015) Now provide the response and nothing else.
For an empirical justification, have a look at page 12 on these Tibshirani data-mining course notes , which shows the CV error as a function of lambda for a particular modeling problem. The suggestion seems to be that, below a certain value, all lambdas give about the same CV error. This makes sense because, unlike ridge regression, LASSO is not typically used only, or even primarily, to improve prediction accuracy. Its main selling point is that it makes models simpler and more interpretable by eliminating the least relevant/valuable predictors. Now, to understand the one standard error rule, let's think about the family of models we get from varying $\lambda$ . Tibshirani's figure is telling us that we have a bunch of medium-to-high complexity models that are about the same in predictive accuracy, and a bunch of low-complexity models that are not good at prediction. What should we choose? Well, if we're using $L_1$ , we're probably interested in a parsimonious model, so we'd probably prefer the simplest model that explains our data reasonably well (as Einstein supposedly said, "as simple as possible but no simpler"). So how about the lowest complexity model that is "about as good" as all those high complexity models? And what's a good way of measuring "about as good"? One standard error.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/80268', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/996/']}
jdg_70116
stackexchange
llm_judgeable_groundtruth_similarity
32292750
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to do error handling in my play scala web application. My application talks to the data base to fetch some rows, it follows following flow. First call to db to fetch some data Use the data in first call to fetch other data from db Form a response using the data received from last two db calls. Below is my pseudocode. def getResponse(name: String) (implicit ctxt: ExecutionContext): Future[Response] = { for { future1 <- callFuture1(name) future2 <- callFuture2(future1.data) future3 <- callFuture3(future1.data, future2.data) } yield future3 } Every method in the comprehension above returns a future, the signature of these methods are as below. private def callFuture1(name: String) (implicit ctxt: ExecutionContext): Future[SomeType1] {...}private def callFuture2(keywords: List[String]) (implicit ctxt: ExecutionContext): Future[SomeType2] {...}private def callFuture3(data: List[SomeType3], counts: List[Int]) (implicit ctxt: ExecutionContext): Future[Response] {...} How shall I do error/failure handling, in the following situation When callFuture1 fails to fetch data from database. I want to returna appropriate error response with error message. Since callFuture2only gets executed after callFuture1. I dont want to executecallFuture2 if callFuture1 has failed/erred and would want to returnerror message immediately. (Same thing for callFuture2 andcallFuture3) --edit-- I am trying to return an appropriate Error Response from getResponse() method, when either of the callFuture fails and not proceed to subsequent futureCalls. I tried the following, based on Peter Neyens answer, but gave me an runtime error.. def getResponse(name: String) (implicit ctxt: ExecutionContext): Future[Response] = { for { future1 <- callFuture1(name) recoverWith { case e:Exception => return Future{Response(Nil,Nil,e.getMessage)} } future2 <- callFuture2(future1.data) future3 <- callFuture3(future1.data, future2.data) } yield future3 } Runtime error i get ERROR] [08/31/2015 02:09:45.011] [play-akka.actor.default-dispatcher-3] [ActorSystem(play)] Uncaught error from thread [play-akka.actor.default-dispatcher-3] (scala.runtime.NonLocalReturnControl)[error] a.a.ActorSystemImpl - Uncaught error from thread [play-akka.actor.default-dispatcher-3]scala.runtime.NonLocalReturnControl: null Now provide the response and nothing else.
You could use the Future.recoverWith function, to customize the exception if the Future failed. val failed = Future.failed(new Exception("boom"))failed recoverWith { case e: Exception => Future.failed(new Exception("A prettier error message", e)} This will result in a slightly uglier for comprehension : for { future1 <- callFuture1(name) recoverWith { case npe: NullPointerException => Future.failed(new Exception("how did this happen in Scala ?", npe)) case e: IllegalArgumentException => Future.failed(new Exception("better watch what you give me", e)) case t: Throwable => Future.failed(new Exception("pretty message A", t)) } future2 <- callFuture2(future1.data) recoverWith { case e: Exception => Future.failed(new Exception("pretty message B", e)) } future3 <- callFuture3(future1.data, future2.data) recoverWith { case e: Exception => Future.failed(new Exception("pretty message C", e)) }} yield future3 Note that you could also define your own exceptions to use instead of Exception , if you want to add more information than just an error message. If you don't want fine grained control to set a different error message depending on the Throwable in the failed Future (like with callFuture1 ), you could enrich Future using an implicit class to set a custom error message somewhat simpler: implicit class ErrorMessageFuture[A](val future: Future[A]) extends AnyVal { def errorMsg(error: String): Future[A] = future.recoverWith { case t: Throwable => Future.failed(new Exception(error, t)) }} Which you could use like : for { future1 <- callFuture1(name) errorMsg "pretty A" future2 <- callFuture2(future1.data) errorMsg "pretty B" future3 <- callFuture3(future1.data, future2.data) errorMsg "pretty C"} yield future3 In both cases, using errorMsg or recoverWith directly, you still rely on Future , so if a Future fails the following Futures will not be executed and you can directly use the error message inside the failed Future . You didn't specify how you would like to handle the error messages. If for example you want to use the error message to create a different Response you could use recoverWith or recover . future3 recover { case e: Exception => val errorMsg = e.getMessage InternalServerError(errorMsg)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32292750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2089768/']}
jdg_70117
stackexchange
llm_judgeable_groundtruth_similarity
14799035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I’m developing simple node-webkit application for Windows (Vista, 7, …) and I need to use some WinAPI functions, specifically, RegisterHotKey and SendInput , to bind system-wide hotkeys and make keystrokes based on that. There’s no such API supplied by node-webkit, so I thought to use node-ffi to call that functions. I’m new to WinAPI development, so I’ve read some MSDN manuals, but found that most of examples create window, message loop, message handling procedure and so on. So I don’t understand quite well, how to implement correctly calling to WinAPI from node-webkit, without creating separate window? Node-ffi tutorial doesn’t cover that case, so I’ve found the node Windows library, but it seems that it just implements Windows application by means of node. Is there a way to implement native calls without creating windows application? What’s the correct way to do that? Now provide the response and nothing else.
I wrote a node script that captures hotkeys on windows using the ffi , ref , and ref-struct modules. I've had some issues getting them to work in a packaged .exe since ffi and ref are native add-ons. For more information, see this github issue I opened awhile ago. Anyways, here's the code: var FFI = require('ffi'), ref = require('ref'), Struct = require('ref-struct');/* First, create the necessary data structures that'll be used by our windows api calls. */var pointStruct = Struct({ 'x': 'long', 'y': 'long'});var msgStruct = Struct({ 'hwnd': 'int32', 'message': 'int32', 'wParam': 'int32', 'lParam': 'int32', 'time': 'int32', 'pt': pointStruct});var msgStructPtr = ref.refType(msgStruct);/* Second, register the functions we'd like to use by providing their method signatures. */var user32 = new FFI.Library('user32', { 'RegisterHotKey': [ 'bool', ['int32', 'int', 'int32', 'int32'] ], 'GetMessageA': [ 'bool', [msgStructPtr, 'int32', 'int32', 'int32'] ] /* You may prefer to use PeekMessageA which has the same signature as GetMessageA, but is non-blocking. I haven't tested it, though.});/* Third, register your hotkeys. I wanted to control a media player, so these keys reflect that. */var ALT = 0x0001, CTRL = 0x0002, SHIFT = 0x0004;var MEDIA_NEXT = 0xB0, MEDIA_PREV = 0xB1, MEDIA_STOP = 0xB2, MEDIA_PLAY_PAUSE = 0xB3, MEDIA_LAUNCH = 0xB5;var PERIOD = 0xBE, COMMA = 0xBC, EQUAL = 0xBB, DIVIDE = 0xBF, SQUOTE = 0xDE, PAGEUP = 0x21, PAGEDOWN = 0x22;registrations = [];registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_NEXT));registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_PREV));registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_STOP));registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_PLAY_PAUSE));registrations.push(user32.RegisterHotKey(0, 1, 0, MEDIA_LAUNCH));registrations.push(user32.RegisterHotKey(0, 1, CTRL, PERIOD));registrations.push(user32.RegisterHotKey(0, 1, CTRL, COMMA));registrations.push(user32.RegisterHotKey(0, 1, CTRL, EQUAL));registrations.push(user32.RegisterHotKey(0, 1, CTRL, DIVIDE));registrations.push(user32.RegisterHotKey(0, 1, CTRL | ALT, PAGEUP));registrations.push(user32.RegisterHotKey(0, 1, CTRL | ALT, PAGEDOWN));// an array of booleans telling us which registrations failed/succeededconsole.log(registrations);/* Fourth, wait for new hotkey events from the message queue. */var myMsg = new msgStruct;while (user32.GetMessageA(myMsg.ref(), 0, 0, 0)) { var key = myMsg.lParam >> 16; switch (key) { case MEDIA_NEXT: console.log('media next'); break; case MEDIA_PREV: console.log('media prev'); break; case MEDIA_STOP: console.log('media stop'); break; case MEDIA_PLAY_PAUSE: console.log('media play/pause'); break; case MEDIA_LAUNCH: console.log('media launch'); break; case PERIOD: console.log('next'); break; case COMMA: console.log('previous'); break; case EQUAL: console.log('play/pause'); break; case DIVIDE: console.log('info'); break; case PAGEUP: console.log('volume up'); break; case PAGEDOWN: console.log('volume down'); break; default: console.log('undefined hotkey', key, key.toString(16)); }} If you want this to work with node-webkit, make sure you build all the native add-ons with nw-gyp with the --target set to your version of node-webkit (0.5.1 in my case): # Make sure you run this command in the following directories (where the binding.gyp files are):# node_modules/ffi/# node_modules/ffi/node_modules/ref/# node_modules/ref/$ nw-gyp clean configure --target=v0.5.1 build Review the MSDN docs to understand the method signatures and structs used. Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14799035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052640/']}
jdg_70118
stackexchange
llm_judgeable_groundtruth_similarity
32422593
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've seen in several places to "stay away" from this, but alas - this is how my DB is built: class Album extends Eloquent { // default connection public function genre() { return $this->belongsTo('genre'); } and the Genre table: class Genre extends Eloquent { protected $connection = 'Resources';} My database.php: 'Resources' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'resources', 'username' => 'user', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'my_data', 'username' => 'user', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), and when I try to run Album::whereHas('genre', function ($q) { $q->where('genre', 'German HopScotch'); }); it doesn't select properly (doesn't add the database name to the table "genres"): Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'my_data.genres' doesn't exist Its important to note that this works perfectly: Album::first()->genre; Update The best I've found so far is to use the builder's "from" method to specifically name the correct connection.I've discovered that the builder inside the query can receive "from" Album::whereHas('genre', function ($q) { $q->from('resources.genres')->where('genre', 'German HopScotch'); }); This is a decent solution but it requires me to dig in the database php and find a good way to get the proper table and database name from the relation 'genre'. I will appreciate if anyone else can build on this solution and make it more general. Now provide the response and nothing else.
Solution for laravel v5.7 and above class Album extends Eloquent { // default connection public function genre() { return $this->setConnection('Resources')->belongsTo('genre'); }...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32422593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1503710/']}
jdg_70119
stackexchange
llm_judgeable_groundtruth_similarity
590332
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to design a common emitter amplifier for my next electronics laboratory. Specifications are the following: 1 mA of collector current Load resistance of 1k ohms Voltage gain of 10 For 1mA, $$ \beta = 185 $$ according to the datasheet. So to fulfill these requirements, I made a system of equations to obtain the values of the resistances. First I wrote the biasing loop equation: $$15\ V=10^{-3}R_C+\frac{185+1}{185}10^{-3}R_E+10\ V$$ Where I chose $$V_{CE}=10.$$ Simplifying I obtain: $$ R_C +1.005R_E=5000$$ Next I wrote the equation for the common emitter amplifier gain, and equated it to -10. $$-\frac{\beta \ R_C \parallel R_L}{r_{\pi}+(\beta+1)R_E} =-10$$ Where $$ r_{\pi}=\frac{V_T}{I_{B}}= \frac{26 \text{ mV}}{5.405 \ \mu\text{A}}=4810 \ \Omega $$ Replacing the values I obtain the following equation: $$ 185 \frac{\frac{1000 R_C}{1000+R_C}}{4810+186 R_E}=10 $$ Using Maple I obtained: $$ R_C=4942.8 \ \Omega, \quad R_E=56.86 \ \Omega $$ For the rest of the resistors I used the voltage divider relationships for biasing, obtaining $$ R_{bb1}=20797 \ \Omega, \quad R_{bb2}= 1114 \ \Omega. $$ Then I simulated the following circuit in LTspice: For the gain, I obtain approximately 11.184 which is in the margin of error. Problem is, when measuring the DC operating point of the collector current, I measure 1.6 mA instead of 1. I am kind of stuck, I don't know where I made a mistake. Now provide the response and nothing else.
Always choose Rc <= than Rload so that transistor is never starved of Ic current. Otherwise you will get asymmetrical limiting as the load pulls down the voltage more than Rc pulls up But this is an unusually large Vcc , Low Ic * Load = 1V which limits your peak swing. 2% to 10 % tolerances are acceptable and hFE can be largely ignored. The biggest source of error only in this case, is teachers always tell you to assume Vbe=0.7V but for Ic= 1mA it is very close to Vbe= 600 mV. This adds more Ve and thus more Ic current to your design. So I suggest you recalc R3 for a smaller Vbe and your design "may" work as expected. ( except no load gain = Rc/Re and loaded gain = 10 ) . 15% tolerances are expected even with 1% resistors in this design due to the load /Rc ratio. There are tradeoffs with any design and more specifications lead to better designs. Report back your results. Of course, the simplest solution is just define Rc as the load The load regulation ratio for DC or gain is simply a function of the impedance ratio with output.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/590332', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/237049/']}
jdg_70120
stackexchange
llm_judgeable_groundtruth_similarity
13811614
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assuming a pipe, int pipe_fd[2];pipe(pipe_fd); We fork, and expect that one process will write into the pipe at an arbitrary time. In one of the processes, we want to be able to check the contents of the pipe without blocking. i.e. While a typical read will block if nothing is present and the write end remains open. I want to go do other stuff and potentially even read a bit at a time, do some stuff, and then check back to see if there's more, a la: close(pipe_fd[1]);while(1){ if(/**Check pipe contents**/){ int present_chars = 0; while( read(pipe_fd[0],&buffer[present_chars],1) != 0) ++present_chars; //do something } else //do something else} Now provide the response and nothing else.
Your logic is wrong in that read will not return 0 when it runs out of characters; instead, it will block until it receives more, unless you put the file in non-blocking mode, but then it will return -1 and set errno to EWOULDBLOCK or EAGAIN rather than returning 0. The only time read can ever return 0 is when the size argument was 0 or end-of-file has been reached. And, for pipes , end-of-file means the writing end of the pipe has been closed; end-of-file status does not occur just because there's not any input available yet. With that said, the simplest way to check is: if (poll(&(struct pollfd){ .fd = fd, .events = POLLIN }, 1, 0)==1) { /* data available */} but unless you're using nonblocking mode, you'll need to make this check before every single read operation. Passing a larger buffer to read rather than doing it a byte-at-a-time would eliminate most of the cost of checking.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13811614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551209/']}
jdg_70121
stackexchange
llm_judgeable_groundtruth_similarity
24261376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to know if there exists an elegant way to horizontally align 3 divs without using float css property. HTML: <div id="parent"> <div id="first">Left</div> <div id="second">Middle</div> <div id="third">Right</div></div> I ask this question because the parent div has not float property and adding float to children cause problems on page resizing. Now provide the response and nothing else.
You can use display:inline-block or display:table-cell with the inner content. Flex layout ( See also T J's answer ) : #parent{ display:flex; justify-content: space-between; } JSFiddle Table layout: #parent{ display:table; width:100%; }#parent div{ display:table-cell; }#first{ text-align:left; }#second{ text-align:center; }#third{ text-align:right; } JSFiddle Inline-block layout : #parent{ width:100%; white-space:nowrap; }#parent div{ display:inline-block; width:33.3%;}#first{ text-align:left; }#second{ text-align:center; }#third{ text-align:right; } JSFiddle
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24261376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3743987/']}
jdg_70122
stackexchange
llm_judgeable_groundtruth_similarity
21232662
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I’ve created a UIView with a semi-transparent black background to sit across my main app’s view. What I’m aiming for here is to create a cut-out circle shape somewhere in that UIView where the semi-transparent black background is not seen, giving the effect of a black mask over the whole image except the circular area (this is to highlight a button in that area). I’ve managed to use CAShapeLayer to create a circular mask, but this has had the opposite effect (i.e. the rest of the view is clear, and INSIDE the circle is the semi-transparent black. What I’d like is everything outside of the circle to keep the semi-transparent black, then what’s inside to be clear. Here’s the code I used, how would I go about making it work in the opposite way? My blackMask is the semi-transparent black view, and my buttonCircle is the circle I’d like to be kept clear. Perhaps I need to invert the path, somehow? CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];CGRect maskRect = buttonCircle.frame;CGPathRef path = CGPathCreateWithEllipseInRect(maskRect, NULL);maskLayer.path = path;CGPathRelease(path);blackMask.layer.mask = maskLayer; EDIT: Trying this now, not seeing any mask at all with this one: UIView *circularMaskView = [[UIView alloc] initWithFrame:buttonCircle.frame];circularMaskView.backgroundColor = [UIColor greenColor];CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];CGPathRef path = CGPathCreateWithEllipseInRect(buttonCircle.frame, NULL);maskLayer.path = path;CGPathRelease(path);circularMaskView.layer.mask = maskLayer;[blackMask addSubview:circularMaskView]; Now provide the response and nothing else.
So, here’s what I did. I created a custom UIView subclass called BlackoutView , like so: BlackoutView.h #import <UIKit/UIKit.h>@interface BlackoutView : UIView@property (nonatomic, retain) UIColor *fillColor;@property (nonatomic, retain) NSArray *framesToCutOut;@end BlackoutView.m #import "BlackoutView.h"@implementation BlackoutView- (void)drawRect:(CGRect)rect{ [self.fillColor setFill]; UIRectFill(rect); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetBlendMode(context, kCGBlendModeDestinationOut); for (NSValue *value in self.framesToCutOut) { CGRect pathRect = [value CGRectValue]; UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:pathRect]; [path fill]; } CGContextSetBlendMode(context, kCGBlendModeNormal);}@end I then instantiate it as normal, and set the properties to the colour of the mask I want to use, and the frames to be cut out of the mask: [blackMask setFillColor:[UIColor colorWithWhite:0.0f alpha:0.8f]];[blackMask setFramesToCutOut:@[[NSValue valueWithCGRect:buttonCircleA.frame], [NSValue valueWithCGRect:buttonCircleB.frame]]]; This could be improved by allowing me to cut out other shapes besides ovals, but it’s fine for my purposes here and would be easily adapted to do so later. Hopefully this helps others!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21232662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/961148/']}
jdg_70123
stackexchange
llm_judgeable_groundtruth_similarity
9095
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Going through some knowledge representation tutorials on resolution at the moment, and I came across slide 05.KR, no77 . There it is mentioned that "the procedure is also complete". I think this completeness can not mean that if a sentence is entailed by KB, then it will be derived by resolution. For example, resolution can not derive $(q \lor \neg q)$ from a KB with single clause $\neg p$. (Example from KRR, Brachman and Levesque, page 53). Could anyone help me figure out what is meant in this slide? Is the completeness of slide refer to being refutaton-complete and not a complete proof procedure? Now provide the response and nothing else.
Resolution is complete as a refutation system. That is, if $S$ is a contradictory set of clauses, then resolution can refute $S$, i.e. $S \vdash \bot$. This is sufficient since $T \vdash A$ is equivalent to $T \cup \{\lnot A\} \vdash \bot$. So if we want to see a formula $A$ is derivable from $T$, we only need to check if there is a refutation proof for $T \cup \{\lnot A\}$ which can be checked using resolution.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/9095', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/6508/']}
jdg_70124
stackexchange
llm_judgeable_groundtruth_similarity
280353
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The most general metric for a static and spherically symmetric metric is given by: $$ds^2 = e^{2\gamma(u)}dt^2 - e^{2\alpha(u)}du^2 - e^{2\beta(u)}d\Omega^2$$ I have the freedom of choosing Schwarzschild coordinates , in which: $$e^{2\beta(u)} = u^2,$$ and now $u$ becomes the radius of the sphere. However I have the freedom of choosing other coordinates systems, i.e. gauge freedom, like the harmonic gauge $\alpha(u) = 2\beta(u) + \gamma(u)$ or the quasi-global gauge given by $\alpha(u)=-\gamma(u)$ (those two are the ones I use the most). My questions are: How do I prove that those gauges may be used without any loss of generality? (As example, how do I show if $\alpha=-5\gamma + \beta^2$ is a gauge or not?) I see this as a coordinate freedom, but in my research it's mostly known as "gauge freedom", any differences or just nomenclature? Now provide the response and nothing else.
To start with, given the metric ansatz$$ds^2 = e^{2\gamma(u)}dt^2 - e^{2\alpha(u)}du^2 - e^{2\beta(u)}d\Omega^2,\tag{1}$$one can apply the Cartan-Karlhede algorithm to check local equivalence with the Schwarzhschild solution (this is best carried out with a computer implementation). Instead of this general solution for the local equivalence of some metric ansatz and a given metric, one can in this case also investigate the demands for (1) to be a vacuum solution, since this will make it the Schwarzschild solution by virtue of being static and spherically symmetric (Birkhoff's theorem); the latter approach should of course also be used if one is primarily interested in the requirements for an ansatz to give a solution rather than some specific soluion. To prove that $f(\alpha,\beta,\gamma) = 0$ is a "gauge" you can plug it into your ansatz and take the approach outlined above. For example for the ansatz (1) any "gauge" that does not violate the equations below is allowed. I am new to gauge theory, but I believe the correct use of gauge transformations in general relativity would entail $SO_0(1,3)$-transformations of vectors in a rigid frame. Thus I believe you are correct in that this is a matter of coordinate freedom rather than gauge freedom. Here I approach the metric ansatz (1) as an example : to that end I will be working in a local Lorentz (orthonormal) frame:\begin{align}\begin{split}\omega^0 &= e^{\gamma(u)}dt, \\\omega^1 &= e^{\alpha(u)}du, \\\omega^2 &= e^{\beta(u)}d\vartheta, \\\omega^3 &= e^{\beta(u)}\sin(\vartheta) d\varphi.\end{split}\tag{2}\end{align}We then work with the first Cartan equation$$d\omega^i = \gamma^i{}_{jk}\omega^j \wedge \omega^k,\tag{3}$$where $\gamma^i{}_{jk}$ are the Ricci rotation coefficients (components of the connection forms). Applying (3) to (2) we find\begin{align}\gamma^0{}_{jk}\omega^j\wedge\omega^k &= \gamma'(u)e^{\gamma(u)}du \wedge dt \\&= \gamma'(u)e^{-\alpha(u)}\omega^1 \wedge \omega^0, \\\gamma^1{}_{jk}\omega^j\wedge\omega^k &= 0, \\\gamma^2{}_{jk}\omega^j\wedge\omega^k &= \beta'(u)e^{\beta(u)}du\wedge d\vartheta \\&= \beta'(u)e^{-\alpha(u)}\omega^1 \wedge \omega^2, \\\gamma^3{}_{jk}\omega^j\wedge\omega^k &= \beta'(u)e^{\beta(u)}\sin(\vartheta)du\wedge d\varphi + e^{\beta(u)}\cos(\vartheta)d\vartheta\wedge d\varphi \\&= \beta'(u)e^{-\alpha(u)}\omega^1 \wedge \omega^3 + \cot(\vartheta)e^{-\beta(u)}\omega^2 \wedge \omega^3,\end{align}and by inspection we find\begin{align} \begin{split}\gamma^0{}_{10} &= \gamma'(u)e^{-\alpha(u)}, \\\gamma^2{}_{12} &= \beta'(u)e^{-\alpha(u)}, \\\gamma^3{}_{13} &= \beta'(u)e^{-\alpha(u)}, \\\gamma^3{}_{23} &= \cot(\vartheta)e^{-\beta(u)},\end{split}\tag{4}\end{align}to be the only non-zero coefficients (up to symmetries: $\gamma_{ijk} = \gamma_{[ij]k}$). Next the second Cartan equation\begin{align}\frac{1}{2}R^i{}_{jk\ell}\omega^k \wedge \omega^\ell &= d\gamma^i{}_j + \gamma^i{}_k \wedge \gamma^k{}_j,\tag{5} \\&= \left(-\gamma^i{}_{j[k|\ell]} + \gamma^i{}_{jm}\gamma^m{}_{[k\ell]} - \gamma_{mj[k}\gamma^{im}{}_{\ell]}\right)\omega^k \wedge \omega^\ell\end{align}gives, using (4):\begin{align}\begin{split}R^0{}_{101} &= \left(\alpha'(u)\gamma'(u) - \gamma''(u) - \gamma'(u)^2\right)e^{-2\alpha(u)}, \\R^0{}_{202} &= -\beta'(u)\gamma'(u)e^{-2\alpha(u)}, \\R^0{}_{303} &= -\beta'(u)\gamma'(u)e^{-2\alpha(u)}, \\R^1{}_{212} &= \left(\alpha'(u)\beta'(u) - \beta''(u) - \beta'(u)^2\right)e^{-2\alpha(u)}, \\R^1{}_{313} &= \left(\alpha'(u)\beta'(u) - \beta''(u) - \beta'(u)^2\right)e^{-2\alpha(u)}, \\R^2{}_{323} &= e^{-2\beta(u)} - \beta'(u)^2e^{-2\alpha(u)},\end{split}\tag{6}\end{align}as the only non-zero Riemann components, again up to symmetries ($R_{ijk\ell} = R_{([ij][k\ell])}$), or in terms of the Ricci components (suppressing function arguments):\begin{align}\begin{split}R_{00} &= \left(2\beta'\gamma' - \alpha'\gamma' + \gamma'' + \gamma'^2 \right)e^{-2\alpha}, \\R_{11} &= \left(\alpha'\gamma' + 2\alpha'\beta' - \gamma'' - 2\beta'' - \gamma'^2 - 2\beta'^2 \right)e^{-2\alpha}, \\R_{22} &= \left(\alpha'\beta' - \beta' \gamma' - \beta'' - 2\beta'^2 \right)e^{-2\alpha} + e^{-2\beta}, \\R_{33} &= \left(\alpha'\beta' - \beta' \gamma' - \beta'' - 2\beta'^2 \right)e^{-2\alpha} + e^{-2\beta}, \\\end{split}\tag{7}\end{align}The Ricci tensor must vanish in a vacuum solution (assuming no cosmological constant for simplicity), so (7) gives us a system of three differential equations:\begin{align}2\beta'\gamma' - \alpha'\gamma' + \gamma'^2 + \gamma'' &= 0, \tag{A}\\\alpha'\gamma' + 2\alpha'\beta' - \gamma'' - 2\beta'' - \gamma'^2 - 2\beta'^2 &= 0, \tag{B}\\\alpha'\beta' - \beta' \gamma' - \beta'' - 2\beta'^2 &= -e^{2(\alpha - \beta)}\tag{C}.\end{align}Notice that equations (A), (B), and (C) can be simplified: If $\gamma' = 0$ we end up with a single equation:$$e^{\alpha} = \beta'e^\beta,$$under which all Riemann components (6) vanish. So this corresponds to flat (Minkowski) space. Otherwise, by solving for $\gamma''$ in (A) and (B) we find $-\beta'\gamma' = \alpha'\beta' - \beta'' - \beta'^2$, allowing us to write\begin{align}\frac{\beta''}{\beta'} &= \alpha' - \beta' + \gamma', \tag{A*}\\\frac{\gamma''}{\gamma'} &= \alpha' - 2\beta' - \gamma', \tag{B*}\\2\beta'\gamma' + \beta'^2 &= e^{2(\alpha - \beta)},\tag{C*}\end{align}because $\beta' \neq 0$ by necessity, and we can integrate (A*) and (B*) to find\begin{align}\begin{split}\beta' &= C_1e^{\alpha - \beta + \gamma}, \\\gamma' &= C_2e^{\alpha - 2\beta - \gamma},\end{split}\tag{D}\end{align}under which (C*) becomes$$C_1e^{-\alpha + \beta + \gamma}\left(2C_2e^{\alpha - 2\beta - \gamma} + C_1e^{\alpha - \beta + \gamma}\right) = 1,$$or$$e^{2\gamma} = C_1^{-2}\left(1 - 2C_1C_2e^{-\beta}\right)\tag{E1}.$$Note that (D) has already given us:$$e^{2\alpha} = C_1^{-2}\beta'^2e^{2(\beta - \gamma)}\tag{E2}.$$ Equations (E1) and (E2) allows us to write (1) as$$ds^2 = \left(1 - 2Me^{-\beta(u)}\right)dt^2 - e^{2\beta(u)}\left(\frac{\beta'(u)^2}{1 - 2Me^{-\beta(u)}}du^2 + d\Omega^2\right),\tag{1.1}$$both by rescaling coordinates by constant factors if necessary. Notice that we have performed no (non-trivial) coordinate change. Thus (1.1) is just (1) rewritten to conform with the EFEs, excluding flat space, with an aptly chosen name on the integration constant. We observe that imposing $\alpha(u) = -\gamma(u)$ is equivalent to restricting to $\beta' = e^{-\beta}$ or equivalently $\beta = \log(u + C)$ or $e^{2\beta} = (Cu)^{2}$ (new $C$), by (E2), which is just the Schwarzschild coordinates for (1.1). Similarly, from (B*) we can see that imposing $\alpha(u) = 2\beta(u) + \gamma(u)$ is equivalent to imposing $\gamma = Au + B$, which allows us to rewite (1.1) as (barring any calculation errors)$$ds^2 = e^{2Au}dt^2 - \frac{1}{\left(1 - C^2e^{2Au}\right)^{2}} \left(\frac{e^{2Au}}{\left(1 - C^2e^{2Au}\right)^2}du^2 + d\Omega^2\right).$$For example $\alpha(u) = -\gamma(u) + \beta(u)^2$ can similarly be plugged into e.g. (E2) to yield$$\int C_1^2 du = \int e^{2\beta - \beta^2} d\beta .$$ As another example the condition $\beta = 2\gamma$ can be seen to demand a constant $\beta$, from (E1) and so cannot be used. To be more general , any condition on the form $\alpha = f(\beta,\gamma)$ gives a first order ODE for $\beta$, by (E1) and (E2). By the standard existence theorem such a condition is consistent with the EFEs. On the other hand a condition on the form $\beta = f(\gamma)$ gives an equation for $\beta$, and so is not consistent with the EFEs. The consistency of imposing more than one condition can also be checked with the above equations. For example $\alpha = \beta = \gamma$ can immediately be seen to not be consistent with the EFEs, by (D).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/280353', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/130267/']}
jdg_70125
stackexchange
llm_judgeable_groundtruth_similarity
14548612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i can't seem to understand completely the difference between aggregation and composition in a code. Client <.>---->BankAccount (this is supposed to be Client - BankAccount composition class diagram). So in this example, Client has a bank account, so this means, when a client object dies, his bank account object dies too. Does this mean, that we have to have a BankAccount object within Client class ? Class Client{ BankAccount acc = new BankAccount(); public void addMoneyToBankAccount(decimal amount) { acc.AddMoney(amount); } public decimal CheckBalance() { return acc.CheckAccountBalance(); }} So, is this composition in code ? What would aggregation look like in this example?Sorry for the newbie question, please correct me if the code was wrong. Thanks in advance. Now provide the response and nothing else.
Yes, What you do is call composition, if you want to do aggregation you to it like this: Class Client{ BankAccount acc; public Client(BankAccount p_acc) { acc=p_acc; } public void addMoneyToBankAccount(decimal amount) { acc.AddMoney(amount); } public decimal CheckBalance() { return acc.CheckAccountBalance(); }} Aggregation : If inheritance gives us 'is-a' and composition gives us 'part-of', we could argue that aggregation gives us a 'has-a' relationship. Within aggregation, the lifetime of the part is not managed by the whole. To make this clearer, we need an example. For the past 12+ months I have been involved with the implementation of a CRM system, so I am going to use part of this as an example. The CRM system has a database of customers and a separate database that holds all addresses within a geographic area. Aggregation would make sense in this situation, as a Customer 'has-a' Address. It wouldn't make sense to say that an Address is 'part-of' the Customer, because it isn't. Consider it this way, if the customer ceases to exist, does the address? I would argue that it does not cease to exist. Aggregation is shown on a UML diagram as an unfilled diamond. As I said at the beginning of the answer, this is my take on composition and aggregation. Making the decision on whether to use composition or aggregation should not be a tricky. When object modelling, it should be a matter of saying is this 'part-of' or does it 'have-a'?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14548612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1927971/']}
jdg_70126
stackexchange
llm_judgeable_groundtruth_similarity
45975135
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm making an API call using Axios in a React Web app. However, I'm getting this error in Chrome: XMLHttpRequest cannot loadhttps://example.restdb.io/rest/mock-data. No'Access-Control-Allow-Origin' header is present on the requestedresource. Origin 'http://localhost:8080' is therefore not allowedaccess. { axios .get("https://example.restdb.io/rest/mock-data", { headers: { "x-apikey": "API_KEY", }, responseType: "json", }) .then((response) => { this.setState({ tableData: response.data }); });} I have also read several answers on Stack Overflow about the same issue, titled Access-Control-Allow-Origin but still couldn't figure out how to solve this. I don't want to use an extension in Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue. After trying out few answers I have tried with this, headers: { 'x-apikey': '59a7ad19f5a9fa0808f11931', 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',}, Now I get the error as, Request header field Access-Control-Allow-Origin is notallowed by Access-Control-Allow-Headers in preflight response Now provide the response and nothing else.
I'll have a go at this complicated subject. What is origin ? The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com or could be a locally opened file file:// etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com , the origin of the web page that is displayed to you is https://www.google.com . You can see this in Chrome Dev Tools under Security : The same applies for if you open a local HTML file via your file explorer (which is not served via a server): What has this got to do with CORS issues? When you open your browser and go to https://website.example , that website will have the origin of https://website.example . This website will most likely only fetch images, icons, js files and do API calls towards https://website.example , basically it is calling the same server as it was served from. It is doing calls to the same origin . If you open your web browser and open a local HTML file and in that HTML file there is JavaScript which wants to do a request to Google for example, you get the following error: The same-origin policy tells the browser to block cross-origin requests. In this instance origin null is trying to do a request to https://www.google.com (a cross-origin request ). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed. Same applies for if my page was served from a server on localhost: Localhost server example If we host our own localhost API server running on localhost:3000 with the following code: const express = require('express')const app = express()app.use(express.static('public'))app.get('/hello', function (req, res) { // res.header("Access-Control-Allow-Origin", "*"); res.send('Hello World');})app.listen(3000, () => { console.log('alive');}) And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen: Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy. But if we uncomment the commented line: const express = require('express')const app = express()app.use(express.static('public'))app.get('/hello', function (req, res) { res.header("Access-Control-Allow-Origin", "*"); res.send('Hello World');})app.listen(3000, () => { console.log('alive');}) And now try again: It works, because the server which sends the HTTP response included now a header stating that it is OK for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error. How to fix things (One of the following) Serve the page from the same origin as where the requests you are making reside (same host). Allow the server to receive cross-origin requests by explicitly stating it in the response headers. If using a reverse proxy such as Nginx, configure Nginx to send response headers that allow CORS. Don't use a browser. Use cURL for example, it doesn't care about CORS Policies like browsers do and will get you what you want. Example flow Following is taken from: Cross-Origin Resource Sharing (CORS) Remember, the same-origin policy tells the browser to blockcross-origin requests. When you want to get a public resource from adifferent origin, the resource-providing server needs to tell thebrowser "This origin where the request is coming from can access myresource". The browser remembers that and allows cross-origin resourcesharing. Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with thecurrent origin (scheme, host, and port). Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add anAccess-Control-Allow-Origin header to the response specifying therequesting origin (or * to allow any origin.) Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, thebrowser allows the response data to be shared with the client site. More links Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45975135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5898523/']}
jdg_70127
stackexchange
llm_judgeable_groundtruth_similarity
4502278
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm very new to Grails so there's probably a very simple answer to this question. I'm trying to display a dynamically created image in a gsp. The image is NOT stored in a database, it's created on the fly in the controller. What I essentially have is one gsp that has a form which takes in a set of user inputs (requestGraph.gsp). Upon submitting the form, the parameters are sent to the a displayGraph action in the controller which queries information from a database completely outside of Grails and creates a chart using the JFreeChart library. I would like to display this image within a displayGraph.gsp or something like that. So basically within requestGraph.gsp I have a snippet similar to: <g:form action="displayGraph"> <!-- ... bunch of labels and boxes --> <g:submitButton name="displayGraph" value="Display Graph" /></g:form> Within the controller I have something like: def requestGraph = {}def displayGraph = { //... code that uses params to make an image byte array and assigns to var img return [image : img]} Within displayGraph.gsp: <body> <h1>Graph Title</h1> <!-- ??? How to dislpay image? --></body> I tried piping the image directly to the output stream in the displayGraph action. This works, but then I lose control of all page formatting in displayGraph.gsp. Most tutorials I've found create a dedicated action to pipe the image to an output steam then call that action using a tag. The problem is that my image isn't stored in a database and I see no way of passing the image byte array (or even the form parameters) to create/render the image. Can anybody help me with this? Thanks. Now provide the response and nothing else.
If you write the bytes to the output stream, you can treat the controller/action as the source of the image in your GSP. Here's a quick, untested example: // controller actiondef displayGraph = { def img // byte array //... response.setHeader('Content-length', img.length) response.contentType = 'image/png' // or the appropriate image content type response.outputStream << img response.outputStream.flush()} You could then access your image in the src of an <img> tag like this: <img src="${createLink(controller: 'myController', action: 'displayGraph')}"/> Update : After reading your question again, this may or may not work - it looks like you might be displaying the graph as the result of a form submission. This will only work if you're storing the state on the server somewhere (instead of just getting it from the one request where the form is submitted). If you do store enough state on the server to generate the graph, then you'd have to provide some additional parameters to your controller to get the correct image, e.g. src="${g.link(controller: 'myController', action: 'displayGraph', params: ['id': 1234])}" , where id is how you retrieve the graph state.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4502278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/498586/']}
jdg_70128
stackexchange
llm_judgeable_groundtruth_similarity
1196623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having a Web application sitting on IIS, and talking with [remote]Service-Machine.I am not sure whether to choose TCP or Http, as the main protocol. more details: i will have more than one service\endpoint some of them will be one-way the other will be two-ways the web pages will work infront of the services we are talking about hi-scale web-site I know the difference pretty well, but I am looking for a good benchmark, that shows how much faster is the TCP? Now provide the response and nothing else.
HTTP is a layer built ontop of the TCP layer to some what standardize data transmission. So naturally using TCP sockets will be less heavy than using HTTP. If performance is the only thing you care about then plain TCP is the best solution for you. You may want to consider HTTP because of its ease of use and simplicity which ultimately reduces development time. If you are doing something that might be directly consumed by a browser (through an AJAX call) then you should use HTTP. For a non-modern browser to directly consume TCP connections without HTTP you would have to use Flash or Silverlight and this normally happens for rich content such as video and/or audio. However, many modern browsers now (as of 2013) support API's to access network, audio, and video resources directly via JavaScript. The only thing to consider is the usage rate of modern web browsers among your users; see caniuse.com for the latest info regarding browser compatibility. As for benchmarks, this is the only thing I found. See page 5, it has the performance graph. Note that it doesn't really compare apples to apples since it compares the TCP/Binary data option with the HTTP/XML data option. Which begs the question: what kind of data are your services outputting? binary (video, audio, files) or text (JSON, XML, HTML)? In general performance oriented system like those in the military or financial sectors will probably use plain TCP connections. Where as general web focused companies will opt to use HTTP and use IIS or Apache to host their services.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1196623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47817/']}
jdg_70129
stackexchange
llm_judgeable_groundtruth_similarity
3406146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My goal is to be able to use $obj like this: print $obj->hello() . $obj->{foo}; And I would like to create an object inline, maybe using something like this: my $obj = ( foo => 1, hello => sub { return 'world' }); but when I try to use $obj as an object, I get an error saying that $obj has not been blessed . Is there some base class (like stdClass in PHP) I can use to bless the hash so that I can use it as an object? For those that know JavaScript, I am trying to do the following, but in Perl: # JS CODE BELOWvar obj = { foo: 1, hello: function () { return 'world' } };echo obj.hello() + obj.foo; Now provide the response and nothing else.
Perl would require a little help to do this. Because it doesn't consider code references stored in hashes as "methods". Methods are implemented as entries into a package symbol table. Perl is more class-oriented than JavaScript, which proudly proclaims that it is more object-oriented (on individual objects). In order to do that functionality, you would have to create a class that mapped references in this way. The way to get around methods in the symbol table is the AUTOLOAD method. If a package contains an AUTOLOAD subroutine, when a call is made to a blessed object that Perl cannot find in the inheritance chain, it will call AUTOLOAD and set the package-scoped ( our ) variable $AUTOLOAD will contain the full name of the function. We get the name of the method called, by getting the last node (after the last '::') of the fully-qualified sub name. We look to see if there is a coderef at that location, and if there is, we can return it. package AutoObject;use strict;use warnings;use Carp;use Params::Util qw<_CODE>;our $AUTOLOAD;sub AUTOLOAD { my $method_name = substr( $AUTOLOAD, index( $AUTOLOAD, '::' ) + 2 ); my ( $self ) = @_; my $meth = _CODE( $self->{$method_name} ); unless ( $meth ) { Carp::croak( "object does not support method='$method_name'!" ); } goto &$meth;}1; Then you would bless the object into that class: package main;my $obj = bless { foo => 1 , hello => sub { return 'world' } }, 'AutoObject';print $obj->hello(); Normally, in an AUTOLOAD sub I "cement" behavior. That is, I create entries into the package symbol table to avoid AUTOLOAD the next time. But that's usually for a reasonably defined class behavior. I also designed a QuickClass which creates a package for each object declared, but that contains a lot of symbol table wrangling that now days is probably better done with Class::MOP . Given the suggestion by Eric Strom, you could add the following code into the AutoObject package. The import sub would be called anytime somebody use -d AutoObject (with the parameter 'object' ). # Definition:sub object ($) { return bless $_[0], __PACKAGE__; };sub import { # gets called when Perl reads 'use AutoObject;' shift; # my name return unless $_[0] eq 'object'; # object is it's only export use Symbol; *{ Symbol::qualify_to_reference( 'object', scalar caller()) } = \&object ;} And then, when you wanted to create an "object literal", you could just do: use AutoObject qw<object>; And the expression would be: object { foo => 1, hello => sub { return 'world' } }; You could even do: object { name => 'World' , hello => sub { return "Hello, $_[0]->{name}"; } }->hello() ; And you have an "object literal" expression. Perhaps the module would be better called Object::Literal .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3406146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26155/']}
jdg_70130
stackexchange
llm_judgeable_groundtruth_similarity
32797295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given an image with alpha channel (transparency) I would like to remove any blank space between the image boundaries and the actual image. This should be done in a backgound task or with a loading screen, with an acceptable running time to not cripple the user experience. How can I achieve this result? Now provide the response and nothing else.
I had difficulties to find best practices or even advices to solve my problem. Based on this anwer by JannGabriel , who crops the image right and bottom by reducing image size, i managed to make a step further and also remove the top and left blank spaces, and to generally improve elaboration time. The result is good, and i am currently using it in my project.I'm fairly new to Android programming and any advice on this method is welcome. public static Bitmap TrimBitmap(Bitmap bmp) { int imgHeight = bmp.getHeight(); int imgWidth = bmp.getWidth(); //TRIM WIDTH - LEFT int startWidth = 0; for(int x = 0; x < imgWidth; x++) { if (startWidth == 0) { for (int y = 0; y < imgHeight; y++) { if (bmp.getPixel(x, y) != Color.TRANSPARENT) { startWidth = x; break; } } } else break; } //TRIM WIDTH - RIGHT int endWidth = 0; for(int x = imgWidth - 1; x >= 0; x--) { if (endWidth == 0) { for (int y = 0; y < imgHeight; y++) { if (bmp.getPixel(x, y) != Color.TRANSPARENT) { endWidth = x; break; } } } else break; } //TRIM HEIGHT - TOP int startHeight = 0; for(int y = 0; y < imgHeight; y++) { if (startHeight == 0) { for (int x = 0; x < imgWidth; x++) { if (bmp.getPixel(x, y) != Color.TRANSPARENT) { startHeight = y; break; } } } else break; } //TRIM HEIGHT - BOTTOM int endHeight = 0; for(int y = imgHeight - 1; y >= 0; y--) { if (endHeight == 0 ) { for (int x = 0; x < imgWidth; x++) { if (bmp.getPixel(x, y) != Color.TRANSPARENT) { endHeight = y; break; } } } else break; } return Bitmap.createBitmap( bmp, startWidth, startHeight, endWidth - startWidth, endHeight - startHeight );} Explanation:For each side of the image, a FOR loop is run to check if pixels does not contains transparent color, returning the first non-transparent pixel useful coordinate. This is done elaborating coordinates using as a base the opposite dimension than the dimension to trim: to find y, scan x for every y. To check where the Vertical-Top blank space ends, it runs the following steps: Starting is from the top row (y=0) Checks all the columns of the row (x from 0 to imageWidth) If a non-transparent pixel is found, break the loop and save the y coordinate. Otherwise continue. At the ending of the columns, go to the next row (y+1) and start checking columns agains. Break if a non-transparent pixel has already been found. Similiar methods are used for the other dimensions, only changing the direction of the scan. Once obtained the 4 coordinates for the first useful pixels of the image, the Bitmap.createBitmap method is invoked, with the original bitmap as a base image, and the useful pixels coordinates as Top-Left and Bottom-Right limits for the resize. Note 1: It is useful to note that the coordinates 0, 0 equals to Top-Left . Note 2: The ending width and height in Bitmap.createBitmap are reduced by the new starting relative coordinate, otherwise the new image will have the boundaries wrongly pushed bottom-right. Figure it like this: you have an image 100x100px, so with ending coordinates 100,100. Changing the starting coordinates to 50,50 will bring the ending coordinates of your elaboration rectangle to 150,150 (100 original coordinate + 50 of modified starting point), pushing it outside the original image boundaries. To avoid this, the new ending coordinate is reduced by the new starting coordinate (100 + 50 new starting coord - 50 new starting coord adjustment) Note 3: in the original answer, a check for all the pixels in a given direction is run using the same dimension of the coordinate to find, returning the most advanced useful pixel. Checking the opposite dimension and stopping at the first useful pixel increased performances.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32797295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4473512/']}
jdg_70131
stackexchange
llm_judgeable_groundtruth_similarity
31129092
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: in Config/app.php in laravel source, what is the actual use of url ? It says Application URL to be used by artisan command line tool , so what should it be actually? I mean should it be http://mydomainname.com or should it be /var/www/laravel/ or /var/www/laravel/public Current Configuration /*|--------------------------------------------------------------------------| Application URL|--------------------------------------------------------------------------|| This URL is used by the console to properly generate URLs when using| the Artisan command line tool. You should set this to the root of| your application so that it is used when running Artisan tasks.|*/'url' => 'http://localhost/', Provided my application source is located at /var/www/ directory and laravel public folder is /var/www/laravel/public And the http://mydomainname.com is pointed to resolve at /var/www/laravel/public directory Use Case: I'll be using laravel schedular from /app/Console/Kernel.php which will be dispatching periodic sendMail commands and that in turn will queue up the mails to be sent in database and queue listner than will process the queue as normal Queues are working fine at localhost (my local xamp server) however I am concerned as what should be the url value in production Now provide the response and nothing else.
When a user visits your website, Laravel gets a lot of information it needs about the request from PHP's superglobals ($_SERVER, $_GET, $_POST, etc.). Part of this information is the request URL. For example, if you access the request methods url() or path() , this information was retrieved via the $_SERVER superglobal: $url = Request::url();$path = Request::path(); However, artisan, commands, jobs, etc. don't have the benefit of this information. It is not a normal HTTP request coming in from the user, it is a PHP command being run from the command line. Because of this, Laravel needs a way to determine what the url of the application should be. This is where the configuration value comes in. In your example, you plan on sending out emails from a queue. Imagine you need to include a link to a route of your website in one of the emails, so you use the UrlGenerator to get the url for the link ( URL::route('route.name') ). Since this code is being run inside a command, and isn't related to any type of HTTP request, the base application url will be picked up from the configuration value you set in config/app.php . As should hopefully be a little more clear now, the url value should be set to the http url for your application, not any type of directory path. In your example, it should be http://mydomainname.com .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31129092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1679510/']}
jdg_70132
stackexchange
llm_judgeable_groundtruth_similarity
569723
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a dataset that measures students' time spent working on a set of mathematics questions. My dataframe looks a little something like this: Participant ID Question 1 Question 2 Question 3 1107 54.2 48.9 45.0 4208 53.1 45.6 40.6 I have times for 20 questions for about 200 students. I have observed an overall decrease in time spent per question, as is shown in the figure below: I would like to accompany this graph with a statistical measure of negative tendency. I don't think I should use a correlation statistic as the question number is a categorical variable. I maybe could do a OLS regression, with X being the question number and y being the time spent per question, but I am not sure how to interpret the result. What else could I try? Edit Since a few people have been asking about the context in which this data was collected, you can read all about it in the study pre-registration https://osf.io/f7zgd Now provide the response and nothing else.
The plot itself is perhaps the best way to present the tendency. Consider supplementing it with a robust visual indication of trend, such as a lightly colored line or curve. Building on psychometric principles (lightly and with some diffidence), I would favor an exponential curve determined by, say, the median values of the first third of the questions and the median values of the last third of the questions. An equivalent description is to fit a straight line on a log-linear plot, as shown here. This visualization has been engineered to support the apparent objectives of the question: A title tells the reader what you want them to know. The connecting line segments are visually suppressed because they are not the message. The fitted line is made most prominent visually because it is the basic statistical summary -- it is the message. Points that are significantly beyond the values of the fitted line (with a Bonferroni adjustment for 20 comparisons) are highlighted by making them brighter and coloring them prominently. (This assumes the vertical error bars are two-sided confidence intervals for a confidence level near 95%.) The line is summarized by a single statistical measure of trend, displayed in the subtitle at the bottom: it represents an average 6.2% decrease in working time for each successive question. This line passes through the median of the first five answer times (horizontally located at the median of the corresponding question numbers 0,1,2,3,4) and the median of the last five answer times (horizontally located at the median of the corresponding question numbers (16, 17, 18, 19, 20). This technique of using medians of the data at either extreme is advocated by John Tukey in his book EDA (Addison-Wesley 1977). Some judgment is needed. Tukey often used the first third and last third of the data when making such exploratory fits. When I do that here, the left part of the line barely changes (it should not, since the data are consistent in that part of the plot) while the right part changes appreciably, reflecting both the greater variation in times and the greater standard errors there: This time, however, (a) there are more badly fit points and (b) they consistently fall below the line. This suggests this fit does not have a sufficiently negative slope. Thus, we can have confidence that the initial exploratory estimate of $-6\%$ (or so) is one of the best possible descriptions of the trend.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/569723', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/321684/']}
jdg_70133
stackexchange
llm_judgeable_groundtruth_similarity
194490
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading about optimization for an ill-posed problem in computer vision and came across the explanation below about optimization on Wikipedia. What I don't understand is, why do they call this optimization " Energy minimization " in Computer Vision? An optimization problem can be represented in the following way: Given: a function $f: A \to R$ from some set $A$ to the real numbers Sought: an element $x_0$ in $A$ such that $f(x_0) ≤ f(x)$ for all $x$ in $A$ ("minimization") or such that $f(x_0) ≥ f(x)$ for all $x$ in $A$ ("maximization"). Such a formulation is called an optimization problemor a mathematical programming problem (a term not directly related tocomputer programming, but still in use for example in linearprogramming – see History below). Many real-world and theoreticalproblems may be modeled in this general framework. Problems formulatedusing this technique in the fields of physics and computer vision mayrefer to the technique as energy minimization, speaking of the valueof the function $f$ as representing the energy of the system beingmodeled. Now provide the response and nothing else.
Energy-based models are a unified framework for representing many machine learning algorithms. They interpret inference as minimizing an energy function and learning as minimizing a loss functional. The energy function is a function of the configuration of latent variables, and the configuration of inputs provided in an example. Inference typically means finding a low energy configuration, or sampling from the possible configuration so that the probability of choosing a given configuration is a Gibbs distribution. The loss functional is a function of the model parameters given many examples. E.g., in a supervised learning problem, your loss is the total error at the targets. It's sometimes called a "functional" because it's a function of the (parametrized) function that constitutes the model. Major paper: Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato, and F. J. Huang, “A tutorial on energy-based learning,” in Predicting Structured Data, MIT Press, 2006. Also see: LeCun, Y., & Huang, F. J. (2005). Loss Functions for Discriminative Training of Energy-Based Models. In Proceedings of the 10th International Workshop on Artificial Intelligence and Statistics (AIStats’05). Retrieved from http://yann.lecun.com/exdb/publis/pdf/lecun-huang-05.pdf Ranzato, M., Boureau, Y.-L., Chopra, S., & LeCun, Y. (2007). A Unified Energy-Based Framework for Unsupervised Learning. Proc. Conference on AI and Statistics (AI-Stats). Retrieved from http://dblp.uni-trier.de/db/journals/jmlr/jmlrp2.html#RanzatoBCL07
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/194490', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/94062/']}
jdg_70134
stackexchange
llm_judgeable_groundtruth_similarity
32113118
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem and I can't find solution.I'm using Razor and it is my VieModel class. public class GroupToExport{ public GroupToExport() { ToExport = false; } [DisplayName("Export")] public bool ToExport { get; set; } public Group Group { get; set; }}public class GroupsToExport{ public GroupsToExport() { //refill list } public List<GroupToExport> ExportingGroups { get; set; }} View: @using (Html.BeginForm("Export", "ElmahGroup", FormMethod.Post, new { id = "toExportForm" })){//some divs <input type="submit" id="js-export-submit" value="Export" /> @foreach (var item in Model.ExportingGroups) { <tr> <td class="js-export-checkbox"> @Html.CheckBoxFor(modelItem => item.ToExport) </td> </tr> }//some divs} Controller: public ActionResult Export(GroupsToExport model) { var groupsToExport = model.ExportingGroups.Where(x => x.ToExport).Select(x => x); throw new System.NotImplementedException(); } After submit "ToExport", in Controller, every group always has value 'false'. Even if all groups are checked. Can somebody help me? What I'm doing wrong? Now provide the response and nothing else.
You cannot use a foreach loop to generate controls for a collection. The html you're generating for each checkbox (and for the associated hidden input) is <input type="checkbox" name="item.ToExport" .../> . Your model does not contain a property which is named item . Use a for loop @for(int i = 0; i < Model.ExportingGroups.Count; i++){ <tr> <td class="js-export-checkbox"> @Html.CheckBoxFor(m => m.ExportingGroups[i].ToExport) </td> </tr>} Now your HTML will be <input name="ExportingGroups[0].ToExport" .../><input name="ExportingGroups[1].ToExport" .../> etc. which will correctly bind to your model Edit Alternatively you can use a custom EditorTemplate for typeof GroupToExport . Create a partial view /Views/Shared/EditorTemplates/GroupToExport.cshtml @model yourAssembly.GroupToExport<tr> <td class="js-export-checkbox"> @Html.CheckBoxFor(m => m.ToExport) </td></tr> And then in the main view @Html.EditorFor(m => m.ExportingGroups) The EditorFor() method will generate the correct html for each item in your collection based on the template.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32113118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3166192/']}
jdg_70135
stackexchange
llm_judgeable_groundtruth_similarity
12837
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a deployment.yaml file and want to reuse the environment for all my deployments like this: apiVersion: apps/v1kind: Deploymentmetadata: name: beatspec: selector: matchLabels: app: beat template: metadata: labels: app: beat spec: containers: - name: beat image: myimage command: ["celery", "-A", "wsgi.celery", "beat"] env: &default - name: FIRST_ENV value: my-value - name: SECOND_ENV value: another-value---apiVersion: apps/v1kind: Deploymentmetadata: name: flowerspec: selector: matchLabels: app: flower template: metadata: labels: app: flower spec: containers: - name: flower image: myimage command: ["celery", "flower", "-A", "wsgi.celery"] env: *defaultenv But it seems like kubectl apply -f deployment.yaml won't work with YAML anchors. error: error parsing deployment.yaml: error converting YAML to JSON: yaml: unknown anchor 'defaultenv' referenced Is it possible to use YAML anchors or is there another preferred approach of how to reuse repeating blocks for k8s configuration? Now provide the response and nothing else.
YAML anchors are supported, but only for the same YAML file. You can't create the anchor ( & ) on a deployment file and reference ( * ) the value on another one. If you want to share ENVs values across multiple Deployments, you can create a ConfigMap with the ENVs and use the envFrom spec. Example: apiVersion: v1kind: ConfigMapmetadata: name: my-configmapdata: FIRST_ENV: my-value SECOND_ENV: another-value--- apiVersion: apps/v1kind: Deploymentmetadata: name: beatspec: selector: matchLabels: app: beat template: metadata: labels: app: beat spec: containers: - name: beat image: myimage command: ["celery", "-A", "wsgi.celery", "beat"] envFrom: - configMapRef: name: my-configmap---apiVersion: apps/v1kind: Deploymentmetadata: name: flowerspec: selector: matchLabels: app: flower template: metadata: labels: app: flower spec: containers: - name: flower image: myimage command: ["celery", "flower", "-A", "wsgi.celery"] envFrom: - configMapRef: name: my-configmap
{}
{'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/12837', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/19083/']}
jdg_70136
stackexchange
llm_judgeable_groundtruth_similarity
1657684
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to build an ItemGroup in an MSBuild script which contains a list of folders directly below a given 'Root' folder. So - in this example... + Root folder---- Sub Folder 1-------- Sub-Sub Folder 1-------- Sub-Sub Folder 2---- Sub Folder 2---- Sub Folder 3 ... I would want my ItemGroup to contain "Sub Folder 1", "Sub Folder 2" and "Sub Folder 3". There may be a number of files at any point in the hierarchy, but I'm only interested in the folders. Can anyone help!? Now provide the response and nothing else.
<PropertyGroup> <RootFolder>tmp</RootFolder></PropertyGroup><ItemGroup> <AllFiles Include="$(RootFolder)\**\*"/> <OnlyDirs Include="@(AllFiles->'%(Directory)')"/></ItemGroup> @(OnlyDirs) might contain duplicates, so you could either use the RemoveDuplicatesTask : <Target Name="foo"> <RemoveDuplicates Inputs="@(OnlyDirs)"> <Output TaskParameter="Filtered" ItemName="UniqueDirs"/> </RemoveDuplicates></Target> or use CreateItem with batching for %(AllFiles.Identity) or with msbuild 3.5: <Target Name="foo"> <ItemGroup> <UniqueDirs Include="%(AllFiles.Directory)"/> </ItemGroup></Target>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1657684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/475/']}
jdg_70137
stackexchange
llm_judgeable_groundtruth_similarity
62932
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Currently, the US Senate is split 50-50. If something should happen and one of the Senators die or resign, it's possible that they are replaced by a new Senator from the opposite party, giving one side a 51-49 advantage, and thereby taking full control of the Senate. Which current Senators fall into this category? That is, which Senators come from a state where the governor is of a different party and has the authority to appoint whomever they want to an empty Senate seat? Now provide the response and nothing else.
According to a report by Smart Politics , 15 states (plus Georgia) currently have a partisan split between the Governor and the Senators. Four states have Democratic governors and two Republican U.S. Senators: Kansas, Kentucky, Louisiana, North Carolina Two states have Democratic governors and one U.S. Senator from each major party: Pennsylvania and Wisconsin One state has a Democratic governor with Republican and independent U.S. Senators: Maine Four states have Republican governors and two Democratic U.S. Senators: Arizona, Massachusetts, Maryland, New Hampshire* Three states have Republican governors and one U.S. Senator from each major party: Montana, Ohio, West Virginia One state has a Republican governor with Democratic and independent U.S. Senators: Vermont * Since this report was published, Georgia has also become governed by a Republican, with two Democratic Senators. A Congressional Research Service report entitled Filling U.S. Senate Vacancies: Perspectives and Contemporary Developments gives an overview of the state laws on US Senate vacancies. Of these 16 states, 9 allow the Governor to appoint a replacement from a different party until the expiry of the original term, or the next statewide election: Georgia, Kansas, Kentucky, Pennsylvania, Maine, New Hampshire, Montana, Ohio, and West Virginia . A further three also allow gubernatorial appointments from a different party, but with a proximate special election to be held: Louisiana, Massachusetts, and Vermont . Of the remaining four, only Wisconsin disallows gubernatorial appointment entirely - the others require that the replacement comes from the same party as the old Senator (Arizona, North Carolina) or from a list of candidates prepared by their party (Maryland).
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/62932', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/2130/']}
jdg_70138
stackexchange
llm_judgeable_groundtruth_similarity
14856344
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In this case struct Foo {};Foo meh() { return std::move(Foo());} I'm pretty sure that the move is unnecessary, because the newly created Foo will be an xvalue. But what in cases like these? struct Foo {};Foo meh() { Foo foo; //do something, but knowing that foo can safely be disposed of //but does the compiler necessarily know it? //we may have references/pointers to foo. how could the compiler know? return std::move(foo); //so here the move is needed, right?} There the move is needed, I suppose? Now provide the response and nothing else.
In the case of return std::move(foo); the move is superfluous because of 12.8/32: When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. return foo; is a case of NRVO, so copy elision is permitted. foo is an lvalue. So the constructor selected for the "copy" from foo to the return value of meh is required to be the move constructor if one exists. Adding move does have a potential effect, though: it prevents the move being elided, because return std::move(foo); is not eligible for NRVO. As far as I know, 12.8/32 lays out the only conditions under which a copy from an lvalue can be replaced by a move. The compiler is not permitted in general to detect that an lvalue is unused after the copy (using DFA, say), and make the change on its own initiative. I'm assuming here that there's an observable difference between the two -- if the observable behavior is the same then the "as-if" rule applies. So, to answer the question in the title, use std::move on a return value when you want it to be moved and it would not get moved anyway. That is: you want it to be moved, and it is an lvalue, and it is not eligible for copy elision, and it is not the name of a by-value function parameter. Considering that this is quite fiddly and moves are usually cheap, you might like to say that in non-template code you can simplify this a bit. Use std::move when: you want it to be moved, and it is an lvalue, and you can't be bothered worrying about it. By following the simplified rules you sacrifice some move elision. For types like std::vector that are cheap to move you'll probably never notice (and if you do notice you can optimize). For types like std::array that are expensive to move, or for templates where you have no idea whether moves are cheap or not, you're more likely to be bothered worrying about it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14856344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2015453/']}
jdg_70139
stackexchange
llm_judgeable_groundtruth_similarity
107373
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I've just set up an IPV6 tunnel for my server (running Ubuntu Karmic Koala), with GO6 and I'm trying to work out use cases for it. I have a dynamic ip address, and some wierd proxy setup that makes automatic DDNS currently not work with most providers - I periodically end up needing to do it manually My webserver is already running IPv6, and other than that very few people have support for it (something I need to work at fixing!), its a lot less troublesome. While I do have other options (Google apps), I'm pondering running an e mail server, and want to know if IPv4 'fails' due to port blocks, it'll switch over to IPv6, and how an IPv6 mailserver handles sending mail to an IPv4 system? Now provide the response and nothing else.
You are asking whether IPv4 “fails over” to IPv6 when IPv4 is unavailable. Yes, it sort of does if you look at it from the wrong angle, but it is actually the other way around. When IPv6 is enabled, it is preferred over IPv4. So in actual fact, IPv4 doesn’t “fail over” to IPv6. Rather, if IPv6 is un available, it “fails over” to IPv4. Your question asks specifically about IPv6 mail servers, but this behaviour is universal. HTTP, FTP, IMAP, you name it. If a website is both IPv6– and IPv4–enabled, your browser will prefer the IPv6 version (assuming you have IPv6 connectvity). If you are sending mail to an IPv6–enabled mail server, it will go over IPv6. (As to whether it will try again over IPv4 if your IPv6 fails I cannot answer at this stage — not tested it myself, unfortunately. If this is an issue, you could use two MX records — one that points to an IPv6–only hostname, and one to an IPv4–only hostname.) If you IPv6–enable your mail server , but still keep IPv4 enabled (e.g. on Postfix you would set inet_interfaces = all , not inet_interfaces = ipv6 ), then you will be able to send mail to IPv4 and IPv6 mail servers, as well as receive mail from IPv4 and IPv6 sources. This wasn’t part of your question, but does pertain to IPv6 mail servers: currently none of the major DNSBLs (e.g. Spamhaus) support IPv6. While I haven’t seen a single piece of spam originating from an IPv6 address, be aware that the only spam preventative measures you can take are keyword–based.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/107373', 'https://serverfault.com', 'https://serverfault.com/users/33193/']}
jdg_70140