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
10988868
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 method that returns void and I need to use it in another method that also returns void. Can I do the following? public void doSomething(){}public void myMethod(){ return doSomething();} Thanks for all your comments, but let me be more specific I only doSomething if something happens, otherwise I do other things public void doSomething(){}public void myMethod(){ for(...) if(somethingHappens) { doSomething(); return; } doOtherStuff();} Instead of the code above, can I just write return doSomething(); inside the if statement? Now provide the response and nothing else.
No, just do this: public void doSomething() { }public void myMethod(){ doSomething();} or in the second case: public void doSomething() { }public void myMethod(){ // ... if (somethingHappens) { doSomething(); return; } // ...} "Returning void" means returning nothing. If you would like to "jump" out of myMethod 's body, use return; The compiler does not allow writing return void; ("illegal start of expression") or return doSomething(); ("cannot return a value from method whose result type is void"). I understand it seems logical to return "void" or the "void result" of a method call, but such a code would be misleading. I mean most programmers who read something like return doSomething(); would think there is something to return.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10988868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1405385/']}
jdg_77741
stackexchange
llm_judgeable_groundtruth_similarity
19124662
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ROW_NUMBER() is only for used in the SELECT clause in MS SQL Server , but I want to use it for update like the following: Update MyTab Set MyNo = 123 + ROW_NUMBER() over (Order By ID)Where a=b; then I got Error like, Windowed functions can only appear in the SELECT or ORDER BY clauses. How to use ROW_NUMBER() in UPDATE clause? Now provide the response and nothing else.
You can use a CTE: ;WITH RowNbrs AS ( SELECT ID , ROW_NUMBER() OVER (ORDER BY ID) AS RowNbr FROM MyTab WHERE a = b)UPDATE t SET t.MyNo = 123 + r.RowNbrFROM MyTab t JOIN RowNbrs r ON t.ID = r.ID;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19124662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125857/']}
jdg_77742
stackexchange
llm_judgeable_groundtruth_similarity
48024720
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 is self explanatory: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(host, port)s.send("some data")# don't close socket just yet... # do some other stuff with the data (normal string operations)if s.stillconnected() is true: s.send("some more data")if s.stillconnected() is false: # recreate the socket and reconnect s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(host, port) s.send("some more data")s.close() How do I implement s.stillconnected() I do not wish to recreate the socket blindly. Now provide the response and nothing else.
If the server connection is no longer alive, calling the send method will throw an exception, so you can use a try-exception block to attempt to send data, catch the exception if it's thrown, and reestablish the connection: try: s.send("some more data")except: # recreate the socket and reconnect s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(host, port) s.send("some more data") EDIT : As per @Jean-Paul Calderone's comments, please consider using the sendall method, which is a higher level method that sends all the data or throws an error, instead of send , which is a lower level method that does not guarantee the transmission of all the data, OR use higher level modules like an HTTP library that can handle socket lifecycles.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48024720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1442789/']}
jdg_77743
stackexchange
llm_judgeable_groundtruth_similarity
5766385
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 this program #include <stdio.h>int main(){ char arr[100]; printf("%d", (int)sizeof(0,arr));} This prints 4 when compiled as a C file and prints 100 as a C++ file. Why? I am using gcc. Now provide the response and nothing else.
In C the result of the right hand operand of the comma operator has a type and value . In C a comma operator does not yield an lvalue. So there is an lvalue to rvalue conversion resulting in decay of array type to pointer type. So in C what you get is the result of sizeof(char*) . In C++ the result of a comma expression is an lvalue. There is no such conversion[as in C] and what you get is the sizeof(arr) i.e 100
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5766385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/720699/']}
jdg_77744
stackexchange
llm_judgeable_groundtruth_similarity
1019365
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 tried compiling my app for OS 3 I encountered an the following error: error: type of accessor does not match the type of property The error was for a property I tried to access that is defined as follows: NSMutableArray *myArray@property (readonly,nonatomic) NSArray* myArray; the property is @synthesized in the implementation file. This worked just fine in OS 2.2.1 but doesn't is OS 3.0 Writing the getter method myself solved the problem. Is anyone aware of changes to objective-c between OS 2.2.1 and 3.0? Is there any documentation for these changes? The API changes document doesn't appear to contain anything about this issue. EDIT the error occurs when you try to access the property e.g. NSArray *anArray = myClass.myArray; As I mentioned above I found a workaround for this: writing the getter method myself, however what I'm really after is some kind of documentation from apple explaining this change and any other changes that are not API related. Thanks for your help Now provide the response and nothing else.
This is a compiler bug. Though you didn't specify it completely, I expect your code looks like this: @interface Foo : NSObject { NSMutableArray *objects;}@property (readonly, copy) NSArray *objects;@end@implementation Foo@synthesize objects;@end The compiler is, unfortunately, confused between the declaration of the objects property and the declaration of the objects instance variable . Remember that properties and instance variables are different things in Objective-C; a property can be backed by an instance variable, but it's really part of the public interface of a class. You can work around this by changing your code to clearly separate the definition of the instance variable from the definition of the property, for example by prefixing the name of the instance variable: @interface Foo : NSObject { NSMutableArray *_objects;}@property (readonly, copy) NSArray *objects;@end@implementation Foo@synthesize objects = _objects;@end This way the compiler doesn't get confused about the property versus the instance variable in expressions like self.objects (which it shouldn't anyway, but apparently does). Just to head off the inevitable response: Apple does not reserve the underbar prefix for instance variables. It's reserved for methods. Regardless, if you dislike the underbar, feel free to use another prefix.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1019365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124737/']}
jdg_77745
stackexchange
llm_judgeable_groundtruth_similarity
10164758
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: CREATE OR REPLACE FUNCTION addUploader(INTEGER, TEXT, TEXT) RETURNS TEXT AS $$DECLARE u_id ALIAS FOR $1 ; username ALIAS FOR $2; email ALIAS FOR $3; BEGIN IF email NOT LIKE '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$' THEN RAISE EXCEPTION 'Wrong E-mail format %', email USING HINT = 'Please check your E-mail format.'; END IF ; INSERT INTO uploader VALUES(u_id,username,email); IF NOT FOUND THEN RETURN 'Error'; END IF; RETURN 'Successfully added' ; EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'This ID already exists. Specify another one.' ; RETURN 'Error' ; END ; $$ LANGUAGE 'plpgsql' ; SELECT addUploader(25,'test','[email protected]'); This regex does not accept a correct email address. It should accept [email protected] is also rejecting any other string. stevengmailcom - rejected Everything is being rejected. What am i doing wrong? Now provide the response and nothing else.
You don't use LIKE with regexes in PostgreSQL, you use the ~ , ~* , !~ , and !~* operators: ~ Matches regular expression, case sensitive ~* Matches regular expression, case insensitive !~ Does not match regular expression, case sensitive !~* Does not match regular expression, case insensitive So your test should look more like this: IF email !~ '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$' THEN You also might want to hunt down a better regex for email addresses, "[email protected]" is a valid email address but your regex doesn't like it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10164758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_77746
stackexchange
llm_judgeable_groundtruth_similarity
36420
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: I just wonder how some website like WhatIsMyIP find out what your real IP address is, even if you use proxy server. It said : Proxy Detected and then they give your real IP address. Is it possible they use JavaScript to send HTTP request for not using web browser proxy settings(How could it be implemented by Java) or there is some magic technique? Now provide the response and nothing else.
There are several ways: Proxy headers, such as X-Forwarded-For and X-Client-IP , can be added by non-transparent proxies. Active proxy checking can be used - the target server attempts to connect to the client IP on common proxy ports (e.g. 8080) and flags it as a proxy if it finds such a service running. Servers can check if the request is coming from an IP that is a known proxy. WhatsMyIP probably has a big list of these, including common ones like HideMyAss. Web client software (e.g. Java applets or Flash apps) might be able to read browser settings, or directly connect to a web service on the target system (bypassing the proxy) to verify that the IPs match. Mobile app software can identify the client IP. Example: PhoneGap plugin
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/36420', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/-1/']}
jdg_77747
stackexchange
llm_judgeable_groundtruth_similarity
7829005
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 running a command in my linux server (Ubuntu).For example: screen -A -h 1500 -m -dmS test_command_one /home/SKY-users/SKY-001/./script Is there any way to the PID of this background progress which screen name is: test_command_one ? ps aux | grep test_command_one: root 6573 8.1 2.4 271688 123804 pts/4 Ss+ Oct19 3:04 /home/SKY-users/SKY-001/./ ... I'd like to get back this PID: 6573 PHP: (easy) <?php $output = shell_exec('sudo ps aux | grep test_command_one');$array = explode("\n", $output);echo '<pre>'.print_r($array, true).'</pre>';?> Thanks for help! Now provide the response and nothing else.
Edit: By combining with code by @WagnerVaz $mystring = "test_command_one";exec("ps aux | grep 'screen .* $mystring' | grep -v grep | awk '{ print $2 }' | head -1", $out);print "The PID is: " . $out[0]; Explanation ps aux - shows processes for all users and hidden processes too grep - filters only lines containing "screen" and then "test_command_one" in the same line grep -v - removes from output the very same line which we are executing, because it will also be matched awk '{ print $2 }' - awk splits input into columns and uses multiple spaces as separator. This print contents of 2nd column head -1 - limits output only to the first line. This is in case you have multiple screen running, only first ID is returned.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7829005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/950553/']}
jdg_77748
stackexchange
llm_judgeable_groundtruth_similarity
54604505
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 a Next.JS app where a user should login to see the content.I want to redirect the user to '/' if their username and password are correct.However my implementation seems not working. I searched on SO for questions regarding this,but all of them were talking about redirecting with getInitialProps but it doesn't help me since I want to redirect user from my custom express server. Login.js async handleSubmit(event) { event.preventDefault() const { username, password } = this.state try { const response = await fetch('/log_in', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) } catch (error) { console.log(error) }} server.js app.post('/log_in', (req,res) => { console.log(`login form data`); console.log(`Username : ${req.body.username}`); console.log(`password : ${req.body.password}`); if(req.body.username == "user" && req.body.password == "123"){ res.redirect('/') }}) Now provide the response and nothing else.
This is now possible on Next.js 10+ without having to do any sort of response header manipulation directly. Use getServerSideProps or getStaticProps and return a redirect key as the only value from it if your conditions are met: export async function getServerSideProps(context) { if(req.body.username == "user" && req.body.password == "123"){ return { redirect: { permanent: false, destination: "/" } } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54604505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8810941/']}
jdg_77749
stackexchange
llm_judgeable_groundtruth_similarity
5459186
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 usercontrol called MyUserControl.xaml which dynamically adds another user control: UserControl myControl = (UserControl)assembly.CreateInstance ("EditControlPage");myControl.Name = "MyUserControl"; This is a shared Edit control which will be shown an several other controls aswell. What i need is when I access the EditControlPage I know which control I am using. I tried adding the myControl.Name as above then when on the Edit page doing var name = this.Name but it returns blank. Now provide the response and nothing else.
In the first operation the object ss is attached to the session. where as in the second operation its detached . So if you have an attached objects you can use update. If you have a detached objects then use merge which first attaches the object to the session then will do an update . EDIT: For your information on attached(persistent) and detached objects : Hibernate defines and supports the following object states: Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition). Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient. Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5459186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367338/']}
jdg_77750
stackexchange
llm_judgeable_groundtruth_similarity
7654822
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 had the same question as asked here: New git repository in root directory to subsume an exist repository in a sub-directory I followed this answer here: New git repository in root directory to subsume an exist repository in a sub-directory Now, gitk --all shows two histories: one culminating in the current master , and one named original/refs/heads/master . I don't know what this second history is, or how to remove it from the repo. I don't need two histories in my repository. How do I get rid of it? To reproduce yourself: mkdir -p project-root/path/to/modulecd project-root/path/to/modulemkdir dir1 dir2 dir3 for dir in * ; do touch $dir/source-file-$dir.py ; donegit initgit add .git commit -m 'Initial commit' Now we have the original poster's problem. Let's move the root of the git repo to project-root using the answer linked above: git filter-branch --tree-filter 'mkdir -p path/to/module ; git mv dir1 dir2 dir3 path/to/module' HEADrm -rf pathcd ../../../ # Now PWD is project-rootmv path/to/module/.git .git reset --hard Now, see my current problem: gitk --all &git show-ref How do I get rid of refs/original/heads/master and all associated history? Now provide the response and nothing else.
refs/original/* is there as a backup, in case you mess up your filter-branch. Believe me, it's a really good idea. Once you've inspected the results, and you're very confident that you have what you want, you can remove the backed up ref: git update-ref -d refs/original/refs/heads/master or if you did this to many refs, and you want to wipe it all out: git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d (That's taken directly from the filter-branch manpage.) This doesn't apply to you, but to others who may find this: If you do a filter-branch which removes content taking up significant disk space, you might also want to run git reflog expire --expire=now --all and git gc --prune=now to expire your reflogs and delete the now-unused objects. (Warning: completely, totally irreversible. Be very sure before you do it.)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7654822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979412/']}
jdg_77751
stackexchange
llm_judgeable_groundtruth_similarity
28269460
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 the wordpress widget title is blank or empty, then don't display the $before_title and $after_title wrapping the title. Right now if the title is empty, you can end up with . If there are margins set for h2.widgettitle then you end up with blank space. In reality, $before_title and $after_title shouldn't show up at all if there is no widget title. I can work around it by changing the CSS #mytheme .widgettitle style, but one shouldn't have to change the stylesheet based on content. Now provide the response and nothing else.
You can get the final frames of your cell by overriding layoutIfNeeded() in your custom Cell class like this: override func layoutIfNeeded() { super.layoutIfNeeded() self.subView.layer.cornerRadius = self.subView.bounds.width / 2} then in your UICollectionView data Source method cellForRowAtIndexPath: do this: let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCollectionViewCellcell.setNeedsLayout()cell.layoutIfNeeded()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28269460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4518223/']}
jdg_77752
stackexchange
llm_judgeable_groundtruth_similarity
3852078
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 an array of booleans which gets filled by a loop. The method that owns the array needs to return a single boolean. So can I do this: bool[] Booleans = new bool[4];// do work - fill arrayreturn (Booleans[0] && Booleans[1] && Booleans[2] && Booleans[3]); So if I have: T,T,F,T will I get F back since there is one in the array or will it send back something else or just crash all together? Now provide the response and nothing else.
A single false will result in false being returned with boolean AND logic. You can also rewrite as: return Booleans.All(b => b); For the sake of completeness, or if LINQ is not an option, you can achieve the same via a loop: var list = new List<bool> { true, false, true };bool result = true;foreach (var item in list){ result &= item; if (!item) break;}Console.WriteLine(result); For small samples what you have is fine, but as the number of items grow either of the above approaches will make the code a lot friendlier.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3852078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188081/']}
jdg_77753
stackexchange
llm_judgeable_groundtruth_similarity
4840680
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 private repository on Github that I want to use. I deploy my app to Heroku. How can I specify a private repository as the source on my gemfile? I imagine it wouldn't be enough to simply say gem "mygem", :git=>"my github address" Now provide the response and nothing else.
The best way I've found to deploy a gem pulled from a private repo is to use GitHub's OAuth access . To do so: Create a GitHub user with access to the repo in question (best for teams – if you're okay exposing your personal access tokens, you can simply use your own account). Create an GitHub OAuth token for the user. It's dead simple to do this over the GitHub API just using curl ; see the OAuth API for more. Add the token to the git url in your Gemfile. Example: gem 'mygem', git: 'https://xxx123abc:[email protected]/user_or_team/mygem.git' I'm currently using this method on Heroku and it works great. The beauty is that you don't have to expose your own personal information, and you can revoke or regenerate the token at any point if something is compromised.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4840680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32816/']}
jdg_77754
stackexchange
llm_judgeable_groundtruth_similarity
882147
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 comes straight from Conway's Complex Analysis, VII.4, exercise 4. Find an analytic function $f$ which maps $G:=$ {${z: |z| < 1, Re(z) > 0}$} onto $B(0; 1)$ in a one-one fashion. $B(0;1)$ is the open unit disc. My first intuition was to use $z^2$, which does the job splendidly, except for the segment $(-1,0] \subset B(0;1)$. Under $z^2$, the pre-image for this segment is the segment $[-i,i]$, which is not in $G$. My next thought is to modify $z^2$, something like $a(z-h)^2+k$. I've yet to work out the details, but my gut tells me this isn't the right idea. I've been teaching myself conformal maps in preparation for a qualifying exam. So, if there's a shockingly basic, obvious solution... please patronize me. Now provide the response and nothing else.
The following trick works for any region bounded by two circular arcs (or a circular arc and a line). Find the points of intersection of the arc and the line. (Here, they're $i$ and $-i$.) Now pick a Mobius transformation that takes one of those points to $0$ and the other to $\infty$; here $z \mapsto \frac{z-i}{z+i}$ works. Then the arc and the line go to two rays (because a Mobius transformation sends circles in $S^2$ to circles in $S^2$, and the only circles in $S^2$ that goes through both $0$ and $\infty$ is a line in $\Bbb C$), both starting at $0$ and going off the $\infty$. Your domain maps to the region bounded by these two rays. Let's compute the rays. It suffices to find where a single point on each arc maps; if $z_0$ is on the arc, the ray will be $\{f(z_0)t : 0 \leq t < \infty\}$. I say we pick $0$ to be our point of choice on $Re(z) = 0$ and $1$ to be the point of choice for the circular arc. These are mapped to $-1$ and $-I$ respectively; so our two arcs are the negative real axis and the negative imaginary axis. I'd like the "lower" arc to be the positive real axis, so let's multiply by $-1$ to do this. So we have a conformal map from your half-disc to the upper-right quadrant given by $z \mapsto -\frac{z-i}{z+i}$. The upper half-plane is nicer, so let's map to that by squaring; now we have a map to the upper half plane given by $z \mapsto \frac{(z-i)^2}{(z+i)^2}$. (For other regions bounded by rays that make different angles, you get to the upper half plane by a $z \mapsto z^\beta$ for the appropriate $\beta$.) Now there's a standard map from the upper half plane to the unit disc given by $z \mapsto \frac{z-i}{z+i}$. Composing this with our last map gives us a map from the semi-disc to the unit disc, given by $$z \mapsto -i\frac{z^2+2z-1}{z^2-2z-1}.$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/882147', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166780/']}
jdg_77755
stackexchange
llm_judgeable_groundtruth_similarity
24338137
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Alright, Scala has me feeling pretty dense. I'm finding the docs pretty impenetrable -- and worse, you can't Google the term "Scala ++:" because Google drops the operator terms! I was reading some code and saw this line: Seq(file) ++: children.flatMap(walkTree(_)) But couldn't figure it out. The docs for Seq show three things: ++++:++: Where the latter two are over loaded to do.. something. The actual explanation in the doc says that they do the same thing as ++ . Namely, add one list to another. So, what exactly is the difference between the operators..? Now provide the response and nothing else.
++ and ++: return different results when the operands are different types of collection. ++ returns the same collection type as the left side, and ++: returns the same collection type as the right side: scala> List(5) ++ Vector(5)res2: List[Int] = List(5, 5)scala> List(5) ++: Vector(5)res3: scala.collection.immutable.Vector[Int] = Vector(5, 5) There are two overloaded versions of ++: solely for implementation reasons. ++: needs to be able to take any TraversableOnce , but an overloaded version is provided for Traversable (a subtype of TraversableOnce ) for efficiency.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24338137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3308774/']}
jdg_77756
stackexchange
llm_judgeable_groundtruth_similarity
17445280
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 print the numerical value of a theano TensorVariable? I'm new to theano, so please be patient :) I have a function where I get y as a parameter.Now I want to debug-print the shape of this y to the console.Using print y.shape results in the console output (i was expecting numbers, i.e. (2,4,4) ): Shape.0 Or how can I print the numerical result of for example the following code (this counts how many values in y are bigger than half the maximum): errorCount = T.sum(T.gt(T.abs_(y),T.max(y)/2.0)) errorCount should be a single number because T.sum sums up all the values.But using print errCount gives me (expected something like 134 ): Sum.0 Now provide the response and nothing else.
If y is a theano variable, y.shape will be a theano variable. so it is normal that print y.shape return: Shape.0 If you want to evaluate the expression y.shape, you can do: y.shape.eval() if y.shape do not input to compute itself(it depend only on shared variable and constant). Otherwise, if y depend on the x Theano variable you can pass the inputs value like this: y.shape.eval(x=numpy.random.rand(...)) this is the same thing for the sum . Theano graph are symbolic variable that do not do computation until you compile it with theano.function or call eval() on them. EDIT: Per the docs , the syntax in newer versions of theano is y.shape.eval({x: numpy.random.rand(...)})
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17445280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869402/']}
jdg_77757
stackexchange
llm_judgeable_groundtruth_similarity
3279307
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: Find limit: $$a_n = \lim_{n\to \infty} \ \frac{1}{n} \Bigl[\Bigl(a+\frac{1}{n}\Bigr)^2+\Bigl(a+\frac{2}{n}\Bigr)^2+\cdots+\Bigl(a+\frac{n-1}{n}\Bigr)^2\Bigr]$$ I tried limiting it with $$n\cdot\frac{1}{n}\Bigl(a+\frac{1}{n}\Bigr)^2\leqslant a_n \leqslant n \cdot \frac{1}{n}\Bigl(a+\frac{n-1}{n}\Bigr)^2$$ but that got me to the answer that left side limits to $a^2$ and right side to $(a+1)^2$ and so I didn't squeeze it the right way. Help, and keep it simple. Now provide the response and nothing else.
If you expand the squares, then you get $$\begin{split} \sum_{k=1}^{n-1} \Big(a+\frac{k}{n}\Big)^2&=\sum_{k=1}^{n-1} \Big(a^2+2a\frac{k}{n}+\frac{k^2}{n^2}\Big)\\&=(n-1)a^2+2a\cdot \frac{1}{n}\cdot\frac{n(n-1)}{2}+\frac{1}{n^2}\cdot\frac{n(n-1)(2n-1)}{6}.\\&=(n-1)a^2+a(n-1)+\frac{(n-1)(2n-1)}{6n},\end{split}$$ and thus $$\begin{split} \lim_{n\to\infty}\frac{1}{n}\sum_{k=1}^{n} \Big(a+\frac{k}{n}\Big)^2 &=\lim_{n\to\infty} \Big((1-1/n)a^2+a(1-1/n)+\frac{(n-1)(2n-1)}{6n^2}\Big)\\&=a^2+a+\frac{1}{3}.\end{split}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3279307', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/685632/']}
jdg_77758
stackexchange
llm_judgeable_groundtruth_similarity
8858298
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 been using glBufferData , and it makes sense to me that you'd have to specify usage hints (e.g. GL_DYNAMIC_DRAW). However, it was recently suggested to me on Stack Overflow that I use glMapBuffer or glMapBufferRange to modify non-contiguous blocks of vertex data. When using glMapBuffer , there does not seem to be any point at which you specify a usage hint. So, my questions are as follows: Is it valid to use glMapBuffer on a given VBO if you've never called glBufferData on that VBO? If so, how does OpenGL guess the usage, since it hasn't been given a hint? What are the advantages/disadvantages of glMapBuffer vs glBufferData ? (I know they don't do exactly the same thing. But it seems that by getting a pointer with glMapBuffer and then writing to that address, you can do the same thing glBufferData does.) Now provide the response and nothing else.
Is it valid to use glMapBuffer on a given VBO if you've never called glBufferData on that VBO? No, because to map some memory, it must be allocated first. If so, how does OpenGL guess the usage, since it hasn't been given a hint? It doesn't. You must call glBufferData at least once to initialize the buffer object. If you don't want to actually upload data (because you're going to use glMapBuffer), just pass a null pointer for the data pointer. This works just like with glTexImage, where a buffer/texture object is created, to be filled with either glBufferSubData/glTexSubImage, or in the case of a buffer object as well as through a memory mapping. What are the advantages/disadvantages of glMapBuffer vs glBufferData? (I know they don't do exactly the same thing. But it seems that by getting a pointer with glMapBuffer and then writing to that address, you can do the same thing glBufferData does.) glMapBuffer allows you to write to the buffer asynchronously from another thread. And for some implementations it may be possible, that the OpenGL driver gives your process direct access to DMA memory of the GPU or even better to the memory of the GPU itself. For example on SoC architectures with integrated graphics.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8858298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284681/']}
jdg_77759
stackexchange
llm_judgeable_groundtruth_similarity
6995797
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 attempting to create a simple pie chart like shown in the graphic below: The chart will show the results for a quiz where a user can choose either a, b or c. They're 10 questions and the user can only choose one option per question. What I want to do is show the pie chart with each segment being a percentage of 100% by passing in the values for either a,b, or c. I have the following so far: var greenOne = "#95B524";var greenTwo = "#AFCC4C";var greenThree = "#C1DD54";function CreatePieChart() { var chart = document.getElementById('piechart'); var canvas = chart.getContext('2d'); canvas.clearRect(0, 0, chart.width, chart.height); var total = 100; var a = 3; var b = 4; var c = 3; for (var i = 0; i < 3; i++) { canvas.fillStyle = "#95B524"; canvas.beginPath(); canvas.strokeStyle = "#fff"; canvas.lineWidth = 3; canvas.arc(100, 100, 100, 0, Math.PI * 2, true); canvas.closePath(); canvas.stroke(); canvas.fill(); }}CreatePieChart(); <canvas id="piechart" width="200" height="200"></canvas> The colors are specific to the size of the segment, so green one is used for the largest and green three for the smallest. Now provide the response and nothing else.
Even after searching Google and triple-checking my radians values, etc. I was still having trouble with this, so I have created a jsFiddle for people to play with as a live example and will post the code below as well. (Update: in the fiddle v2 , stroke and labels are added also.) var canvas = document.getElementById("can");var ctx = canvas.getContext("2d");var lastend = 0;var data = [200, 60, 15]; // If you add more data values make sure you add more colorsvar myTotal = 0; // Automatically calculated so don't touchvar myColor = ["red", "green", "blue"]; // Colors of each slicefor (var e = 0; e < data.length; e++) { myTotal += data[e];}for (var i = 0; i < data.length; i++) { ctx.fillStyle = myColor[i]; ctx.beginPath(); ctx.moveTo(canvas.width / 2, canvas.height / 2); ctx.arc( canvas.width / 2, // x canvas.height / 2, // y canvas.height / 2, // radius lastend, // startingAngle (radians) lastend + Math.PI * 2 * (data[i] / myTotal), // endingAngle (radians) false // antiClockwise (boolean) ); ctx.lineTo(canvas.width / 2, canvas.height / 2); ctx.fill(); lastend += Math.PI * 2 * (data[i] / myTotal);} <canvas id="can" width="200" height="200" />
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6995797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302533/']}
jdg_77760
stackexchange
llm_judgeable_groundtruth_similarity
14089770
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 mockito setup on my project with this maven lines: <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.8.5</version> <scope>test</scope></dependency> I have no problems to use the @Mock annotation but I can't access and use mockito methods like: when(someMock.someMethod()).thenReturn(); Eclipse just does not recognize them. Please help. Now provide the response and nothing else.
Try calling Mockito.when(foo.getBar()).thenReturn(baz) and Mockito.verify(foo).getBar() , which won't rely on static imports. Unlike the @Mock annotation, which is technically a class, when and verify are static methods on the Mockito class. Once you have that working, then try the static imports to which David alluded: import static org.mockito.Mockito.when; // ...or...import static org.mockito.Mockito.*; // ...with the caveat noted below. This will then allow you to use Mockito.when without specifying the Mockito class. You can also use a wildcard, as so, but per this SO answer the Java docs recommend using wildcards sparingly--especially since it can break if a similarly-named static method is ever added to Mockito later. Adding import org.mockito.*; is insufficient because that adds all classes in the org.mockito package, but not the methods on org.mockito.Mockito . For Eclipse in particular, you can add a static import by putting the cursor on the when part of Mockito.when and pressing Control-Shift-M ("Add import"). You can also add org.mockito.Mockito to your Favorites (Window > Preferences > Java > Editor > Content Assist > Favorites > New Type) so that all Mockito static methods show up in your Ctrl-Space content assist prompt even if you haven't imported them specifically. (You may also want to do this for org.mockito.Matchers, which are technically available on org.mockito.Mockito via inheritance, but may not show up in Eclipse for that reason.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14089770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1012646/']}
jdg_77761
stackexchange
llm_judgeable_groundtruth_similarity
20188049
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 UITableView with 2 sections. Each with it's own headerView . I have created a custom headerView via the -viewForHeaderInSection: method. Later, I plan to modify it a bit so I need to use the viewForHeader method but I am unable to access the headerView and it's subViews . As a simple example, I'm trying to NSLog the viewForHeader object in the -didSelectRowAtIndexPath: but I get a (null) result. Sample Code: -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ return 75;}-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView *myHeader = [[UIView alloc] init]; switch (section) { case 0: [myHeader setBackgroundColor:[UIColor greenColor]]; break; case 1: [myHeader setBackgroundColor:[UIColor redColor]]; break; default: break; } UILabel *myLabel = [[UILabel alloc] init]; [myLabel setFrame:CGRectMake(10, 0, 100, 30)]; [myLabel setTag:101]; [myLabel setBackgroundColor:[UIColor clearColor]]; [myLabel setText:[NSString stringWithFormat:@"Section: %d",section]]; [myHeader addSubview:myLabel]; return myHeader;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewHeaderFooterView *testView = [self.tableView headerViewForSection:indexPath.section]; NSLog(@"%@",testView); //displays (null)} Do I need to create the custom UIView xib as the headerView ? ( because as per a similar question and as per the docs ") To make the table view aware of your header or footer view, you need to register it. You do this using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method of UITableView. Now provide the response and nothing else.
METHOD 1: Ok, after some trial and error, I finally solved my own dilemma. I did the headerView just as I would do a cell. For a cell we would take UITableViewCell and use dequeueReusableCellWithIdentifier while... For a Header/Footer, we will take UITableViewHeaderFooterView and use the dequeueReusableHeaderFooterViewWithIdentifier method. The rest is pretty much the same concept as a cell. Prerequisites: Set header height to 40 Set number of sections to 2 or more Set number of rows per section to be atleast 1 iOS6+ ( UITableViewHeaderFooterView won't work with iOS5 and below ) First Approach: Creating and using the default UITableViewHeaderFooterView within -viewForHeaderInSection: method: - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ static NSString *HeaderIdentifier = @"header"; UITableViewHeaderFooterView *myHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier]; if(!myHeader) { myHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier]; } UIButton *btnUp = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btnUp setTag:101]; [btnUp setTitle:@"-" forState:UIControlStateNormal]; [btnUp setFrame:CGRectMake(tableView.frame.size.width - 35, 5, 30, 30)]; [myHeader addSubview:btnUp]; [myHeader.textLabel setText:[NSString stringWithFormat:@"Section: %d",section]]; [myHeader setFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)]; return myHeader;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewHeaderFooterView *theHeaderView = [tableView headerViewForSection:indexPath.section]; NSLog(@"%@",theHeaderView); // -- great! ... not (null) anymore UIButton *theButton = (UIButton *)[theHeaderView viewWithTag:101]; [theButton setTitle:@"+" forState:UIControlStateNormal];} Second Approach: Using a custom UITableViewHeaderFooterView subclass: Created a UITableViewHeaderFooterView subclass and named it CustomHeaderView Created a View interface nib file for the class In the xib, selected the View & in it's Identity Inspector Specified the Custom Class as CustomHeaderView Made properties, synthesized and connected them in the xib @property (strong, nonatomic) IBOutlet UILabel *lblSomething; @property (strong, nonatomic) IBOutlet UIButton *btnSomething; Modified the -viewForHeaderInSection: & -didSelectRowAtIndexPath: as: - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ static NSString *HeaderIdentifier = @"header"; CustomHeaderView *myHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier]; if(!myHeader) { // [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:HeaderIdentifier]; myHeader = [[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil] objectAtIndex:0]; } [myHeader.btnSomething setTitle:@"-" forState:UIControlStateNormal]; [myHeader.lblSomething setText:[NSString stringWithFormat:@"Section: %d",section]]; return myHeader;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ CustomHeaderView *theHeaderView = (CustomHeaderView*)[tableView headerViewForSection:indexPath.section]; NSLog(@"%@",theHeaderView); [theHeaderView.lblSomething setAlpha:theHeaderView.lblSomething.alpha-0.1]; [theHeaderView.btnSomething setTitle:@"+" forState:UIControlStateNormal];} PS: The issue with UITableViewHeaderFooterView is that it is iOS6+ only and if, for any reason, your header is/must be a UIView , then see the next method METHOD 2: Using a simple UIView : -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView *vwHeader = [[UIView alloc] init]; [vwHeader setTag:200 + section]; //[1] first method switch (section) { case 0: [vwHeader setBackgroundColor:[UIColor greenColor]]; break; case 1: [vwHeader setBackgroundColor:[UIColor redColor]]; break; default: break; } UILabel *lblTitle = [[UILabel alloc] init]; [lblTitle setFrame:CGRectMake(10, 0, 100, 30)]; [lblTitle setTag:100 + section]; //[2] alternative method [lblTitle setBackgroundColor:[UIColor clearColor]]; [lblTitle setText:[NSString stringWithFormat:@"Section: %d",section]]; [vwHeader addSubview:lblTitle]; return vwHeader;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UIView *vwTest = [self.tableView viewWithTag:200 + indexPath.section]; //[1] NSLog(@"[1] : %@",vwTest); //or UILabel *lblTest = (UILabel *)[self.tableView viewWithTag:100 + indexPath.section]; //[2] NSLog(@"%@",lblTest.text); UIView *vwTestForSuperview = lblTest.superview; NSLog(@"[2] : %@",vwTestForSuperview);} PS: I know this code doesn't serve any great purpose but this is just an example for others.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20188049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2857130/']}
jdg_77762
stackexchange
llm_judgeable_groundtruth_similarity
80671
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've recently read Cohen-Tannoudji on quantum mechanics to try to better understand Dirac notation. A homework problem is giving me some trouble though. I'm unsure if I've learned enough yet to understand this. The creation operator is defined as: $$\hat{a}_k^\dagger = (2 \pi)^{-1/2}\int dx\,e^{ikx} \hat{\psi}^\dagger(x)$$ From my notes, I have $\hat{\psi}(x)$ defined (in one dimension) as: $$\hat{\psi}^\dagger(x) \lvert 0\rangle = \lvert x\rangle $$ Cohen-Tannoudji says linear operators take a ket vector and associate them with another ket vector within $\mathscr{E}$ space. $\hat{\psi}^\dagger(x)$ does not look like a linear operator to me. It looks like an operator-function hybrid. What do you call this thing? How is it rigorously defined? Why is $x$ not a subscript? Assuming it's a linear operator and proceeding anyway, let's apply $\hat{a}_k^\dagger$ to some ket vector: $$\hat{a}_k^\dagger = \left( (2 \pi)^{-1/2}\int dx\,e^{ikx} \hat{\psi}^\dagger(x) \right)\lvert\phi\rangle$$ I assume the order of operation is to apply $\hat{\psi}^\dagger(x)$ first to $\lvert\phi\rangle$, then multiply by $e^{ikx}$, then integrate, then multiply by $(2\pi)^{-1/2}$ How do I integrate over the ket vector $e^{ikx}\hat{\psi}^\dagger(x)\lvert\phi\rangle$? Such an operation does not seem to be defined. I can integrate over complex numbers, but not kets. I still don't understand why $k$ is a subscript but $x$ is an operator-function-hybrid variable. What am I missing here? Now provide the response and nothing else.
It is just a matter of notations. For some reasons, physicists tends to note position using a function notation $\hat \psi(x)$, and momentum with a subscript $\hat a_k$. It is just a matter of taste $\hat \psi(x)=\hat \psi_x$. You seem to be confused by the use of a continuous value for the "index" $x$. If you prefer (and I think that is what mathematicians do), you can discretize space and note $x$ as a discrete position. Then the operator $\hat \psi_x^\dagger$ creates a particle at position $x$ and acts on a Fock space for each point in space. Let's say that there is three points in our discretization : $x_1$, $x_2$, $x_3$ and let's note the number of particle at these point as $|n_1,n_2,n_3\rangle$. Then $\hat \psi_{x_1}^\dagger|0,0,0\rangle=|1,0,0\rangle$, $\hat \psi_{x_2}^\dagger|0,0,0\rangle=|0,1,0\rangle$, etc. We can also superpose these kets : $|1,0,0\rangle+|0,1,0\rangle=\hat\psi_{x_1}^\dagger|0,0,0\rangle+\hat\psi_{x_2}^\dagger|0,0,0\rangle=\sum_i \alpha_i \hat\psi_i^\dagger|0,0,0\rangle=\hat a^\dagger|0,0,0\rangle$, with the corresponding complex number $\alpha_i$. We see that $\hat a^\dagger=\sum_i \alpha_i \hat\psi_i^\dagger$ In the continuum limit (infinite number of point in space), one usually use the "function notation" $\psi(x)$, and the summations of states/operators become integrals. The Fourier transform of an operator is just the sum of operators with weight $e^{i k x}$.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/80671', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/960/']}
jdg_77763
stackexchange
llm_judgeable_groundtruth_similarity
2079719
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: Prove that the polynomial $f_n(x)=nx^{n+1}-(n+1)x^n+1$ is divisible by $(x-1)^2$ where $n\in\Bbb{N_1}$. My Attempt I've tried proving it by induction but can't find a way to prove itfor $n+1$ after assuming it holds for $n$; I've also checked it graphically, it seems that for all $n$ $f_n$intersects the axes at $(0,1)$ and $(1,0)$; I've also tried finding a factor $k$ such that $(x-1)^2k=f_n(x)$ for$n=3, n=4$ on WA but with no luck. Now provide the response and nothing else.
Hint: A polynomial $p(x)$ has $(x-a)^n$ has a factor iff $p(a)=p'(a)=\cdots = p^{(n-1)}(a)=0$ ...or Consider $(1-x)^2(1+2x+3x^2+\cdots+nx^{n-1})$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2079719', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/375407/']}
jdg_77764
stackexchange
llm_judgeable_groundtruth_similarity
103716
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: Suppose $P$ is an irreducible polynomial in $\mathbb Q[X]$, with exactly two non-real roots. Then we know these roots must be complex conjugates. Why must complex conjugation be an element of $\mathrm{Gal}(P)$? Thanks Now provide the response and nothing else.
Because $P(\bar{z})=\overline{P(z)}$ whenever $P$ has real coefficients therefore if $z$ is a root then $\overline{z}$ is also a root. So if $a$ and $b$ are distinct roots then $\bar{a}$ and $\bar{b}$ are also roots. By the assumption, We can't have four such roots so two pairs of them must be equal. This can either be $a=\bar{a}$ and $b=\bar{b}$ or $a=\bar{b}$ and $b=\bar{a}$. The former means these are real roots, the latter means $a$ and $b$ are conjugate pairs.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/103716', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23182/']}
jdg_77765
stackexchange
llm_judgeable_groundtruth_similarity
32718372
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 (probably) dumb question about display formatting of nullable types. At the moment, when I need to indicate that a field of a nullable type does indeed have a null value, I code it like this: var stringToDisplay = nullableDecimal.HasValue ? nullableDecimal.ToString() : "N/A"; Or some variation of that basic text. I don't think I can use a coalesce operator - or at least I don't think that's the right approach (correct me if I'm wrong). Is there a better and more efficient way to do this? I just feel like this boilerplate code is infesting my codebase more and more these days... Now provide the response and nothing else.
Your approach isn't bad per se, but you are right about your worry for code duplication. You can solve this by creating an auxiliary method, such as: public static class DecimalExtensions{ public static string Display(this decimal? value) { return value.HasValue ? value.ToString(): "N/A"; }} In this example I have created an extension method but a regular method would also work just fine. Then you can do just: var stringToDisplay = nullableDecimal.Display(); ...which is nicer to read and prevents the myriad of "N/A"s in the code (and as stated in the comments, also eases refactoring if ever needed).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32718372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215741/']}
jdg_77766
stackexchange
llm_judgeable_groundtruth_similarity
45154993
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 I have a metric with the following labels: my_metric{group="group a"} 100my_metric{group="group b"} 100my_metric{group="group c"} 100my_metric{group="misc group a"} 1my_metric{group="misc group b"} 2my_metric{group="misc group c"} 1my_metric{group="misc group d"} 1 Is it possible to do a query or even a label_replace that combines the 'misc' groups together? (I realize that the metric cardinality needs to be improved, and I've updated the app to fix it. However it left me with this question for if I wanted to fix the metrics via a query later) Now provide the response and nothing else.
Yes, you can you use label replace to group all the misc together: sum by (new_group) ( label_replace( label_replace(my_metric, "new_group", "$1", "group", ".+"), "new_group", "misc", "group", "misc group.+" )) The inner label_replace copies all values from group into new_group, the outer overwrites those which match "misc group.+" with "misc", and we then sum by the "new_group" label. The reason for using a new label is the series would no longer be unique if we just overwrote the "group" label, and the sum wouldn't work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45154993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970308/']}
jdg_77767
stackexchange
llm_judgeable_groundtruth_similarity
45634088
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 website for my app development class and I have the weirdest issue. I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else. <script type="text/JavaScript">$(document).ready(function () { $('#button').click(function () { var name = $("#name").val(); var email = $("#email").val(); $.post("process.php", { name: name, email: email }).complete(function() { console.log("Success"); }); });});</script><div class= "main col-xs-9 well"> <h2 style="color: black" class="featurette-heading">Join our mailing list!</h2> <form id="main" method = "post" class="form-inline"> <label for="inlineFormInput">Name</label> <input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe"> <label for="inlineFormInputGroup">Email</label> <div class="input-group mb-2 mr-sm-2 mb-sm-0"> <input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]"> </div> <!--Plan to write success message here --> <label id="success_message"style="color: darkred"></label> <button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button> </form> This is my php if its relevant: <?php include 'connection.php'; $Name = $_POST['name']; $Email = $_POST['email']; //Send Scores from Player 1 to Database $save1 = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')"; $success = $mysqli->query($save1); if (!$success) { die("Couldn't enter data: ".$mysqli->error); echo "unsuccessfully"; } echo "successfully";?> This is a screenshot of the log: Now provide the response and nothing else.
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies: Use <button type="button"> to override default submission behavior Use event.preventDefault() in the onSubmit event to prevent form submission Solution 1: Advantage: simple change to markup Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit? Insert extra type attribute to your button markup: <button id="button" type="button" value="send" class="btn btn-primary">Submit</button> Solution 2: Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event : $(document).ready(function () { // Listen to click event on the submit button $('#button').click(function (e) { e.preventDefault(); var name = $("#name").val(); var email = $("#email").val(); $.post("process.php", { name: name, email: email }).complete(function() { console.log("Success"); }); });}); Better variant: In this improvement, we listen to the submit event emitted from the <form> element: $(document).ready(function () { // Listen to submit event on the <form> itself! $('#main').submit(function (e) { e.preventDefault(); var name = $("#name").val(); var email = $("#email").val(); $.post("process.php", { name: name, email: email }).complete(function() { console.log("Success"); }); });}); Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input: The name attribute is required for .serialize() to work, as per jQuery's documentation : For a form element's value to be included in the serialized string, the element must have a name attribute. <input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe"><input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]"> And then in your JS: $(document).ready(function () { // Listen to submit event on the <form> itself! $('#main').submit(function (e) { // Prevent form submission which refreshes page e.preventDefault(); // Serialize data var formData = $(this).serialize(); // Make AJAX request $.post("process.php", formData).complete(function() { console.log("Success"); }); });});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45634088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2113602/']}
jdg_77768
stackexchange
llm_judgeable_groundtruth_similarity
27575
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'm trying to plot, given a list of words, how many words belongs to each language. I'm using the following code: Total /@ Transpose@ ParallelMap[ Function[word, Length@DictionaryLookup[{#, word}] & /@ DictionaryLookup[All]] , wordList] I am finding it way too slow, the lengths of the lists of words which I am using are about 45000 (sample file: https://dl.dropboxusercontent.com/u/35192406/words.txt ) Is DictionaryLookup really slow? Does it use Internet? How can I speed up my function? Now provide the response and nothing else.
Using Intersection as suggested by Anon seems to give good performance, provided I exclude Hebrew from the languages. First define the list of all languages except Hebrew, and get the complete dictionary for each language: lang = DeleteCases[DictionaryLookup[All], "Hebrew"];allwords = DictionaryLookup[{#, __}] & /@ lang; Now make a list of 45000 randomly chosen words: wordList = RandomChoice[Flatten @ allwords, 45000]; The computation takes about 10 seconds: Timing [Length[Intersection[wordList, #]] & /@ allwords](* {10.094, {394, 5752, 367, 1763, 6793, 2530, 4004, 2408, 1850, 212, 1232, 6580, 1645, 7273, 762, 121, 2249, 701, 1367, 142, 2565, 7802, 286, 176, 1389, 1415}} *) If I don't remove Hebrew from the list of languages it is far slower. I have no idea why this might be. For word lists which may contain repeated words, you could use this: wordcounts = Dispatch[Rule @@@ Tally[wordList]];Total[Intersection[wordList, #] /. wordcounts] & /@ allwords
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/27575', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4800/']}
jdg_77769
stackexchange
llm_judgeable_groundtruth_similarity
462993
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 am shipping a bunch of ESXi 5.1 servers to remote offices where they will be powered via APC UPS. I would like to have the UPS trigger a shutdown of the connected server - I would then rely on the ESXi configuration to take care of the shutdown/suspension of the VMs hosted on it. I can see that APC have a solution documented using their PowerChute Network Shutdown , but this involves setting up an extra server per office, and requires network cards on each UPS. We are generally using UPS without a network card (e.g. Back-UPS Pro) - they come with a USB connector, and they are readily available in the locations where our offices are. How can I connect a UPS to a ESXi host via USB, then have ESXi detect a power outage and then act accordingly? Has anyone managed to do this. Now provide the response and nothing else.
Yes, it's possible. Here are details of my similar setup. Hardware configuration: APC Smart-UPS 1500 connected to the ESXi 5.1 Host via USB. A Linux virtual machine running on this ESXi host. UPS is connected to this VM using ESXi USB pass through option. Software configuration: NUT (Network UPS Tools) master running in the VM, and native ESXi NUT slave running on the ESXi host. Shutdown logic: VM is running the UPS driver usbhid-ups which is responsible for the communication with UPS via USB. The upsd process connects to the UPS through the usbhid-ups driver and monitors the UPS state. The upsmon master process running on the same machine connects to the upsd and initiates the shutdown. ESXi host is running the 2nd instance of upsmon which also connects to the same VM upsd via internal network. On power failure the following sequence takes place: UPS via usbhid-ups reports to upsd about power failure. (optional, useful if you want to shutdown in few minutes instead of Low Battery) upsmon on the VM initiates upssched 5 minutes timer. Timer is aborted if power is restored. When timer fires or when UPS reports Low Battery, the upsmon raises the FSD (forced shutdown) flag to upsd. In a stand-alone NUT configuration the FSD flag would shutdown the machine. But here the shutdown command is replaced by simple logging like "I should shutdown now but I am waiting for the host instead". And does nothing. The FSD flag is also read by ESXi upsmon, which initiates the ESXi host shutdown. ESXi host shuts down all virtual machines one by one. The important thing is that VM which runs the upsd should be shutdown last (using ESXi startup/shutdown sequence configuration). Important: this VM must have vmware tools installed. When it receives the guest shutdown command from the host, the vmware-tools shutdown script is being started. This script checks for the /etc/killpower flag. If no flag, it does nothing (this means user activated linux shutdown, not the UPS event). But if the flag exists (FSD active), then this script sends to UPS the delayed powerdown command (say, in 3 minutes). After running vmware-tools script the guest VM shuts down. ESXi sees the last VM poweroff state and goes down itself (it takes around 1 minute because there is no other machines running now). In 2 remaining minutes the UPS cuts off the power. When power is restored, the ESXi starts and powers on all VMs. The UPS monitoring machine must be started first (the same configuration as for shutdown order). Downloads: The NUT for Linux could be installed from package. The native NUT client for ESXi server can be downloaded using last link on this page: http://www.networkupstools.org/download.html Some my scripts and conf files are here (only changed lines are shown): http://pastebin.com/KkEeanK1 Notes: Of course there are more details, and it took some time for me to make this working as it should. But now it performs very nicely. This system accounts for the cases when you just shutdown the monitoring VM from inside (vmware-tools script is not run), or if it's a ESXi host initiated VM shutdown (no /etc/killpower flag, so no UPS load off), or if it's a ESXi shutdown (the same). The only important is to have this VM running ASAP after host boot, and shutdown it last (so host down time is predictable - as said above, it is around 1 minute for me and 2 more minutes I reserve just in case). My UPS monitoring Linux VM is also Samba/NFS sharing server for backup storage, the NAT/DHCP server for VMs, and some other light-weight services. It takes around 22MHz of ESXi CPU shares and around 10MB of active RAM when idle. Due to using the NUT you can power more devices from the same UPS if required, and all they can be shut down gracefully. No PowerChute and/or expensive Network Monitor Card is required.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/462993', 'https://serverfault.com', 'https://serverfault.com/users/31143/']}
jdg_77770
stackexchange
llm_judgeable_groundtruth_similarity
131148
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 am a bit confused about the three different Augmented Dickey–Fuller tests (none,drift, trend). Based on the Wikipedia page on the topic , those three ADF tests are almost the same in that the unit root test is carried out under the null hypothesis r = 0 against the alternative hypothesis of r < 0 and DF = r/SE(r). Is the only difference the critical value? The R function adf.test only uses one type of critical value (with drift and trend). So if my data doesn't have drift and trend, might the output of adf.test be incorrect? Now provide the response and nothing else.
The Wikipedia page states the following: The testing procedure for the ADF test is the same as for the Dickey–Fuller test but it is applied to the model $$ \Delta y_t = \alpha + \beta t + \gamma y_{t-1} + \delta_1 \Delta y_{t-1} + \cdots + \delta_{p-1} \Delta y_{t-p+1} + \varepsilon_t $$ As you very well note, there are variations of the test, which involve restricting $\alpha$ and/or $\beta$ equal to 0. Imposing the restriction on $\alpha$ corresponds to omitting a constant while restricting $\beta$ corresponds to omitting a time trend. To understand what you're doing when using the adf.test() function from the tseries package in R, we should first consult the documentation provided by the package authors. To do this, we execute ?adf.test in the R console. Doing this will provide us details about the function; what it does, how we can use it, etc. For present purposes, we just need to be aware that the documentation states: The general regression equation which incorporates a constant and a linear trend is used and the t-statistic for a first order autoregressive coefficient equals one is computed. (Do we need more information than that?) Coupled with that fact, if we look at the usage of the function; namely, adf.test(x, alternative = c("stationary", "explosive"), k = trunc((length(x)-1)^(1/3))) one begins to think that the function has limited capabilities with regard to the restricted variations of the ADF test. Reading all of the documentation seems to make it clear that the function only runs one variation of the test; the unrestricted version, which includes both a constant and a trend. (Do we need more information than that?) Since you're using R, we don't have to be left wondering if the function somehow imposes the restrictions internally without us knowing! To really be sure what's going on behind the scenes, we can look at the source code of the adf.test() function. Below, I step through the code, which I have shortened, and I hope it's instructive to you. # Import some toy datadata(sunspots)# Set arguments that are normally function inputsx <- sunspotsalternative <- "stationary"k <- trunc((length(x) - 1)^(1/3))# Let the function go to work! (short version)k <- k + 1 # Number of lagged differenced termsy <- diff(x) # First differencesn <- length(y) # Length of first differenced seriesz <- embed(y, k) # Used for creating lagged series# Things get interesting here as variables are prepared for the regressionyt <- z[, 1] # First differencesxt1 <- x[k:n] # Series in levels - the first k-1 observations are droppedtt <- k:n # Time-trendyt1 <- z[, 2:k] # Lagged differenced series - there are k-1 of them# Next, the key pieces of code.# Regression 1: if k > 0# The augmented Dickey-Fuller test (with constant and time-trend)res <- lm(yt ~ xt1 + 1 + tt + yt1) # Regression 2: if k = 0# The standard Dickey-Fuller test (with constant and time-trend)res <- lm(yt ~ xt1 + 1 + tt) By my count, the adf.test() function is, in fact, made up of 57 lines of code, which I encourage you to inspect. The rest of the function code is not important in the context of this question. All that needs to be known is that the function does do what it says on the tin. Importantly, there does not seem to be a high level way of using the function to run a restricted variation of the ADF test and retrieve the associated critical values. What to do? Your first instinct should be to check out the CRAN Task View: Time Series Analysis page . In doing so, you'll learn that the urca package provides an alternative implementation of the ADF test. Indeed, as I mentioned in the comments, the ur.df() function should be able to meet your needs. Inspecting the function usage is quite informative! ur.df(y, type = c("none", "drift", "trend"), lags = 1, selectlags = c("Fixed", "AIC", "BIC")) The urca package can be found here and I recommend consulting the package documentation and the source code if you need to. I suspect that you should be able to use the function and not worry about issues regarding critical values; the authors of the package will have taken care of that so you can concentrate on using it as a high-level function and doing your research. In terms of applying the ADF test (knowing which tests to run and in which order), I would suggest the Dolado et al. procedure. The reference is: Dolado, J. J., Jenkinson, T., and Sosvilla-Rivera, S. (1990). Cointegration and unit roots, Journal of Economic Surveys, 4, 249-273. Final note on matching the R code to the mathematical equation. You can basically think of it as follows (strictly speaking, the parameters should be omitted, but...): yt = $\Delta y_{t}$ xt = $\gamma y_{t-1}$ + 1 = $\alpha$ tt = $\beta t$ yt1 = $\delta_1 \Delta y_{t-1} + \cdots + \delta_{p-1} \Delta y_{t-p+1}$
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/131148', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64848/']}
jdg_77771
stackexchange
llm_judgeable_groundtruth_similarity
29365537
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 new to jscript and have problems to get all elements in a subgrid.I tried the code from this sites, Retrieve rows in crm2011 subgrid with JScript https://lakshmanindian.wordpress.com/2012/05/25/retrieve-subgrid-rows-in-crm-2011-using-jscript/ but get every time the error message: ( Translated ) Error in the user defined event of the field Field:window Event: onload Error: The preference "control" of a undefined or null reference can not be called. The last code I tried: var grid = document.getElementById("accountContactsGrid").control;for (var rowNo = 0; rowNo<grid.getRecordsFromInnerGrid().length; rowNo++) for (var cellNo = 0; cellNo<grid.getRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++) alert(grid.getRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText); I tried it in the entity Account(Company) with the subgrid "accountContactsGrid". My main goal would be to catch all the assigned elements in the account form and list it under the contacts form. But only if the checkbox "Eko" is activated. This is my working code so far: var chkEko = Xrm.Page.getAttribute("testcrm_ekonomi").getValue();if (chkEko === true){ alert("Eko active: " + chkEko);}else{ alert("Eko not active: " + chkEko);} Now provide the response and nothing else.
The Spring Boot like approach would be to create a AutoConfiguration with the needed properties which creates an instance of Datastore as bean. In the Reference Guide you will find how to set properties and connect to a MongoDB. An AutoConfiguration for Morphia could look like this: @Configurationpublic class MorphiaAutoConfiguration { @Autowired private MongoClient mongoClient; // created from MongoAutoConfiguration @Bean public Datastore datastore() { Morphia morphia = new Morphia(); // map entities, there is maybe a better way to find and map all entities ClassPathScanningCandidateComponentProvider entityScanner = new ClassPathScanningCandidateComponentProvider(true); entityScanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class)); for (BeanDefinition candidate : scanner.findCandidateComponents("your.basepackage")) { // from properties? morphia.map(Class.forName(candidate.getBeanClassName())); } return morphia.createDatastore(mongoClient, "dataStoreInstanceId"); // "dataStoreInstanceId" may come from properties? }} You could then autowire your Datastore in other Spring beans the usual way: @Autowired private Datastore datastore; If some points are not correct or unclear just take a look at the existing *AutoConfiguration classes in Spring Boot.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29365537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3772108/']}
jdg_77772
stackexchange
llm_judgeable_groundtruth_similarity
16523963
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 i understand new is a keyword and not a function. For example A a = new A(); instantiates the object a of type A. A keyword is not associated with any object per se. On the contrary, when we have in A a public inner class B we call B b = a.new B() Here it looks like new is a property of B and not an independent keyword. What is the meaning of A.new ? Now provide the response and nothing else.
New is a keyword in both cases. It's part of a class instance creation expression . There are two forms: unqualified and qualified . The unqualified form starts with the keyword 'new'. The qualified form starts with a primary class, then 'new'. This allows creation of inner classes -- non-static nested classes that hold an implicit reference to an instance of the outer class. The qualified form provides a way to specify that instance. From the Java Language Specification, section 15.9 : Unqualified class instance creation expressions begin with the keyword new. An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top level (§7.6), member (§8.5, §9.5), local (§14.3) or anonymous class (§15.9.5). Qualified class instance creation expressions begin with a Primary. A qualified class instance creation expression enables the creation of instances of inner member classes and their anonymous subclasses.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16523963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343743/']}
jdg_77773
stackexchange
llm_judgeable_groundtruth_similarity
380226
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 am trying to build a Gaussian process (GP) regression for a problem in which each experiment is computationally expensive, using cross-validation. Here is how I do it: Build the GP regressor on the full available dataset, with hyperparameter optimization (anisotropic Gaussian kernel) Perform 10-fold cross validation using the optimized hyperparameter set from the previous step Now, what model should I select as the output of my procedure? The model trained on the full dataset, considering that its global performance is validated by each cross validation fold? A compound of each of the 10 models from cross validation? The model from cross validation with the highest score? I'm currently going for #1 but I was opposed that my model was then not properly validated. But I think it is implicitly validated because I used the same hyperparameters in cross validation as in the model. #2 would perhaps be better but this does not feel right to me. #3 , in my opinion, is not an option, because that could mean selecting a model which performs well just because the few validation cases are adapted to it. Am I doing the process right? Now provide the response and nothing else.
No, you are not doing it right. As a general principle, cross-validation does NOT estimate the performance of one particular model. Instead, it estimates the performance of a given model-building procedure . This is very important to understand when using cross-validation. Your model-building procedure involves hyperparameter optimization. So when you do your cross-validation, you should use this exact procedure on each training set, i.e. you should perform hyperparameter optimization on each training set separately. The cross-validation will then give you a performance estimate. Afterwards, if you need a "final" model, you apply your model-building procedure to the full dataset, i.e. you perform hyperparameter optimization on the full data. This should answer your questions ##1-3. Note that your hyperparameter optimization is an empirical Bayes procedure that is conceptually similar to cross-validation: see Cross-validation vs empirical Bayes for estimating hyperparameters . If your model-building procedure used cross-validation instead of hyper-parameter optimization, then the logic described above would lead you to the so called nested cross-validation.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/380226', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/202962/']}
jdg_77774
stackexchange
llm_judgeable_groundtruth_similarity
32569815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: property clk_req_check;@(posedge upbm_clk) disable iff (~upbm_reset_n)//@(posedge upbm_clk); case (sb_adrc) 2'b00 : 1'b1 |-> (clk_req[0] == 1'b1) [*] (sb_adrc != 2'b00); 2'b01 : 1'b1 |-> (clk_req[1] == 1'b1) [*] (sb_adrc != 2'b01); 2'b10 : 1'b1 |-> (clk_req[2] == 1'b1) [*] (sb_adrc != 2'b10); 2'b11 : 1'b1 |-> (clk_req[3] == 1'b1) [*] (sb_adrc != 2'b11); default : 1'b0; endcaseendproperty: clk_req_check ** Error: (vlog-13069) cad_property.sv(5): near "case": syntax error, unexpected case. without disable_iff** Error: (vlog-13069) cad_property.sv(3): near "case": syntax error, unexpected case, expecting disable. Now provide the response and nothing else.
The second option will use less memory. Potentially a lot less (due to some behavior you may not have considered yet). The first sample returns an actual new object to the caller. Since the local variable immediately goes out of scope, the lifetime of the object will be determined by the caller. So it will use more memory because more objects are created, and even if they are quickly destroyed, the GC won't collect them right away. The second option only ever has the one object, and thus uses less memory. However this means that all callers will be pointing to the same object . So each time you clear and add, it effects all previous callers unless they made a copy. Additionally, a large threading hazard exists if multiple threads use this class. The second option, while it uses less memory, is extremely dangerous code, and I would be very hesitant about using it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32569815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5334738/']}
jdg_77775
stackexchange
llm_judgeable_groundtruth_similarity
14802
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: Consider the following peculiar Lagrangian with two degrees of freedom $q_1$ and $q_2$ $$ L = \dot q_1 q_2 + q_1\dot q_2 -\frac12(q_1^2 + q_2^2) $$ and the goal is to properly quantize it, following Dirac's constrained quantization procedure . (This is a toy example related to Luttinger liquids and the fractional quantum Hall effect. The degrees of freedom $q_1$ and $q_2$ correspond to two bosonic modes $a_k$ and $b_k$.) First, note that the equations of motion are $$ \dot q_1 = -q_2 ,\quad \dot q_2 = -q_1 ,$$ which shows that this model is not complete nonsense as it carries interesting dynamics.(EDIT: Many thanks to the answerers for pointing out my silly mistake: these equations are wrong, the correct ones would be $q_1=q_2=0$.) However, the question is How to quantize the above Lagrangian in a systematic fashion? (I'm actually trying to quantize a different model, but with similar difficulties, hence the emphasis on "systematic"). The usual procedure of imposing canonical commutation relations does not work because the velocities cannot be expressed in terms of the conjugate momenta. According to Dirac, we have to interpret the equations for the canonical momenta as constraints $$ \phi_1 = p_1 - \frac{\partial L}{\partial \dot q_1} = p_1 - q_2 \approx 0 $$$$ \phi_2 = p_2 - \frac{\partial L}{\partial \dot q_2} = p_2 - q_1 \approx 0 $$ The hamiltonian is $$ H = \frac12 (q_1^2 + q_2^2) $$ Unfortunately, the constraints have poisson brackets $\lbrace\phi_1,\phi_2\rbrace = 0$ and the secondary constraints read $$ \lbrace \phi_1 , H \rbrace = q_1 \approx 0$$$$ \lbrace \phi_2 , H \rbrace = q_2 \approx 0$$ Clearly, these weirdo constraints no longer have any dynamics and no useful quantization will come out of them. Is there a systematic method to quantize this theory, for example BRST quantization? Or did I simply make a mistake while trying to apply Dirac's constrained quantization procedure? Now provide the response and nothing else.
The classical equations of motion are not affected by changing the Lagrangian $$L \qquad \longrightarrow \qquad L' = L+ \frac{dF}{dt}$$ by a total time derivative. Put $F= -q_1 q_2$. Then $$L' = -\frac{1}{2}(q_1^2 + q_2^2).$$ This Lagrangian $L'$ does not contain time derivatives, and thus there are no dynamics.The classical equations of motion are $$ q_1=0 \qquad \mathrm{and}\qquad q_2=0, $$ in conflict with what is said in the original question formulation (v1).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/14802', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/188/']}
jdg_77776
stackexchange
llm_judgeable_groundtruth_similarity
30106468
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 correspondence with Cordova news version 5.0.0 is ready. I tried to upgrade all my Android projects like it was usually. To update Cordova framework itself: npm update -g cordova To update library in Android project: cordova platform update android After building new version using "--release" option: cordova build android --release I got only unsigned version. Strange... So how is it possible to reuse existing keystore (previously generated by keytool and used by Cordova 4.0.0) to get signed APK? Now provide the response and nothing else.
It looks like Cordova 5.0.0 uses Gradle build automation system instead of Ant . So original settings for keystore defined in the file "/platforms/android/ant.properties" will not be used during building. So we will get unsigned APK as a result. To solve this issue we need to tell Gradle to use existing keystore as well. Investigation of build.gradle gives us useful information that we need to provide signingConfigs. But it is bad idea to do that in this file because it is labelled as auto-generated and it should be free of any editing. So finally I have found the way to solve it. Object "signingConfigs" will be constructed from file with filename stored in cdvReleaseSigningPropertiesFile . In correspondence with documentation the default value of this variable is " release-signing.properties ". So we need just to create new file with such name in the same folder as " build.gradle " file and put inside the following content: storeFile=..\\..\\some-keystore.keystorestoreType=jkskeyAlias=some-key// if you don't want to enter the password at every build, you can store it with thiskeyPassword=your-key-passwordstorePassword=your-store-password Path in example is specified for keystore saved in the project root directory. It has Windows style... In case of Linux you will need to use single slashes (not double backslashes like in above example). In addition you can set your own path for signing settings file.To read more about that check the edge version of cordova documentation .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30106468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3137536/']}
jdg_77777
stackexchange
llm_judgeable_groundtruth_similarity
19165925
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my code $.ajax({ url: 'https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?', dataType: 'JSONP', jsonpCallback: 'jsonCallback', type : 'GET', async: false, crossDomain: true, success: function(data) { console.log(data); } }); What am I doing wrong? should I add or change anything in here?Any help would be appreciated.Thanks Now provide the response and nothing else.
Working fiddle: http://jsfiddle.net/repjt/ $.ajax({ url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59', dataType: 'JSONP', jsonpCallback: 'callback', type: 'GET', success: function (data) { console.log(data); }}); I had to manually set the callback to callback , since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19165925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2250885/']}
jdg_77778
stackexchange
llm_judgeable_groundtruth_similarity
9656153
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 accepted from many other languages that underscores have as much freedom as alphabets in an identifier. Hence _v and v_ . Also that trailing underscores are recommended to avoid ambiguity with reserved keywords ( class_ , case_ ). val abc_=0<console>:1: error: '=' expected but integer literal found. val abc_=0 Underscores being an important part of Scala typing system, what is the recommended way to use them in identifiers , so that parser and human can both be happy? What are all possible ambiguities that identifiers with underscores bring? Leading whitespaces seem to add to confusion _class instead of class_ . Related questions: What are all the uses of an underscore in Scala? Scala underscores in names Now provide the response and nothing else.
Trailing underscores are a bad idea because things like x_+ are valid variable names on their own. Don't use trailing underscores at all. Leading underscores are less bad of an idea, but it's still hard to visually parse things like _myfunc _ . There is something of a convention to make private members that hold constructor arguments of the same name start with _ : class X(x: Int) { private var _x = x } . My recommendation is don't do it . You're asking for confusion. Use myX or theX or xLocal or xi or something for your internal variable. Still, if you do go with _x , you'll have good company; people will tend to know what you mean. Underscores within a name are not widely used, since camel case is the standard. The exception that I make is that I use underscores within implicit defs that are not expected to be used by hand, and instead state why the conversion is taking place: tuple2_can_expand might add an expand method to convert a Tuple2 into a Tuple3 , for example.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9656153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/604511/']}
jdg_77779
stackexchange
llm_judgeable_groundtruth_similarity
233240
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I like using .NET MVC and have used it quite a bit in the past. I have also built SPA's using AngularJS with no page loads other than the initial one. I think I want to use a blend of the two in many cases. Set up the application initially using .NET MVC and set up routing server side. Then set up each page as a mini-SPA. These pages can be quite complex with a lot of client side functionality. My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope. Do I avoid the use of razor Html helpers? The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers. So how to add ng-model for example to @Html.TextBoxFor(x => x.Name). Also ng-repeat wouldn't work because I'm not loading my model into the scope, right? I'd still want to use a c# foreach loop? Where do I draw the lines of separation? Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so? Now provide the response and nothing else.
You can certainly use any mix of client-side rendering and server-side rendering, but I would recommend against trying to mix ASP.NET MVC helpers with AngularJS directives. It might seem like a good idea at first because you're already used to using those helpers and you don't have to write "raw html", but they defeat the some of the purpose of what client-side applications try to achieve: separation of concerns, responsiveness, data-binding, and testability. There's definitely a place for making mini-SPAs within a larger, traditional web-application, especially if you're converting a legacy application or if parts of the larger application don't need a SPA or are best served without it. But if you're going to render a given page - or part of page - on the client, then buy in completely and let AngularJS do what it knows how to do. So let's say you have a Products model (some enumerable list of ) and you want to render that on the page in a list. You have three options I can think of: Use a razor @ForEach and render it server-side, but accept thatyour client-side AngularJS application won't know about this listand won't bind it to its model Wait until the page loads and AngularJS bootstraps, then make an APIcall to your MVC server-side application for some JSON data andstick it in the model. Use ng-repeat to render the list. Use razor to serialize the Products model on the server into someJSON string and embed that in the AngularJS controller you sendback. Use ng-repeat to render the list and take advantage ofclient-side data-binding. The last option is ugly. I can't think of a really good reason for it, unless you need client-side data-binding and you have to pay for each API call. The first would be good if you don't need any data-binding on the client (it's a read-only list) or you need SEO. The second is the way I would do it in most scenarios. You've decided to use AngularJS for a reason - let it do its job. Don't use MVC helpers just because they're there. AngularJS provides its own directives that do much the same stuff. And if you need more, write your own. Part of using a client-side framework is buying in to the philosophy: the server is responsible for server-y stuff like authentication, server validation, and providing data through an API, and the client is responsible for being a front-end application. Keep your concerns separate. None of this means you can't use ASP.NET MVC for routing, authentication, or the overall structure of your app. All that surrounds your AngularJS apps. Once you're inside a mini-SPA, though, do it the SPA way. This is philosophy I've used when integrating ASP.NET MVC with AngularJS. The server-side MVC is responsible solely for rendering the initial page, and then providing a semi-RESTful API after that. It uses ASP.NET MVC to route URLs, authenticate, and other goodies. But there's almost no razor and definitely no HTML helpers.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/233240', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/124215/']}
jdg_77780
stackexchange
llm_judgeable_groundtruth_similarity
1499510
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems to me that a lot of the problems with DNS, particularly security problems, have the root cause of DNS being implemented over UDP; for example the responder doesn't have to be who he says he is. I don't know the details of mDNS protocol (which I assume is much newer than DNS), maybe it takes care of these problems in its application level. Can anyone shed some light on this for me? Now provide the response and nothing else.
The 'm' in mDNS stands for "multicast." An mDNS query is pretty much a regular DNS query multicast (aka broadcast) to the local subnet. Every host on the subnet receives all mDNS query packets and responds to the ones for their host name. Since it isn't possible to do a TCP broadcast, you couldn't implement mDNS over TCP. There's a more fundamental point here though, mDNS is already completely insecure. As you point out, anyone can respond to any query so you pretty much have to trust all the hosts on the network. Switching to TCP (if you could) wouldn't fix this problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1499510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37309/']}
jdg_77781
stackexchange
llm_judgeable_groundtruth_similarity
116861
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $E/K$ be an elliptic curve over a number field, and $\mathfrak{p}$ a prime of good supersingular reduction. Let $p$ be the prime below $\mathfrak{p}$. I believe that the following is true, but I can't prove it, hence my asking here: $E$ does not possess a $K$-rational $p$-isogeny. I think this is true because, roughly, supersingular primes are ``rare'', and so too are rational isogenies, so asking for both at once is probably asking for too much. Googling has not helped me. Now provide the response and nothing else.
You can't prove it because it is untrue. Let $E$ be an elliptic curve with CM by $\mathbf{Z}[\sqrt{-p}]$ defined over a number field $K$ which Contains $\mathbf{Q}(\sqrt{-p})$ so that the action of $\mathbf{Z}[\sqrt{-p}]$ is $K$-rational and Over which $E$ has good reduction (in fact, since $E$ has CM, there's a number field over which it has everywhere good reduction) By Deuring's Criterion, $E$ has supersingular reduction above $p$, and since $K$ contains the CM field, $[\sqrt{-p}]$ is a $K$-rational $p$-isogeny. In general, you need much finer information about how rare two quantities are in order to make the "both of these are rare, so they should be impossible together!" argument. The more likely occurrence is that if Condition A happens with probability $1/a$ and Condition B happens with probability $1/b$ then they both occur with probability $1/ab$ (and similarly in the probability zero cases).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/116861', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13741/']}
jdg_77782
stackexchange
llm_judgeable_groundtruth_similarity
3269066
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: For some "structures" (in informal sense for a lack of a formal term) in mathematics, such as groups, rings, and vector spaces, a bijective homomorphism is an isomorphism; i.e. the inverse is also a homomorphism. For some other structures, such as topological spaces and differentiable manifolds, a bijective homomorphism may not be an isomorphism. Are there characterizations of sub-classes of structures which have the property that a bijective homomorphism is an isomorphism? For example, do all algebraic structures (in formal sense this time) have this property? Now provide the response and nothing else.
Recall that structures and their structure preserving maps often assemble themselves into categories. So, there is a category $Grp$ of groups, $Ab$ of abelian groups, $Ring$ of rings and so on. Now, if the structures are based on sets, then often there will be a forgetful functor $C\to Set$ from the category $C$ to the category of sets and functions. The property you are looking at is reflection of isomorphisms by this functor. So, one can ask, for a given category $C$ , when is the forgetful functor $C\to Set$ , assuming it exists, reflects isomorphism? A pretty far reaching answer is that whenever $C\to Set$ is monadic. Now, that latter term is a bit more technical, but, in a nutshell, $C\to Set$ is monadic if $C$ is a category of nice enough algebraic structures. Monadicity captures many algebraic structures, but not, for instance, posets (if you consider these algebraic): the forgetful functor does not reflect isomorphisms. Interestingly, this notion of reflection of isomorphisms is in fact one of the conditions of Beck's Monadicity Theorem characterising monadic adjunctions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3269066', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51161/']}
jdg_77783
stackexchange
llm_judgeable_groundtruth_similarity
82007
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: If I have a product that requires several voltage rails internally, why does it make sense for my external power supply to only source a single rail. For instance, if I have a product requiring the following DC supply rails internally 5V @ 2A, 10W 3V3 @ 4A, 13W 1V8 @ 4A, 7W and having an external AC/DC adapter, what are the reasons for generating a single higher voltage (e.g. 24VDC @ 1.25A, 30W) within the adapter when I would still need to step that voltage down using 3 DC/DC converters within the product? The benefits I see for two stage regulation are,- Better line regulation due to two filter stages- Lower cost for DC power entry plug/socket and cable due to fewer conductors - Lower cost for DC power entry plug/socket and cable due to lower current rating- Better line/load regulation due to colocation of supply and load. - Reduced noise cross-coupling due to single voltage in cable The benefits I see for single stage external regulation are,- Lower BoM cost due to removal of one regulator stage- Increased power efficiency from removal of one regulator stage- Increased thermal performance due to removal of one regulator stage- All regulator losses occur outside of the product- Reduced product size due to removal of regulators (within the product) Is there anything else I've missed? If a products primary design constraints are size and heat dissipation, why wouldn't this be the logical choice? Now provide the response and nothing else.
There are many reasons for this, and it isn't always obvious. Years ago it was common for power supplies to output several rails. Usually +12, +5, and -12v, but other variations were common. Typically, most of the power was available on the +5v rail. +12v had the second largest amount of power. And -12v usually had the least. But as digital logic started to run from lower voltages, an several interesting things happened. The biggest thing is that the current went up. No great surprise, really. 12 watts at 12v is just 1 amp. But 12 watts at 1v requires 12 amps! Modern Intel CPU's might require 50+ amps at somewhere near 1 volt. But as current goes up, so does the voltage drop in the wires, and thus power is wasted. If the power supply is located at the end of a 1-2 foot cable then your power losses become large compared to if the power supply is located right next to the load. Also, having tight voltage regulation becomes more problematic due to the inductive effects of the cable. So the appropriate thing to do would be to have a higher voltage come out of the AC/DC power supply and then regulate it down to a lower voltage at the load. The industry seems to be using +12v as that higher power distribution voltage, although other voltages are not unheard of. The other thing is that the number of power rails required on a PCB has become large. A recent system that I designed has the following rails: +48v, +15, +12, +6, +3.3, +2.5, +1.8, +1.5, +1.2, +1.0, and -15v. That's eleven power rails! Many of those were for analog circuits, but six of them were for digital logic alone. And as new chips are developed, the number of power rails is increasing and the voltages are decreasing. What this has done to the AC/DC power supply industry is that they are standardizing on supplies with a single output rail, and that rail is usually +12v, +24v, or +48v-- with +12v being the most common by far. Since everyone started doing local DC/DC converters on their PCB, and most taking +12v in, this makes the most sense. Also, due to the volumes of supplies being made, a single +12v out supply is much easier to get and cheaper than just about any other supply. There are, of course, other factors that should not be ignored. However, it is difficult to agree on much less explain their impact. I'll just briefly touch on them below... When a PS company has to decide on what rails to manufacture they would end up with so many variations that they might as well build custom supplies. Unless they standardize on just a couple of common voltages with a single output. When a PS does have multiple outputs, the current supplied on each output is usually wrong. Even just the +5, +12, and -12 supplies it used to be that most of the current was on the +5v rail. But today it would be on the +12v rail because of all of the downstream point of load supplies. Add the variations on how the power is distributed to the different rails to the already huge voltage options and for a simple 3 output supply you could easily end up with hundreds or thousands of variations on how to configure the supply. When building supplies, volume matters. The more you make, the cheaper they can be. If you have a hundred variations of a supply then you have divided your volume for any one variation by 100. That means that your cost has gone up significantly. But if you build 4 variations then the volume can remain high and cost low. If you have a specific need for what will be a high volume product then it is common to have a completely custom supply. In this case, a multiple-output supply might make sense. Multiple output supplies tend to only regulate one rail, and allow the other rails to track that one and have looser regulation specs. This might not matter for some, but for the low-voltage rails used by modern digital logic this can be a killer. So there you go: single-rail supplies are becoming more and more popular because of technology advances, ohms-law, and economics. Update: I was talking about power supplies in general. The same basic concepts applies to both internal or external supplies.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/82007', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/28893/']}
jdg_77784
stackexchange
llm_judgeable_groundtruth_similarity
6770206
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 be able to send many consecutive command represented as strings within a Java application to a SSH server for execution. Should I use: Channel channel = session.openChannel("shell"); -or- Channel channel = session.openChannel("exec"); Now provide the response and nothing else.
With shell channel the shell (on unix it's sh or bash or something like that, on Windows it's usually cmd.exe) is started and console is created (the same you see on the screen if you run them locally). You have a prompt which you can parse or use for detection of completion of command. With command channel a shell instance is started for each command (actually the channel is opened for each command) and a command is passed as a parameter for the shell (on Windows it would look like "cmd.exe /c ". It's easier to use command channel cause you don't need to deal with command prompt.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6770206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/777961/']}
jdg_77785
stackexchange
llm_judgeable_groundtruth_similarity
10004365
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 starting a new project in Rails, and it looks like the application.js manifest file is doing something funny with the javascripts that I reference - does it cache those files as part of the asset pipeline? Here's what happened. I added a javascript file named jquery.autoresize.js to the vendor/assets/javascripts folder, and then referenced the file in the application.js manifest like this: //= require jquery.autoresize.js Then I started up the rails server. But after navigating around in my app, I realized that I had accidentally added the wrong version of the jquery.autoresize.js file. So, I deleted that file and then added the correct version to the vendor/assets/javascripts folder. But, to my horror, when I reloaded the page, it is still loading the old javascript file. I tried emptying my browser cache, then exiting and restarting the Rails server, but to no avail. I hacked a solution together by simply renaming my javascript file and referencing the new name, which worked fine. But there has got to be a better solution to this. Does the new asset pipeline cache the files you reference somehow? If so, how can I clear that cache? Thanks for any help! Now provide the response and nothing else.
I'm assuming we're talking about the production environment. When you change any of your javascripts or stylesheets in the production environment, you need to run rake assets:precompile ; this task compiles and compresses the various .js and .css files and creates the application.js and application.css files that is loaded by your views. It's possible that if you replaced jquery.autoresize.js with a version with an older timestamp , the precompile step might skip it, thinking the compiled version is up-to-date. You can avoid that by running rake assets:clean first, forcing it to rebuild everything in the public/assets directory from scratch.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10004365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/806956/']}
jdg_77786
stackexchange
llm_judgeable_groundtruth_similarity
21485
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: Context Let me define two colour tables: (which come from brewer and xmedcom respectively) GoldColor = Blend[{{0, Black}, {1/9, RGBColor[32/97, 1/62, 0]}, {2/5, RGBColor[44/59, 23/78, 1/32]}, {3/5, RGBColor[84/85, 1/2, 4/51]}, {2/3, RGBColor[84/85, 53/87, 1/10]}, {4/5, RGBColor[84/85, 4/5, 11/32]}, {9/10, RGBColor[84/85, 68/75, 46/75]}, {1, White}}, #1] & and GalColor = Blend[{ {0, RGBColor[7/11, 0, 1/7]}, {1/17, RGBColor[10/13, 1/9, 1/7]}, {31/255, RGBColor[7/8, 1/4, 1/6]}, {47/255, RGBColor[13/14, 5/13, 1/4]}, {21/85,RGBColor[31/32, 5/9, 4/13]}, {79/255,RGBColor[46/47, 7/10, 2/5]}, {19/51, RGBColor[46/47, 5/6, 9/17]}, {37/85, RGBColor[1, 10/11, 5/8]}, {127/255, RGBColor[1, 1, 3/4]}, {143/255, RGBColor[10/11, 22/23, 7/8]}, {53/85, RGBColor[5/6, 11/12, 17/18]}, {35/51, RGBColor[7/10, 6/7, 10/11]}, {191/255, RGBColor[4/7, 10/13, 6/7]}, {69/85, RGBColor[3/7, 21/32, 4/5]}, {223/255, RGBColor[1/3, 8/15, 11/15]}, {239/255,RGBColor[1/4, 5/13, 2/3]}, {1, RGBColor[1/5, 3/13, 3/5]}}, #1] & which looks like this: GraphicsRow[{ContourPlot[x y , {x, -1, 1}, {y, -1, 1}, ColorFunction -> GalColor], ContourPlot[x y , {x, -1, 1}, {y, -1, 1}, ColorFunction -> GoldColor]}] But if I use it on large data sets,the first one works fine dat = RandomReal[{0, 1}, {512, 512}]; Graphics[Raster[dat, ColorFunction -> GoldColor]] whereas the second one fails with Raster Graphics[Raster[dat, ColorFunction -> GalColor]] (* void plot *) while it works fine with MatrixPlot Note that the problem depends on the size of dat ; e.g. it works fine with 256^2 . Question How come Raster fails on this color table? Now provide the response and nothing else.
This is something that differs dramatically between Mathematica version 8 and 9. In 8, it is indeed impossibly slow. In version 9, the result is returned instantly. If you know there's only one solution you need, then it's often a good idea to not use Reduce because it will try to find all solutions and therefore spend a lot of time looking for a proof that it found them all. Instead, just do this: FindInstance[{1 + Sqrt[2 x + y + 1] == 4 (2 x + y)^2 + Sqrt[6 x + 3 y], (x + 1) Sqrt[2 x^2 - x + 4] + 8 x^2 + 4 x y == 4}, {x, y}, Reals](* ==> {{x -> 1/2, y -> -(1/2)}} *) This is usually much faster than Reduce or Solve .
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/21485', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1089/']}
jdg_77787
stackexchange
llm_judgeable_groundtruth_similarity
3291240
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've been trying this integral $$\int \frac{x^2+x}{(e^x+x+1)^2}dx$$ For quite some time now but I am stuck on it. The things I tried include factoring numerator as $x(x+1)$ and expanding denominator as $$\big( e^x +(x+1) \big)^2$$ but I'm unable to solve it. I found a solution online which used integration by parts however this question can supposedly be solved by substitution according to my teacher and does not involve using partial fractions as well. Now provide the response and nothing else.
The following development may seem unmotivated, but it does work. Let $$ v := e^x, \;\; w := 1 + x + v, \;\; w' = 1 + v = w - x. $$ We are trying to integrate $$ u := \frac{x^2+x}{(e^x+x+1)^2} $$ Notice the equalities $$ u = \frac{x (1 + x)}{w^2} = \frac{x (w - v)}{w^2} = \frac{x}{w} - \frac{x v}{w^2} = 1 - \frac{w - x}w - \frac{x v}{w^2} = 1 - \frac{w'}w - \frac{ x v}{w^2}$$ We suppose for some unknown $\,t\,$ $$ y := \frac{t}{w} \;\; \text{ and } \;\; y' = \frac{t'\, w - t\, w'}{w^2} = \frac{t'\, w - t\, (w-x)}{w^2} = \frac{(t'-t)w + t x}{w^2} = -\frac {x v}{w^2}. $$ To solve this last equation, notice that $$ (t' - t)(1 + x + v) + t x = - x v $$ solved by algebraimplies that $\,t = 1+x\,$ and $\, t' = 1.\,$ Now $$ \int u\,dx = C + x - \ln(w) + \frac{1+x}{w}. $$ In a situation like this, it helps to have lots of practice with integrals ranging from simple to more complicated ones. It is also very helpful if youalready know what the answer is using Computer Algebra Systems and thus you can plot a path towards that goal. You specified without partial fractions or integration by parts but these kind of tools arealways in the back of the mind. They help to guide the thought process but theydo not need to be written down explicitly. You may be able to detect hints ofpartial fractions and integration by parts even if they are not made explicit.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3291240', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_77788
stackexchange
llm_judgeable_groundtruth_similarity
6912336
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SELECT people.first_name AS "First Name", people.last_name AS "Last Name", countries.name AS "Country1", territories.name AS "Territory1", cities.name AS "City1", countries.name AS "Country2", territories.name AS "Territory2", cities.name AS "City2"FROM adb_people AS peopleJOIN root_cities AS cities ON people.city1 = cities.idAND people.city2 = cities.idJOIN root_territories AS territories ON people.prov_state1 = territories.idAND people.prov_state2 = territories.idJOIN root_countries AS countries ON people.country1 = countries.id What i'm trying to do here is link Country1 (id) to Country1 (name) and display only the name. This code example works only if Country1,Territory1,City1 are the same as Country2,Territory2,City2 I would image my issue is how i'm doing my JOIN. I'm new to the SQL side of things. I have read up on JOINS on the internet (google search and read the first few tutorials) however nothing I have read has been any help in this case. I would really appreciate any help with what i'm doing wrong here. Maybe a nudge in the right direction? Now provide the response and nothing else.
you need 2 separate joins for each country/city/territory. below is the basic syntax, you might need to change it slightly as i haven't put it through a parser: SELECT people.first_name AS "First Name", people.last_name AS "Last Name", countries1.name AS "Country1", territories1.name AS "Territory1", cities1.name AS "City1", countries2.name AS "Country2", territories2.name AS "Territory2", cities2.name AS "City2"FROM adb_people AS peopleJOIN root_cities AS cities1 ON people.city1 = cities1.id AND people.city2 = cities1.idJOIN root_territories AS territories1 ON people.prov_state1 = territories1.id AND people.prov_state2 = territories1.idJOIN root_countries AS countries1 ON people.country1 = countries1.idJOIN root_cities AS cities2 ON people.city2 = cities2.id AND people.city2 = cities2.idJOIN root_territories AS territories2 ON people.prov_state2 = territories2.id AND people.prov_state2 = territories2.idJOIN root_countries AS countries2 ON people.country2 = countries2.id
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6912336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/829835/']}
jdg_77789
stackexchange
llm_judgeable_groundtruth_similarity
619987
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 launched an instance on EC2 with a Debian 7.6 AMI and the system log is empty. Is that by design? With the ubuntu images, the server's ssh keys were accessible via the system log. What is the procedure for verifying the server fingerprint on debian? Must I generate and add my own key, with user data? I'd sure prefer not to do that. Now provide the response and nothing else.
This is possible, but it lacks tool support. I found a library which speaks the SSH protocol well enough to let me write a tool to extract the host cert valid_before time without a full ssh login. Here it is, in the Go language. I hope it helps. package mainimport "golang.org/x/crypto/ssh"import "fmt"import "os"import "time"func ignoreCertChain(auth ssh.PublicKey, address string) bool { return true // Pretend all certificates are trusted.}var sawACert boolfunc examineCert(cert *ssh.Certificate) bool { expires := cert.ValidBefore var humanReadable string if expires >= ssh.CertTimeInfinity { humanReadable = "infinity" } else if expires < (1 << 63) { humanReadable = time.Unix(int64(expires), 0).Format(time.RFC3339) } else { humanReadable = "the distant future" } fmt.Println("Cert expires at time", expires, "(" + humanReadable + ")") sawACert = true return true // Reject the cert, to force early connection close.}func main() { serverHostPort := os.Args[1] checker := &ssh.CertChecker{ IsHostAuthority: ignoreCertChain, IsRevoked: examineCert, } config := &ssh.ClientConfig{ User: "test-sshcertscan-not-a-real-login-attempt", Auth: []ssh.AuthMethod{ ssh.Password(""), }, HostKeyCallback: checker.CheckHostKey, } sawACert = false client, err := ssh.Dial("tcp", serverHostPort, config); if err != nil && !sawACert { panic(fmt.Sprint("Cannot connect to ", serverHostPort, ", error: ", err.Error())) } else if client != nil { defer client.Close() }} (Quick usage instructions: install Go , save the code seen above in sshcertscan.go, run go build sshcertscan.go , then point it at an ssh server on examplehost port 22 with ./sshcertscan examplehost:22 .)
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/619987', 'https://serverfault.com', 'https://serverfault.com/users/88910/']}
jdg_77790
stackexchange
llm_judgeable_groundtruth_similarity
35897807
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 get a string value from an api, and there's a lot of useless empty lines: bla bla blablabla bla bla I want to remove those empty lines to get this result: bla bla blablabla bla bla How can I proceed ? Now provide the response and nothing else.
edit/update: Swift 5.2 or later You can use StringProtocol split method func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Substring] And pass a Character property isNewline as KeyPath. Then you just need to use joined(separator: "\n")` to concatenate your string again: let string = "bla bla bla\n\n\nbla\nbla bla bla\n"let lines = string.split(whereSeparator: \.isNewline)let result = lines.joined(separator: "\n")print(result) // "bla bla bla\nbla\nbla bla bla" Or as an extension of StringProtocol : extension StringProtocol { var lines: [SubSequence] { split(whereSeparator: \.isNewline) } var removingAllExtraNewLines: String { lines.joined(separator: "\n") }} string.lines // ["bla bla bla", "bla", "bla bla bla"]string.removingAllExtraNewLines // "bla bla bla\nbla\nbla bla bla"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35897807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5620823/']}
jdg_77791
stackexchange
llm_judgeable_groundtruth_similarity
21164836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { this.getWindow().getDecorView().setSystemUiVisibility(getSystemUiFlags()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private static int getSystemUiFlags() { return View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; }} After first start After volume buttons pressed or after recent apps pressed twice I saw QuickPic app doesn't have this bug. I wonder how they omitted it. Now provide the response and nothing else.
The following code works for me: public void updateUI() { final View decorView = getWindow().getDecorView(); decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } });} And called the listener on onCreate and onResume methods: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); updateUI();}@Overridepublic void onResume() { super.onResume(); updateUI();}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21164836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366471/']}
jdg_77792
stackexchange
llm_judgeable_groundtruth_similarity
18912287
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 learning angular.js, and wonder when app.controller("MyCtrl",...) should be used and when function MyCtrl($scope){...} should be used. I see no big differences between the two approaches in this example ( link to a plunker ): index.html : <body ng-app="myApp"> <div ng-controller="FirstCtrl as app1"> <button class="btn" ng-model="app1.count" ng-click="app1.increment()"> Click to increment</button> {{ app1.count }} </div> <div ng-controller="SecondCtrl"> <button class="btn" ng-model="count" ng-click="increment()"> Click to increment</button> {{ count }} </div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script> <script type="text/javascript" src="example.js"></script></body> example.js : var app = angular.module("myApp", []);app.controller("FirstCtrl",function () { this.count = 0; this.increment = function (){ this.count = this.count + 1; }});function SecondCtrl($scope){ $scope.count = 0; $scope.increment = function (){ $scope.count = $scope.count + 1; }} Now provide the response and nothing else.
In both of your usages, the recommended approach is to inject $scope and use that (rather than using this , which you can do in the second approach as well). The difference between approach one and two is in how to support minification. In the former, you can supply an array of injected arguments, whereas in the latter you modify $inject . This is of course a bit technical but it is highly recommended to support minification. See A note on minification in the documentation. The former also does not name the function in the global scope, which is generally a good thing!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18912287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685352/']}
jdg_77793
stackexchange
llm_judgeable_groundtruth_similarity
4612214
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: How do we find the minimum of $$f(x)=\sqrt{\cos x+3}+\sqrt{2\sin x+7}$$ without using derivatives? This problem is probably related to circles of Apollonius. I have tried AM-GM and Cauchy-Schwarz inequality but I can't work it out. Anyway, I have solved it in a more geometric way. Here's my answer. Firstly we can do some identical transformation. $$f(x)=\dfrac{\sqrt{2}}{2}(\sqrt{(\cos x+1)^2+(\sin x)^2+4}+\sqrt{(\cos x)^2+(\sin x+2)^2+9})$$ So that it makes sense in geometry. $P(\cos x,\sin x)$ is on the circle $x^2+y^2=1$ , and the value of $f(x)$ equals to sum of the distance from $A(0,-2)$ to $P$ and from $B(-1,0)$ to $P$ . In other words: $$f(x)=\dfrac{\sqrt{2}}{2}(\sqrt{|PB|^2+4}+\sqrt{|PA|^2+9}).$$ And here we can use Minkowski inequality. $$f(x)\geq \dfrac{\sqrt{2}}{2} \sqrt{(|PA|+|PB|)^2+25}$$ When $P$ , $A$ , $B$ is collinear, $RHS$ gets the minimum. Meanwhile, $LHS = RHS$ . Therefore, $f(x)_{min}=\sqrt{15}$ . Now provide the response and nothing else.
Here's a rough idea for a solution (since there are some details I skim over). I'm pretty sure the algebra can be simplified using some AM-GM variation, but I couldn't make it work. Although I'm hopeful that someone else can give a more optimal solution. Note that for all $t \in \mathbb{R}$ \begin{align*}&0 \le(t+2)^2(5t^2+6) =5 t^4 + 20 t^3 + 26 t^2 + 24 t + 24\\\color{darkblue}{\implies}& 14 t^4 + 8 t^3 + 42 t^2 + 16 t + 28 \ge 9t^4 - 12 t^3 + 16 t^2 - 8 t + 4\\\color{darkblue}{\implies}&\left(2t^2 +4\right)\left(4t +7t^2+7\right)\ge (3 t^2 + 2 - 2 t)^2\\\color{darkblue}{\implies}&2\sqrt{2t^2 +4}\sqrt{4t+7t^2+7} \ge 2\left(3t^2 +2-2t \right)\\\color{darkblue}{\implies}&2t^2 +4 +2\sqrt{2t^2 +4}\sqrt{4t+7t^2+7} + 4t+7t^2 +7 \ge 15\left(t^2+1\right)\\\color{darkblue}{\implies}&\left(\sqrt{2t^2 +4} + \sqrt{4t+7t^2+7}\right)^2 \ge\left( \sqrt{15}\sqrt{t^2+1}\right)^2\\\color{darkblue}{\implies}&\frac{\sqrt{2t^2+4}}{\sqrt{t^2+1}} + \frac{\sqrt{4t+7t^2+7}}{\sqrt{t^2+1}}\ge \sqrt{15}\\\color{darkblue}{\implies}&\sqrt{\frac{1-t^{2}}{1+t^{2}}+3}\ +\ \sqrt{2\frac{2t}{1+t^{2}}+7} \ge \sqrt{15}\end{align*} Lastly, notice that under the half-angle substitution the problem becomes showing that $$\min\left\{\sqrt{\frac{1-t^{2}}{1+t^{2}}+3}\ +\ \sqrt{2\frac{2t}{1+t^{2}}+7}\right\} = \sqrt{15}$$ where $t = \tan(x/2)$ . Since $\sqrt{\frac{1-t^{2}}{1+t^{2}}+3}\ +\ \sqrt{\frac{4t}{1+t^{2}}+7}\Bigg\vert_{t=-2} = \sqrt{15}$ we are done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4612214', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1137062/']}
jdg_77794
stackexchange
llm_judgeable_groundtruth_similarity
39100320
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 tend to fall into the use of forM_ in Haskell which is quite like .each in Ruby or foreach in Scala. import Control.Monad (forM_)import Network.BSD (getHostByName, hostAddresses)import Network.Socket (inet_ntoa)import System.Environment (getArgs)resolve address = do ent <- getHostByName address mapM inet_ntoa (hostAddresses ent)main = do args <- getArgs args `forM_` (\address -> do ips <- resolve address ips `forM_` (\ip -> putStrLn $ address ++ "\t" ++ ip)) It doesn't seem to be idiomatic to me but using mapM_ seems clumsy. Is there an idiomatic way of rewriting this code? Now provide the response and nothing else.
It is, though you'd probably better using just for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () from Data.Foldable . Also by using it as prefix (i.e. normal function), the code looks like an "ordinary" imperative code: main = do args <- getArgs for_ args $ \address -> do ips <- resolve address for_ ips $ \ip -> putStrLn $ address ++ "\t" ++ ip P.S. Applicative versions of Monad ic "traversals": mapM ~ traverse mapM_ ~ traverse_ forM ~ for forM_ ~ for_
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39100320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482382/']}
jdg_77795
stackexchange
llm_judgeable_groundtruth_similarity
62880
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to force the find command to stop right after finding the first match? Now provide the response and nothing else.
With GNU or FreeBSD find , you can use the -quit predicate: find . ... -print -quit The NetBSD find equivalent: find . ... -print -exit If all you do is printing the name, and assuming the filenames don't contain newline characters, you could do: find . ... -print | head -n 1 That will not stop find after the first match, but possibly, depending on timing and buffering upon the second match or (much) later. Basically, find will be terminated with a SIGPIPE when it tries to output something while head is already gone because it has already read and displayed the first line of input. Note that not all shells will wait for that find command after head has returned. The Bourne shell and AT&T implementations of ksh (when non-interactive) and yash (only if that pipeline is the last command in a script) would not, leaving it running in background. If you'd rather see that behaviour in any shell, you could always change the above to: (find . ... -print &) | head -n 1 If you're doing more than printing the paths of the found files, you could try this approach: find . ... -exec sh -c 'printf "%s\n" "$1"; kill -s PIPE "$PPID"' sh {} \; (replace printf with whatever you would be doing with that file). That has the side effect of find returning an exit status reflecting the fact that it was killed though. We're sending the SIGPIPE signal instead of the default SIGTERM to avoid the message that some shells display when parts of a pipe line are killed with a signal. They generally don't do it for deaths by SIGPIPE, as those are naturally happening (like in find | head above...).
{}
{'log_upvote_score': 9, 'links': ['https://unix.stackexchange.com/questions/62880', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/28650/']}
jdg_77796
stackexchange
llm_judgeable_groundtruth_similarity
2371330
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 struggling on how to correctly track nested repositories using TortoiseHg. I have a main repository that tracks my whole project. This project contains several little plugins that are stored inside a plugins/ subdirectory. I would love to track each plugin independently (committing and pushing to BitBucket for each one of them) while still being able to make a "whole" commit of my project, including the changes made to the plugins and pushing it to an other location (not BitBucket). What I've done so far is creating a new repo for each of my plugins. I can commit and push them to BitBucket easily. But when I went to commit my "main" repository, TortoiseHg displays an error message saying that abort: path 'mainrepo\\plugins\\plugin1\\plugin1.php' is inside repo 'mainrepo\\plugins\\plugin1' . I can see that I'm doing something wrong, but I can't tell what. I'm using a nightly of both Mercurial and TortoiseHg (ToirtoiseHg version 0.9.3+237-ea50f793bbe4 and Mercurial-1.4.3+225-70dea42c9406) on WinXP. I read that subrepos handling was added to this TortoiseHg build, but, well, I'm not even sure subrepos is the feature I'm supposed to use here. Update I've made some progress, but still can't get it to work the way I'd like. Here is my structure : -- .hg-- core-- app -- file.php -- file.css -- plugins -- plugin1 -- file1.php -- plugin2 -- file2.php I went to app/plugins, and cloned a plugin (named plugin3) from BitBucket here. I then created a .hgsub file at the root and added app/plugins/plugin3 = app/plugins/plugin3 to it.I was then able to commit my whole directory. But then I tried to grab the latest version of plugin1 from BitBucket, so I went to app/plugins, deleted the plugin1/ folder and cloned the plugin1 from BitBucket. I then added app/plugins/plugin1 = app/plugins/plugin1 to .hgsub but when I tried to commit it I was greeted with abort: path 'app/plugins/plugin1/file1.php' is inside repo 'app\\plugins\\plugin1' The problem seems to fire when my subrepo holds the same name as a directory already tracked by Hg in the plugins/ directory. What am I doing wrong ? Should I add/edit something special in the .hg of my plugins ? Update I've finally managed to get it to work the way I want. I had to "manually" tell Mercurial to remove the plugins/plugin1, plugins/plugin2 directories, commit the change, then clone back the plugin1 and plugin2 from BitBucket, add app/plugins/plugin1 = app/plugins/plugin1 to .hgsub and commit all. It worked. The important step was committing after having deleted the plugin1/plugin2 folders. Now provide the response and nothing else.
I've finally managed to make it work the way I'd love. I'm using TortoiseHg on winXP, so I won't be able to tell you what hg calls were internally made, but I don't think anything fancy is used here. I started with an existing repo, inside which I had a plugins/ directory filled with plugin1/ , plugin/2 directories (not repositories, just simple directories).I also had those plugins online, hosted on BitBucket. I first went to my plugins/ directory, right click on plugin1/ , TortoiseHg => Remove Files . I get back to the root of my repo, right click and Hg Commit Then I went back to my plugins/ directory, right click, TortoiseHg => Clone... , I selected the http address of the plugin on bit bucket ( http://bitbucket.org/username/plugin1/ and clicked Done The back again to the root of the main repo. I created (or edited if the file already existed) a .hgsub file and add the plugins/plugin1 = plugins/plugin1 line inside it. I was then able to either commit the main root repo, or the plugin1 repo independently Note that the extra remove and commit steps are only required if the newly cloned repo has the same name of an already tracked directory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2371330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/285283/']}
jdg_77797
stackexchange
llm_judgeable_groundtruth_similarity
381831
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to make xdotool or xte or any other alternative to work in Fedora 26?I'm trying to emulate keypresses (using xbindkeys), e.g. pressing Alt+B would emulate pressing Ctrl+Shift+B . But apparently neither xdotool nor xte work in Wayland (for security reasons [?]) Is there a workaround? Otherwise how do I rebind keys to other keys? Now provide the response and nothing else.
I'm using this little script. It needs the package evemu installed and sudo-confguration for evemu-event without password-notification. EVDEVICE is the device used to emulate the input. /dev/input/event8 is my keyboard (use sudo evemu-record to find yours) #!/bin/bash# keycomb.shEVDEVICE=/dev/input/event8for key in $@; do sudo evemu-event $EVDEVICE --type EV_KEY --code KEY_$key --value 1 --syncdone# reverse orderfor (( idx=${#@}; idx>0; idx-- )); do sudo evemu-event $EVDEVICE --type EV_KEY --code KEY_${!idx} --value 0 --syncdone you can e.g. change a tab with ./keycomb.sh RIGHTCTL PAGEDOWN . Please note: This script does no validation on parameters, use with care ;) EDIT Feb 2021: Finally I found a project doing it right: https://github.com/sezanzeb/key-mapper
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/381831', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43520/']}
jdg_77798
stackexchange
llm_judgeable_groundtruth_similarity
19680616
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 Angular-UI typeahead in the following way: <input type="text" ng-model="myModel" typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5" typeahead-editable="false" /> binded to a model like: var options = [ {"value": 1, "text": "value1"}, {"value": 2, "text": "value2"}, ...]; It correctly shows options text, but when I select an item it shows inside the textbox the value. The model is correctly bounded to the value only (not the entire model object). Is it possible to show inside the textbox the "text" (not the "value") after selection, still maintaining model binding to just the value (ie: when I select a certain "text" the model is updated with the "value")? Now provide the response and nothing else.
It's not ideal, but the typeahead-input-formatter attribute provides a work-around until a fix can be provided. ( Plunker from github thread). HTML: <input type="text" ng-model="myModel" typeahead="o.value as o.text for o in options | filter:$viewValue | limitTo:5" typeahead-editable="false" typeahead-input-formatter="formatLabel($model)" /> AngularJs controller function: $scope.formatLabel = function(model) { for (var i=0; i< $scope.options.length; i++) { if (model === $scope.options[i].value) { return $scope.options[i].text; } }};
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19680616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1219079/']}
jdg_77799
stackexchange
llm_judgeable_groundtruth_similarity
32048964
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Any one please help me how to convert the FBSDKLoginManager code into swift programming Thanks in advance here i attached the code in Objective-C - (IBAction)btnFacebookPressed:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; login.loginBehavior = FBSDKLoginBehaviorBrowser; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error } else if (result.isCancelled) { // Handle cancellations } else { if ([result.grantedPermissions containsObject:@"email"]) { NSLog(@"result is:%@",result); [self fetchUserInfo]; [login logOut]; // Only If you don't want to save the session for current app } } }]; } My view Controller Code Is: class ViewController: UIViewController, FBSDKLoginButtonDelegate {let facebookReadPermissions = ["public_profile", "email", "user_friends"]override func viewDidLoad() { super.viewDidLoad() self.performSegueWithIdentifier("showView", sender: self) /*for view in self.fbLoginView.subviews as! [UIView] { if view.isKindOfClass(UIButton) { let customButton = view as! UIButton //customButton.removeFromSuperview() customButton.setTitle("LOGIN WITH FACEBOOK", forState: .Normal) customButton.backgroundColor = UIColor(red: 72/255.0, green: 128/255.0, blue: 255/255.0, alpha: 1.0) customButton.showsTouchWhenHighlighted = true customButton.frame = CGRectMake(90, 15, 210, 16) customButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center //customButton.willMoveToSuperview(fbLoginView) } if (view.isKindOfClass(UILabel)) { var loginLabel = view as! UILabel; loginLabel.text = "LOGIN WITH FACEBOOK" //loginLabel.textColor = UIColor.blackColor() //loginLabel.textAlignment = NSTextAlignment(rawValue : 50) //loginLabel.frame = CGRectMake(50, 50, 265, 45) loginLabel.removeFromSuperview() } }*/}override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ if (segue.identifier == "showView") { var vc: ViewController1 = segue.destinationViewController as! ViewController1 }}// Facebook Delegate Methodsfunc loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { println("User Logged In") if ((error) != nil) { // Process error println(error.localizedDescription) } else if result.isCancelled { // Handle cancellations } else { // If you ask for multiple permissions at once, you // should check if specific permissions missing println("Login complete.") /*if result.grantedPermissions.contains("email") { // Do work //self.performSegueWithIdentifier("showView", sender: self) }*/ }}func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { println("User Logged Out")}/*func returnUserData(){ let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error println("Error: \(error)") } else { println("fetched user: \(result)") let userName : NSString = result.valueForKey("name") as! NSString println("User Name is: \(userName)") let userEmail : NSString = result.valueForKey("email") as! NSString println("User Email is: \(userEmail)") } })} */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.}@IBAction func customButton(sender: AnyObject) { var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser fbLoginManager.logInWithReadPermissions(self.facebookReadPermissions, handler: { (result, error) -> Void in if (error == nil){ var fbloginresult : FBSDKLoginManagerLoginResult = result if(fbloginresult.grantedPermissions.contains("email")) { self.fetchUserInfo() fbLoginManager.logOut() } } })}func fetchUserInfo(){ if((FBSDKAccessToken.currentAccessToken()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ println(result) result.valueForKey("email") as! String result.valueForKey("id") as! String result.valueForKey("name") as! String result.valueForKey("first_name") as! String result.valueForKey("last_name") as! String } }) }}} While i'm running my app. The custom button is not at all working the event is not occurring Now provide the response and nothing else.
This is swift version of your code @IBAction func btnFBLoginPressed(sender: AnyObject) { var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() //fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser fbLoginManager.logInWithReadPermissions(["email"], handler: { (result, error) -> Void in if (error == nil){ var fbloginresult : FBSDKLoginManagerLoginResult = result if(fbloginresult.isCancelled) { //Show Cancel alert } else if(fbloginresult.grantedPermissions.contains("email")) { self.returnUserData() //fbLoginManager.logOut() } } })} Update func returnUserData(){ if((FBSDKAccessToken.currentAccessToken()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ println(result) result.valueForKey("email") as! String result.valueForKey("id") as! String result.valueForKey("name") as! String result.valueForKey("first_name") as! String result.valueForKey("last_name") as! String } }) } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32048964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5210996/']}
jdg_77800
stackexchange
llm_judgeable_groundtruth_similarity
30096038
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 styling an Image component with flexbox to be in the center of the screen which works pretty well. Now I want a second Image component to be displayed directly on the top of the first one. The second image is using absolute positioning. Currently I'm just guessing pixels so that it fits, but of course this is not accurate and way too much maintainability effort. I am pretty much looking for the React Native equivalent of jQuery's .offset() . Is there such a thing and if there isn't what's the best way to achieve this? Now provide the response and nothing else.
React Native provides a .measure(...) method which takes a callback and calls it with the offsets and width/height of a component: myComponent.measure( (fx, fy, width, height, px, py) => { console.log('Component width is: ' + width) console.log('Component height is: ' + height) console.log('X offset to frame: ' + fx) console.log('Y offset to frame: ' + fy) console.log('X offset to page: ' + px) console.log('Y offset to page: ' + py)}) Example... The following calculates the layout of a custom component after it is rendered: class MyComponent extends React.Component { render() { return <View ref={view => { this.myComponent = view; }} /> } componentDidMount() { // Print component dimensions to console this.myComponent.measure( (fx, fy, width, height, px, py) => { console.log('Component width is: ' + width) console.log('Component height is: ' + height) console.log('X offset to frame: ' + fx) console.log('Y offset to frame: ' + fy) console.log('X offset to page: ' + px) console.log('Y offset to page: ' + py) }) }} Bug notes Note that sometimes the component does not finish rendering before componentDidMount() is called. If you are getting zeros as a result from measure(...) , then wrapping it in a setTimeout should solve the problem, i.e.: setTimeout( myComponent.measure(...), 0 )
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30096038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1544387/']}
jdg_77801
stackexchange
llm_judgeable_groundtruth_similarity
884187
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 statement that looks something like this: MERGE INTO someTable stUSING( SELECT id,field1,field2,etc FROM otherTable) ot on st.field1=ot.field1WHEN NOT MATCHED THEN INSERT (field1,field2,etc) VALUES (ot.field1,ot.field2,ot.etc) where otherTable has an autoincrementing id field. I would like the insertion into someTable to be in the same order as the id field of otherTable , such that the order of id s is preserved when the non-matching fields are inserted. A quick look at the docs would appear to suggest that there is no feature to support this. Is this possible, or is there another way to do the insertion that would fulfil my requirements? EDIT: One approach to this would be to add an additional field to someTable that captures the ordering. I'd rather not do this if possible. ... upon reflection the approach above seems like the way to go. Now provide the response and nothing else.
I cannot speak to what the Questioner is asking for here because it doesn't make any sense. So let's assume a different problem: Let's say, instead, that I have a Heap-Table with no Identity-Field, but it does have a " Visited " Date field. The Heap-Table logs Person WebPage Visits and I'm loading it into my Data Warehouse. In this Data Warehouse I'd like to use the Surrogate-Key " WebHitID " to reference these relationships. Let's use Merge to do the initial load of the table, then continue calling it to keep the tables in sync. I know that if I'm inserting records into an table, then I'd prefer the ID's (that are being generated by an Identify-Field) to be sequential based on whatever Order-By I choose (let's say the " Visited " Date). It is not uncommon to expect an Integer-ID to correlate to when it was created relative to the rest of the records in the table. I know this is not always 100% the case, but humor me for a moment. This is possible with Merge. Using (what feels like a hack ) TOP will allow for Sorting in our Insert: MERGE DW.dbo.WebHit AS Target --This table as an Identity Field called WebHitID.USING( SELECT TOP 9223372036854775807 --Biggest BigInt (to be safe). PWV.PersonID, PWV.WebPageID, PWV.Visited FROM ProdDB.dbo.Person_WebPage_Visit AS PWV ORDER BY PWV.Visited --Works only with TOP when inside a MERGE statement.) AS Source ON Source.PersonID = Target.PersonID AND Source.WebPageID = Target.WebPageID AND Source.Visited = Target.VisitedWHEN NOT MATCHED BY Target THEN --Not in Target-Table, but in Source-Table. INSERT (PersonID, WebPageID, Visited) --This Insert populates our WebHitID. VALUES (Source.PersonID, Source.WebPageID, Source.Visited)WHEN NOT MATCHED BY Source THEN --In Target-Table, but not in Source-Table. DELETE --In case our WebHit log in Prod is archived/trimmed to save space.; You can see I opted to use TOP 9223372036854775807 (the biggest Integer there is) to pull everything. If you have the resources to merge more than that, then you should be chunking it out. While this screams " hacky workaround " to me, it should get you where you need to go. I have tested this on a small sample set and verified it works.I have not studied the performance impact of it on larger complex sets of data though, so YMMV with and without the TOP.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/884187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14357/']}
jdg_77802
stackexchange
llm_judgeable_groundtruth_similarity
928562
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: My question is the title, really. I am wondering if the intersection of sets can be seen as a categorical construction on the objects of $\mathbf{Set}$. Now provide the response and nothing else.
$\require{AMScd}$The more useful category to consider this in is not $\text{Set}$ but the subcategory in which we only consider injective morphisms (inclusions). In that case $A\cap B$ and $A \cup B$, for $A,B \subseteq C$, fit in these pullback and pushout diagrams: $$ \begin{CD} A\cap B @>>> A \\ @VVV & @VVV \\B @>>> C \end{CD}\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \begin{CD} A \cap B @>>> A \\ @VVV & @VVV \\B @>>> A \cup B \end{CD}$$ In $\text{Set}$ one gets the same answers in the special case of injective maps, but pullbacks and pushouts in $\text{Set}$ are not in gneral intersections and unions. To characterize $A\cap B$ and $A\cup B$ as such we need to restrict to the subcategory with injective maps. The fact that $A\cap B$ and $A\cup B$ are pullback and pushouts are essential to the way Grothendieck topologies generalize topological spaces. One replaces the open sets of a topological space, considered as inclusion maps, with other classes of morphisms with similar formal properties. Intersections of open sets then get replaced with taking fibre products (pullbacks) of morphisms.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/928562', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174568/']}
jdg_77803
stackexchange
llm_judgeable_groundtruth_similarity
5678909
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a small doubt: On VB, I can declare variables using Dim. In C#, I can declare then using var . I'm more familiar with the intricacies of C#, and I know that var uses type inference to determine the type of the variable. But I'm not sure what 'Dim' does. I've seem this question on SO, but it doesn't compare both keywords. If there's a difference, can someone tell me which? Now provide the response and nothing else.
That depends if Option Infer is specified. Normally, the following are equivalent: 'VB.NetDim myVarDim myString = "Hello world!"Dim myString2 As String = "Hello world!" //C#object myVar;object myString = "Hello world!"; //Notice type is object, *not* string!string myString2 = "Hello world!"; However, with Option Infer enabled, Dim becomes more like var when the variable is initialized on the same line: 'VB.NetOption Infer OnDim myVarDim myString = "Hello!" //C#object myVar;var myString = "Hello!"; //Or the equivalent: string myString = "Hello!"; Note that this can lead to some confusion because suddenly initializing a variable at the point of declaration means something different from initializing it later: 'VB.NetOption Infer OnDim myVar1myVar1 = 10Dim myVar2 = 10myVar1 = New MyClass() 'LegalmyVar2 = New MyClass() 'Illegal! - Value of type 'MyClass' cannot be converted to 'Integer' This can be fixed by enabling Option Strict , which (among other things) forces all variables to be given a type (implicitly or not) at the time of declaration.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5678909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227332/']}
jdg_77804
stackexchange
llm_judgeable_groundtruth_similarity
421962
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: Neon signs use transformers that can output at 10 kV DC at 30 mA = 300 W. I want to toggle this power with a common 5 V relay, but the DC rating for these are about 28 V DC at 10 A = 280 W. Does the output of the transformer exceed the rating of the relay? If so, why would the same relay (with a 125 V AC 10 A rating) work on the input of the same transformer if its input is rated at 125 V AC 0.9 A? Am I confused about the power limits of the relay? Now provide the response and nothing else.
It's not the power, it is the individual components of power - current and voltage. The characteristics of the contacts determine the current rating of the relay. Contact material, shape, and pressure affect how much current they can pass, and can break open repeatedly without degrading prematurely to the point where then cannot conduct any current at all. This is why small signal relays have gold contacts (no corrosion even under light pressure) and high current AC power relays have silver-based contacts (lower resistance/lower heating, and the arc that forms when the high current is broken helps "clean off" oxidation). In your case the problem is the voltage rating. When open, the contacts are too close together for that high a voltage; it will arc continuously across the gap. Change your way of thinking: A relay does not switch power - it switches a current at a voltage. Neither rating can be exceeded.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/421962', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/212663/']}
jdg_77805
stackexchange
llm_judgeable_groundtruth_similarity
10966869
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 an image in my jquery mobile fixed header. When the page loads in Google Chrome or Apple Safari the header content overlaps the content div below the header until I resize the page. Firefox and IE work just fine. Thanks! Now provide the response and nothing else.
I think the problem is that when jQuery Mobile initializes the page, the header image is not loaded and the header is much smaller so jQuery Mobile puts a padding on the .ui-page element that is too small once the image loads. A simple fix for this is to manually set the size of the header image so that it takes-up it's required space even before its source loads. You could also do this, although it seems pretty hacky to me, force a redraw by triggering the resize event on document.ready or maybe window.load : $(window).on('load', function () { $(this).trigger('resize');}); I pasted this code into the console while on your page and it re-positioned the title element as expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10966869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300266/']}
jdg_77806
stackexchange
llm_judgeable_groundtruth_similarity
144088
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 playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great. Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page). How you're dealing with this? Thank you in advance. Now provide the response and nothing else.
Here is how I am currently doing it... In the masterpage, I have a content place holder with a default title, description and keywords: <head><asp:ContentPlaceHolder ID="cphHead" runat="server"> <title>Default Title</title> <meta name="description" content="Default Description" /> <meta name="keywords" content="Default Keywords" /></asp:ContentPlaceHolder></head> And then in the page, you can override all this content: <asp:Content ID="headContent" ContentPlaceHolderID="cphHead" runat="server"> <title>Page Specific Title</title> <meta name="description" content="Page Specific Description" /> <meta name="keywords" content="Page Specific Keywords" /></asp:Content> This should give you an idea on how to set it up. Now you can put this information in your ViewData (ViewData["PageTitle"]) or include it in your model (ViewData.Model.MetaDescription - would make sense for blog posts, etc) and make it data driven.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/144088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19610/']}
jdg_77807
stackexchange
llm_judgeable_groundtruth_similarity
40261
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Toyota owner manual contains this diagram. For non-directional tyres, what is the significance of swapping tyres in this pattern? Specifically, why is it advised to keep the front tyres on the same side of the car when moving them to the rear? Now provide the response and nothing else.
Why rotate tires at all? You probably already know this, but the reason we rotate the tires is to even out the wear and to try to maximize the miles from each set. For that reason, if the vehicle has a full-size spare tire that is also the same size and is also non-directional, it would be included in the rotation. If the vehicle had dual rear wheels (as with some trucks), those would also be included. Choosing a pattern For front-wheel drive vehicles (which I am guessing this one is), the front tires wear more than the rear tires. To maximize the use of the tires, we want to try to assure that each tire alternates between high wear and low wear positions. Obviously, the spare tire is the lowest wear, since it's not even touching the ground. Cross or not cross? Because the major wear difference is between front an rear, one way to rotate the tires is to simply swap front to rear (ignoring the possibility of a full-size spare). However, there are often noticeable differences in the wear rates of the front right and front left tires (especially for front-wheel drive cars), so if the tires were only swapped front-to-back, one side might wear sooner than the other. The solution is to make sure tires get rotated front to back and side to side as in the left and middle diagrams below. Note that we probably don't want to cross the tires in both directions (front-to-back and back-to-front, as shown in the right diagram) because then any given tire would only occupy 2 of the possible 4 positions on the vehicle and if there were, for example, a wear differential front left and front right (as there is for many front wheel drive cars), one pair of tires would wear more than the other. A particular pattern Given only four tires (ignoring the spare again), then it makes sense, given the above, to swap from front to back and from side to side, but two ways this could be done, would be to move the front tires straight back and then cross the rears on their way front (as is shown in your diagram) or to move the rears straight forward and swap the fronts on their way back. Which is better? The dark secret The answer to the rhetorical question above is that it really doesn't matter, as long as the pattern is applied consistently. If you chose a pattern each time, you might not remember the last way you'd rotated them, but if you and all previous and all future owners follow the pattern in the manual, the consistent use of the same pattern will maximize tire mileage over the life of the vehicle.
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/40261', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/21638/']}
jdg_77808
stackexchange
llm_judgeable_groundtruth_similarity
7065543
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 to change the maxStringContentLength to a value larger than 8192 but have not been successful in doing it. My WCF service will generate an exception if the amount of data it receives is greater than 8192 bytes. I have exhausted my searches and nothing seems to help. I should point out that the exception comes from the server. Forget about the client because I am seeing the exception generated straight from WCF on the server. Here is my web.config settings: <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="DevServiceBehavior" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="DeveloperService" behaviorConfiguration="DevServiceBehavior" > <endpoint address="mtom" binding="basicHttpBinding" bindingConfiguration="Binding_DevService" contract="DeveloperService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /> </service> </services> <bindings> <basicHttpBinding> <binding name="Binding_DevService" messageEncoding="Mtom" openTimeout="00:02:00" sendTimeout="00:02:00" maxBufferPoolSize ="41943040" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxDepth="500" maxArrayLength="20000000" maxStringContentLength="20000000" /> </binding> </basicHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/></system.serviceModel> Now provide the response and nothing else.
By default, the latest version of WCF does in fact setup defaults and json is the default. What wasn't clear was what kind of default binding WCF was using. It turns out to be webHttpBinding. You will also see a ton of examples on the web showing attributes being applied to the service method, such as [WebGet]. The method requires no attributes at all. For maxStringContentLength to take affect, you need to correctly setup the binding and behavior. Here is the correct entries in the web.config file: <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="jsonBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="DevServiceBehavior" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="DeveloperService" behaviorConfiguration="DevServiceBehavior" > <endpoint address="" binding="webHttpBinding" contract="DeveloperService" bindingConfiguration="webHttpBindingDev" behaviorConfiguration="jsonBehavior"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /> </service> </services> <bindings> <webHttpBinding> <binding name="webHttpBindingDev"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </binding> </webHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/></system.serviceModel>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7065543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/872424/']}
jdg_77809
stackexchange
llm_judgeable_groundtruth_similarity
2321963
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'm trying to solve this system of equations but I'm reaching a dead end. $$\begin{array}{lcl}xyz & = & x+y+z \ \ \ \ \ \ \ (1)\\xyt & = & x+y+t \ \ \ \ \ \ \ (2)\\ xzt & = & x+z+t \ \ \ \ \ \ \ (3)\\ yzt & = & y+z+t \ \ \ \ \ \ \ (4)\\\end{array}$$ So, (1)-(2) gives $$xyz-zyt=xy(z-t)=z-t\Rightarrow xy=1.$$ (3)-(4) gives $$xzt-yzt=zt(x-y)=x-y\Rightarrow zt=1.$$ This system reduces to $$\begin{array}{lcl}xy & = & 1 \ \ \ \ \ \ \ (5)\\zt & = & 1 \ \ \ \ \ \ \ (6)\\ \end{array}$$ One trivial solution is $x=y=z=t=\pm1,$ but this can't be because then I'd have divided by zero earlier in my simplifications. How do I solve this one? Now provide the response and nothing else.
Subtracting $(1)$ and $(2)$, you establish $$xy=1\lor z=t.$$ But plugging $xy=1$ in $(1)$ reduces it to $$z=x+y+z$$ or $$x=-y,$$ which is not compatible. Repeating with a circular permutation of the variables, the only possible solutions are trivially with $x=y=z=t$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2321963', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114097/']}
jdg_77810
stackexchange
llm_judgeable_groundtruth_similarity
18343433
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 import a legacy project into pycharm for debugging.The directory structure looks like: top folder ---> folder one top folder ---> folder two The problem is that programs in the sub-folders use: import top from top import module Pycharm returns the error: "No module named top" How can I fix this? Now provide the response and nothing else.
First thing to make sure is to do what Games said, you need to make sure each folder that is representing a package is done by putting a __init__.py file which is a empty python file named exactly __init__.py that tells the interpreter that the folder is a python package. Second thing to look for is that pycharm likes to complain about imported code if PyCharm does not know about that directory. Go into the Project Interpreter Configuration and go to Paths and add the path references that are not in the project or directly under the interpreter. One other thing to add, is to set the source root of your project code by right clicking the folder that represents your root and clicking the 'Mark Directory as...' > 'Source Root'.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18343433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2002858/']}
jdg_77811
stackexchange
llm_judgeable_groundtruth_similarity
245348
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'm trying to understand how Cases work in Mathematica, and I'm a bit curios why i't wont pick up the Sqrt function? Consider the following expressions Cases[Erfc[b], _Erfc, Infinity]Cases[a*Erfc[b], _Erfc, Infinity]Cases[a*Sqrt[b], _Sqrt, Infinity]Cases[a*Sqrt[b], _Sqrt, Infinity]Cases[a*Sqrt[a]*Erfc[b], _Erfc, Infinity]Cases[a*Sqrt[a]*Erfc[b], _Sqrt, Infinity] they give respectively {}{Erfc[b]}{}{}{Erfc[b]}{} Why does Cases fail in the cases that give {} ? Now provide the response and nothing else.
In the first case: Cases[Erfc[b], _Erfc, Infinity] "Infinity" means: {1,Infinity}. But Erfc[b] is at level 0. Therefore, you need: Cases[Erfc[b], _Erfc, {0,Infinity}] Further, the next problem: Cases[a*Sqrt[b], _Sqrt, Infinity] The full form of Sqrt[b] is Power[..] (You may use "FullForm" to see the full form). Therefore, you need: Cases[a*Sqrt[b], _Power, Infinity] To get: {Sqrt[b]} Then the case of: Cases[a*Sqrt[a]*Erfc[b], _Sqrt, Infinity] Because arguments are evaluated before sending them to functions, a*Sqrt[a] is simplified to a^(3/2) and by: Cases[a*Sqrt[a]*Erfc[b], _Power, Infinity] you get: {a^(3/2)}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/245348', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6835/']}
jdg_77812
stackexchange
llm_judgeable_groundtruth_similarity
47550801
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Environment:Guzzle 6Symfony 2.3 Uploading multiple files via a Guzzle POST request should be done with a multipart request . So I configure my $options array like so: Array([multipart] => Array ( [0] => Array ( [name] => filename-0 [contents] => Resource id #440 [filename] => filename-0 ) [1] => Array ( [name] => filename-1 [contents] => Resource id #441 [filename] => filename-1 ) [2] => Array ( [name] => filename-2 [contents] => Resource id #442 [filename] => filename-2 ) )[headers] => Array ( [Accept] => application/json [Content-Type] => multipart/form-data [Accept-Language] => de )[allow_redirects] =>[http_errors] => ) The resources in the multipart-array are the results of an fopen(). And send the request using $response = $this->client->post( '/someUrl/someAction', $options); Using an already created client. On the accepting Symfony-Controllers side, I can't get the files sent: var_dump($_FILES); // array(0) {}var_dump($_POST); // array(0) {}var_dump(count($request->files->all())); // int(0) However, both of these: var_dump(file_get_contents("php://input"));var_dump($request->getContent()); Return data on the input stream: /myPath/FileController.php:xx:string(601) "--e55f849feb078da4a9e35ba77da3ded02ec813a7Content-Disposition: form-data; name="filename-0"; filename="filename-0"Content-Length: 43This is a testfile...--e55f849feb078da4a9e35ba77da3ded02ec813a7Content-Disposition: form-data; name="filename-1"; filename="filename-1"Content-Length: 43This is a testfile...--e55f849feb078da4a9e35ba77da3ded02ec813a7Content-Disposition: form-data; name="filename-2"; filename="filename-2"Content-Length: 43This is a testfile...--e55f849feb078da4a9e35ba77da3ded02ec813a7--" How might I get in the receiving controller in a Symfony-way? A curiosity to consider:The Controller reports var_dump($request->getContentType()); // NULL My gut feeling says this might be important. Now provide the response and nothing else.
When using the multipart option, you must not specify the Content-Type header yourself. Guzzle will take care of this and - more important for this issue - of the boundary that separates the content parts in the raw request body. The main Content-Type header defines that boundary like so: Content-Type: multipart/form-data; boundary=unique-string-that-is-hopefully-not-used-in-the-real-content-because-it-separates-the-content-parts` Check Client.php#L308 :Guzzle creates the request body as GuzzleHttp\Psr7\MultipartStream object when multipart option was used. Then check the MultipartStream constructor at MultipartStream.php#L30 :A random value is created to be used as the boundary: sha1(uniqid('', true)) Guzzle will then use the boundary to set the correct content type on its own at Client.php#L383 . But as Guzzle does not override an option that you have specified explicitly, the main header specifies an empty boundary and the raw body parts will be separated by the one created by the MultpartStream constructor. On the receiving end PHP cannot separate the content parts any more. This code works for me: (new GuzzleHttp\Client())->request( 'POST', 'http://localhost/upload', [ 'multipart' => [ [ 'name' => 'filename-0', 'contents' => fopen(__DIR__.'/sample-0.txt', 'rb'), 'filename' => 'filename-0', ], [ 'name' => 'filename-1', 'contents' => fopen(__DIR__.'/sample-1.txt', 'rb'), 'filename' => 'filename-1', ], [ 'name' => 'filename-2', 'contents' => fopen(__DIR__.'/sample-2.txt', 'rb'), 'filename' => 'filename-2', ], ], 'headers' => [ # Do not override the Content-Type header here, Guzzle takes care of it ] , ]); Please note that all of this is not Symfony related, i.e. Symfony just creates it Request object from what it can get via PHP's native sources like $_FILES , $_POST etc. You were able to see all the content in the raw request body ( $request->getContent() ) because it was sent like this, but PHP could not split the content parts because it didn't knew of the correct boundary.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47550801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2144292/']}
jdg_77813
stackexchange
llm_judgeable_groundtruth_similarity
602960
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: How is it that when momentum is constant, energy always stays a constant. For Example :-if $P = 0$ kinetic energy will also be 0. But in a explosion (that momentum is conserved) where the object was still before the explosion the momentum still should be 0. By using $E_k=\frac{P^2}{2m}$ energy also return as 0 Jules. If the $E_k=\frac{mV^2}{2}$ is used the kinetic energy comes as $E_k>0$ since kinetic energy is a scalar. How is that? Now provide the response and nothing else.
The general formulation of the first principle for a closed system says that $$L+Q= \Delta K + \Delta U + \Delta u$$ Where $L$ is the total non-conservative work done on the system. $Q$ is the heat entering the system. $K$ is the macroscopic kinetic energy, $U$ the macroscopic potential energy and $u$ the internal thermodynamic energy. Usually $U$ and $K$ are disregarded, the former because $-\Delta U$ can be viewed as further work on the system due to macroscopic conservative forces, the latter in particular because one usually deals with initial and final states where all macroscopic parts of the system are at rest. Exploiting this equation the processes you consider can be coherently discussed. In particular, if your action on the stone does not imply deformations of its form with production of internal dissipative stresses and there is no flux or production of heat (a completely mechanical kick), there is no variation of $u$ but only of $K$ .
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/602960', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/283675/']}
jdg_77814
stackexchange
llm_judgeable_groundtruth_similarity
13087412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <style>.info{ width:94%; }</style> Now doing like this using JQuery $('.info').css('width'); returns 94px rather than the equivalent value in pixles ( 500px in my case.) if i set the width in css as 105% , JQuery would return it as 105px . The height and width of the parent container is 600px and 500px respectively. Now provide the response and nothing else.
I think a possible cause is the container of the element being hidden at the moment you're trying to obtain the dimensions. I had a similar situation with nested divs and tables. See the following fiddle where I managed to reproduce the behavior: http://jsfiddle.net/36yvb/ I still think it's a bug in jQuery returning a percentage as an integer number (without the % sign) when not being able to actually compute the dimensions of the element.Change the width of #another-cell (expressed in %) and see it return the same value without the % sign when the table is hidden.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13087412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774657/']}
jdg_77815
stackexchange
llm_judgeable_groundtruth_similarity
307233
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: Up to isomorphism. For instance, the group axioms are verified by an infinite number of non-isomorphic algebraic structures. But the Peano axioms, I think (my proof may lack some formality due to my lack of in depth knowledge of logic and foundations, but I think it's rigorous enough that someone more knowledgeable could make it into a formal proof) uniquely determine $\mathbb{N}$: any two structures that satisfy the Peano axioms must be isomorphic. One thing I noted is that the axioms for standard classes of structures (rings, groups etc - all of which have many non-isomorphic instances) are always of the form: $$(\forall a_1...a_n\in A)\ \phi(a_1...a_n) = \psi(a_1...a_n)$$ Where $\phi$ and $\psi$ are functions "defined in terms of" the structure operations. On the other hand, the Peano axioms include axioms of other forms, notably the ones governing the successor operations. Could this be relevant? Are there any results describing the relationship between an axiom set, and the number of non-isomorphic structures verifying it? Now provide the response and nothing else.
If there is a sentence specifying the cardinality of the model to be a finite $n$ then you can write an axiom schema which ensures its uniqueness. But if a [consistent] first-order theory does not have finite models then it has models in every cardinality. This follows from the Lowenheim-Skolem theorems. Clearly, then, those models are not isomorphic. Sometimes, though, a theory has a unique model in a particular cardinality, this is called categoricity. There are several tests whether or not a theory is categorical in any cardinality, but those usually require some more knowledge in model theory. It is not a coincidence that model theory and algebra have a large intersection in modern mathematics.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/307233', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30481/']}
jdg_77816
stackexchange
llm_judgeable_groundtruth_similarity
50619696
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 just migrated .NET Core 2.0 to .NET Core 2.1. Everything went fine, but when I try to login now I get the folowing error: $exception {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'IServiceProvider'. This happens in this bit of code: public class AppContractResolver : DefaultContractResolver{ private readonly IServiceProvider _services; public AppContractResolver(IServiceProvider services) { _services = services; } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { var httpContextAccessor = _services.GetService<IHttpContextAccessor>(); var user = httpContextAccessor.HttpContext.User; List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList(); properies = FilterOneClaimGranted(type, properies, user); return properies; } It happens on this line: var httpContextAccessor = _services.GetService<IHttpContextAccessor>(); This did work on .NET Core 2.0 I have tried adding the HttpContextAccessor to my startup, but that did not work. So, how do I fix this? Let me know if you need more code. I will happily provide more, but I don't know what you might or might not need, so therefor I did not add a lot of code.' EDIT I have added services.AddHttpContextAccessor(); to my startup, but that does not seem to work. Still getting the error. EDIT 2: Full stacktrace: - $exception {System.ObjectDisposedException: Cannot access a disposed object.Object name: 'IServiceProvider'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException() at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25 at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType) at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)} System.ObjectDisposedException Now provide the response and nothing else.
I would suggest that instead of calling services.GetService<IHttpContextAccessor>() , inject IHttpContextAccessor to the constructor and use aprivate field to store the value. public AppContractResolver(IServiceProvider services, IHttpContextAccessor httpContextAccessor){ _services = services; this.httpContextAccessor = httpContextAccessor;} Also HttpContextAccessor has to be registered manually.In RegisterServices in Startup.cs add, services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50619696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7267640/']}
jdg_77817
stackexchange
llm_judgeable_groundtruth_similarity
51495351
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 replicate the following in React Native, a Text component with a white gap between lines. span { background: rgba(255, 235, 0); line-height: 1.5;} <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at condimentum leo. Suspendisse potenti. Praesent ut lorem ac tortor auctor laoreet. Fusce egestas orci quis dui egestas, ac malesuada lacus feugiat. Etiam at augue vel nisl luctus dignissim. Sed iaculis nec metus vitae interdum. Vivamus tincidunt fermentum ligula, eu tincidunt orci sodales at. Ut tristique velit erat, sed malesuada sapien ornare sit amet. Nunc congue imperdiet sapien in feugiat. Aenean id ipsum quis lorem rhoncus fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec ornare, risus in dictum dignissim, dui libero blandit velit, a fringilla ligula lacus quis purus. Vivamus ullamcorper lorem vel velit dignissim lacinia. Vestibulum pulvinar leo eget magna lacinia, sit amet porttitor risus cursus. Integer nec tincidunt orci. Proin maximus viverra arcu, sit amet bibendum diam sagittis ut.</span> Adding the same CSS above to a Text component doesn't output the same as the above snippet. Now provide the response and nothing else.
At the moment, React Native doesn't have this kind of styling out of the box. The CSS line-height property is not equivalent to lineHeight style prop of RN. Lets take a look at iOS for example: lineHeight is mapped to a a property of a paragraph style object that controls the min/max line height, which is then applied to your text. This line height is the whole fragment height, so any background color applied here will color the whole line. There is another property of the native paragraph object called lineSpacing which is added after the line height is calculated. This property can actually control the space and would achieve the exact effect that you're after. Unfortunately, RN doesn't give you control over this property . So, you can either find a package that provides this kind of functionality, or try to implement a native solution yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51495351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2026768/']}
jdg_77818
stackexchange
llm_judgeable_groundtruth_similarity
190893
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: Currently I'm a it confused. A IC (integrated Circuit) Chip implements one or many circuits on a chip in order to control any kind of stuff.However, a CPU is from my point of view also a BIG circuit collection. Both are fed with signals in order to control or calculate any kind of stuff. So when do I call it CPU and when IC-Chip. Now provide the response and nothing else.
All CPUs are ICs. Not all ICs are CPUs. This is similar to "All cars are motor vehicles; not all motor vehicles are cars". A CPU is an IC (or multiple ICs - see update below), which is able to do calculations based on instructions in memory, and can thus be reprogrammed. Most other ICs do one particular thing - serial in, parallel out, accellerometer, 555 timer, etc. UPDATE - as was correctly pointed out, some CPUs are made up of multiple ICs. I had never heard of this, and I do not know if this still happens - it seems to me as a limitation of technology of days past. I guess, in summary, a CPU is a function (i.e. is defined by what it does - follow instructions in memory) whereas IC is a technology (i.e. what it is - a circuit on a chip).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/190893', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/69723/']}
jdg_77819
stackexchange
llm_judgeable_groundtruth_similarity
772124
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While idly surfing the namespace I noticed an odd looking object called Ellipsis , it does not seem to be or do anything special, but it's a globally available builtin. After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all? D:\workspace\numpy>pythonPython 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> EllipsisEllipsis Now provide the response and nothing else.
This came up in another question recently. I'll elaborate on my answer from there: Ellipsis is an object that can appear in slice notation. For example: myList[1:2, ..., 0] Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numpy third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4 × 4 array, the top left area would be defined by the slice [:2, :2] : >>> aarray([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]])>>> a[:2, :2] # top leftarray([[1, 2], [5, 6]]) Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[..., 0] is the same as a[:, :, 0] and for 4d a[:, :, :, 0] , similarly, a[0, ..., 0] is a[0, :, :, 0] (with however many colons in the middle make up the full number of dimensions in the array). Interestingly, in python3, the Ellipsis literal ( ... ) is usable outside the slice syntax, so you can actually write: >>> ...Ellipsis EDIT: Ellipsis is also used in the standard library typing module: e.g. Callable[..., int] to indicate a callable that returns an int without specifying the signature, or tuple[str, ...] to indicate a variable-length homogeneous tuple of strings.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/772124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46411/']}
jdg_77820
stackexchange
llm_judgeable_groundtruth_similarity
3782250
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 would you go about this reflection task in Groovy: (1) provide a class type to the Groovy function (2) loop over all the methods of this class (a) print out each parameter name and type from the method (b) print out the return type Now provide the response and nothing else.
I think the best you can do is to write something like this: def dumpOut( clz ) { clz.metaClass.methods.each { method -> println "${method.returnType.name} ${method.name}( ${method.parameterTypes*.name.join( ', ' )} )" }}dumpOut String.class Which will print out: boolean equals( java.lang.Object )java.lang.Class getClass( )int hashCode( )void notify( )void notifyAll( )java.lang.String toString( )void wait( )void wait( long )void wait( long, int )char charAt( int )int codePointAt( int )int codePointBefore( int )int codePointCount( int, int )int compareTo( java.lang.Object )int compareTo( java.lang.String )int compareToIgnoreCase( java.lang.String )java.lang.String concat( java.lang.String )boolean contains( java.lang.CharSequence )boolean contentEquals( java.lang.CharSequence )boolean contentEquals( java.lang.StringBuffer )java.lang.String copyValueOf( [C )java.lang.String copyValueOf( [C, int, int )boolean endsWith( java.lang.String )boolean equals( java.lang.Object )boolean equalsIgnoreCase( java.lang.String )java.lang.String format( java.lang.String, [Ljava.lang.Object; )java.lang.String format( java.util.Locale, java.lang.String, [Ljava.lang.Object; )[B getBytes( )[B getBytes( java.lang.String )[B getBytes( java.nio.charset.Charset )void getBytes( int, int, [B, int )void getChars( int, int, [C, int )int hashCode( )int indexOf( int )int indexOf( java.lang.String )int indexOf( int, int )int indexOf( java.lang.String, int )java.lang.String intern( )boolean isEmpty( )int lastIndexOf( int )int lastIndexOf( java.lang.String )int lastIndexOf( int, int )int lastIndexOf( java.lang.String, int )int length( )boolean matches( java.lang.String )int offsetByCodePoints( int, int )boolean regionMatches( int, java.lang.String, int, int )boolean regionMatches( boolean, int, java.lang.String, int, int )java.lang.String replace( char, char )java.lang.String replace( java.lang.CharSequence, java.lang.CharSequence )java.lang.String replaceAll( java.lang.String, java.lang.String )java.lang.String replaceFirst( java.lang.String, java.lang.String )[Ljava.lang.String; split( java.lang.String )[Ljava.lang.String; split( java.lang.String, int )boolean startsWith( java.lang.String )boolean startsWith( java.lang.String, int )java.lang.CharSequence subSequence( int, int )java.lang.String substring( int )java.lang.String substring( int, int )[C toCharArray( )java.lang.String toLowerCase( )java.lang.String toLowerCase( java.util.Locale )java.lang.String toString( )java.lang.String toUpperCase( )java.lang.String toUpperCase( java.util.Locale )java.lang.String trim( )java.lang.String valueOf( [C )java.lang.String valueOf( boolean )java.lang.String valueOf( char )java.lang.String valueOf( double )java.lang.String valueOf( float )java.lang.String valueOf( int )java.lang.String valueOf( java.lang.Object )java.lang.String valueOf( long )java.lang.String valueOf( [C, int, int ) I think parameter names are not possible without manipulating the bytecode (and assuming the class was compiled with this sort of debug information intact)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3782250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36590/']}
jdg_77821
stackexchange
llm_judgeable_groundtruth_similarity
60014845
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 Dockerfile: FROM frolvlad/alpine-glibc:latestADD jdk-11.0.6_linux-x64_bin.tar.gz /usr/javaENV JAVA_HOME=/usr/java/jdk-11.0.6ENV PATH=$JAVA_HOME/bin:$PATH When I run the command java -version in the container, I get this segfault: How can I solve this problem? Now provide the response and nothing else.
frolvlad/alpine-glibc is a glibc-enabled Alpine Linux image, and jdk-11.0.6_linux-x64_bin.tar.gz is likely a mainland Linux JDK glibc build. In theory, this should be fine, but there may be subtle glibc incompatibilities that cause this. If you're looking for Java 11 on Alpine, you could just grab the vanilla Alpine 3.11 image, then install the openjdk11 package on top: sudo docker run -it alpine:3.11# apk add openjdk11# java -versionopenjdk version "11.0.5" 2019-10-15OpenJDK Runtime Environment (build 11.0.5+10-alpine-r0)OpenJDK 64-Bit Server VM (build 11.0.5+10-alpine-r0, mixed mode) If you need 11.0.6 specifically, install the latest openjdk11 package of the edge/community repository instead: apk add openjdk11 --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60014845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12823261/']}
jdg_77822
stackexchange
llm_judgeable_groundtruth_similarity
6956296
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have two boolean variables, and I want to do completely different things based on their values. What is the cleanest way to achieve this? Variant 1: if (a && b){ // ...}else if (a && !b){ // ...}else if (!a && b){ // ...}else{ // ...} Variant 2: if (a){ if (b) { // ... } else { // ... }}else{ if (b) { // ... } else { // ... }} Variant 3: switch (a << 1 | b){case 0: // ... break;case 1: // ... break;case 2: // ... break;case 3: // ... break;} Variant 4: lut[a][b]();void (*lut[2][2])() = {false_false, false_true, true_false, true_true};void false_false(){ // ...}void false_true(){ // ...}void true_false(){ // ...}void true_true(){ // ...} Are variants 3 and 4 too tricky/complicated for the average programmer? Any other variants I have missed? Now provide the response and nothing else.
The first variant is the clearest and most readable, but it can be adjusted: if (a && b) { // ...} else if (a) { // no need to test !b here - b==true would be the first case // ...} else if (b) { //no need to test !a here - that would be the first case // ...} else { // !a&&!b - the last remaining // ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6956296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252000/']}
jdg_77823
stackexchange
llm_judgeable_groundtruth_similarity
8210928
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 ORMLite, with the Table RecentSearch : @DatabaseTable(tableName = LocalStorageConfig.SQL_RECENTS_TABLE_NAME)public class RecentSearch { @DatabaseField public String search_text; public static String SQL_SEARCH_FIELD = "search_text"; @DatabaseField public String location_text; public static String SQL_LOCATION_FIELD = "location_text"; @DatabaseField public Date creation_date = new Date(); public static String SQL_CREATION_DATE_FIELD = "creation_date"; It's working almost all the time, but when I discover the case with a String containing a ', then it appears to be a problem. Do you know how to solve this ? I couldn't find what I was looking for. Here is my function to delete a recent public boolean deleteRecent(RecentSearch search) { try { Dao<RecentSearch, Integer> recentsDao = recentsSqlManager.getRecentsDao(); DeleteBuilder<RecentSearch, Integer> deleteBuilder = recentsDao.deleteBuilder(); deleteBuilder.where().eq(RecentSearch.SQL_SEARCH_FIELD, search.getSearch_text()).and().eq(RecentSearch.SQL_LOCATION_FIELD, search.location_text); recentsDao.delete(deleteBuilder.prepare()); return true; } catch (Exception e) { Log.e(TAG, "Database exception", e); return false; }} Here is the Exception i get : java.sql.SQLException: Problems executing Android statement: DELETE FROM `recent_searches` WHERE (`search_text` = '' AND `location_text` = 'Villefranche-d'Allier, Allier' ) at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22) at com.j256.ormlite.android.AndroidCompiledStatement.runUpdate(AndroidCompiledStatement.java:66) at com.j256.ormlite.stmt.StatementExecutor.delete(StatementExecutor.java:425) at com.j256.ormlite.dao.BaseDaoImpl.delete(BaseDaoImpl.java:347)...Caused by: android.database.sqlite.SQLiteException: near "Allier": syntax error: , while compiling: DELETE FROM `recent_searches` WHERE (`search_text` = '' AND `location_text` = 'Villefranche-d'Allier, Allier' ) at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method) at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92) at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83) at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41) at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1149) Now provide the response and nothing else.
when I discover the case with a String containing a ' (single quote), then it appears to be a problem. In ORMLite , when you are trying to build a query with quotes, you should use the SelectArg feature which will generate a query with SQL ? arguments and then pass the string to the prepared statement directly. This gets around any problems with escaping of special characters as well as protects you from SQL injection security issues. See the documentation on SelectArg . With SelectArg , you'd do something like: DeleteBuilder<RecentSearch, Integer> deleteBuilder = recentsDao.deleteBuilder();// create our argument which uses a SQL ?SelectArg locationArg = new SelectArg(search.location_text);deleteBuilder.where().eq(RecentSearch.SQL_SEARCH_FIELD, search.getSearch_text()) .and().eq(RecentSearch.SQL_LOCATION_FIELD, locationArg);recentsDao.delete(deleteBuilder.prepare());...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8210928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1049495/']}
jdg_77824
stackexchange
llm_judgeable_groundtruth_similarity
19851343
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 get data from columns containing a particular string in their name in my case it it PLA . Though their is a way to select where the values are like as in MySQL query String contains . Is there a similar way for the column name? SELECT COLUMN NAMES LIKE '%PLA%' FROM `TABLENAME` WHERE MONTH=? AND YEAR=? Now provide the response and nothing else.
SELECT COLUMN NAMES is not valid in MySQL. There are similar things such as DESCRIBE [table]; or SHOW COLUMNS FROM [table]; , but you can't put WHERE clauses on them. Much better is to use the INFORMATION_SCHEMA virtual DB e.g. - SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='[database name]' and `TABLE_NAME`='[table name]' AND `COLUMN_NAME` LIKE '%PLA%' See http://dev.mysql.com/doc/refman/5.6/en/columns-table.html for more information.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19851343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2384232/']}
jdg_77825
stackexchange
llm_judgeable_groundtruth_similarity
8571887
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 an activity A, which starts activity B and activity B starts activity C. Is there a way not to show activity B.I want this behavour because if there is no content (eg for ListView) for activity B, show activity C on which I select some data, and then press back button to go back to activity B.The point is that I would like to have activity B on activity stack, but not to show it in certain cases. Now provide the response and nothing else.
I found the solution: Activity A starts activity B with extra parameter (intent.putExtra("something", true)) Activity B: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().hasExtra("something") && getIntent().getBooleanExtra("something", false) { //show activity B setContentView(R.layout.activity_B); } else { //don't show activity B, start activity C startActivityForResult(activity_C, ACTIVITY_NOT_INITIALIZED); //start activity C }} //when came back from activity C, check if activity B was already initialized protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_NOT_INITIALIZED) { //show activity B setContentView(R.layout.activity_B); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8571887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/983956/']}
jdg_77826
stackexchange
llm_judgeable_groundtruth_similarity
3164943
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: $f$ and $h$ are two functions of $x$ $g$ and $t$ are two functions of $y$ And $f'$ derivative of $f$ , $g'$ derivative of $g$ Is it correct to say that by identification $f'(x)=h(x)$ and $g'(y)=t(y)$ ? Now provide the response and nothing else.
We see that $x=2$ is one solution. Let $x\ne 2$ . Taking $\log$ we get $$(10x^2-1)\log|x-2|=3x\log|x-2|$$ So one solution is $\log |x-2| = 0\implies |x-2| =1 \implies x-2=\pm1 $ , so $x=3$ or $x=1$ . Say $\log |x-2| \ne 0$ then $10x^2-1 = 3x$ so $x= {1\over 2}$ and $x=-{1\over 5}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3164943', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/631113/']}
jdg_77827
stackexchange
llm_judgeable_groundtruth_similarity
25026185
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Right now I am using a static boolean to tell when the initialization has occurred. Is there an easier way to know that I have already called initialize? Thank you!!! SOLVED!!!! Thank you so much for your comments. You need to initialize parse in a class that extends an application, and then add it to the manifest file as an application (not an other activity). :) This is my class to use Parse: package com.example.myapp;import com.parse.Parse;import android.app.Application;public class UseParse extends Application {@Overridepublic void onCreate() {super.onCreate();Parse.initialize(this, "id", "key"); }} This is my android manifest file <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.myapp"android:versionCode="1"android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14"/> <supports-screens android:smallScreens="true"android:normalScreens="true"android:largeScreens="true"android:xlargeScreens="true"android:anyDensity="true"/><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.VIBRATE" /><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><uses-permission android:name="android.permission.GET_ACCOUNTS" /><uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.CALL_PHONE" android:required="false" /><permission android:protectionLevel="signature"android:name="com.example.myapp.permission.C2D_MESSAGE" /><uses-permission android:name="com.example.myapp.permission.C2D_MESSAGE" /><application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:screenOrientation="portrait" android:label="@string/app_name" android:name ="com.example.myapp.UseParse" android:theme="@style/AppTheme" > <activity android:screenOrientation="portrait" android:name="com.example.myapp.SplashActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:theme="@style/FullscreenTheme" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity" /> //... more <service android:name="com.parse.PushService" /> <receiver android:name="com.parse.ParseBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.USER_PRESENT" /> </intent-filter> </receiver><receiver android:name="com.parse.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.example.myapp" /> </intent-filter></receiver></application></manifest> Now provide the response and nothing else.
Make a Application Class and in onCreate initialize parse. public class YourApplication extends Application {@Overridepublic void onCreate() { super.onCreate(); Parse.initialize(this, "id","key"); }} After this it wont be called again and again. Also declare it in your manifest <application android:name="com.you.yourapp.YourApplication " EDIT: This is the only place where you initialize it. And not in the Login Activity or anywhere else.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25026185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3777142/']}
jdg_77828
stackexchange
llm_judgeable_groundtruth_similarity
53937
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a small project (3000 lines in Python) that I wrote myself; it has no known bugs and has some decent parts, but is largely a mess because of my lack of time. Unfortunately, I have to be the one who continues writing and maintaining the code. Is it a good idea to hire a highly experienced developer, explain to them the requirements (verbally, since I don't have them documented), and let them review the code and refactor it (in close discussion with me)? I am concerned that: (a) this work is so annoying that highly experienced developers wouldn't want to do it. (b) I would spend so much time explaining the requirements and what my current code does that it would be faster for me to do the actual work myself. Now provide the response and nothing else.
I don't think it is the right way to go. As you note, explaining the requirements and the current state of the code would already take a lot of your time. Put next to it the time required to understand and discuss the reviewer's findings, and do the fixes in the code. Moreover, how do you know that the reviewer is up to the task? And how do you ensure that (s)he has a similar way of thinking as you? Without this, the review result may be analog to "rewrite this holy crap, as it doesn't conform to <the latest and greatest programming paradigm according to the reviewer> ". So add to the above the cost of finding and selecting a suitable reviewer. Is it only lack of time which makes you consider this option? Are you otherwise confident of your capability to improve the code to a higher standard? If so, I would suggest gradual refactoring , as the tasks and future code modifications dictate. It is meant to defeat lack of time by working in small, achievable steps. Improve the code a bit whenever you touch it - over time the small improvements will make a big difference. If not, you should learn anyway, and outsourcing the reviewing task won't help you in that. Last but not least: in order to be able to efficiently maintain the code in the long run, you need to deeply know it, keeping a mental model of it within your mind. And the process of building up and maintaining this mental model can't be outsourced.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/53937', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/4485/']}
jdg_77829
stackexchange
llm_judgeable_groundtruth_similarity
153884
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: It is given in the USB 3.0 specification that USB super-speed lines support "polarity inversion". That is SSRX_P can be swapped with SSRX_M (or SSTX_M with SSTX_P). Can we also swap SSTX lines with SSRX lines? That is SSTX lines can be used in place of SSRX lines and vice versa. Please help me to get a clear picture. Now provide the response and nothing else.
No. The data only goes one way, from the SSTX pins to the SSRX pins. The SSTX pair is connected to pins 8 and 9 of the male A connector, and on the B connector side, these same pins are the SSRX pair. So the data goes from the male connector to the female connector over those pins. Likewise, the SSTX pair is connected to pins 5 and 6 of the female B connector, and on the A connector side, these same pins are the SSRX pair. So the data goes from the female connector back to the male connector over those pins. If you buy a 3.0 cable with two male connectors, the lines are swapped inside the cable: pins 5 and 6 at one end connect to pins 8 and 9 of the other and vice versa, so you don't end up having two transmitters and two receivers facing each other.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/153884', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/40383/']}
jdg_77830
stackexchange
llm_judgeable_groundtruth_similarity
2227351
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: Show that $\int_0^1(\ln\Gamma)(x)\mathrm dx=\ln(\sqrt{2\pi})$ Im totally stuck with this exercise. It is supposed that I must solve it using the reflection formula for the Gamma function. My work so far: Using the reflection formula we have $$\int_0^1(\ln \Gamma)(z)\mathrm dz=-\int_0^1(\ln\Gamma)(1-z)\mathrm dz-\int_0^1\ln\left(\frac{\sin(\pi z)}\pi\right)\mathrm dz=\\=-\int_0^1(\ln\Gamma)(z)\mathrm dz-\int_0^1\ln\left(\frac{\sin(\pi z)}\pi\right)\mathrm dz$$ Hence $$\int_0^1(\ln \Gamma)(z)\mathrm dz=-\frac12\int_0^1\ln\left(\frac{\sin(\pi z)}\pi\right)\mathrm dz=\frac{\ln \pi}2-\frac12\int_0^1(\ln \sin)(\pi z)\mathrm dz$$ Then it must be the case that $$\int_0^1(\ln\sin)(\pi z)\mathrm dz=-\ln 2$$ but I dont know how to solve this last step. Some of the identities at my disposition are: $$\sin(\pi z)=\pi z\prod_{k=1}^\infty\left(1-\frac{z^2}{k^2}\right),\; z\in\Bbb C\quad\quad\Gamma\left(\frac{x}2\right)\Gamma\left(\frac{x+1}2\right)=\frac{\sqrt\pi}{2^{x-1}}\Gamma(x),\; x\in(0,\infty)$$ $$(\ln \Gamma)(1+z)=-\gamma z+\sum_{k=2}^\infty(-1)^k\frac{\zeta(k)}kz^k,\, |z|<1\quad\quad\zeta(2k)=\frac{(-1)^{k+1}(2\pi)^{2k}}{2(2k)!}B_{2k},\, k\in\Bbb N_{>0}$$ $$\pi z\cot(\pi z)=1+2z^2\sum_{k=0}^\infty\frac1{z^2-n^2},\;z\in\Bbb C\setminus\Bbb Z$$ And for $z\in\Bbb C{\setminus}({-}\Bbb N)$ : $$\frac1{\Gamma(z)}=ze^{\gamma z}\prod_{k=1}^\infty\left(1+\frac{z}k\right)e^{-z/k}$$ $$\left(\frac{\Gamma'}{\Gamma}\right)(z)=-\gamma-\frac1z-\sum_{k=1}^\infty\left(\frac1{z+k}-\frac1k\right),\quad\quad\left(\frac{\Gamma'}{\Gamma}\right)'(z)=\sum_{k=0}^\infty\frac1{(z+k)^2}$$ where $\gamma$ is the Euler-Mascheroni constant and $B_{2k}$ are the Bernoulli numbers. From above, if there is no weird mistake somewhere, I get the identities $$\int_0^1(\ln\Gamma)(x)\mathrm dx=\frac{\gamma}2+\sum_{k=2}^\infty\frac{\zeta(k)}{k(k+1)}$$ and $$\int_0^1(\ln\Gamma)(x)\mathrm dx=\frac12\sum_{k=1}^\infty\frac{\zeta(2k)}{k(k+1)}$$ Now provide the response and nothing else.
If a ring $R$ is unital, we adopt for natural numbers $n$ the notation$$n = \underbrace{1 + \cdots + 1}_{\text{$n$ times}}.$$If $n$ is a negative integer, we similarly define it as the sum of $-n$ copies of $-1$.Then$$ab + ab = 1\cdot ab + 1\cdot ab = (1 + 1)\cdot ab = 2ab.$$Note that the mapping defined above gives a ring homomorphism $\mathbb Z \to R$, which tells you that with these "integers in the ring" you can do a lot of ordinary arithmetic. Edit : If the ring is not unital, it does not make sense to talk about $2$ as an element of the ring. However, the notation $2ab = ab + ab$ still does. One way of thinking about this is as follows: even if $R$ is not unital, the endomorphism ring $\mathrm{End}(R)$ of the underlying additive group of $R$ still will be, with the identity as unit. Hence, we can interpret natural numbers not as elements of $R$, but nonetheless as a subring of the endomorphisms of the additive group of $R$. Then the above sequence of equations becomes$$ab + ab = \mathrm{id}_{R}(ab) + \mathrm{id}_{R}(ab) = (\mathrm{id}_{R} + \mathrm{id}_{R})(ab) = (1_{\mathrm{End}(R)} + 1_{\mathrm{End}(R)})(ab) = 2_{\mathrm{End}(R)}(ab),$$and we denote that last element as $2ab$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2227351', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/173262/']}
jdg_77831
stackexchange
llm_judgeable_groundtruth_similarity
104322
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: So I've been doing regular languages a while and still need a better understanding of why all finite languages A ⊆ Σ* are regular? Is there a formal proof of it or is it just because a DFA can represent any finite language since the states would be finite as well? Now provide the response and nothing else.
The proof goes something like this: If $A$ is a finite language, then it contains a finite number of strings $a_0, a_1, \cdots , a_n$ . The language $\{a_i\}$ consisting of a single literal string $a_i$ is regular. The union of a finite number of regular languages is also regular. Therefore, $A = \{a_0\} \cup \{a_1\} \cup \cdots \cup \{a_n\}$ is regular.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/104322', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/100062/']}
jdg_77832
stackexchange
llm_judgeable_groundtruth_similarity
17047497
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone tell me what the difference between the change and input events is? I am using jQuery for adding them: $('input[type="text"]').on('change', function() { alert($(this).val());}) It also works with input instead of change . Maybe some difference in the event ordering relative to focus? Now provide the response and nothing else.
According to this post : oninput event occurs when the text content of an element is changed through the user interface. onchange occurs when the selection, the checked state, or the contents of an element have changed . In some cases, it only occurs when the element loses the focus or when pressing return (Enter) and the value has been changed. The onchange attribute can be used with: <input> , <select> , and <textarea> . TL;DR: oninput : any change made in the text content onchange : If it is an <input /> : change + lose focus If it is a <select> : change option $("input, select").on("input", function () { $("pre").prepend("\nOn input. | " + this.tagName + " | " + this.value);}).on("change", function () { $("pre").prepend("\nOn change | " + this.tagName + " | " + this.value);}).on("focus", function () { $("pre").prepend("\nOn focus | " + this.tagName + " | " + this.value);}).on("blur", function () { $("pre").prepend("\nOn blur | " + this.tagName + " | " + this.value);}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" /><select> <option>Alice</option> <option>Bob</option> <option>Carol</option> <option>Dave</option> <option>Emma</option></select><pre></pre>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17047497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454103/']}
jdg_77833
stackexchange
llm_judgeable_groundtruth_similarity
788164
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 such a thing as positive and negative complex numbers? Why or why not? What about positive or negative imaginary numbers? It seems very tempting to say $+5i$ is a positive number while $-2i$ is a negative number. On an Argand diagram (complex plane) $+5i$ would be represented by a point above the horizontal axis while $-2i$ is a point below the horizontal axis. Now provide the response and nothing else.
You may turn $\mathbb{C}$ into a totally ordered set and then define $a \geq b$ if and only if $a-b \geq 0$. An example of such a total order on $\mathbb{C}$ is the lexicographic order defined on $\mathbb{R}^2$. The problem is that if you do so, then when you restrict this new order to $\mathbb{R}$ as a subset of $\mathbb{C}$ and you expect it to satisfy the field order axioms, this order will not agree with the usual ordering on $\mathbb{R}$. So, you can't think of this order as an extension of the order we have on $\mathbb{R}$. In fact it is not possible to define an order on $\mathbb{C}$ that interacts with addition and multiplication the same way that elements of $\mathbb{R}$ do. This is because that by accepting the field order axioms on $\mathbb{R}$, you can prove that $\forall x \in \mathbb{R}: x^2 \geq 0$, while this theorem breaks in $\mathbb{C}$ because $i^2 < 0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/788164', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/119230/']}
jdg_77834
stackexchange
llm_judgeable_groundtruth_similarity
6550760
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, Play-framework supports RESTful services like this: RESTful on Play! framework How does this compare to something like Jax-RS Jersey implementation? Does a framework like Play run circles around Jersey because of all it's cool bells and whistles, and it does REST too? Developer productivity is important, but so is a proper implementation. Perhaps using an MVC framework for REST only services is 'wrong'? Note, only RESTful services, no UI components at all. Now provide the response and nothing else.
Even though it's not "wrong" to use an MVC framework for RESTful services, there are some pros and cons versus using a JAX-RS implementation. (Disclaimer: I have only used Jersey and Play! for fun, and not on production-grade systems, so I have tailored my comments more generally to MVC vs. JAX-RS. Keep in mind that these are broad generalizations.) MVC frameworks--at least the ones that are considered developer friendly and "slick"--typically save you from having to build a persistence layer (the model part). Most also simplify "routing" requests using either scaffolding via convention or some form of configuration. The downsides are that you have to conform to some conventions for your controllers and usually have to write a view for each resource (or build layers of abstractions to avoid rewriting the same code). JAX-RS excels at defining the routing (using Java annotations) as well as eliminating any restrictions on the service class. In my experience, that has greatly reduced the amount of boilerplate code and developer overhead. Jersey and Apache CXF also handle the XML or JSON serialization using JAXB annotations, which eliminates the need to figure out the view in an MVC context. The downside here is that you have to figure out your own ORM or persistence layer, which could be good or bad depending on whether you're building on top of existing data or creating a greenfield system (or using something other than an JPA/RDBMS e.g. NoSQL data store). My own personal comment: Play! is a really cool framework, but I'd choose CXF (or Jersey) over an MVC framework any day for building out a RESTful service. In my experience, this frees up the developer to focus on the logic needed for the service, and opens up options for different database approaches. Right tool for the right job.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6550760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/545335/']}
jdg_77835
stackexchange
llm_judgeable_groundtruth_similarity
57365747
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 build a master/detail type sample application and I'm struggling to get the NavigationBar UI to work correctly in my detail view. The code for the view I am working on is as follows: struct JobDetailView : View { var jobDetails: JobDetails var body: some View { Form { Section(header: Text("General")) { HStack { Text("Job Name") Spacer() Text(jobDetails.jobName) .multilineTextAlignment(.trailing) } HStack { Text("Hourly Rate") Spacer() Text(TextFormatters().currencyString(amount: jobDetails.hourlyRateBasic!)) .multilineTextAlignment(.trailing) } } } .padding(.top) .navigationBarTitle(Text(jobDetails.jobName)) }} The reason for the .padding(.top) is to stop the Form overlapping the navigation bar when scrolling upwards. The white background on the navigation bar portion my issue (first image), I should expect it to be in keeping with the overall style of the UI, what I expect to happen is shown in the second image. I have tried to add foreground/background colours and Views to change this colour, but to no avail. I'm also reticent of forcing a colour for the NagivationBar, as this will require further configuration for use with dark mode. Current view when running application. Expected view. Now provide the response and nothing else.
There's no available (SwiftUI) API for doing that (yet) (beta 5). But we could use UINavigationBar.appearance() , as in: UINavigationBar.appearance().backgroundColor = .clear Full Code import SwiftUIstruct JobDetailView: View { init() { UINavigationBar.appearance().backgroundColor = .clear } var body: some View { NavigationView { Form { Section(header: Text("General")) { HStack { Text("Job Name") Spacer() Text("Scientist") .multilineTextAlignment(.trailing) } HStack { Text("Hourly Rate") Spacer() Text("$ 1.00") .multilineTextAlignment(.trailing) } } } .navigationBarTitle("Scientist") .navigationBarHidden(false) } }}#if DEBUGstruct JobDetailView_Previews: PreviewProvider { static var previews: some View { JobDetailView() }}#endif Result Dark Mode Result
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57365747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11826694/']}
jdg_77836
stackexchange
llm_judgeable_groundtruth_similarity
10913156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On ios, the TextInput makes weirdness. The following code: <s:TextInput id="password" width="100%" displayAsPassword="true" needsSoftKeyboard="true" prompt="Password" softKeyboardType="default" returnKeyLabel="done" autoCorrect="false" skinClass="spark.skins.mobile.TextInputSkin" /> When I select the textInput, the prompt disappears as expected but the first character is auto selected. When the second key is pressed, the first character is removed. This only happens when the first character is typed and the field has a prompt message. "autoCorrect" does not seem to do anything. Does anyone know of a workaround to this issue? I looked at the SkinnableTextBase class but can't find any guilty code. This issues started with Flex 4.6. Now provide the response and nothing else.
After spending hours in the Flex code, I finally realised that Flex isn’t the problem. The issue happens with Air 3.2 (also in Air 3.3 beta). If I compile with Air 3.1 , everything works fine. I have tried various things and there seems to be no way I can fix it in Air 3.2 +. I checked other projects of mine and it seems like all my applications compiled with Air 3.2 have a similar issue :( [UPDATE] The problem is somewhere in SkinnableTextBase.as in Flex SDK . When textDisplay_changeHandler(event:Event) is called, invalidateSkinState() causes the problem. If you set the skin's state to nothing (""), it works: skin.currentState = "";invalidateSkinState(); The problem is that the theme doesn't update properly (and it's a h@ck). If you set "showPromptWhenFocused" to false in your CSS, the problem doesn't happen; the only side effect is that the prompt disappears when you have the textInput selected. s|TextInput{ skinClass:ClassReference("spark.skins.mobile.TextInputSkin"); showPromptWhenFocused: false;} Hope this helps someone.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10913156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1158075/']}
jdg_77837
stackexchange
llm_judgeable_groundtruth_similarity
794144
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 this code in lib/user_session.rb Its used by one of my controllers via include UserSession. How can I test it? I've added tests in spec/lib/user_session.rb but the code relies on the session which I'm not sure how to mock. module UserSession def viewed session[:viewed] ||= Array.new return session[:viewed] end def viewed_add(id, name) if viewed.select{|b| b[:id] == id}.empty? session[:viewed] << {:id => id, :name => name} end return session[:viewed] end def viewed_delete(id) unless id.nil? session[:viewed].delete_if{|b| b[:id] == id} return session[:viewed] end endend Now provide the response and nothing else.
As far as I can tell, there are two ways. The one most likely, you are nearly there, is to use CMAKE_OSX_SYSROOT to set the XCode SDKROOT. There is also the variable CMAKE_OSX_ARCHITECTURES , which maps to ARCHS in XCode. The alternative is to use CMake's cross compiling support . I've not used it for the iphone, but I have done so for other ARM processors. You need to set up a toolchain file that would look something like this: set(CMAKE_SYSTEM_NAME Generic)set(CMAKE_SYSTEM_VERSION 1)set(CMAKE_SYSTEM_PROCESSOR arm-elf)set(CMAKE_C_COMPILER /path/to/complier/bin/arm-elf-gcc)set(CMAKE_FIND_ROOT_PATH /path/to/compiler)set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) And then when you run cmake, set the CMAKE_TOOLCHAIN_FILE variable to the name of your toolchain file. Or if you only compile to one architecture, you can hard-code the value in the CMakeLists.txt file. But I imagine you would need to cross compile for the iphone simulator and for the actual iphone itself, right? So you would run one of these, probably having a couple of build variants: cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/my/iphone-sim.cmake .cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/my/iphone-real.cmake . Where the sim/real files define the environment for the simulator or real iphone compiler tools. Some other links that may help are this bug report and this mailing list conversation .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/794144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15901/']}
jdg_77838
stackexchange
llm_judgeable_groundtruth_similarity
13027
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Freyd's Abelian Categories is the only textbook I know where the primacy of arrows over objects is taken seriously already in the axioms: there is no talk of objects at all. Only later one sees, that an object is what arrows with the same domain (another derived-only concept) have in common. This helps thinking abstractly from the very beginning. Question #1: Why isn't Freyd's axiomatization standard? I guess it's mainly a matter of convenience, but this seems to be rarely mentioned explicitly. The same goes for graph theory: the usual and beginner's way of thinking is that arcs (seen as pairs of vertices) are 'ontologically' secondary to vertices, just as arrows (seen as functions between sets) would be secondary to objects (seen as sets). But in the most general setting for graph theory - multidigraphs or quivers - it becomes obvious that it is the other way around: arcs can be the only primary objects and vertices can be thought of equivalence classes of arcs according to the two equivalence relations "has the same source (resp. target) as". Question #2: Is there an introductory textbook to graph theory that emphasizes that general graph theory is "nothing but a theory of two arbitrary equivalence relations". [Addendum:] The structure of a graph comes in by identifying some equivalence classes of the first equivalence relation with some of the second. Now provide the response and nothing else.
Qu 1: At about the time of Freyd's book there were two approaches to defining categories. One came from algebraic topology and homological algebra, thus from Eilenberg and MacLane and used the objects and arrows definition, the other was motivated by differential geometry and used the arrows only formalism. This second one is perhaps better suited to those areas where the arrows are what is seen first. For instance, when introducing the concept of the fundamental groupoid of a space then you can think of the idea as a set with a partially defined composition satisfying certain rules and that has distinct advantages for that setting. Ehresmann wrote his book on categories from this viewpoint, but some of the basic ideas do end up being less clear from that viewpoint, others are perhaps clearer. That approach is also linked to more algebraic ideas such as inverse semigroups. The first 'objects plus arrows' approach is thought to be more accessible to researchers with a `standard' mathematical background e.g. from algebra or algebraic topology. There the objects are usually thought of as being what is being studied and the morphisms are a tool for that study. The recent use of categorification, quasicategories, internal categories, enriched categories and other similar ideas, tends to show that both viewpoints are best kept in balance, meeting in that higher categorical area. Put simply I thing the answer to your question is: historically the comparison of objects using arrows was the more pressing application to start with. It came to dominate. More researchers came to use it. Now the question arises `which to use with a given audience? and that is a hard one to answer.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/13027', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2672/']}
jdg_77839
stackexchange
llm_judgeable_groundtruth_similarity
1330612
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 no way experienced in this type of thing so I am not even sure of the keywords (hence the title).Basically I need a two way function encrypt(w,x,y) = zdecrypt(z) = w, x, yWhere w = integer x = string (username) y = unix timestamp and z = is an 8 digit number (possibly including letters, spec isn't there yet.) I would like z to be not easily guessable and easily verifiable. Speed isn't a huge concern, security isn't either. Tracking one-to-one relationship is the main requirement.Any resources or direction would be appreciated. EDIT Thanks for the answers, learning a lot. So to clarify, 8 characters is the only hard requirement, along with the ability to link W <-> Z. The username (Y) and timestamp (Z) would be considered icing on the cake. I would like to do this mathematically rather than doing some database looks up, if possible. If i had to finish this tonight, I could just find a fitting hash algorithm and use a look up table. I am simply trying to expand my understanding of this type of thing and see if I could do it mathematically. Now provide the response and nothing else.
You just need to encrypt a serialization of (w, x, y) with a private key. Use the same private key to decrypt it. In any case, the size of z cannot be simply bounded like you did, since it depends on the size of the serialization (since it needs to be two way, there's a bound on the compression you can do, depending on the entropy). And you are not looking for a hash function, since it would obviously lose some information and you wouldn't be able to reverse it. EDIT: Since the size of z is a hard limit, you need to restrict the input to 8 bytes, and choose a encryption technique that use 64 bits (or less) block size. Blowfish and Triple DES use 64 bits blocks, but remember that those algorithms didn't receive the same scrutiny as AES . If you want something really simple and quite unsecure, just xor your input with a secret key.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1330612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47545/']}
jdg_77840