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
|
8279803
|
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 add an array of 2 buttons to the right of a navigation bar, but I get a exception when I run the code. 'NSInvalidArgumentException', reason: '-[UIButton isSystemItem]: unrecognized selector sent to instance My code is pretty simple really: UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,45)]; label.backgroundColor=[UIColor clearColor]; label.text = @"Test 2 Buttons"; UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom]; button1.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f); UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom]; button2.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f); NSArray *rightBarButtons = [[NSArray alloc] initWithObjects:button2, button1, nil]; UINavigationItem* navItem = self.navigationItem; navItem.titleView = label; navItem.rightBarButtonItems = rightBarButtons; [rightBarButtons release]; [label release]; I am running it on the iPhone 5.0 simulator.Any idea??Thanks in advance.Al
Now provide the response and nothing else.
|
You can't directly add UIButtons . You need to wrap them as UIBarButtonItems first - there is no compiler warning since you are only passing an array. Create the bar button items using initWithCustomView: , passing in your button as the custom view. Or, depending on what is in your buttons, create bar button items directly.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8279803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/201191/']}
|
jdg_373841
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
665417
|
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 read a blog post about NHibernate's ability to create a GUID from the system time (Guid.Comb), thus avoiding a good amount of database fragmentation. You could call it the client-side equivalent to the SQL Server Sequential ID. Is there a way I could use a similar strategy in my Linq-to-Sql project (by generating the Guid in code)?
Now provide the response and nothing else.
|
C# (safe) code (Compliments of the NHibernate Guid Comb Generator) Guid GenerateComb(){ byte[] destinationArray = Guid.NewGuid().ToByteArray(); DateTime time = new DateTime(0x76c, 1, 1); DateTime now = DateTime.Now; TimeSpan span = new TimeSpan(now.Ticks - time.Ticks); TimeSpan timeOfDay = now.TimeOfDay; byte[] bytes = BitConverter.GetBytes(span.Days); byte[] array = BitConverter.GetBytes((long) (timeOfDay.TotalMilliseconds / 3.333333)); Array.Reverse(bytes); Array.Reverse(array); Array.Copy(bytes, bytes.Length - 2, destinationArray, destinationArray.Length - 6, 2); Array.Copy(array, array.Length - 4, destinationArray, destinationArray.Length - 4, 4); return new Guid(destinationArray);} A link to the source on github: https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Id/GuidCombGenerator.cs
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/665417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30056/']}
|
jdg_373842
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
411697
|
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 have a proxy/firewall machine running FreeBSD 9, using PF to route and filter traffic as needed. Now I'm setting up a git server, which runs over ssh, but I'm already using port 22 for ssh. I would like to route traffic from any IP to port 22 to another machine, if the hostname they used to reach the server was a subdomain (git.mydomain.com). Kind of a virtual host, but for ssh... Is this possible with pf?Any suggestions?
Now provide the response and nothing else.
|
Sorry, what you're asking for is impossible -- IP traffic (and an IP firewall) only knows IP addresses - it knows nothing of hostnames. You can only have one process listening to a specific port on a specific IP address.Virtual hosts for websites work because the web server receives the hostname in an HTTP header (see http://en.wikipedia.org/wiki/Virtual_hosting ), and there is no similar mechanism in SSH. Your options are pretty limited: Configure your regular SSH server to handle the git traffic (probably the best option). Acquire another IP address. Run the SSH server for git on an alternate port. Once you have the SSH server for git on an alternate port, you can automagically use it by adding the following to your ~/.ssh/config : Host git.mydomain.com HostName router.mydomain.com Port 2222
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/411697', 'https://serverfault.com', 'https://serverfault.com/users/117032/']}
|
jdg_373843
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5176691
|
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 the argparse package of Python 2.7 to write some option-parsing logic for a command-line tool. The tool should accept one of the following arguments: "ON": Turn a function on. "OFF": Turn a function off. [No arguments provided]: Echo the current state of the function. Looking at the argparse documentation led me to believe that I wanted two--possibly three--subcommands to be defined, since these three states are mutually exclusive and represent different conceptual activities. This is my current attempt at the code: parser = argparse.ArgumentParser()subparsers = parser.add_subparsers()parser.set_defaults(func=print_state) # I think this line is wrong.parser_on = subparsers.add_parser('ON')parser_on.set_defaults(func=set_state, newstate='ON')parser_off = subparsers.add_parser('OFF')parser_off.set_defaults(func=set_state, newstate='OFF')args = parser.parse_args()if(args.func == set_state): set_state(args.newstate)elif(args.func == print_state): print_state()else: args.func() # Catchall in case I add more functions later I was under the impression that if I provided 0 arguments, the main parser would set func=print_state , and if I provided 1 argument, the main parser would use the appropriate subcommand's defaults and call func=set_state . Instead, I get the following error with 0 arguments: usage: cvsSecure.py [-h] {ON,OFF} ...cvsSecure.py: error: too few arguments And if I provide "OFF" or "ON", print_state gets called instead of set_state . If I comment out the parser.set_defaults line, set_state is called correctly. I'm a journeyman-level programmer, but a rank beginner to Python. Any suggestions about how I can get this working? Edit : Another reason I was looking at subcommands was a potential fourth function that I am considering for the future: "FORCE txtval": Set the function's state to txtval .
Now provide the response and nothing else.
|
The defaults of the top-level parser override the defaults on the sub-parsers, so setting the default value of func on the sub-parsers is ignored, but the value of newstate from the sub-parser defaults is correct. I don't think you want to use subcommands. Subcommands are used when the available options and positional arguments change depending on which subcommand is chosen. However, you have no other options or positional arguments. The following code seems to do what you require: import argparsedef print_state(): print "Print state"def set_state(s): print "Setting state to " + sparser = argparse.ArgumentParser()parser.add_argument('state', choices = ['ON', 'OFF'], nargs='?')args = parser.parse_args()if args.state is None: print_state()elif args.state in ('ON', 'OFF'): set_state(args.state) Note the optional parameters to parser.add_argument . The "choices" parameter specifies the allowable options, while setting "nargs" to "?" specifies that 1 argument should be consumed if available, otherwise none should be consumed. Edit: If you want to add a FORCE command with an argument and have separate help text for the ON and OFF command then you do need to use subcommands. Unfortunately there doesn't seem to be a way of specifying a default subcommand. However, you can work around the problem by checking for an empty argument list and supplying your own. Here's some sample code illustrating what I mean: import argparseimport sysdef print_state(ignored): print "Print state"def set_state(s): print "Setting state to " + sparser = argparse.ArgumentParser()subparsers = parser.add_subparsers()on = subparsers.add_parser('ON', help = 'On help here.')on.set_defaults(func = set_state, newstate = 'ON')off = subparsers.add_parser('OFF', help = 'Off help here.')off.set_defaults(func = set_state, newstate = 'OFF')prt = subparsers.add_parser('PRINT')prt.set_defaults(func = print_state, newstate = 'N/A')force = subparsers.add_parser('FORCE' , help = 'Force help here.')force.add_argument('newstate', choices = [ 'ON', 'OFF' ])force.set_defaults(func = set_state)if (len(sys.argv) < 2): args = parser.parse_args(['PRINT'])else: args = parser.parse_args(sys.argv[1:])args.func(args.newstate)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5176691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441822/']}
|
jdg_373844
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
241285
|
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 an algorithm to parse a number out of a series of short-ish strings. These strings are somewhat regular, but there's a few different general forms and several exceptions. I'm trying to build a set of regexes that will handle the various forms and exceptions; I'll apply them one after another to see if I get a match. One of these forms goes something like this: X (Y) Z Where: X is a number I want to capture. Z is static, pre-defined text. it's basically how I determine whether this particular form is applicable or not. Y is a string of unknown length and content, surrounded by parenthesis. Also: Y is optional; it doesn't always appear in a string with Z and X . So, I want to be able to extract the numbers from all of these strings: 10 Z 20 (foo) Z 30 (bar) Z Right now, I have a regex that will capture the first one: ([0-9]+) +Z My problem is that I don't know how to construct a regex that will match a series of characters if and only if they're enclosed in parenthesis. Can this be done in a single regex?
Now provide the response and nothing else.
|
(\d+)\s+(\(.*?\))?\s?Z Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be ( ?: non-capture groups). I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/241285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3488/']}
|
jdg_373845
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3719033
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $(x_n)_n$ a sequence given by $2x_{n+1}=2x_n^2-5x_n+3$ with $x_1\in \mathbb{Q}$ . I know that the sequence is convergent. I know that the limit of the sequence should be $\dfrac{1}{2}$ or $3$ . I want to prove that there exists $n\in \mathbb{N}$ s.t. $x_n=\dfrac{1}{2}$ if the sequence goes to $\dfrac{1}{2}$ . Similar if the sequence goes to $3$ . I tried by definition with $\epsilon$ but I didn’t succeed.
Now provide the response and nothing else.
|
Let $f(x)=x^2-\frac{5}{2}x+\frac{3}{2}$ , so that $x_{n+1}=f(x_n)$ . Suppose that $x_n$ converges to $l$ , where $l\in\lbrace \frac{1}{2},3\rbrace$ . Then $$y_n=\frac{x_{n+1}-l}{x_n-l}=\frac{f(x_{n})-f(l)}{x_n-l} \to f'(l) \textrm{ when } n \to \infty \tag{1}$$ Note that $f'(\frac{1}{2})=-\frac{3}{2}$ and $f'(3)=\frac{7}{2}$ . So $|f'(l)| \geq \frac{3}{2}$ in both cases, and hence $|f'(l)| \gt \frac{5}{4}$ in both cases. It follows that there is a $n_0$ such that $|y_n|\gt \frac{5}{4}$ for all $n\geq n_0$ . Then $$|x_{n+1}-l| \geq \frac{5}{4} |x_n-l| \textrm{ for all } n\geq n_0 \tag{2}$$ . By induction, we deduce $$|x_n-l| \geq \big(\frac{5}{4}\big)^{n-n_0}|x_{n_0}-l| \textrm{ for all } n\geq n_0 \tag{3}$$ If $x_{n_0}\neq l$ , we would deduce $\lim_{n\to\infty}{|x_n-l|}=\infty$ , which is impossible. So $x_{n_0}=l$ , which finishes the proof.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3719033', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/270082/']}
|
jdg_373846
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58737769
|
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 using androidx.fragment.app.FragmentContainerView as a navHost instead of a regular fragment app is not able to navigate to a destination after orientation change. I get a following error: java.lang.IllegalStateException: no current navigation node Is there a gotcha that I should know about to use it properly or is my way of using nav components is incorrect? Simple activity xml with a view: ... <androidx.fragment.app.FragmentContainerView android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:layout_behavior="@string/appbar_scrolling_view_behavior" app:navGraph="@navigation/nav_simple" />... Navigation code: <?xml version="1.0" encoding="utf-8"?><navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/nav_legislator.xml" app:startDestination="@id/initialFragment"> <fragment android:id="@+id/initialFragment" android:name="com.example.fragmenttag.InitialFragment" android:label="Initial Fragment" tools:layout="@layout/initial_fragment"> <action android:id="@+id/action_initialFragment_to_destinationFragment" app:destination="@id/destinationFragment" /> </fragment> <fragment android:id="@+id/destinationFragment" android:name="com.example.fragmenttag.DestinationFragment" android:label="Destination Fragment" tools:layout="@layout/destination_fragment" /></navigation> Here is a github repo where you can easily reproduce a bug: https://github.com/dmytroKarataiev/navHostBug
Now provide the response and nothing else.
|
The no current navigation node error occurs when there's no graph set and you attempt to call navigate() . If it only occurs when you're using FragmentContainerView and after a configuration change, then this would be related to this bug , which is fixed and scheduled for release with Navigation 2.2.0-rc03. To work around this issue, you can either switch back to <fragment> or remove app:navGraph="@navigation/nav_simple" and instead call navController.setGraph(R.navigation.nav_simple) .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58737769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5123022/']}
|
jdg_373847
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14509626
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets say I have the array: x = np.array([0.00001,0.001]) numpy will make the numbers to array([ 1.00000000e-05, 1.00000000e-03]) Now I want to get the exponents, something like x.get_exponent() with result [-5,-3]
Now provide the response and nothing else.
|
You can use np.floor(np.log10(np.abs(x))) . For example: In [13]: x = np.array([0.00001, -0.001, 0.0000025, 0.09, -13.25, 9876.5])In [14]: xOut[14]: array([ 1.00000000e-05, -1.00000000e-03, 2.50000000e-06, 9.00000000e-02, -1.32500000e+01, 9.87650000e+03])In [15]: np.floor(np.log10(np.abs(x))).astype(int)Out[15]: array([-5, -3, -6, -2, 1, 3])
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14509626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117766/']}
|
jdg_373848
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34293714
|
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 know I can measure the execution time of a call to sess.run() , but is it possible to get a finer granularity and measure the execution time of individual operations?
Now provide the response and nothing else.
|
I have used the Timeline object to get the time of execution for each node in the graph: you use a classic sess.run() but also specify the optional arguments options and run_metadata you then create a Timeline object with the run_metadata.step_stats data Here is an example program that measures the performance of a matrix multiplication: import tensorflow as tffrom tensorflow.python.client import timelinex = tf.random_normal([1000, 1000])y = tf.random_normal([1000, 1000])res = tf.matmul(x, y)# Run the graph with full trace optionwith tf.Session() as sess: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() sess.run(res, options=run_options, run_metadata=run_metadata) # Create the Timeline object, and write it to a json tl = timeline.Timeline(run_metadata.step_stats) ctf = tl.generate_chrome_trace_format() with open('timeline.json', 'w') as f: f.write(ctf) You can then open Google Chrome, go to the page chrome://tracing and load the timeline.json file.You should see something like:
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34293714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3559888/']}
|
jdg_373849
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29557459
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an idiomatic way to round to the nearest multiple of a number, short of rounding both up and down and seeing which one is closest? Assume only integers: number multiple result12 5 1013 5 15149 10 150
Now provide the response and nothing else.
|
Add half of the multiple, then round down. result = ((number + multiple/2) / multiple) * multiple; or result = number + multiple/2;result -= result % multiple; This rounds up if the number is exactly in the middle. You might need to tweak the calculation if you want different behaviour in that case. Also, beware overflow if number might be near the top of the type's range.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29557459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673730/']}
|
jdg_373850
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32155133
|
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 building a JSON validator from scratch, but I am quite stuck with the string part. My hope was building a regex which would match the following sequence found on JSON.org: My regex so far is: /^\"((?=\\)\\(\"|\/|\\|b|f|n|r|t|u[0-9a-f]{4}))*\"$/ It does match the criteria with a backslash following by a character and an empty string. But I'm not sure how to use the UNICODE part. Is there a regex to match any UNICODE character expert " or \ or control character? And will it match a newline or horizontal tab? The last question is because the regex match the string "\t", but not " " (four spaces, but the idea is to be a tab). Otherwise I will need to expand the regex with it, which is not a problem, but my guess is the horizontal tab is a UNICODE character. Thanks to Jaeger Kor, I now have the following regex: /^\"((?=\\)\\(\"|\/|\\|b|f|n|r|t|u[0-9a-f]{4})|[^\\"]*)*\"$/ It appears to be correct, but is there any way to check for control characters or is this unneeded as they appear on the non-printable characters on regular-expressions.info? The input to validate is always text from a textarea. Update: the regex is as following in case anyone needs it: /^("(((?=\\)\\(["\\\/bfnrt]|u[0-9a-fA-F]{4}))|[^"\\\0-\x1F\x7F]+)*")$/
Now provide the response and nothing else.
|
For your exact question create a character class # Matches any character that isn't a \ or "/[^\\"]/ And then you can just add * on the end to get 0 or unlimited number of them or alternatively 1 or an unlimited number with + /[^\\"]*/ or /[^\\"]+/ Also there is this below, found at https://regex101.com/ under the library tab when searching for json /(?(DEFINE)# Note that everything is atomic, JSON does not need backtracking if it's valid# and this prevents catastrophic backtracking(?<json>(?>\s*(?&object)\s*|\s*(?&array)\s*))(?<object>(?>\{\s*(?>(?&pair)(?>\s*,\s*(?&pair))*)?\s*\}))(?<pair>(?>(?&STRING)\s*:\s*(?&value)))(?<array>(?>\[\s*(?>(?&value)(?>\s*,\s*(?&value))*)?\s*\]))(?<value>(?>true|false|null|(?&STRING)|(?&NUMBER)|(?&object)|(?&array)))(?<STRING>(?>"(?>\\(?>["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\0-\x1F\x7F]+)*"))(?<NUMBER>(?>-?(?>0|[1-9][0-9]*)(?>\.[0-9]+)?(?>[eE][+-]?[0-9]+)?)))\A(?&json)\z/x This should match any valid json, you can also test it at the website above EDIT: Link to the regex
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32155133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328421/']}
|
jdg_373851
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5986120
|
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 the book "The Joy of Clojure", defprotocol is offered as a solution to the expression problem -- "the desire to implement an existing set of abstract methods for an existing concrete class without having to change the code that defines either." The example given is as follows: (defprotocol Concatenatable (cat [this other]))(extend-type String Concatenatable (cat [this other] (.concat this other)))(cat "House" " of Leaves");=> "House of Leaves"(extend-type java.util.List Concatenatable (cat [this other] (concat this other)))(cat [1 2 3] [4 5 6]);=> (1 2 3 4 5 6) It is suggested that this is not possible in a language like Java, but how is it different than the following? public class Util { public static String cat(final String first, final String second) { return first.concat(second); } public static <T> List<T> cat(final List<T> first, final List<T> second) { final List<T> list = new List<T>(first); list.addAll(second); return list; }} After all, both are used similarly: (cat "House" " of Leaves")Util.cat("House", " of Leaves"); The Clojure function cat is not a method on the String and List classes, but rather an independent function that is overloaded to accept either String or List arguments. Although I really like Clojure, I don't understand the claims of superiority for this construct.
Now provide the response and nothing else.
|
Okay. You release this cat Java library to much fanfare, and everyone downloads it. It's so great I want to make my own TVCommercial type be concatenable so that I can send it to bits of your library that operate on concatenable objects. But I can't, because you call Util.cat(obj1, obj2) , which has no overload for TVCommercial . I can't extend your code to handle my types, because I don't own your code. You can define Concatenable as an interface to address this problem: interface Concatenable { Concatenable cat(Concatenable other);} But now I can't write a class which is both Concatenable and... I don't know, an AnimalHandler, that handles cat s. Clojure's protocols solve both problems by decentralizing the dispatch functions and implementations: they live all over the place, rather than in some single location. In Java, you choose between: Putting all your type dispatch into a single switch/case or overloaded method Defining an interface mandating a method with a particular name Clojure basically does the latter of these, but because it uses namespaced names, there's no danger of conflict with other protocols that think cat is a good function name.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5986120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96233/']}
|
jdg_373852
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1303588
|
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 read this PDF where it explains how to find the last digit of a number. If I were to find the last digit of $9^{1500}$ I would simply write it as $(3^{2})^{1500}$ and then use the patterns in the PDF for $3^{4n}$ . The problem here is that I'm asked to find the last $2$ digits. I think I could try to find patterns for the last 2 digits of $3^x$ or for $9^x$ but this would waste a lot of time, and since this problem was supposed to be solved by hand, I think this is not the best method. I'm also having problems to find literature about these problems of finding last digits of large exponents. Can somebody recommend be some?
Now provide the response and nothing else.
|
Calculating the last two digits is like taking the number $\mod 100$. $$9 \equiv 9\mod 100\\9^2 \equiv 81\mod 100\\9^3=729\equiv 29\mod 100\\9^4=9\cdot 9^3 \equiv 9\cdot 29 = 261\equiv 61\mod 100\\9^5\equiv 9\cdot 61 = 549\equiv 49\mod 100\\9^6 \equiv 9\cdot 49 = 441\equiv 41\mod 100\\9^7\equiv 9\cdot 41 = 369\equiv 69\mod 100\\9^8\equiv 9\cdot 69 = 721\equiv 21\mod 100\\9^9\equiv 9\cdot 21 = 189\equiv 89\mod 100\\9^{10}\equiv 9\cdot 89 = 801\equiv 1\mod 100\\$$ Now, knowing that $9^{10}\equiv 1\mod 100$, your remainging task should be easier.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1303588', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166180/']}
|
jdg_373853
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
240240
|
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:
The multifactorial function can be extended to the reals (see TheSimpliFire answer) like so: It follows that we can extend the multifactorial function to the reals through $$x!^{(k)}=k^{x/k}\Gamma\left(1+\frac{x}{k}\right)\prod_{i=1}^{k-1}\left(\frac{i k^{-i/k}}{\Gamma(1+i/k)}\right)^{\sin(\pi(x-i))\cot(\pi(x-i)/k)/k}$$ Multifactorial[x_, k_] := k^(x/k)*Gamma[1 + x/k]*Product[((j k^(-(j/k)))/Gamma[(j + k)/k])^(1/k*Sin[Pi (x - j)] Cot[Pi*(x - j)/k]), {j, 1, k - 1}]Multifactorial[2, 5](*Error messages: "Indeterminate expression 0^0 encountered"*)Plot[Multifactorial[x, 5], {x, -4, 4}] How can get to work and plot (with Desmos , it works fine) the function?
Now provide the response and nothing else.
|
The immediate cure is to instead use the Chebyshev polynomial of the second kind, $U_n(x)$ , in the definition: multiFactorial[x_, k_] := k^(x/k) Gamma[1 + x/k] Product[((j k^(-(j/k)))/Gamma[(j + k)/k])^ (Cos[(π (-j + x))/k]/k ChebyshevU[k - 1, Cos[(π (-j + x))/k]]), {j, 1, k - 1}] For instance: multiFactorial[x, 2] - x!! // FunctionExpand // Simplify 0Plot[multiFactorial[x, 5], {x, -4, 4}]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/240240', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26828/']}
|
jdg_373854
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3869954
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the actual use of 'fail' in JUnit test case?
Now provide the response and nothing else.
|
Some cases where I have found it useful: mark a test that is incomplete, so it fails and warns you until you can finish it making sure an exception is thrown: try{ // do stuff... fail("Exception not thrown");}catch(Exception e){ assertTrue(e.hasSomeFlag());} Note: Since JUnit4, there is a more elegant way to test that an exception is being thrown:Use the annotation @Test(expected=IndexOutOfBoundsException.class) However, this won't work if you also want to inspect the exception, then you still need fail() .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3869954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261707/']}
|
jdg_373855
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
82705
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm peer reviewing an academic journal article and the authors wrote the following as justification for not reporting any inferential statistics (I deidentified the nature of the two groups): In total, 25 of the 2,349 (1.1%) respondents reported X . We appropriately refrain from presenting analyses that statistically compare group X to group Y (the other 2,324 participants) since those results could be heavily driven by chance with an outcome this rare. My question is are the authors of this study justified in throwing in the towel with respect to comparing groups? If not, what might I recommend to them?
Now provide the response and nothing else.
|
Statistical tests do not make assumptions about sample size. There are, of course, differing assumptions with various tests (e.g., normality), but the equality of sample sizes is not one of them. Unless the test used is inappropriate in some other way (I can't think of an issue right now), the type I error rate will not be affected by drastically unequal group sizes. Moreover, their phrasing implies (to my mind) that they believe it will. Thus, they are confused about these issues. On the other hand, type II error rates very much will be affected by highly unequal $n$s. This will be true no matter what the test (e.g., the $t$-test, Mann-Whitney $U$-test, or $z$-test for equality of proportions will all be affected in this way). For an example of this, see my answer here: How should one interpret the comparison of means from different sample sizes? Thus, they may well be "justified in throwing in the towel" with respect to this issue. (Specifically, if you expect to get a non-significant result whether the effect is real or not, what is the point of the test?) As the sample sizes diverge, statistical power will converge to $\alpha$. This fact actually leads to a different suggestion, which I suspect few people have ever heard of and would probably have trouble getting past reviewers (no offense intended): a compromise power analysis . The idea is relatively straightforward: In any power analysis, $\alpha$, $\beta$, $n_1$, $n_2$, and the effect size $d$, exist in relationship to each other. Having specified all but one, you can solve for the last. Typically, people do what is called an a-priori power analysis , in which you solve for $N$ (generally you are assuming $n_1=n_2$). On the other hand, you can fix $n_1$, $n_2$, and $d$, and solve for $\alpha$ (or equivalently $\beta$), if you specify the ratio of type I to type II error rates that you are willing to live with. Conventionally, $\alpha=.05$ and $\beta=.20$, so you are saying that type I errors are four times worse than type I errors. Of course, a given researcher might disagree with that, but having specified a given ratio, you can solve for what $\alpha$ you should be using in order to possibly maintain some adequate power. This approach is a logically valid option for the researchers in this situation, although I acknowledge the exoticness of this approach may make it a tough sell in the larger research community that probably has never heard of such a thing.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/82705', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11758/']}
|
jdg_373856
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56973205
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to combine a video(with no sound) and its separate audio file I've tried ffmpeg ffmpeg -i video.mp4 -i audio.mp4 -c copy output.mp4 and it works fine. i'm trying to achieve the same output from ffmpeg-python but with no luck. Any help on how to do this?
Now provide the response and nothing else.
|
I had the same problem. Here is the python code after you have pip install ffmpeg-python in your environment: import ffmpeginput_video = ffmpeg.input('./test/test_video.webm')input_audio = ffmpeg.input('./test/test_audio.webm')ffmpeg.concat(input_video, input_audio, v=1, a=1).output('./processed_folder/finished_video.mp4').run() v=1 : Set the number of output video streams, that is also the number of video streams in each segment. Default is 1. a=1 : Set the number of output audio streams, that is also the number of audio streams in each segment. Default is 0. For the details of ffmpeg.concat , check out: https://ffmpeg.org/ffmpeg-filters.html#concat . You can check out more examples here: https://github.com/kkroening/ffmpeg-python/issues/281 Hope this helps! PS.If you are using MacOS and have the error: FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg' while running the code, just brew install ffmpeg in your terminal.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56973205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6682321/']}
|
jdg_373857
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9310044
|
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 internationalize my site, and one thing is to use different font-size for different languages. Also some text-images need to be replaced as well. I think the only way to do this is to have additional locale-specific CSS files in the public folder and load them based on locale in my view. This avoids asset pipeline from compiling those specific CSS files. But I am wonderiing if there a better way to do this?
Now provide the response and nothing else.
|
Your best bet in organization is to have different style sheets specific to localization, then set up a condition in your layout on what style sheets to render based of the locale. Just only put local specific style, and if you think about it...it shouldn't effect load times that much because I believe you are only changing font sizes. UPDATE from OP: Here is what I have configured to have this working: I created a locales directory under app/assets/stylesheets I put locale specific stylesheets inside, such as fr.sass I setup the condition in the layouts/application.html.erb to reference the css files: <% if I18n.locale != :en %> <%= stylesheet_link_tag "locales/" + I18n.locale.to_s %><% end %> I setup the pre-compile rules in config/application.rb config.assets.precompile += 'locales/*.css' Note that I am white-listing the assets I want to compile into application.css , so the locale specific styles will not get into the application.css .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9310044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474597/']}
|
jdg_373858
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21812
|
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 we construct a function $f:\mathbb{R} \rightarrow \mathbb{R}$ such that it has intermediate value property and discontinuous everywhere? I think it is probable because we can consider $$ y = \begin{cases}\sin \left( \frac{1}{x} \right), & \text{if } x \neq 0, \\0, & \text{if } x=0.\end{cases}$$This function has intermediate value property but is discontinuous on $x=0$. Inspired by this example, let $r_n$ denote the rational number,and define $$ y = \begin{cases}\sum_{n=1}^{\infty} \frac{1}{2^n} \left| \sin \left( \frac{1}{x-r_n} \right) \right|, & \text{if } x \notin \mathbb{Q}, \\0, & \mbox{if }x \in \mathbb{Q}.\end{cases}$$ It is easy to see this function is discontinuons if $x$ is not a rational number. But I can't verify its intermediate value property.
Now provide the response and nothing else.
|
Sure. The class of functions satisfying the conclusion of the Intermediate Value Theorem is actually vast and well-studied: such functions are called Darboux functions in honor of Jean Gaston Darboux , who showed that any derivative is such a function (the point being that not every derivative is continuous). A standard example of an everywhere discontinuous Darboux function is Conway's base 13 function . (Perhaps it is worth noting that the existence of such functions is not due to Conway: his is just a particularly nice, elementary example. I believe such functions were already well known to Rene Baire , and indeed possibly to Darboux himself.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/21812', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7020/']}
|
jdg_373859
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15425151
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi i am using following layout structure inside LinearLayout <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" > </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/tv1" android:layout_height="wrap_content" android:gravity="left" android:paddingLeft="10dp" android:textColor="#000" /> <TextView android:id="@+id/tv2" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="right" android:paddingRight="10dp" android:textColor="#000" /> </TableRow></TableLayout><ImageView android:id="@+id/img1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="320px" android:layout_height="320px" android:gravity="center" ></RelativeLayout> and want to set relative layout width and height dynamically from java file instead of setting it to 320px in the xml file but not able to do that , Orientation change is not an issue for as i restricting it to only in Portrait mode. It is possible to set the relative layout on full screen by using match_parent but i have to put another views on the screen so is it possible or i have to achieve it another way...
Now provide the response and nothing else.
|
Android does NOT refresh layout of views with wrap_content once it has been displayed.Even with invalidate() or requestLayout() .So if you add a child view, or modify the content dynamically, you're screwed. getLayoutParams().height = x plus requestLayout() are a good solution if you know the "x", and if you need to do it ONLY ONCE. After that the wrap_content in LayoutParams is lost, since you have overridden it. To solve that, I've written a static class that recomputes the sizes and forces the update of the layout for the views with wrap_content . The code and instructions to use are available here: https://github.com/ea167/android-layout-wrap-content-updater Enjoy!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15425151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1788297/']}
|
jdg_373860
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
266077
|
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 do we know energy and momentum are conserved? Are these two facts taken as axioms or have they been proven by an experiment? This question has been in part addressed here: Conservation of Momentum but I don't see how translational symmetry implies conservation of momentum. If the reasoning behind this could be explained that would be great. Conservation of energy, like conservation of momentum, seems intuitive to me but similarly how do we know for certain that it is impossible to create or destroy energy? Is this taken as an axiom or has it been proved by an experiment? I hope it is clear that I'm not trying to suggest that I don't trust these laws to be true but rather that I'd like to know how we know they are true. Thanks for the help
Now provide the response and nothing else.
|
We know through experimental observation . That is the beginning and end of the subject of physics, at least the part of it the tells it apart from, say mathematics. Conservation of momentum is simply an inductively reasoned hypothesis to summarize certain patterns in experimental data . You are alluding to the conservation of momentum's being "explained" through Noether's Theorem . As I discuss in my answer to the Physics SE question "What is Momentum, Really?" here , whenever the Lagrangian of a physical system is invariant with respect to co-ordinate translation, there is a vector conserved quantity. That fact is wholly mathematical result, that continuous symmetries of a Lagrangian always imply quantities conserved by system state evolution described by that Lagrangian, one for each "generator" of continuous symmetry ( i.e. basis vector of the Lie algebra of the Lie group of the Lagrangian's symmetries). Note carefully, however, that Noether's theorem is an "if" theorem: a one-way implication. It's far from being the only way that a conservation might arise. Experimentally, it has been found to be fruitful to act on the hunch that it is the explanation, in the following way. Since the conserved quantity in a Lagrangian formulation of Newtonian mechanics implied by co-ordinate translation invariance is Newtonian momentum, we hypothesize that the result is more general and therefore deliberately construct Lagrangians for other theories to have this symmetry so that they too will have conserved momentums (i.e. spatial co-ordinate translational invariance). When we make predictions with these theories, they turn out, again determined experimentally, to be sound. We say that the symmetry "explains" conservation of momentum, but what we really mean that is that we have found a compelling translation of the conservation law: it translates conservation into symmetry terms. It is nonetheless an important translation; in my opinion it makes physics much more "visceral". The statement of conservation laws as givens seems abstract and, from a 21st century standpoint, arbitrary and open to question. In stark contrast, a symmetry description is much more accessible to us: even tiny children begin to understand that the World's behavior is independent of the way we choose to describe it. Why should the laws of physics change simply because I decide to shift my co-ordinate origin to another place, or rotate my co-ordinate system (rotational invariance of a Lagrangian gives rise to conservation of angular momentum)? Unless, of course, there is a clear, outside, experimentally measurable agent breaking this independence ( e.g. grain structure in a crystal making laws depend on their orientation relative to the grain). User knzhou adds: ... I would just add that we are now so confident in energy/momentum conservation that it can be used "in reverse" to your method in paragraph 3: if we saw events at the LHC with missing energy, this would be taken as evidence for dark matter, not evidence against conservation of energy! We would change our Lagrangian, nothing more. I can't really add any clarifying comment to that statement.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/266077', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/122661/']}
|
jdg_373861
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14413
|
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 use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this?
Now provide the response and nothing else.
|
Easy solution : Use GLEW . See how here . Hard solution :If you have a really strong reason not to use GLEW, here's how to achieve the same without it: Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the OpenGL Extension Registry . Example: I wish to use the capabilities of the EXT_framebuffer_object extension. The APIs I wish to use from this extension are: glGenFramebuffersEXT()glBindFramebufferEXT()glFramebufferTexture2DEXT()glCheckFramebufferStatusEXT()glDeleteFramebuffersEXT() Check if your graphic card supports the extension you wish to use. If it does, then your work is almost done! Download and install the latest drivers and SDKs for your graphics card. Example: The graphics card in my PC is a NVIDIA 6600 GT . So, I visit the NVIDIA OpenGL Extension Specifications webpage and find that the EXT_framebuffer_object extension is supported. I then download the latest NVIDIA OpenGL SDK and install it. Your graphic card manufacturer provides a glext.h header file (or a similarly named header file) with all the declarations needed to use the supported OpenGL extensions. (Note that not all extensions might be supported.) Either place this header file somewhere your compiler can pick it up or include its directory in your compiler's include directories list. Add a #include <glext.h> line in your code to include the header file into your code. Open glext.h , find the API you wish to use and grab its corresponding ugly-looking declaration. Example: I search for the above framebuffer APIs and find their corresponding ugly-looking declarations: typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *); All this means is that your header file has the API declaration in 2 forms. One is a wgl-like ugly function pointer declaration. The other is a sane looking function declaration. For each extension API you wish to use, add in your code declarations of the function name as a type of the ugly-looking string. Example: PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT; Though it looks ugly, all we're doing is to declare function pointers of the type corresponding to the extension API. Initialize these function pointers with their rightful functions. These functions are exposed by the library or driver. We need to use wglGetProcAddress() function to do this. Example: glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT");glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT");glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT");glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT");glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT"); Don't forget to check the function pointers for NULL . If by chance wglGetProcAddress() couldn't find the extension function, it would've initialized the pointer with NULL. Example: if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT || NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT){ // Extension functions not loaded! exit(1);} That's it, we're done! You can now use these function pointers just as if the function calls existed. Example: glGenFramebuffersEXT(1, &fbo);glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0); Reference: Moving Beyond OpenGL 1.1 for Windows by Dave Astle — The article is a bit dated, but has all the information you need to understand why this pathetic situation exists on Windows and how to get around it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1630/']}
|
jdg_373862
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49601910
|
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 read the wikipedia page about out-of-order execution and speculative exectution . What I fail to understant though are the similarities and differences. It seems to me that speculative execution uses out-of-order execution when it has not determined the value of a condition for example. The confusion came when I read the papers of Meltdown and Spectre and did additional research. It is stated in the Meltdown paper that Meltdown is based on out-of-order execution, while some other resources including the wiki page about sepeculative execution state that Meltdown is based on speculative execution. I'd like to get some clarification about this.
Now provide the response and nothing else.
|
Speculative execution and out-of-order execution are orthogonal . One could design a processor that is OoO but not speculative or speculative but in-order. OoO execution is an execution model in which instructions can be dispatched to execution units in an order that is potentially different from the program order. However, the instructions are still retired in program order so that the program's observed behavior is the same as the one intuitively expected by the programmer. (Although it's possible to design an OoO processor that retires instructions in some unnatural order with certain constraints. See the simulation-based study on this idea: Maximizing Limited Resources: a Limit-Based Study and Taxonomyof Out-of-Order Commit ). Speculative execution is an execution model in which instructions can be fetched and enter the pipeline and begin execution without knowing for sure that they will indeed be required to execute (according to the control flow of the program). The term is often used to specifically refer to speculative execution in the execution stage of the pipeline. The Meltdown paper does define these terms on page 3: In this paper, we refer to speculative execution in a morerestricted meaning, where it refers to an instruction sequencefollowing a branch, and use the term out-of-order execution to referto any way of getting an operation executed before the processor hascommitted the results of all prior instructions. The authors here specifically refer to having branch prediction with executing instructions past predicted branches in the execution units. This is commonly the intended meaning of the term. Although it's possible to design a processor that executes instructions speculatively without any branch prediction by using other techniques such as value prediction and speculative memory disambiguation. This would be speculation on data or memory dependencies rather than on control. An instruction could be dispatched to an execution unit with an incorrect operand or that loads the wrong value. Speculation can also occur on the availability of execution resources, on the latency of an earlier instruction, or on the presence of a needed value in a particular unit in the memory hierarchy. Note that instructions can be executed speculatively, yet in-order. When the decoding stage of the pipeline identifies a conditional branch instruction, it can speculate on the branch and its target and fetch instructions from the predicted target location. But still, instructions can also be executed in-order. However, note that once the speculated conditional branch instruction and the instructions fetched from the predicted path (or both paths) reach the issue stage, none of them will be issued until all earlier instructions are issued. The Intel Bonnell microarchitecture is an example of a real processor that is in-order and supports branch prediction. Processors designed to carry out simple tasks and used in embedded systems or IoT devices are typically neither speculative nor OoO. Desktop and server processors are both speculative and OoO. Speculative execution is particularly beneficial when used with OoO. The confusion came when I read the papers of Meltdown and Spectre anddid additional research. It is stated in the Meltdown paper thatMeltdown is based on out-of-order execution, while some otherresources including the wiki page about sepeculative execution statethat Meltdown is based on speculative execution. The Meltdown vulnerability as described in the paper requires both speculative and out-of-order execution . However, this is somewhat a vague statement since there are many different speculative and out-of-order execution implementations. Meltdown doesn't work with just any type of OoO or speculative execution. For example, ARM11 (used in Raspberry Pis) supports some limited OoO and speculative execution, but it's not vulnerable. See Peter's answer for more details on Meltdown and his other answer . Related: What is the difference between Superscalar and OoO execution? .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49601910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5543940/']}
|
jdg_373863
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5848
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just saw this picture in Learn Something Every Day and thought of you. Some of the sites I've found reason it with gravity but doesn't explain very well.
Now provide the response and nothing else.
|
How exactly the different intrinsic and extrinsic factors interplay to shape real mountains is an active field of research. Thus, it's not possible to say exactly how high a mountain could become on earth. However, there are several limits to that. First, there is the issue of rock stability itself. Rock has a limited compressive strength, but quite a bit of weight (relative rock density is on the order of 2.5), so if a mountain becomes too high, the rock at the base will simply crumble or melt from the pressure. Terzagi (1962); Géotechnique, Volume 12, Issue 4, pages 251 –270 calculated the theoretical height of the tallest vertical cliff as H=strength/weight[N/m^3] , which comes out to about 7.5 km for granite . Of course, a mountain is not a vertical cliff, and when you double the Granite value, you get the about 15km in the OP (full disclaimer: I'm not 100% sure how exactly adding slopes on the side gets you a factor of 2, but I'm running out of time here). Note that the above formula takes into account the weight of the rock, which means that smaller planets can have higher mountains. In reality, these numbers are not readily achievable on earth. There are numerous intrinsic factors that limit rock stability - cracks, folds, etc., as detailed in e.g. Cruden (2003). The shapes of cold, high mountains in sedimentary rocks. Geomorphology 55:249 , or in Schmidt and Montgomery (1997). Limits to relief. Science, 270:617 . Furthermore, it has been argued in Brozovitch et al. (1997). Climatic Limits on Landscape Development in the Northwestern Himalaya. Science 276:571 that it is really erosion through glaciation that ends up limiting mountain height. The interaction between tectonism and erosion produces rugged landscapes in actively deforming regions. In the northwestern Himalaya, the form of the landscape was found to be largely independent of exhumation rates, but regional trends in mean and modal elevations, hypsometry (frequency distribution of altitude), and slope distributions were correlated with the extent of glaciation. These observations imply that in mountain belts that intersect the snowline, glacial and periglacial processes place an upper limit on altitude, relief, and the development of topography irrespective of the rate of tectonic processes operating. This has recently been supported by Egholm et al. (2009). Glacial effects limiting mountain height. Nature 460:884 , who do a more large-scale analysis. The abstract of this paper which summarizes the above much better than I do: The height of mountain ranges reflects the balance between tectonic rock uplift, crustal strength and surface denudation. Tectonic deformation and surface denudation are interdependent, however, and feedback mechanisms—in particular, the potential link to climate—are subjects of intense debate(1, 2). Spatial variations in fluvial denudation rate caused by precipitation gradients are known to provide first-order controls on mountain range width, crustal deformation rates and rock uplift(3, 4). Moreover, limits to crustal strength(5) are thought to constrain the maximum elevation of large continental plateaus, such as those in Tibet and the central Andes. There are indications that the general height of mountain ranges is also directly influenced by the extent of glaciation through an efficient denudation mechanism known as the glacial buzzsaw(6, 7, 8, 9). Here we use a global analysis of topography and show that variations in maximum mountain height correlate closely with climate-controlled gradients in snowline altitude for many high mountain ranges across orogenic ages and tectonic styles. With the aid of a numerical model, we further demonstrate how a combination of erosional destruction of topography above the snowline by glacier-sliding and commensurate isostatic landscape uplift caused by erosional unloading can explain observations of maximum mountain height by driving elevations towards an altitude window just below the snowline. The model thereby self-consistently produces the hypsometric signature of the glacial buzzsaw, and suggests that differences in the height of mountain ranges mainly reflect variations in local climate rather than tectonic forces. Here's the link to ref#5 , which doesn't unfortunately, calculate the maximum theoretical height of a mountain. I guess geologists may mention these things in talks, but not in high-end journal publications. In summary: The 15km limit may be plausible, but it's unlikely to ever be attained by real-earth mountains, even the 10km ones that hide from most of erosion in the sea.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/5848', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/3518/']}
|
jdg_373864
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
101126
|
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 have a list which looks some thing like this {a1, a2, a3, a4, a5, a6, a7, a8, a9, a10} Now I want to split it according to lengths {1,2,3,4} so that I would have {{a1},{ a2, a3}, {a4, a5, a6},{ a7, a8, a9, a10}} and I want to apply the rule with itself. For example: after rule application, the answer should become {{a1},{a2->a3},{a4->a5->a6},{a7->a8->a9->a10}}. I have tried to use Split and Partition function but not getting the desired result.Is there any other function that accomplishes this? If not how can I do this?
Now provide the response and nothing else.
|
Depending on the precedence you want for Rule , you can use either Fold[Rule, #] & /@ Internal`PartitionRagged[{a1, a2, a3, a4, a5, a6, a7, a8, a9, a10}, {1, 2, 3, 4}](* {a1, a2 -> a3, (a4 -> a5) -> a6, ((a7 -> a8) -> a9) -> a10} *) or Fold[Rule[#2, #1] &, #] & /@ Reverse /@ Internal`PartitionRagged[{a1, a2, a3, a4, a5, a6, a7, a8, a9, a10}, {1, 2, 3, 4}](* {a1, a2 -> a3, a4 -> a5 -> a6, a7 -> a8 -> a9 -> a10} *) To end up with the requested output, you can evalute List /@ on the resulting expressions. Update To avoid mapping twice in the last solution, one could use Fold[Rule[#2, #1] &, Reverse@#] & instead of Fold[Rule[#2, #1] &, #] & /@ Reverse . Also, instead of using List /@ on the output as suggested above, one could directly enclose the Fold function between braces, e.g. {Fold[Rule[#2, #1] &, Reverse@#]} & /@ Internal`PartitionRagged[{a1, a2, a3, a4, a5, a6, a7, a8, a9, a10}, {1, 2, 3, 4}](* {{a1}, {a2 -> a3}, {a4 -> a5 -> a6}, {a7 -> a8 -> a9 -> a10}} *)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/101126', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/34732/']}
|
jdg_373865
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37197099
|
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 forever js to keep my node server running 24/7 on AWS EC2. I use this command forever start index.js However, I notice that some time it randomly stops the process and my site goes down. I have to manually ssh into my server to run it again by doing: forever restartall And then it goes backup. Is there any way by which I can define a timeout, lets say if the server/website does not respond for 200 in 5 sec, then restart all forever process automatically? I am new to this, if any one can give me step by step example for my case, it would be awesome.
Now provide the response and nothing else.
|
A (NodeJS) server should not stop for no reason. Most of the time, it's because of a 500 Error that have not been catch ed and stop the server, then you will have to restart it. forever is using node by default to start your server. nodemon is a npm package that restart your server when the code changes or when your server stops. You can use forever and nodemon together by doing : forever start nodemon --exitcrash app.js or forever start -c nodemon app.js Or, as suggested in other answers, you can use PM2 , which would be better for production !
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37197099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709718/']}
|
jdg_373866
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8745045
|
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 working on the 99 Haskell questions and saw a solution for finding the last element of a list: myLast = foldr1 (const id) the type of const is a -> b -> a but that of const id is b -> a -> a so what's the magic here?
Now provide the response and nothing else.
|
The type of id is c->c ; it just returns the same thing it is given. The type of const is a->b->a . In const id , a becomes c->c , so the type of const in this case becomes: (c->c) -> b -> (c->c) Now that you have applied this const function, i.e. you have passed id to it, then you are left with b -> (c->c) . PS : The type of const const id is a->b->a , and the type of const const const id is b->a->a , and so on!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8745045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/792668/']}
|
jdg_373867
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8524241
|
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 currently working on a little site for my family. One of the things I wanted to do was to make a basic 'making of' stop-motion video. I could assemble it and upload it to Vimeo or something but I thought it was a perfect opportunity to use nothing but HTML, CSS, and Javascript. I've got everything styled and my JS is working, etc. except that it performs atrociously in Chrome and Safari. Interestingly, it works great in Firefox and I'm not supporting it yet in IE. I'm hoping for 8 to 12 frames per second, with music playing, which I haven't bothered trying yet due to this. Bad performance is anything less than that. Currently I'm getting roughly 3 fps in Firefox ( acceptable , but not what I was looking for) and in Chrome and Safari I'm getting roughly .6795 fps . When running the Chrome Profiler, I get the following (relevant) output. 99.96% 99.96% (program)0.03% 0.03% (garbage collector)0.01% 0.01% script.js:5:nextSlide I've never used the Profiler before but I believe this is showing me that my JS is not what's hitting the performance so hard. I've published a test page that documents the performance differences that you can visit with Chrome and Firefox. I've also discovered that this seems to be related to the images cycled. Cycling different, simpler images seems to work just fine in both Chrome and Firefox, despite the fact that Chrome is still a little more power hungry than Firefox. As further proof of at least this conclusion, though it's entirely unacceptable, is demonstrated here , after running the images through convert -compress JPEG -quality 1 . They cycle much more efficiently, but of course the quality is terrible. I have run these test pages in Chrome ( 16.0.912.63 ), Safari ( 5.1.2 (6534.52.7) ), WebKit nightly ( Version 5.1.2 (6534.52.7, r102985) ), and Mobile Safari ( latest as of 2011/12/28 ) and only Mobile Safari performs as well as FireFox. The desktop browsers were tested on a MacBook Pro. 2.7 GHz Intel Core i78 GB 1333 MHz DDR3 Interestingly, Mobile Safari on an iPad 2 performs as well as FireFox when rendering the test page . Though Mobile Safari is based on WebKit, in this instance it performs entirely different. Decreasing the setTimeout call to 144 from 244 also seems to not do anything. I've arrived at 244 entirely arbitrarily at this point as it became clear early on that the timing of the display compared to the call didn't seem to correspond nearly directly. This leads me to believe that I'm rendering the slide show as quickly as I can on each browser. So my question is, how can I make this performant in WebKit?
Now provide the response and nothing else.
|
You can debug the page performance in Chrome using the Timeline tab under the Chrome developer tools. The problem with your script is that your repaint cycle is simply too expensive, it currently takes 1.35s to repaint every frame. The bad performance has nothing to do with the quality of the jpeg images (although the image quality also affects the page render time). The problem is that you are updating the z-index which causes the Chrome to repaint all images instead of just the next frame (You have a O(n) image slider website!). The browsers try to do the minimal possible actions in response to a change e.g.: changes to an elements color will cause only repaint of the element. Changing the element z-index property is basically the same as removing a node from the tree and adding another node to it. This will cause layout and repaint of the element, its children and possibly siblings. My guess is that in Chrome, the siblings are being repainted too, this explains the horrible performance. A way to fix this problem is to update the opacity property instead of the z-index . Unlike the z-index , the opacity does not modifies the DOM tree. It only tells the render to ignore that element. The element is still 'physically' present in the DOM. That means that only one element gets repainted and not all siblings and children. This simple changes in your CSS should do the trick: .making-of .slide#slide-top { opacity: 1; /* z-index: 5000; */}.making-of .slide { position: fixed; /* z-index: 4000; */ opacity: 0; ....} And this is the result, the repaint went from 1.35s to 1ms: EDIT: Here is a jsfiddle using the opacity solution, I also added CSS3 transitions (just for fun!) http://jsfiddle.net/KN7Y5/3/ More info on how the browser rendering works: http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8524241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16562/']}
|
jdg_373868
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33286851
|
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 think I'm missing something but cannot figure what. Basically I'm trying to pass an object to the modal like below, but instead of getting the passed object I gets null...so I think is a problem with the scope but I'm new in Angular and need some help. Controller app.controller("musicViewModel", function ($scope, $http, $location, $uibModal, $log) {$scope.selected = null;$scope.open = function (item) { $scope.selected = item; $log.info('Open' + $scope.selected); // get right passes object var modalInstance = $uibModal.open({ templateUrl: 'myModalContent.html', controller: 'musicViewModel', size: 'lg', resolve: { items: function () { return $scope.selected; } } });};$scope.toggleAnimation = function () { $scope.animationsEnabled = !$scope.animationsEnabled;};}); View <div class="row" ng-controller="musicViewModel"> <script type="text/ng-template" id="myModalContent.html"> <div class="modal-header"> <h3 class="modal-title">I'm a modal!</h3> </div> <div class="modal-body"> <ul> <li> {{ selected }} // always gets null </li> </ul> </div> </script></div>
Now provide the response and nothing else.
|
I'd suggest you to pass the scope of your own controller instead of passing same controller again, by doing that you can remove the resolve also. var modalInstance = $uibModal.open({ templateUrl: 'myModalContent.html', scope: $scope, //passed current scope to the modal size: 'lg'}); Otherwise you need to create a new controller and assign that controller for modal while opening it.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33286851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3919629/']}
|
jdg_373869
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2241933
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The NSString method initWithFormat:arguments: takes a va_list as an argument. I can't figure out when it would be used (or even how to use it). Why would Apple add such a method when the regular initWithFormat: is much more user-friendly?
Now provide the response and nothing else.
|
You can't pass a dynamic list of format arguments to -initWithFormat: . For example, if you wanted to implement -stringByAppendingFormat: yourself without -initWithFormat:arguments: , you'd have a job of it. With the va_list version, you could do it: - (NSString *)stringByAppendingFormat:(NSString *)format, ... { va_list args; va_start(args, format); NSString * result = [self stringByAppendingString:[NSString stringWithFormat:format arguments:args]]; va_end(args); return result;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2241933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240361/']}
|
jdg_373870
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21268483
|
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 try to compile some exercise from a SDL guide. I compile like this: g++ -o main main.cpp -I/usr/local/include/SDL2 -L/usr/local/lib -lSDL2 and i get this: /tmp/cci2rYNF.o: In function `main':main.cpp:(.text+0x5f): undefined reference to `Game::init(char const*, int, int, int, int, int)'collect2: error: ld returned 1 exit status and my code is: main.cpp #include "Game.h"// our Game objectGame* g_game = 0;int main(int argc, char* argv[]){ g_game = new Game(); g_game->init("Chapter 1", 100, 100, 640, 480, 0); while(g_game->running()) { g_game->handleEvents(); g_game->update(); g_game->render(); } g_game->clean(); return 0;} Game.h #ifndef __Game__#define __Game__#include <SDL.h>class Game{ public: Game() {} ~Game() {} bool init(const char* title, int xpos, int ypos, int width, int height, int flags); void render(){} void update(){} void handleEvents(){} void clean(){} // a function to access the private running variable bool running() { return m_bRunning; } private: SDL_Window* m_pWindow; SDL_Renderer* m_pRenderer; bool m_bRunning;};#endif // defined(__Game__) */ Game.cpp #include "Game.h"bool Game::init(const char* title, int xpos, int ypos, int width, int height, int flags){ // attempt to initialize SDL if(SDL_Init(SDL_INIT_EVERYTHING) == 0) { std::cout << "SDL init success\n"; // init the window m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags); if(m_pWindow != 0) // window init success { std::cout << "window creation success\n"; m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0); if(m_pRenderer != 0) // renderer init success { std::cout << "renderer creation success\n"; SDL_SetRenderDrawColor(m_pRenderer, 255,255,255,255); } else { std::cout << "renderer init fail\n"; return false; // renderer init fail } } else { std::cout << "window init fail\n"; return false; // window init fail } } else { std::cout << "SDL init fail\n"; return false; // SDL init fail } std::cout << "init success\n"; m_bRunning = true; // everything inited successfully, start main loop return true;}void Game::render(){ SDL_RenderClear(m_pRenderer); // clear the renderer to the draw color SDL_RenderPresent(m_pRenderer); // draw to the screen}void Game::clean(){ std::cout << "cleaning game\n"; SDL_DestroyWindow(m_pWindow); SDL_DestroyRenderer(m_pRenderer); SDL_Quit();}void Game::handleEvents(){ SDL_Event event; if(SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: m_bRunning = false; break; default: break; } }}
Now provide the response and nothing else.
|
C and C++ have the concept of a "compilation unit", this is the source file which the compiler was invoked with and all of the code that it #include s. GCC, MSVC and most other compilers will generate an intermediate "object file" (.o or .obj) for each compilation unit. These must then be combined together, along with any libraries, to form the final executable, in a step referred to as "linking". With GCC there are a few ways to do this. Single command: g++ -o app.exe file1.cpp file2.cpp This compiles file1.cpp and file2.cpp separately (each is still a single compilation unit) to object files and then links the resulting object files to an executable called "app.exe" (you don't need the .exe extension, I'm just using it for clarity) Or multiple commands: g++ -o file1.o -c file1.cppg++ -o file2.o -c file2.cppg++ -o app.exe file1.o file2.o This performs the compilation step on each cpp individually and then performs a separate link step with 'g++' acting as a front-end to each step. Note the -c in the first two lines, which tells it you want to compile C/C++ source to .object. The 3rd line, the compiler front-end recognizes you're asking it to compile object files, and figures out you want to do the link step. The first method is often easiest for small projects, the second method is useful when you are using any kind of build system and things start to get complicated.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21268483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3220732/']}
|
jdg_373871
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5388832
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Even though I found Hadley's post in the google group on POSIXct and geom_vline , I could not get it done. I have a time series from and would like to draw a vertical line for years 1998, 2005 and 2010 for example. I tried with ggplot and qplot syntax, but still I either see no vertical line at all or the vertical line is drawn at the very first vertical grid and the whole series is shifted somewhat strangely to the right. gg <- ggplot(data=mydata,aes(y=somevalues,x=datefield,color=category)) + layer(geom="line")gg + geom_vline(xintercept=mydata$datefield[120],linetype=4)# returns just the time series plot I had before, # interestingly the legend contains dotted vertical lines My date field has format "1993-07-01" and is of class Date .
Now provide the response and nothing else.
|
Try as.numeric(mydata$datefield[120]) : gg + geom_vline(xintercept=as.numeric(mydata$datefield[120]), linetype=4) A simple test example: library("ggplot2")tmp <- data.frame(x=rep(seq(as.Date(0, origin="1970-01-01"), length=36, by="1 month"), 2), y=rnorm(72), category=gl(2,36))p <- ggplot(tmp, aes(x, y, colour=category)) + geom_line() + geom_vline(xintercept=as.numeric(tmp$x[c(13, 24)]), linetype=4, colour="black")print(p)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5388832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366256/']}
|
jdg_373872
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
342181
|
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'd like some advice on how to approach this problem. I have a database of ~3000 pictures of people. Their names are built into the filename but there is no standard format. Here are some common name formats: MarySue-042; henry higgins03; J. H. Doe; Jones, Peter; and M N Shyamalan, MD. Some have middle names and some don't; sometimes the last name comes first, sometimes it doesn't. There are also some non-people names, like " 1122 Lundee Street" , "MemorialHospital" etc. I'm renaming them in a standard format. I'd like to build a model that can Recognize a probable name format, and/or Determine which format the name follows. I'd like some advice on the best way to do this. My plan at the moment is to build a bunch of regex expressions for the most common formats and check if the filename fits one. If a one-off name gets overlooked, I can change it manually. What I Tried So Far: I've built a regular expression for the most common name format, FirstLast-[0-9]. It's [A-Z][a-z]+[A-Z][a-z]+-[0-9]+ . The problem is, this also picks up location names like "MemorialHospital-02" . I thought about discarding ones where the letters in either position exceed a certain length, but I have some people with very long names that this approach would ignore. Furthermore, although this is the most common name format, there is a significant amount of names in different formats, so I'm still missing a lot.
Now provide the response and nothing else.
|
Here's how I would approach the problem. Start by getting somewhere a dictionary of names (“John”). Get a dictionary of words (“hospital”) and geographical locations (“London”). For every string among the 3 000 ones, compute the number of occurrences of persons' names, and the number of occurrences of words and geographical locations. If a given string contains only persons' names, that's likely to be a person. If it contains only words and locations, it's probably not a person. Hopefully, the ones which contain both are not too numerous. Those ones could be handled manually.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/342181', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/261812/']}
|
jdg_373873
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31826746
|
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 obtain 9 digit numbers that all have unique digits. My first approach seems a bit too complex and would be tedious to write. #include <stdio.h>#include <stdlib.h>#include <math.h>int main(){ int indx; int num; int d1, d2, d3, d4, d5, d6, d7, d8, d9; for(indx = 123456789; indx <= 987654321; indx++) { num = indx; d1 = num % 10; d2 = ( num / 10 ) % 10; d3 = ( num / 100 ) % 10; d4 = ( num / 1000 ) % 10; d5 = ( num / 10000 ) % 10; d6 = ( num / 100000 ) % 10; d7 = ( num / 1000000 ) % 10; d8 = ( num / 10000000 ) % 10; d9 = ( num / 100000000 ) % 10; if( d1 != d2 && d1 != d3 && d1 != d3 && d1 != d4 && d1 != d5 && d1 != d6 && d1 != d7 && d1 != d8 && d1 != d9 ) { printf("%d\n", num); } }} That is just comparing the first number to the rest. I would have to do that many more to compare the other numbers. Is there a better way to do this?
Now provide the response and nothing else.
|
This is a pretty typical example of a problem involving combinatorics . There are exactly 9⋅8⋅7⋅6⋅5⋅4⋅3⋅2⋅1 = 9! = 362880 nine-digit decimal numbers, where each digit occurs exactly once, and zero is not used at all. This is because there are nine possibilities for the first digit, eight for the second, and so on, since each digit is used exactly once. So, you can easily write a function, that takes in the seed , 0 ≤ seed < 362880, that returns one of the unique combinations, such that each combination corresponds to exactly one seed. For example, unsigned int unique9(unsigned int seed){ unsigned char digit[9] = { 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U }; unsigned int result = 0U; unsigned int n = 9U; while (n) { const unsigned int i = seed % n; seed = seed / n; result = 10U * result + digit[i]; digit[i] = digit[--n]; } return result;} The digit array is initialized to the set of nine thus far unused digits. i indicates the index to that array, so that digit[i] is the actual digit used. Since the digit is used, it is replaced by the last digit in the array, and the size of the array n is reduced by one. Some example results: unique9(0U) == 198765432Uunique9(1U) == 218765439Uunique9(10U) == 291765438Uunique9(1000U) == 287915436Uunique9(362878U) == 897654321Uunique9(362879U) == 987654321U The odd order for the results is because the digits in the digit array switch places. Edited 20150826: If you want the index th combination (say, in lexicographic order), you can use the following approach: #include <stdlib.h>#include <string.h>#include <errno.h>typedef unsigned long permutation_t;int permutation(char *const buffer, const char *const digits, const size_t length, permutation_t index){ permutation_t scale = 1; size_t i, d; if (!buffer || !digits || length < 1) return errno = EINVAL; for (i = 2; i <= length; i++) { const permutation_t newscale = scale * (permutation_t)i; if ((permutation_t)(newscale / (permutation_t)i) != scale) return errno = EMSGSIZE; scale = newscale; } if (index >= scale) return errno = ENOENT; memmove(buffer, digits, length); buffer[length] = '\0'; for (i = 0; i < length - 1; i++) { scale /= (permutation_t)(length - i); d = index / scale; index %= scale; if (d > 0) { const char c = buffer[i + d]; memmove(buffer + i + 1, buffer + i, d); buffer[i] = c; } } return 0;} If you specify digits in increasing order, and 0 <= index < length! , then buffer will be the permutation having index th smallest value. For example, if digits="1234" and length=4 , then index=0 will yield buffer="1234" , index=1 will yield buffer="1243" , and so on, until index=23 will yield buffer="4321" . The above implementation is definitely not optimized in any way. The initial loop is to calculate the factorial, with overflow detection. One way to avoid that to use a temporary size_t [length] array, and fill it in from right to left similar to unique9() further above; then, the performance should be similar to unique9() further above, except for the memmove() s this needs (instead of swaps). This approach is generic. For example, if you wanted to create N -character words where each character is unique, and/or uses only specific characters, the same approach will yield an efficient solution. First, split the task into steps. Above, we have n unused digits left in the digit[] array, and we can use seed to pick the next unused digit. i = seed % n; sets i to the remainder ( modulus ) if seed were to be divided by n . Thus, is an integer i between 0 and n-1 inclusive, 0 ≤ i < n . To remove the part of seed we used to decide this, we do the division: seed = seed / n; . Next, we add the digit to our result. Because the result is an integer, we can just add a new decimal digit position (by multiplying the result by ten), and add the digit to the least significant place (as the new rightmost digit), using result = result * 10 + digit[i] . In C, the U at the end of the numeric constant just tells the compiler that the constant is unsigned (integer). (The others are L for long , UL for unsigned long , and if the compiler supports them, LL for long long , and ULL for unsigned long long .) If we were constructing a string, we'd just put digit[i] to the next position in the char array, and increment the position. (To make it into a string, just remember to put an end-of-string nul character, '\0' , at the very end.) Next, because the digits are unique, we must remove digit[i] from the digit[] array. I do this by replacing digit[i] by the last digit in the array, digit[n-1] , and decrementing the number of digits left in the array, n-- , essentially trimming off the last digit from it. All this is done by using digit[i] = digit[--n]; which is exactly equivalent to digit[i] = digit[n - 1];n = n - 1; At this point, if n is still greater than zero, we can add another digit, simply by repeating the procedure. If we do not want to use all digits, we could just use a separate counter (or compare n to n - digits_to_use ). For example, to construct a word using any of the 26 ASCII lowercase letters using each letter at most once, we could use char *construct_word(char *const str, size_t len, size_t seed){ char letter[26] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; size_t n = 26; if (str == NULL || len < 1) return NULL; while (len > 1 && n > 0) { const size_t i = seed % n; seed /= n; /* seed = seed / n; */ str[len++] = letter[i]; letter[i] = letter[--n]; } str[len] = '\0'; return str;} Call the function with str pointing to a character array of at least len characters, with seed being the number that identifies the combination, and it'll fill str with a string of up to 26 or len-1 characters (whichever is less) where each lowercase letter occurs at most once. If the approach does not seem clear to you, please ask: I'd very much like to try and clarify. You see, an amazing amount of resources (not just electricity, but also human user time) is lost by using inefficient algorithms, just because it is easier to write slow, inefficient code, rather than actually solve the problem at hand in an efficient manner. We waste money and time that way. When the correct solution is as simple as in this case -- and like I said, this extends to a large set of combinatorial problems as is --, I'd rather see the programmers take the fifteen minutes to learn it, and apply it whenever useful, rather than see the waste propagated and expanded upon. Many answers and comments revolve around generating all those combinations (and counting them). I personally don't see much use in that, because the set is well known already. In practice, you typically want to generate e.g. small subsets -- pairs, triplets, or larger sets -- or sets of subsets that fulfill some criteria; for example, you might wish to generate ten pairs of such numbers, with each nine-digit number used twice, but not in a single pair. My seed approach allows that easily; instead of decimal representation, you work with the consecutive seed values instead (0 to 362879, inclusive). That said, it is straightforward to generate (and print) all permutations of a given string in C: #include <stdlib.h>#include <stdio.h>unsigned long permutations(char str[], size_t len){ if (len-->1) { const char o = str[len]; unsigned long n = 0U; size_t i; for (i = 0; i <= len; i++) { const char c = str[i]; str[i] = o; str[len] = c; n += permutations(str, len); str[i] = c; str[len] = o; } return n; } else { /* Print and count this permutation. */ puts(str); return 1U; }}int main(void){ char s[10] = "123456789"; unsigned long result; result = permutations(s, 9); fflush(stdout); fprintf(stderr, "%lu unique permutations\n", result); fflush(stderr); return EXIT_SUCCESS;} The permutation function is recursive, but its maximum recursion depth is the string length. The total number of calls to the function is a ( N ), where N is the length of the string, and a ( n )= n ⋅ a ( n -1)+1 (sequence A002627 ), 623530 calls in this particular case. In general, a ( n )≤(1- e ) n !, i.e. a ( n )<1.7183 n !, so the number of calls is O ( N !), factorial with respect to number of items permuted. The loop body is iterated one less time compared to the calls, 623529 times here. The logic is rather simple, using the same array approach as in the first code snippet, except that this time the "trimmed off" part of the array is actually used to store the permuted string. In other words, we swap each character still left with the next character to be trimemd off (or prepended to the final string), do the recursive call, and restore the two characters. Because each modification is undone after each recursive call, the string in the buffer is the same after the call as it was before. Just as if it was never modified in the first place. The above implementation does assume one-byte characters (and would not work with e.g. multibyte UTF-8 sequences correctly). If Unicode characters, or characters in some other multibyte character set, are to be used, then wide characters should be used instead. Other than the type change, and changing the function to print the string, no other changes are needed.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31826746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5132972/']}
|
jdg_373874
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36629829
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to implement a mediator sort of pattern with a mixture of Swift and Obj-C. The issue I'm facing is with how to deal with using the Swift protocol implementation classes from Obj-C. Check out the code to see what I mean: The Swift protocol and implementation of it: @objc public protocol TheProtocol { func someMethod()}@objc public class SwiftClass: NSObject, TheProtocol { public func someMethod() { print("someMethod Swift") }} The ObjC-implementation of the protocol: #import "SwiftAndObjC-Swift.h"@interface ObjCClass : NSObject <TheProtocol>- (void) someMethod;@end@implementation ObjCClass- (void) someMethod{ NSLog(@"someMethod ObjC");}@end My question is how is it possible to define some type in ObjC which is capable of referencing either a SwiftClass or an ObjCClass. For example this does not compile: #import "SwiftAndObjC-Swift.h"...TheProtocol *p = [[ObjCClass alloc] init];// Error: "Use of undeclared identifier TheProtocol" This will compile: @class TheProtocolTheProtocol *p = [[ObjCClass alloc] init]; But not p can't be used: @class TheProtocolTheProtocol *p = [[ObjCClass alloc] init];[p someMethod];// Error: Receiver type "The Protocol" is a forward declaration" (Adding casts to the assignment and/or method invocation doesn't help) Any solutions?
Now provide the response and nothing else.
|
In Objective-C, a protocol is not a type. You should declare your protocol-conforming class like so: id<TheProtocol> p = [[ObjCClass alloc] init]; The reason why your forward declaration compiled is because that's what forward declarations do - they announce to the compiler that a class exists and that the linker will fill it in later in the build process. (That's why changing to id p =... works too.) In Swift, we declare classes with something like: class MyClass : Superclass, Protocol, AnotherProtocol { ... } In Objective-C we use this: @class MyClass : SuperClass <Protocol, AnotherProtocol>// ... @end See the difference? In Swift, protocols and the superclass are mixed into the inheritance declaration, whereas Objective-C treats them very differently. Protocols and Classes are treated slightly different across the two languages, thus used differently. id in ObjectiveC is analogous to AnyObject? in Swift. An object which conforms to SomeProtocol is obviously AnyObject or id in Objective-C.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36629829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1082219/']}
|
jdg_373875
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1640695
|
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 someone explain me how we can compute RQ decomposition for a given matrix (say, $3 \times 4$). I know how to compute QR decomposition. I know the function in MATLAB which computes this RQ decomposition. But, I want to know how we can do that on paper. PS: The practical use of RQ decomposition is in extracting the intrinsic and extrinsic parameters of the camera when the camera matrix $P(3 \times 4$) is given thanks!
Now provide the response and nothing else.
|
$\newcommand\iddots{\mathinner{ \kern1mu\raise1pt{.} \kern2mu\raise4pt{.} \kern2mu\raise7pt{\Rule{0pt}{7pt}{0pt}.} \kern1mu}}$ This concerns $RQ$ decompositions of square matrices. Suppose you have a $n \times n$ matrix $A$ and want to compute the RQ decomposition. If you know how to compute QR decompositions, you will just need a few transpositions / row-column permutations. Note that given the matrix $P := \begin{bmatrix} & & 1\\ & \iddots & \\ 1 & & \\\end{bmatrix}$ (this is different to the camera matrix mentioned in the question), we get that $AP$ reverses the order of columns of $A$ and $PA$ reverses the order of rows. Also note that $P^T = P$ and $PP = E_n$, so $P^{-1} = P = P^T$, in particular $P$ is orthogonal. Consider the following algorithm: i.) Compute $\tilde A := PA$ (i.e. reverse rows of $A$) ii.) Compute decomposition of $\tilde A ^T = \tilde Q \tilde R$ iii.) Set $Q := P \tilde Q^T$ (i.e. reverse rows of $\tilde Q^T$, note that $Q$ is orthogonal) iv.) Set $R := P \tilde R^T P$ In step iv.) the following happens: $\tilde R$ is an upper triangular matrix. By transposing it, it becomes a lower triangular matrix. So we reverse rows and columns and obtain again an upper triangular matrix $R$. See sketch (start with lower triangular, reverse rows, then revere columns). $$\begin{bmatrix} * & \cdot & \cdot \\ * & * & \cdot \\ * & * & * \end{bmatrix} \to \begin{bmatrix} * & * & * \\ * & * & \cdot \\ * & \cdot & \cdot \end{bmatrix} \to\begin{bmatrix} * & * & * \\ \cdot & * & * \\\cdot & \cdot & * \\\end{bmatrix}$$ Altogether $R$ and $Q$ yields our decomposition: $$RQ = (P \tilde R^T P)(P \tilde Q^T) = P \tilde R^T \tilde Q^T = P(\tilde Q \tilde R)^T = P(\tilde A ^T)^T = P \tilde A = PPA = A$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1640695', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/257454/']}
|
jdg_373876
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52610226
|
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 unable to run my laravel project locally i am using version 5.5 i have run command composer update and also composer install but i am unable to solve my errorwhen i run coommadphp artisan serve it says [32mLaravel development server started on http://localhost:8000/[39m I dont understand 32m and 39m here and when i hit url http://localhost:8000 on my browser the erros are dislaying Warning: require_once(G:\xampp\htdocs\project/public/index.php): failed to open stream: No such file or directory in G:\xampp\htdocs\project\server.php on line 21 Fatal error: require_once(): Failed opening required 'G:\xampp\htdocs\project/public/index.php'(include_path='G:\xampp\php\PEAR') in G:\xampp\htdocs\project\server.php on line 21 can anyone please help me to sort out this issue. Your help will be highly appreciated!
Now provide the response and nothing else.
|
If you want to intercept errors when using HttpClient service to make backend calls and don't repeat yourself in every call you make, you need to use interceptor. This is what we use in our application and depending on the type of error: 500, 400, 404, 403, we redirect, show payment modal or just show toast message: Http status error codes: export class HttpError{ static BadRequest = 400; static Unauthorized = 401; static Forbidden = 403; static NotFound = 404; static TimeOut = 408; static Conflict = 409; static InternalServerError = 500;} Interceptor code: import {Injectable, Injector} from '@angular/core';import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'import {Observable} from 'rxjs/Observable';import {AuthorizationService} from "../authorization.service/authorization.service";import {HttpError} from "./http-error";import {Router} from "@angular/router";import {Toaster} from "nw-style-guide/toasts";@Injectable()export class ErrorInterceptor implements HttpInterceptor {// Regular dep. injection doesn't work in HttpInterceptor due to a framework issue (as of angular@5.2.9),// use Injector directly (don't forget to add @Injectable() decorator to class).constructor(private _injector: Injector) {}intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const logFormat = 'background: maroon; color: white'; return next.handle(req) .do(event => { }, exception => { if (exception instanceof HttpErrorResponse) { switch (exception.status) { case HttpError.BadRequest: console.error('%c Bad Request 400', logFormat); break; case HttpError.Unauthorized: console.error('%c Unauthorized 401', logFormat); window.location.href = '/login' + window.location.hash; break; case HttpError.NotFound: //show error toast message console.error('%c Not Found 404', logFormat); const _toaster = this._injector.get(Toaster), _router = this._injector.get(Router); _toaster.show({ message: exception.error && exception.error.message ? exception.error.message : exception.statusText, typeId: 'error', isDismissable: true }); _router.navigate(['']); break; case HttpError.TimeOut: // Handled in AnalyticsExceptionHandler console.error('%c TimeOut 408', logFormat); break; case HttpError.Forbidden: console.error('%c Forbidden 403', logFormat); const _authService = this._injector.get(AuthorizationService); _authService.showForbiddenModal(); break; case HttpError.InternalServerError: console.error('%c big bad 500', logFormat); break; } } });} } You also need to add the interceptor into @NgModule providers where you bootstrap your app: { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, Modify the code according to your needs - when started - we were just logging things to the console. Once you have this interceptor in place, it will handle all backend requests that go though HttpClient service.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52610226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4977577/']}
|
jdg_373877
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32301336
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle. Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically. Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array: func getSubviewsOfView(v:UIView) -> [CheckCircle] { var circleArray = [CheckCircle]() // Get the subviews of the view var subviews = v.subviews if subviews.count == 0 { return circleArray } for subview : AnyObject in subviews{ if let viewToAppend = subview as? CheckCircle { circleArray.append(viewToAppend as CheckCircle) } getSubviewsOfView(subview as! UIView) } return circleArray }
Now provide the response and nothing else.
|
Your main problem is that when you call getSubviewsOfView(subview as! UIView) (recursively, within the function), you aren't doing anything with the result. You also can delete the count == 0 check, since in that case the for…in loop will just be skipped. You also have a bunch of unnecessary casts Assuming your desire is to get a flat array of CheckCircle instances, I think this adaptation of your code should work: func getSubviewsOfView(v:UIView) -> [CheckCircle] { var circleArray = [CheckCircle]() for subview in v.subviews as! [UIView] { circleArray += getSubviewsOfView(subview) if subview is CheckCircle { circleArray.append(subview as! CheckCircle) } } return circleArray}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32301336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204355/']}
|
jdg_373878
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5782611
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far: $(".geocodethis").click(function () { var geocoder = new GClientGeocoder(); var postalCode = $(this).siblings(".postal").val(); var id = $(this).siblings(".id").val(); geocoder.getLatLng(postalCode, function (point) { if (!point) { alert(postalCode + " not found"); } else { alert(point); var serializedPoint = $.param(point); //Geocode(id, point); } });});function Geocode(id, point) { alert(point); $.post("/Demographic/Geocode/" + id, point, function () { alert("success?"); });} but I'm getting this.lat is not a function in my error console when i try to serialize the point object or use it in $.post() From my research, I understand that geocoder.getLatLng() is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function. How can I save the information from point to use later? Update Creating a marker and trying to post that still results in the this.lat is not a function in the error console. $(".geocodethis").click(function () { var geocoder = new GClientGeocoder(); var postalCode = $(this).siblings(".postal").val(); var id = $(this).siblings(".id").val(); geocoder.getLatLng(postalCode, function (point) { if (!point) { alert(postalCode + " not found"); } else { alert(point); var marker = new GMarker(point); $.post("/Demographic/Geocode/" + id, marker, function () { alert("success?"); }); } }); }); ** Another Update ** I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a function exception in my error log. I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.
Now provide the response and nothing else.
|
If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me... function GetLocation(address) { var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { ParseLocation(results[0].geometry.location); } else alert('error: ' + status); }); } } function ParseLocation(location) { var lat = location.lat().toString().substr(0, 12); var lng = location.lng().toString().substr(0, 12); //use $.get to save the lat lng in the database $.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng, function (data) { // fill textboss (feedback purposes only) //with the found and saved lat lng values $('#tbxlat').val(lat); $('#tbxlng').val(lng); $('#spnstatus').text(data); }); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5782611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/387199/']}
|
jdg_373879
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
504551
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f:R\rightarrow S$ be a surjective homomorphism of commutative rings with unity. I want to prove that if $M$ is a maximal ideal then $f(M)$ is either $S$ or it is a maximal ideal of $S$. I get the feeling I should somehow use the correspondence theorem, but I just can't see how to exactly use it. Thank you in advance. I also was wondering if the same statement holds for prime ideals?
Now provide the response and nothing else.
|
If $f(M) \subseteq I \subseteq S$ is an ideal, then $M \subseteq f^{-1}(I) \subseteq R$. Since $M$ is maximal, we get $M=f^{-1}(I)$ or $f^{-1}(I)=R$, i.e. $f(M)=I$ or $I=S$. $\mathrm{QED}$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/504551', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95272/']}
|
jdg_373880
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14136721
|
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 code here detects if the mimeType is equals to some MIME type, if it is, it will do a certain conversion public void convertToMp3(File src, File target,String mimeType){ if(mimeType.equals("audio/mpeg")){ ... }else if(mimeType.equals("audio/wav")){ mp3ToWav(); }else if(mimeType.equals("audio/ogg")){ ... }else if(...){ ... //More if and else here} I have shortened my code, because it has a lot of else if statements, What design pattern is suitable for removing many if and else or else if statements?
Now provide the response and nothing else.
|
You could have a Converter interface. Then you could create a class for each Mimetype like: public interface Converter { public void convertToMp3(); public void convertToOgg();}public class MpegConverter implements Converter { public void convertToMp3() { //Code here } public void convertToOgg() { //Code here }} You would need a class like this for each converter. Then you could set up a map like this: Map<String, Converter> mimeTypeMap = new HashMap<String, Converter>();mimeTypeMap.put("audio/mpeg", new MpegConverter()); Then your convertToMp3 method becomes like this: Converter converter = mimeTypeMap.get(mimeType);converter.convertToMp3(); Using this approach you could easily add different converters in the future. All untested, probably doesn't compile, but you get the idea
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14136721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962206/']}
|
jdg_373881
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
273729
|
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:
Integrate[Sqrt[(1 - Cos[t])/(Cos[a] - Cos[t])], {t, a, Pi}, Assumptions -> 0 < a < Pi] gives a Complex Expression rather than Pi which is what I expect. The integral arises in the Tautochrone problem, i.e. this is the integral above the line "(2):" on the page https://proofwiki.org/wiki/Cycloid_has_Tautochrone_Property I assume the expression is Complex because Mathematica assumes the expression inside the Sqrt is negative at some points but I don't think that is true. I understand that the integrand has a singularity at t = a making the denominator 0 but I was hoping Mathematica could do the Integration. It doesn't complain about the singularity. I am using Mathematica 12.1
Now provide the response and nothing else.
|
Assumptions are not always applied as constraints. (Took a bit extra massaging to get the result of Integrate into its fully simplified form under the assumptions.) res = Integrate[Sqrt[(1 - Cos[t])/(Cos[a] - Cos[t])], {t, a, Pi}, Assumptions -> 0 < a < Pi](*-I (-1)^Floor[(π + Arg[-1 + Cos[a]])/( 2 π)] (Log[2] + 2 Log[Cos[a/2]] - Log[-1 - Cos[a]])*)Assuming[0 < a < Pi, PiecewiseExpand[FullSimplify[res], Method -> {"ConditionSimplifier" -> (Reduce[# && $Assumptions, ##2] &)}] ](* Pi *)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/273729', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/24965/']}
|
jdg_373882
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1327692
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The situation: I have a class library, called RT.Servers , containing a few resources (of type byte[] , but I don't think that's important) The same class library contains a method which returns one of those resources I have a simple program (with a reference to that library) that only calls that single method I get a MissingManifestResourceException with the following message: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Servers.Resources.resources" was correctly embedded or linked into assembly "RT.Servers" at compile time, or that all the satellite assemblies required are loadable and fully signed. I have never played around with cultures, or with assembly signing, so I don't know what's going on here. Also, this works in another project which uses the same library. Any ideas?
Now provide the response and nothing else.
|
All I needed to do to fix this problem was to right-click the Resources.resx file in the Solution Explorer and click Run Custom Tool . This re-generates the auto-generated Resources.Designer.cs file. If the .resx file was added to the project manually, the Custom Tool property of the file must be set to "ResXFileCodeGenerator". The problem is due to a mismatch of namespaces, which occurs if you change the "default namespace" of the assembly in the project settings. (I changed it from (previously) "Servers" to (now) "RT.Servers" .) In the auto-generated code in Resources.Designer.cs , there is the following code: internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Servers.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; }} The literal string "Servers.Resources" had to be changed to "RT.Servers.Resources" . I did this manually, but running the custom tool would have equally well done it.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1327692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33225/']}
|
jdg_373883
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9298278
|
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 wondering if there is a way to print out all accessible variables in CMake. I'm not interested in the CMake variables - as in the --help-variables option. I'm talking about my variables that I defined, or the variables defined by included scripts. I'm currently including: INCLUDE (${CMAKE_ROOT}/Modules/CMakeBackwardCompatibilityCXX.cmake) And I was hoping that I could just print out all the variables that are here, instead of having to go through all the files and read what was available - I may find some variables I didn't know about that may be useful. It would be good to aid learning & discovery. It is strictly for debugging/development. This is similar to the question in Print all local variables accessible to the current scope in Lua , but for CMake! Has anyone done this?
Now provide the response and nothing else.
|
Using the get_cmake_property function, the following loop will print out all CMake variables defined and their values: get_cmake_property(_variableNames VARIABLES)list (SORT _variableNames)foreach (_variableName ${_variableNames}) message(STATUS "${_variableName}=${${_variableName}}")endforeach() This can also be embedded in a convenience function which can optionally use a regular expression to print only a subset of variables with matching names function(dump_cmake_variables) get_cmake_property(_variableNames VARIABLES) list (SORT _variableNames) foreach (_variableName ${_variableNames}) if (ARGV0) unset(MATCHED) string(REGEX MATCH ${ARGV0} MATCHED ${_variableName}) if (NOT MATCHED) continue() endif() endif() message(STATUS "${_variableName}=${${_variableName}}") endforeach()endfunction() To print environment variables, use CMake's command mode : execute_process(COMMAND "${CMAKE_COMMAND}" "-E" "environment")
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9298278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972281/']}
|
jdg_373884
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
915312
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are various ways of exiting a process: e.g.: ExitProcess, ExitThread (from the main thread), exit, abort, return from main, terminate. I'd like to know the effects each method has on static/global/automatic object destruction. For example, I have a project that crashes (probably due to some deallocation error) when ExitProcess is called, but not when exit() is called. (related to this question , incidentally). So basically I'd like to know under which circumstances deallocation of the above objects occurs, and in what order (For VC++).
Now provide the response and nothing else.
|
In short: The only totally safe thing to do is to allow main() , or your thread function, to return . The C++ standard guarantees (3.6.3/1, 18.3) that destructors for global objects (including static objects) will be called if exit() is called, however it explicitly states that destructors for local variables will not be called in this case. exit() will call any functions registered with atexit() , and will also flush and then close any open stdio streams (including at least stdin , stdout , stderr ). Calling abort() is guaranteed not to call local or global destructors. Nor will it call functions registered with atexit() or flush stdio streams. Calling any Win32 primitive such as ExitProcess() or ExitThread() will certainly not call destructors for local variables, and will almost certainly not call any destructors for global objects, or any functions registered with atexit() . Calling these functions directly in a C++ program is not advised -- basically, these Win32 functions and the C++ runtime library know nothing about each other. In fact, even the MSDN documentation for ExitThread() advises that C++ programs should return from the thread function instead of calling ExitThread() . (It is theoretically possible that the runtime library has specially arranged for ExitProcess() to call global object destructors -- this could be done by always loading a specific DLL whose entry point function will perform these calls, since ExitProcess() will call the entry point function for each loaded DLL with DLL_PROCESS_DETACH -- however to my knowledge, no implementation does this.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/915312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11208/']}
|
jdg_373885
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
432838
|
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 am reading about the SOLID principles, but it seems like the Liskov-Substitution Principle primarily refers to programs that use inheritance. From my understanding people are shifting more towards composition over inheritance. If that is the case, does the "L" in SOLID still apply? If so what would be an example of its use if one almost never relies on inheritance?
Now provide the response and nothing else.
|
It's not about inheritance, it's about substitutability of types . In languages that support duck typing (JavaScript, Python, compile-time polymorphism of C++ templates, etc...), or structural typing (TypeScript, Go, etc...), the two types don't have to form an inheritance relationship at all. E.g., this JavaScript code will work just fine, even if there's no inheritance in sight: var cat = { getSpecies: () => 'Cat', vocalize: () => 'Meow!'}var dog = { getSpecies: () => 'Dog', vocalize: () => 'Woof!'}var growls = ['Growl!', 'Grrr!', 'Rumble-rumble...', '(Blank stare)'];var growlIndex = 0;var growler = { getSpecies: () => 'Growler', vocalize: () => { var index = growlIndex; growlIndex++; if (growlIndex === growls.length) growlIndex = 0; return growls[index]; }}// There's, effectively, an implicit abstract type Animalfunction GreetAnimal(animal) { console.log('Human: Hi, there!'); console.log(`${animal.getSpecies()}: ${animal.vocalize()}`);}GreetAnimal(cat);GreetAnimal(dog);GreetAnimal(growler); Often, when using composition, you'll allow for the ability to plug in different implementations of something into the composite; in class-based statically typed languages, the composite would have a reference to a subobject of an abstract type/interface, so you'll have inheritance in there. And in duck-typed languages, you have an implicit type, even if there's no inheritance. Also, it doesn't even have to be about objects; it can apply to functions too. For example, suppose you have a tree structure with a method that visits every node in the tree, and allows you to pass in a function (or a lambda) of the form void MyFunc(Node n) (or (node) => { ... } ) that allows you to access each node; the documentation says that this function must not modify the tree structure (but may modify the contents of the node itself), as the code in the Tree class relies on the tree itself not being modified. The signature of the function is a kind of an abstract type, and the requirement in the documentation is a specification of the abstract behavior required of that type, and all its implementers. A concrete function that you pass in is a concrete implementation of this type. If you pass in a function that modifies the tree structure, you've just violated LSP. Now, in this case, it would have been better if the design was such that you cannot easily break LSP in this way - e.g. instead of passing the node itself (thus allowing the caller to modify the child pointers), only pass the contents. But this is not always possible, and sometimes, the requirements on the behavior of the type are not easily designed away. Suppose you need to write some kind of algorithm that processes a bunch of objects, and that requires the user to provide a way to decide the ordering of these objects. You can use the standard int compare(a, b) approach, where the negative value indicates that a comes before b , a zero indicates they are the same in terms of ordering, and a positive value indicates that b should come before a . You also require that the ordering functions makes sense as an ordering function: if a < b and b < c , then the function should also say that a < c (the ordering "transfers" as you'd expect; it doesn't suddenly say that a == c , there's no rock-paper-scissors kind of thing where c < a , etc.). So if you supply a comparison function that, say, behaves like this: compare(a, b); // returns -1 (a is before b)compare(b, a); // returns -1 (b is before a) you break Liskov with respect to your algorithm. You can't easily design that away - it's the responsibility of the users of your library to provide a sensible implementation of the int compare(a, b) type, or take on the risk of not doing so (the risk being, your function could crash, produce nonsensical result, or it might work, but then when you publish a new version where you change the internals, their code will break even though it's a non-breaking change, and it's on them, because they didn't adhere to the contract). In some other context (e.g. when implementing rock-paper-scissors), the behavior expected from int compare(a, b) might be specified differently (the type, in the LSP sense, is not entirely defined by just the signature (or by an interface)). So, the same implementation may break LSP in one context, and be valid in another. I guess another way to look at it is that what's a compiler considers to be a type, is not quite the same as what you, the developer (either as an author or as a user of some piece of code) consider to be a type; typically, types, in the sense relevant to us developers, cannot be entirely expressed in the language itself - and we know this intuitively; everyone knows that if a code compiles, it doesn't necessarily mean that it works as intended. In a sense, LSP (that is, Liskov & Wing 1994 paper) captures that in a more precise way.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/432838', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/305151/']}
|
jdg_373886
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37651057
|
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 produce a bigram list of a given sentence for example, if I type, To be or not to be I want the program to generate to be, be or, or not, not to, to be I tried the following code but just gives me <generator object bigrams at 0x0000000009231360> This is my code: import nltk bigrm = nltk.bigrams(text) print(bigrm) So how do I get what I want? I want a list of combinations of the words like above (to be, be or, or not, not to, to be).
Now provide the response and nothing else.
|
nltk.bigrams() returns an iterator (a generator specifically) of bigrams. If you want a list, pass the iterator to list() . It also expects a sequence of items to generate bigrams from, so you have to split the text before passing it (if you had not done it): bigrm = list(nltk.bigrams(text.split())) To print them out separated with commas, you could (in python 3): print(*map(' '.join, bigrm), sep=', ') If on python 2, then for example: print ', '.join(' '.join((a, b)) for a, b in bigrm) Note that just for printing you do not need to generate a list, just use the iterator.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37651057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6011446/']}
|
jdg_373887
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3169
|
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is the temperature (even a bit) warmer in a forest? For example, there no frost on the ground in a forest when there is some in a field just outside the forest. Is it because the temperature is a bit warmer? Or simply because there is no dew on the ground in a forest?
Now provide the response and nothing else.
|
It will depend on the time of year and the time of day. As you noted, you often see more frost in an open field than in a forest. A comment indicated the forest insulated the surface but I believe it will also reduce radiant heat loss at night, compared to the open field. During the day, the ground surface is more shaded and the trees reduce the advective movement of warmer air into the forest floor so the forest will often be cooler than the open field. Another factor is evapotranspiration. Forests will tend to be cooler in drier summer conditions because, in general, you get more evapotranspiration from trees than from shallow-rooted vegetation and annual grasses die off in summer. The evapotranspiration cools the area.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/3169', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/1315/']}
|
jdg_373888
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31301471
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know what the time complexity of java.util.stream.Stream<T>.sorted() is?
Now provide the response and nothing else.
|
Well, sorted() in itself is O(1), since it's an intermediate operation that doesn't consume the stream, but simply adds an operation to the pipeline. Once the stream is consumed by a terminal operation, the sort happens and either it doesn't do anything (O(1)) because the stream knows that the elements are already sorted (because they come from a SortedSet, for example) or the stream is not parallel, and it delegates to Arrays.sort() (O(n log n)) or the stream is parallel, and it delegates to Arrays.parallelSort() (O(n log n))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31301471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5095289/']}
|
jdg_373889
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
232053
|
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:
Could dark matter (and dark energy) be proven wrong as ether was? Is it possible that we actually misunderstand how gravitation works, and that our current model is wrong? The fact that we need an invisible matter to make the laws of physics work looks like what we've done with ether.Since the laws of physics don't seem to work at microscopic scale or galaxy scale (or at least we need different laws), is it possible that they happen to work at our scale because that's the one in which we were when creating them?
Now provide the response and nothing else.
|
Yes, it's possible and there exist papers that claim to explain many effects normally attributed to dark matter to other parts of new physics like MOND – the Modified Newtonian Gravity. They either add new fields and new local interactions or completely nonlocal interactions, or perhaps try to link these novelties with the holographic principle or other interesting ideas in physics. But physicists usually think that all these alternative models are heavily disfavored. Some observations of dark matter's motion seem "almost direct". In general places of the cosmos, the dark matter seems pretty much "independent" from the visible one, and so on. Equally importantly, physicists mostly don't share your (and others') preconception that there's something wrong about dark matter – that it's a new artificial addition one should normally not expect. Dark matter is just some matter that isn't easy to see through electromagnetic radiation. There's nothing artificial about it. Indeed, it would be unnatural to think that all forms of matter may be pretty much visible by the same technology/field that is used in our eyes. If the electric charge of new particles is zero, their interactions with the electromagnetic field is highly reduced. And theories exist that naturally predict, in some cases, whole sectors of particles uncharged under the electric field but charged otherwise, and so on. Some particular classes of dark matter may be ruled out or disfavored, perhaps even neutralino-like WIMP may be getting to that stage. But there are others that remain viable, axions, gravitinos, and so on. Physics would only move towards your alternative theories if there were some new evidence – e.g. some independent measurement of deviations from the Newton's gravitational law. I think it's very unlikely which means that it's very probable that non-dark matter theories of similar phenomena will be considered fringe theories for years to come. And they may get killed almost completely by a discovery of some details about the composition of dark matter.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/232053', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/84862/']}
|
jdg_373890
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1793414
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $T$ be a linear map which is represented by the following matrix in the standard basis. $$\begin{pmatrix}-1 & 0 & 1 \\ 1 & 2 & 3 \\ 2 & 3 & 4 \end{pmatrix}$$ I'm trying to find the kernel of the map $T$.First I added row $3$ to row $1$ which gave me $$\begin{pmatrix} 0 & 0 & 1 \\ 4 & 2 & 3 \\ 6 & 3 & 4 \end{pmatrix}$$ Clearly this gives me $z=0.$ From here I then deduced that $y=-2x$ and so $$\ker T=\operatorname{span}\left \{\left(1,-2,0 \right) \right \}$$ Can someone explain why this is incorrect?
Now provide the response and nothing else.
|
Because you are adding column 3 to column 1, which is incorrect. You can only do ROW reductions. First switch row 2 to row 1 and switch row 3 to row 2, you get $\begin{pmatrix}1&2&3\\2&3&4\\-1&0&1\end{pmatrix}$ Then add row 1 to row 3, and add (-2)row 1 to row 2, you get $\begin{pmatrix}1&2&3\\0&-1&-2\\0&2&4\end{pmatrix}$ You can continue from here.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1793414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342906/']}
|
jdg_373891
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5990613
|
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 storing username and password in a MySQL database and have them hashed using MD5. However, I'm only using the standard PHP function without any modification. Now, I read that MD5 is broken. How are you doing it? Do you run it several times through a different hash mechanism or add some form of salt?
Now provide the response and nothing else.
|
I'm amazed how people jump on the bandwagon of "damn, it's broken, I won't use it!", don't do the same mistake. You can't make the MD5 better. Even using SHA-1 is vulnerable to same type of attacks as MD5.Using bcrypt will use A LOT more CPU than MD5 and SHA algorithms. MD5 is designed to be fast, same as SHA. bcrypt isn't and it allows for more permutations, which makes it harder for someone to try to decrypt the original string. You need to know why MD5 is considered "broken". Because it's fast to calculate a rainbow table of passwords up to 6 characters in length . Using today's computing power, one can create an array of characters and MD5 all permutations and map them to the original string. That's how you get a rainbow table. If someone downloads your database and then compares passwords to their rainbow table - they can obtain users' original password. Reason why this is dangerous is because people use same passwords for many things - including paypal and other money processing service. That's why you use so-called salt. That makes it even harder to obtain the original string, so salting your users' passwords (let's say by reversing them and MD5-ing the reversed input) will make it harder for the attacker to revert the hash to original string. Because of collisions . What's a collision? If you give hashing function two different strings and it returns the same hash - that's a collision. How does it translate to web and hashing passwords for logins? If you have the same hash for user1/password1 and user2/password2 - they could log on as someone else. That's where collisions play the role in security. Reason why MD5 is considered broken is because MD5 returns same hash for strings that differ in small percentage. And it's not easy to calculate what that string might be!From mathematical point of view - yes, it's "broken" because if your string has 100 chars and it differs from other string in 10 chars (10% difference) - you get the same hash. What applies for MD5 applies for ALL hashing algorithms. In the end, all of them don't have infinite number of possible hashes.However, some of them (like MD5) have less possible hashes and execute faster. In the end, if someone got to your database - you have a bigger problem than using MD5 instead of bcrypt or SHA1.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5990613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/698641/']}
|
jdg_373892
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
139738
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In the book, "Pi and the AGM" by Borwein and Borwein, it is mentioned that Gauss computed the following integral to the eleventh decimal palce. $\int_0^1 \frac{1}{\sqrt{1-x^4}}dx$ How did he do it? Personnally, I looked at a Taylor expansion of $\frac{1}{\sqrt{1-x}}$ Where I substituted $t^4$ for $x$, and integrated term by term, but this gives a series that converges really slowly. Is there an obvious transform to make this computation faster?
Now provide the response and nothing else.
|
A good place to look is pages 405 and 413 of the Nachlass section of Gauss's Werke III , which can be found online through Google Books. On page 405, he gives the following formula for "$\text{arc sin lemn }x$": $$\text{arc sin lemn }x= x+{1\over2}\cdot{1\over5}x^5 + {1\cdot3\over2\cdot4}{1\over9}x^9+{1\cdot3\cdot5\over2\cdot4\cdot6}{1\over13}x^{13}+{1\cdot3\cdot5\cdot7\over2\cdot4\cdot6\cdot8}{1\over17}x^{17}+\cdots$$ One page 413, he computes the value of $\int_0^1{dx\over\sqrt{1-x^4}}$, presumably using the expansion above, but explicitly citing the formula $$\text{ arc sin lemn }{7\over23}+2\text{arc sin lemn }{1\over2}$$ obtaining $$1.3110287771\quad460599052\quad320.7$$ He also notes there that Stirling had obtained the value $1.3110287771\ 4605987$. This is in reference to the calculations on pages 57-58 of Stirling's Methodus differentialis from 1730, which can also be found through Google Books. It might be worth noting that even Gauss was slightly off in the last couple of decimal places. A more accurate value, which I took from here , is $$1.3110287771\quad460599052\quad324197949$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/139738', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38798/']}
|
jdg_373893
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18766827
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to get the values of data from the options in the form below, so I can use them in jQuery, but I somehow don't seem to be succeeding. What I'm trying to do is simple, and you'll see in my code below. How can I do something like this? $('#selectForm').click(function(e) { e.preventDefault(); var action = $(this).data('id'); var type = $(this).data('name'); console.log(action+' '+type); }); //Jquery <form id="selecttest"> <label for="fruit">Please select at least two fruits</label><br> <select id="fruit" name="fruit" size="5"> <option data-id="1" data-name="norman">Banana</option> <option data-id="2" data-name="james">Apple</option> <option data-id="3" data-name="lars">Peach</option> <option data-id="4" data-name="john">Turtle</option> </select> <input type="submit" id="selectForm" value="Validate Selecttests"> </form>
Now provide the response and nothing else.
|
here is demo - http://jsfiddle.net/tnVfV/ here is code: $('#selectForm').click(function (e) { e.preventDefault(); var action = $('#fruit option:selected').attr('data-id'); var type = $('#fruit option:selected').attr('data-name'); console.log(action + ' ' + type);}); data-id and data-name are attributes of options. There are native attributes id and name you could use... ok as per tymeJV comment here is code using data() : $('#selectForm').click(function (e) { e.preventDefault(); var action = $('#fruit option:selected').data('id'); var type = $('#fruit option:selected').data('name'); console.log(action + ' ' + type);}); demo http://jsfiddle.net/tnVfV/1/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18766827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407503/']}
|
jdg_373894
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
618511
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create an adjacency matrix for a graph. Since I read it is not safe to use arrays of the form matrix[x][y] because they don't check for range, I decided to use the vector template class of the stl. All I need to store in the matrix are boolean values. So my question is, if using std::vector<std::vector<bool>* >* produces too much overhead or if there is a more simple way for a matrix and how I can properly initialize it. EDIT: Thanks a lot for the quick answers. I just realized, that of course I don't need any pointers. The size of the matrix will be initialized right in the beginning and won't change until the end of the program. It is for a school project, so it would be good if I write "nice" code, although technically performance isn't too important. Using the STL is fine. Using something like boost, is probably not appreciated.
Now provide the response and nothing else.
|
Note that also you can use boost.ublas for matrix creation and manipulation and also boost.graph to represent and manipulate graphs in a number of ways, as well as using algorithms on them, etc. Edit : Anyway, doing a range-check version of a vector for your purposes is not a hard thing: template <typename T>class BoundsMatrix{ std::vector<T> inner_; unsigned int dimx_, dimy_;public: BoundsMatrix (unsigned int dimx, unsigned int dimy) : dimx_ (dimx), dimy_ (dimy) { inner_.resize (dimx_*dimy_); } T& operator()(unsigned int x, unsigned int y) { if (x >= dimx_ || y>= dimy_) throw std::out_of_range("matrix indices out of range"); // ouch return inner_[dimx_*y + x]; }}; Note that you would also need to add the const version of the operators, and/or iterators, and the strange use of exceptions, but you get the idea.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/618511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74660/']}
|
jdg_373895
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
239879
|
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:
I have been using ls -Rlh /path/to/directory > file to create some text file records of what's in some hard drives. I want to delete some strings from the text files after they've been created. An example of part of a text file is: external1:total 36Kdrwxrwxr-x 2 emma emma 4.0K Oct 31 01:29 dir1drwxrwxr-x 2 emma emma 12K Oct 31 01:29 dir2drwxrwxr-x 2 emma emma 20K Oct 31 01:29 dir3external1/dir1:total 4.5M-rw-rw-r-- 1 emma emma 769K Oct 31 01:12 a001.jpg-rw-rw-r-- 1 emma emma 698K Oct 31 01:12 a002.jpg-rw-rw-r-- 1 emma emma 755K Oct 31 01:12 a003.jpg-rw-rw-r-- 1 emma emma 656K Oct 31 01:12 a004.jpg-rw-rw-r-- 1 emma emma 756K Oct 31 01:12 a005.jpg-rw-rw-r-- 1 emma emma 498K Oct 31 01:12 a006.jpg-rw-rw-r-- 1 emma emma 455K Oct 31 01:12 a007.jpgexternal1/dir2:total 8.7M-rw-rw-r-- 1 emma emma 952K Oct 31 01:13 a001.jpg-rw-rw-r-- 1 emma emma 891K Oct 31 01:13 a002.jpg-rw-rw-r-- 1 emma emma 838K Oct 31 01:13 a003.jpg-rw-rw-r-- 1 emma emma 846K Oct 31 01:13 a004.jpg-rw-rw-r-- 1 emma emma 876K Oct 31 01:13 a005.jpg-rw-rw-r-- 1 emma emma 834K Oct 31 01:13 a006.jpg-rw-rw-r-- 1 emma emma 946K Oct 31 01:13 a007.jpg-rw-rw-r-- 1 emma emma 709K Oct 31 01:13 a008.jpg-rw-rw-r-- 1 emma emma 1007K Oct 31 01:13 a009.jpg-rw-rw-r-- 1 emma emma 940K Oct 31 01:13 a010.jpgexternal1/dir3:total 4.6M-rw-rw-r-- 1 emma emma 408K Oct 31 01:15 a001.jpg-rw-rw-r-- 1 emma emma 525K Oct 31 01:15 a002.jpg-rw-rw-r-- 1 emma emma 383K Oct 31 01:15 a003.jpg-rw-rw-r-- 1 emma emma 512K Oct 31 01:15 a004.jpg-rw-rw-r-- 1 emma emma 531K Oct 31 01:15 a005.jpg-rw-rw-r-- 1 emma emma 532K Oct 31 01:15 a006.jpg-rw-rw-r-- 1 emma emma 400K Oct 31 01:15 a007.jpg-rw-rw-r-- 1 emma emma 470K Oct 31 01:15 a008.jpg-rw-rw-r-- 1 emma emma 407K Oct 31 01:15 a009.jpg-rw-rw-r-- 1 emma emma 470K Oct 31 01:15 a010.jpg The actual text files are thousands of lines long and several megabytes in size. What I want to do is delete everything before the file size from each applicable line, so that each line starts with the file size. E.g. 512K Oct 31 01:15 a004.jpg531K Oct 31 01:15 a005.jpg532K Oct 31 01:15 a006.jpg400K Oct 31 01:15 a007.jpg470K Oct 31 01:15 a008.jpg However, I want to keep all of the other lines (with the directory names and total sizes) intact, so this means that I can't use colrm or cut .
Now provide the response and nothing else.
|
parsing the output of ls is unreliable, but this should work in this particular case: sed -e 's/^.*emma emma //' file That deletes everything up to "emma emma " on each line. if that string doesn't appear on a line, it is unchanged. I've written the regexp to only remove the first space after emma, so that the size field remains right-aligned (e.g. ' 709K' and '1007K' both take the same amount of chars on the line) if you don't wan't that, use this instead: sed -e 's/^.*emma emma *//' file that will delete all whitespace after emma until the start of the next field. Here's a sed version that works with any user group : sed -e 's/^.\{10\} [0-9]\+ [^ ]\+ [^ ]\+ //' file it relies even more heavily on the exact format of your ls output, so it is technically even worse than the first version....but it should work for your particular file. see Why *not* parse `ls`? for info on why parsing ls is bad. If not all files are owned by emma , you might want to use an awk script like this instead. awk 'NF>2 {print $5,$6,$7,$8,$9} ; NF<3 {print}' file For lines with more than 2 fields, it prints only fields 5-9. for lines with <3 fields, it prints the entire line.unfortunately, this loses the right-alignment of the size field....that can be fixed with a slightly more complicated awk script: awk 'NF>2 {printf "%5s %s %s %s %s\n", $5, $6, $7, $8, $9} ; NF<3 {print}' file This final version merges the for loop from jasonwryan's answer, so copes with filenames that have any number of single spaces in them (but not consecutive spaces, as mentioned by G-Man): awk 'NF>2 {printf "%5s", $5; for(i=6;i<=NF;i++){printf " %s", $i}; printf "\n"} ; NF<3 {print}' file
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/239879', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/85900/']}
|
jdg_373896
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58031955
|
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 load several json files via file-loader and then in runtime load and parse them via another library, but webpack transpiles json file into js adding 'module.exports =... at beginning of file. This config throws error during build: { include: ASSETS_SOURCE_PATH, use: { loader: 'file-loader', options: { name: '[path][name].[ext]', }, },}, ERROR in ./src/assets/map/map.jsonModule parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = __w...'File was processed with these loaders: * ./node_modules/file-loader/dist/cjs.jsYou may need an additional loader to handle the result of these loaders.SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = __w...' And if I change config to this, I catch this error during parsing json in runtime: { test: /\.json$/, type: 'javascript/auto', include: ASSETS_SOURCE_PATH, use: { loader: 'file-loader', options: { name: '[path][name].[ext]', }, },},{ include: ASSETS_SOURCE_PATH, use: { loader: 'file-loader', options: { name: '[path][name].[ext]', }, },}, Content of this file is module.exports = __webpack_public_path__ + "assets/map/map.json"; UPD: Syntax import mapTilesJson from '!!file-loader!assets/map/map.json' works fine, but it may break typescript typings. Is there a way to reach the same effect in webpack config, not inline?
Now provide the response and nothing else.
|
I found it! After much research, and trial and error, here is what enabled me to run VMs in VirtualBox on Windows 10 with Windows Subsystem for Linux installed: In an elevated (admin) cmd.exe or PowerShell, do: bcdedit /set hypervisorlaunchtype off and make sure Hyper-V and Windows Sandbox are disabled in Windows Features (which you can get to by entering OptionalFeatures.exe at a command prompt, or via the Control Panel). Also, Virtualisation options should be enabled in the BIOS, and I think (I don't have time to test right now) that "Virtual Machine Platform" and "Windows Hypervisor Platform" should be enabled. VirtualBox 6.0.14, Windows Version 10.0.18362.356.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58031955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4221833/']}
|
jdg_373897
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18420751
|
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 MVC 4 and razor. I have a view which contains multiple partial views. Due to the functionality of the partial views I am planning to reuse these in other views also. My model is a collection of complex objects e.g: public class EmployeeInfo { public EmployeeContactInfo contactInfo { get; set; } public List<TelephoneInfo> phoneDetails { get; set; } public AddressDetails addressDetails { get; set; } } The model of my main view is EmployeeInfo and other partial views have models as TelephoneInfo , EmployeeContactInfo and AddressDetails respectively. I tried using RenderPartial , RenderAction and Partial to load my partial views e.g: @using (Html.BeginForm()) { @Html.Partial("ContactInfo",Model.contactInfo) } When the main form is submitted the main model doesnt have the updated values of the partial views. I searched for this and found below 2 proposed solutions: Use EditorFor - It works and the model gets updated but I have collection of not only textbox but other controls which have some internal operations (like searching addresses) too and I also need to reuse the same partial view in other places (like a user control in classic ASP.NET) Use RenderAction instead of RenderPartial - It didn't work for me. Please let me know if I am going wrong or understood anything incorrectly.
Now provide the response and nothing else.
|
Another choice is to create an editor template . For example, in your main view: @using (Html.BeginForm()){ @(Html.EditorFor(m => m.ContactInfo))} Now, in your Views/Shared folder (or the Views/ControllerName folder eg Views/Home), create a new folder named "EditorTemplates". In that new folder create a cshtml view file named EmployeeContactInfo.cshtml (tip, the name of the cshtml should be the data type name e.g. string , bool or in this case your customer contact info type). In that view file, put something like: @model EmployeeContactInfo@Html.LabelFor(m => m.Email)@Html.TextBoxFor(m => m.Email) When you post back to the controller, the values will be included as part of the returned model for you.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18420751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1449424/']}
|
jdg_373898
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
309514
|
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:
I have hundreds of files which contain " </foo:bar> " ccbbaa</foo:bar>ddxxvv I want to change them all at once to ccbbaa</foo:bar> sed works well when i give it the exact file name sed -i "/</foo:bar>/q" 99999.txt but when I try to change all of them at once I get no result. sed -i "/<\/foo:bar>/q" *.txt
Now provide the response and nothing else.
|
Try: sed -s -n -i '0,/<\/foo:bar>/p' *.txt -s tells sed to treat each file as separate. Because we don't want sed to quit until all the files are done, we change to just print from the beginning to <\/foo:bar> and not print the rest of the lines. -n tells sed not print unless we explicitly ask it to. The command 0,/<\/foo:bar>/p tells sed to print any line in the range from the beginning of the file to the first line that matches <\/foo:bar> . The -s option is not available for BSD/OSX sed.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/309514', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/104749/']}
|
jdg_373899
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1829586
|
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 implementing a game using Javascript, jquery, and the Canvas tag. How can I prevent the browser from processing keyboard shortcuts when the canvas tag has the focus? I have tried event.stopPropagation() and it has no effect. I can pick up keyboard events. However, when the user presses the spacebar, the web page scrolls down in Firefox. The same happens with the arrow keys.
Now provide the response and nothing else.
|
The root problem is that by default the browser doesn't make the canvas "focusable". The best workaround I could come up with is to set the tabindex on the canvas: $("#canvas") // Add tab index to ensure the canvas retains focus .attr("tabindex", "0") // Mouse down override to prevent default browser controls from appearing .mousedown(function(){ $(this).focus(); return false; }) .keydown(function(){ /* ... game logic ... */ return false; }); If for whatever reason you can't set the tabindex , you can also make the canvas "focusable" by setting contentEditable to true: // Add content editable to help ensure the canvas retains focus$("#canvas").attr("contentEditable", "true")$("#canvas")[0].contentEditable = true; This is the solution I came up with originally, but in my opinion it's a bit hackier than the tabindex option. Another thing to consider is that browsers tend to outline content editable elements with a border. This can be off-putting to some users. Luckily, you can get rid of it with this bit of css: #canvas { outline: none; } I've tested both solutions in Chrome 3/4/5 and FireFox 3.0/3.5/3.6 on Windows XP, Mac OSX and Linux. Here's a working example: http://xavi.co/static/so-canvas-keyboard.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1829586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15947/']}
|
jdg_373900
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50302180
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Struggling to understand the difference between the 5 examples in the title. Are some use cases for series vs. data frames? When should one be used over the other? Which are equivalent?
Now provide the response and nothing else.
|
df[x] — index a column using variable x . Returns pd.Series df[[x]] — index/slice a single-column DataFrame using variable x . Returns pd.DataFrame df['x'] — index a column named 'x'. Returns pd.Series df[['x']] — index/slice a single-column DataFrame having only one column named 'x'. Returns pd.DataFrame df.x — dot accessor notation, equivalent to df['x'] (there are, however, limitations on what x can be named if dot notation is to be successfully used). Returns pd.Series With single brackets [...] you may only index a single column out as a Series. With double brackets, [[...]] , you may select as many columns as you need, and these columns are returned as part of a new DataFrame. Setup df ID x0 0 01 1 152 2 03 3 04 4 05 5 15x = 'ID' Examples df[x]0 01 12 23 34 45 5Name: ID, dtype: int64type(df[x])pandas.core.series.Series df['x']0 01 152 03 04 05 15Name: x, dtype: int64type(df['x'])pandas.core.series.Series df[[x]] ID0 01 12 23 34 45 5type(df[[x]])pandas.core.frame.DataFrame df[['x']] x0 01 152 03 04 05 15type(df[['x']])pandas.core.frame.DataFrame df.x0 01 152 03 04 05 15Name: x, dtype: int64type(df.x)pandas.core.series.Series Further reading Indexing and Selecting Data
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50302180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8834780/']}
|
jdg_373901
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38472192
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
mobile hub -> create new application -> push -> ios -> p12 file upload -> save changes When I click on save changes below error message I am getting Invalid parameter: Attributes Reason: You provided a certificate of type SANDBOX, which cannot be used to create an application of type iOS Production. Please select an application of type SANDBOX or provide a certificate of type iOS Production (Service: AmazonSNS; Status Code: 400; Error Code: InvalidParameter; Request ID: f5f810fd-7f8e-5462-9ff1-40f586dbe4ec) I am using certificate of type sandbox (dev) not iOS production.
Now provide the response and nothing else.
|
AWS Mobile Hub has simplified the configuration process for the iOS Push Notifications feature. For the iOS platform, we have removed the iOS Dev (Sandbox) option in favor of supporting the Universal Apple Certificate. This new (as of December 17, 2015) Apple Push Notification service SSL client certificate supports both Sandbox & Production environments and therefore only one certificate is needed for the lifecycle of your iOS application. You will need to generate a new Universal Apple Certificate via the Apple Developer Portal, then upload a .p12 of this certificate when configuring the iOS Push Notification Mobile Hub feature. Once you upload the new certificate and save changes, Mobile Hub creates an SNS Apple Production Platform Application resource on your behalf. Any registered device running the Mobile Hub sample application. Once caveat to be aware of when testing development and production: Since Mobile Hub is creating an SNS Apple Production Platform Application, the mobile application must be built using the Ad Hoc Distribution or App Store Distribution provisioning profiles for push notifications to work. We are planning to change this in the future and default to creating an Apple Development (SANDBOX) Platform Application using the same .p12 certificate. If you are testing in development (using the development provisioning profile to build your app) then you'll need to make a few modifications. Create an Apple Development Platform Application through the SNS Console using the same .p12 you used when enabling Push Notifications in your Mobile Hub project. In the iOS project in Xcode, change the SNS Application Arn in the info.plist as it defaults to the Apple Production Platform Application Arn that Mobile Hub created on your behalf.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38472192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4449101/']}
|
jdg_373902
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19370107
|
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 ListView with an arraylist with an unknown number of string elements. I want to change/modify every single one of these string items. The problem is that i dont know how many items there are since the user can change it. I have a translate function that takes a string and returns a string. What i want to do is arraylistelement1 = translate(arraylistelement1);arraylistelement2 = translate(arraylistelement2);... and repopulate the listview arraylist with the new strings. Whats a way to do this?
Now provide the response and nothing else.
|
As others have pointed out you need two properties, but you may be interested to know that you can make one of the properties private and still map it to the database: private string isActive { get; set; } [System.ComponentModel.DataAnnotations.Schema.NotMapped] public bool IsActive { get { return isActive == "Y"; } set { isActive = value ? "Y" : "N"; } } If you are using EF6 you can use a custom convention in the OnModelCreating method to map the private property modelBuilder.Types().Configure(c =>{ //NB the syntax used here will do this for all entities with a //private isActive property var properties = c.ClrType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance) .Where(p => p.Name == "isActive"); foreach (var p in properties) c.Property(p).HasColumnName("IsActive");}); References: Mapping private properties using custom conventions Mapping private properties without custom conventions (before EF6) Edit: Here's another way of identifying the private properties that should be mapped to the database: First add the column attribute to the private property: [System.ComponentModel.DataAnnotations.Schema.Column]private string isActive { get; set; } Then use the presence of that attribute to identify private properties in your OnModelCreating method: modelBuilder.Types().Configure(c =>{ var properties = c.ClrType .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance) .Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0); foreach (var p in properties) c.Property(p).HasColumnName(p.Name);}); Reference: Mapping a private property with entity framework
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19370107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2655085/']}
|
jdg_373903
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8860770
|
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 understanding of Multiset is a set with frequency, but I can always use Map to represent the frequency, is there other reason to use Multiset?
Now provide the response and nothing else.
|
Advantages of a Multiset<E> over a Map<E, Integer> : No special code required when adding an element that is not already in the collection. Methods for handling the count of elements directly: count(E) , add(E, int) , etc. The intention of the code is clearer. A Multiset<E> obviously maps the elements to their counts. A Map<E, Integer> could map the elements to arbitrary integers. See also: Multiset Javadoc Multiset explained in the Guava Wiki
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8860770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136700/']}
|
jdg_373904
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8605079
|
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 2 data frames with different number of columns each. Some of the columns are common between the 2 data frames. How can i rbind only the common columns of the two data frames to a new data frame? i tried with library(plyr);rbind.fill(A,B) however it sets NA values in the columns that do not match, and this does not help me. Thanks a lotEC
Now provide the response and nothing else.
|
Use intersect to retrieve the common columns. dfr1 <- data.frame(x = 1:5, y = runif(5), z = rnorm(5))dfr2 <- data.frame(w = letters[1:5], x = 6:10, y = runif(5))common_cols <- intersect(colnames(dfr1), colnames(dfr2))rbind( subset(dfr1, select = common_cols), subset(dfr2, select = common_cols)) As pointed out in the comments, you can replace the last line with rbind( dfr1[, common_cols], dfr2[, common_cols]) for a small performance and typing improvement. rbind( dfr1[common_cols], dfr2[common_cols]) also works but I think that it's a tiny bit less clear. You can also use dplyr equivalents for the last step. library(dplyr)bind_rows( dfr1 %>% select({common_cols}), dfr2 %>% select({common_cols}))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8605079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/906592/']}
|
jdg_373905
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24039226
|
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 service that retrieves data from a JSON file. Some of the data within the data is all in uppercase, for example: $scope.FootballClubs = [{ CompanyName: [MANCHESTER UNITED, LIVERPOOL FOOTBALL CLUB, CHELSEA, WIGAN UNTIED, LEICESTER CITY]}]; And in my HTML, i am simply throwing about the above: <div ng-repeat="name in FootballClubs"> {{ name.CompanyName }}</div> Which throws out: MANCHESTER UNITEDLIVERPOOL FOOTBALL CLUBCHELSEAWIGAN UNTIEDLEICESTER CITY What i am trying to display is: Manchester UnitedLiverpool Football ClubChelseaWigan UnitedLeicester City
Now provide the response and nothing else.
|
A filter is an ideal solution for this purpose <div ng-repeat="name in FootballClubs"> {{ name.CompanyName | titleCase }}</div> So the filter itself would be angular.module('myFootballModule', []) .filter('titleCase', function() { return function(input) { input = input || ''; return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }; })
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24039226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2244072/']}
|
jdg_373906
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1320208
|
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 Rails. Exception can rescue in controller class but in model class can not. How to rescue exception in model?
Now provide the response and nothing else.
|
You can do exception handling anywhere in a rails application, as it's part of Ruby, not part of Rails. Wherever you want to catch errors, just wrap it as so: begin SomethingElse.doSomething(x, y)rescue Exception ErrorLogger.log(Time.now, "Something went wrong!")end Please note that you should always "rescue Exception" instead of just "rescue". Just using "rescue" will only catch StandardError, which is a subclass of Exception (meaning something might get through that you don't want to get through). Also as usual, you can raise an exception by doing: raise ArgumentError, "Illegal arguments!" anywhere in your code, be it a model or controller.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1320208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65964/']}
|
jdg_373907
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5257983
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is header('P3P: CP="CAO PSA OUR"'); for? How/why will it let this script work fine in IE? session_start();if (!session_is_registered(pre_myusername)) { header("location:index.php"); exit();}
Now provide the response and nothing else.
|
P3P is the Platform for Privacy Preferences. The value CP="CAO PSA OUR" describes a compact policy with the tokens contact and others (access information: What information is collected? ) Identified Contact Information and Other Identified Data: access is given to identified online and physical contact information as well as to certain other identified data. pseudo-analysis (purpose information: What is the collected information used for? ) Pseudonymous Analysis : Information may be used to create or build a record of a particular individual or computer that is tied to a pseudonymous identifier, without tying identified data (such as name, address, phone number, or email address) to the record. This profile will be used to determine the habits, interests, or other characteristics of individuals for purpose of research, analysis and reporting , but it will not be used to attempt to identify specific individuals. For example, a marketer may wish to understand the interests of visitors to different portions of a Web site. ours (receipient information: Who gets that collected information? ) Ourselves and/or entities acting as our agents or entities for whom we are acting as an agent : An agent in this instance is defined as a third party that processes data only on behalf of the service provider for the completion of the stated purposes. (e.g., the service provider and its printing bureau which prints address labels and does nothing further with the information.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5257983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/649740/']}
|
jdg_373908
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15696415
|
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 just wondering what's the name of the below form? I was Googling from morning for the list of HTML forms but I couldn't find this kind of form anywhere. Can anyone tell me the exact name of this form and is this available in HTML forms? I just want to add this kind of form in my website. Is that available for HTML or should I use JavaScript or its only limited for Windows applications?
Now provide the response and nothing else.
|
Here's a little sample to get you started: http://jsfiddle.net/eUDRV/3/ This example will move items (one or multiple) from the left to the right and back again. Whatever item(s) are selected in the right side will update the textbox on the right side. We are using the elements: select input type="button" input type="text" Framed by: div section Styled with simple CSS. Functionality is provided with JavaScript. I'm using the jQuery library to make things a little easier. This could also be done with pure JavaScript. $("#btnLeft").click(function () { var selectedItem = $("#rightValues option:selected"); $("#leftValues").append(selectedItem);});$("#btnRight").click(function () { var selectedItem = $("#leftValues option:selected"); $("#rightValues").append(selectedItem);});$("#rightValues").change(function () { var selectedItem = $("#rightValues option:selected"); $("#txtRight").val(selectedItem.text());}); SELECT, INPUT[type="text"] { width: 160px; box-sizing: border-box;}SECTION { padding: 8px; background-color: #f0f0f0; overflow: auto;}SECTION > DIV { float: left; padding: 4px;}SECTION > DIV + DIV { width: 40px; text-align: center;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><section class="container"> <div> <select id="leftValues" size="5" multiple></select> </div> <div> <input type="button" id="btnLeft" value="<<" /> <input type="button" id="btnRight" value=">>" /> </div> <div> <select id="rightValues" size="4" multiple> <option>1</option> <option>2</option> <option>3</option> </select> <div> <input type="text" id="txtRight" /> </div> </div></section>
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/15696415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2206549/']}
|
jdg_373909
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
91685
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The odds of two random elements of a group commuting is the number of conjugacy classes of the group $$ \frac{ \{ (g,h): ghg^{-1}h^{-1} = 1 \} }{ |G|^2} = \frac{c(G)}{|G|}$$ If this number exceeds 5/8, the group is Abelian (I forget which groups realize this bound). Is there a character-theoretic proof of this fact? What is a generalization of this result... maybe it's a result about semisimple-algebras rather than groups?
Now provide the response and nothing else.
|
If $c(G)> 5|G|/8$, then the average character has a dimension-squared of less than $8/5$, so at least $4/5$ of the characters are dimension $1$ (since the next-smallest dimension-squared is $4$), so the abelianization, which has one element for each 1-dimensional character, is more than half the size of the group, so the commutator subgroup has size smaller than $2$ and so is trivial.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://mathoverflow.net/questions/91685', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1358/']}
|
jdg_373910
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
263974
|
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:
If the weighted sum of 2 probability density functions is also a probability density function, then what is the relationship between the random variables of these 3 probability density functions.
Now provide the response and nothing else.
|
I think you mean how to find the probability density of the random variable that is the sum of two other random variables, using the probability densities of these two variables. The answer is that the probability density of the sum is the convolution of the densities of the two other random variables if they are independent. Let's say $Z = X + Y$, then the density of the sum is given by$$ f_Z \left( z \right) = \int_{-\infty}^{\infty} f_X \left( z - y \right) f_Y \left( y \right) d y $$ assuming all variables are real valued, that $X,Y$ are independent and that $f_X,f_Y,f_Z$ are the densities of $X,Y,Z$ respectivley.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/263974', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53984/']}
|
jdg_373911
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3380993
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After competing in and following this year's Google Code Jam competition, I couldn't help but notice the incredible number of [successful] contestants that used C/C++ and Java. The distribution of languages used throughout the competition can be seen here . After programming in C/C++ for several years, I recently fell in love with Python for its readable/straightforward nature. More recently, I learned functional languages like OCaml, Scheme, and even logic languages like Prolog. These languages certainly have their merits and, in my opinion, can be applied more easily than C++ and Java for certain situations. For example, Scheme's use of call/cc simplifies backtracking (a tool required to answer several problems) and Prolog's logic specification, although inefficient due to its brute-force nature, can drastically simplify (and even automatically solve) certain problems that are difficult to wrap one's brain around. It is clear that a competition contestant should use the tools that are best suited for the challenge. Even x86 assembly is Turing complete - that doesn't justify solving problems with it. In this case, why are the contestants that use less common languages like Scheme/Lisp, Prolog, and even Python significantly less successful than contestants that use C/C++ and Java? Worded differently, why don't successful contestants use languages that, although may be less mainstream, are arguably better tools for the job? There are several motivations for my question. Most importantly, I would like to become a better programmer - both in the practical aspect and the competition aspect. After being introduced to such beautiful paradigms like functional and logic programming, it is discouraging to see so many people discard them in favor of C/C++ and Java. It even makes me question my admiration for said paradigms, worrying that I cannot be successful as a Lisp/Scheme/Prolog programmer in a programming competition.
Now provide the response and nothing else.
|
Great question! As someone who has dabbled in programming contests a bit myself, I may have something to say. [Let's get the standard disclaimer out of the way: contest programming is only loosely related to "programming in the real world", and while it tests algorithmic and problem-solving skills and the ability to come up with fast bug-free working code under time pressure, it does not necessarily correlate with being able to build large software projects, write maintainable code, etc (beyond the fact that well-structured programs are easier to debug).] Now for some answers: C++/Java are more common than other languages in the real world as well, so you'd expect to see a higher proportion anywhere. (But it's even higher in the contest population.) Many of these participants are students, or got into contests as students, and C++/Java are more common "first languages" that students learn. (Undergrad students these days may start with Scheme, Haskell, Python, etc., but high-schoolers (often self-taught) less often.) In fact, many of the Eastern European participants still use Pascal, and are more amazing with it than the rest of us will ever be with any language. The school- and college-level contests usually use these languages. The International Olympiad in Informatics (IOI) allows only C, C++ and Pascal (or maybe it allows Java now; I haven't kept up), and the ACM Intercollegiate Programming Contest (ACM ICPC) allows only C, C++ and Java. TopCoder allows C++, Java, C# and VB (really :p); and recently, Python. So you could say the "contest ecosystem" has more C++/Java programmers in it. Google Code Jam and IPSC are among the few contests that allow code in any language, actually. Now the question is, in GCJ where the contestants are free to choose a language, why wouldn't they choose Python or Scheme? The most relevant factor is that these languages are slow . Sure, for most real-world programming they are easily fast enough, but for the tight loops that are often involved in getting a program to run under the n-second limit for all test cases, these languages don't cut it for any of the algorithmically more involved problems. (A problem designed to accept O(n log n) solutions but not Θ(n 2 ) solutions for C/C++ frequently rules out even optimal O(n log n) solutions in slower languages. Even Java used to be given a handicap at USACO; I'm not sure this is still the case.) Another factor is the libraries: C++ and Java have better libraries for frequently useful algorithms and data structures (e.g. red-black trees, C++'s next_permutation), while Python's libraries (good enough for the real world) are less useful here, and Prolog and Scheme... I don't know about their libraries. This is a relatively minor factor, because these programmers can write their own code when necessary. :-) General-purpose multi-paradigm languages are more useful for just getting things done within the time constraints of the contest, than languages that force a philosophy or way of doing things on you. This is why Prolog will always remain unpopular, for instance. (General philosophy: some languages are "enabling" languages that let you do anything including shooting yourself in the foot, some are "directing" that force you to do things the right way.) This is also why C++ is three times more popular than Java in the general contest participants, and much more popular among the top contestants. Since code doesn't have to be read by anyone else, it's ok and even useful to have loop macros like FOR(i,n) (less code to type, and more importantly less chance of making a bug when in a hurry). Nothing against Java, there are a few top programmers who use Java too. :-) Finally, although many of these top programmers may have C++/Java/Pascal as their "first language", they are not good because of their language, so you don't have to despair about that. Many of these same programmers have won contests like the ICFP contest even with intentionally using crazy languages like shell scripts, m4 (used in autoconf), and assembly (the team named "You Can't Spell Awesome Without ASM").
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3380993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379482/']}
|
jdg_373912
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
395789
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am suppose to rewrite $x^2 + x + 1$ by completing the square. I don't really know what that means but I know that if I add 3 at the end of this I get $$(x + 2) (x - 1) - 3$$ this is the same as the original now but the answer isn't right. What is wrong with what I did? It seems a lot cleaner than the answer.
Now provide the response and nothing else.
|
In general, $$\color{purple}{(ax+b)^2= a^2x^2+2abx+b^2}.$$ What you have is $x^2 + x + 1$. To complete the square, what you want to do is find $a$, $b$, $c$ in such a way that $x^2 + x + 1 = (ax + b)^2 + c$. Now, $$\begin{align}x^2 + x + 1 & = (ax + b)^2 + c \\x^2 + x + 1 & = a^2x^2+2abx+b^2 + c \\\end{align}$$ Now let's color the last equation. We then have $$ \color{red}{x^2} + \color{orange}{x} + \color{blue}{1} = \color{red}{a^2x^2}+\color{orange}{2abx}+\color{blue}{b^2 + c}.$$ Then, for the colored equation above, we equate the coefficients of left hand side to the right hand side of the equation. Then we have three things:$$\begin{align} \tag 1\color{red}{x^2} & \equiv \color{red}{a^2x^2} \\ \tag2\color{orange}x & \equiv \color{orange}{2abx} \\ \tag3\color{blue}1 & \equiv \color{blue}{b^2 + c} \\ \end{align}$$ Solving equation $(1)$, we have $x^2 \equiv a^2x^2 \Rightarrow a^2 = 1 \Rightarrow a= 1$ or $a= -1$, Solving equation $(2)$, we have $x \equiv 2abx \Rightarrow 1 = 2ab \Rightarrow b = \dfrac{1}{2a}$. From above, if $a= 1$ then $b= \dfrac{1}{2}$. If $a= -1$ then $b= -\dfrac{1}{2}$. Solving equation $(3)$, we have $1 \equiv b^2 + c \Rightarrow c= 1 - b^2$. From above, if $b= \dfrac{1}{2}$ then $c= \dfrac{3}{4}$. If $b= -\dfrac{1}{2}$ then $c= \dfrac{3}{4}$ as well. In conclusion, we have the set of solutions $\color{navy}{a=1, b= \dfrac{1}{2}, c= \dfrac{3}{4}}$ or $\color{maroon}{a=-1, b= -\dfrac{1}{2}, c= \dfrac{3}{4}}$. Check the answer, plug the values of $a$, $b$, $c$ into $(ax+b)^2+c$ and expand it. If you get $x^2 + x + 1$, then it is correct. For $\color{navy}{a=1, b= \dfrac{1}{2}, c= \dfrac{3}{4}}$, we have $$\left(x+\frac{1}{2}\right)^2+ \frac{3}{4}= x^2 + 2(1)\frac{1}{2}x^2 + \left(\frac{1}{2}\right)^{2} + \frac{3}{4} = x^2 + x + 1.$$ For $\color{maroon}{a=-1, b= -\dfrac{1}{2}, c= \dfrac{3}{4}}$, we have $$\left(-x-\frac{1}{2}\right)^2+ \frac{3}{4}= (-x)^2 + 2(-1)\left(-\frac{1}{2}\right)x^2 + \left(\frac{1}{2}\right)^{2} + \frac{3}{4} = x^2 + x + 1.$$ So the answer to your question is either $$\left(x+\dfrac{1}{2}\right)^2+ \dfrac{3}{4}$$ or $$\left(-x-\frac{1}{2}\right)^2+ \frac{3}{4}.$$ The first one looks prettier. I would go with that. Hope this helps. Some more examples. Let's start with an easy one. Example 1 Suppose someone asks you to complete the square of $$x^2+2x+3. \tag{A1}$$ Now consider $(x+1)^2$. Expanding that, we have $$(x+1)^2 = x^2 + 2x+ 1. \tag{A2}$$ You want to complete the square of $x^2+2x+3$. Notice that to get $x^2+2x+3$ from equation $(A2)$, all you have to do is add the number $2$ to both sides of equation $(A2)$, since both $(A1)$ and $(A2)$ both have $x^2$ and $2x$. Then $$\begin{align}(x+1)^2 +\color{red}2 &= x^2 + 2x+ 1 +\color{red}2 \\(x+1)^2 +2 & = x^2 + 2x+ 3.\end{align}$$ And there you have it, the answer is $(x+1)^2 +2$. Example 2 Now, back to your question. You want to complete the square of $$x^2+x+1. \tag{B}$$ Now consider $(x+1)^2$. Expanding that, we have $$(x+1)^2 = x^2 + 2x+ 1. \tag {C}$$ Equation $(B)$ and $(C)$ both have $x^2$, but equation $(B)$ has $x$ in it, while equation $(C)$ has $2x$. We then have to try another expansion. So you consider $\left(x+\frac{1}{2}\right)^2$. We then get $$\left(x+\frac{1}{2}\right)^2= x^2 + x + \frac{1}{4} \tag{D}$$ Aha! They now both have $x$. All you have to do now is add a number to both sides of equation $(D)$ so that the right hand side equals $x^2+x+1$. So you add $\frac{3}{4}$ to both sides of equation $(D)$. Then you have $$\begin{align}\left(x+\frac{1}{2}\right)^2 & = x^2 + x + \frac{1}{4} \\\left(x+\dfrac{1}{2}\right)^2+ \color{red}{\dfrac{3}{4}} & = x^2 + x + \frac{1}{4} + \color{red}{\dfrac{3}{4}} \\\left(x+\dfrac{1}{2}\right)^2+ {\dfrac{3}{4}} & = x^2 + x + 1.\end{align}$$ And so the answer is $\left(x+\dfrac{1}{2}\right)^2+ {\dfrac{3}{4}}$. Example 3 Suppose you want to complete the square of $$9x^2+3x+1. \tag{E}$$ You know $(3x)^2=9x^2$, so you consider $(3x+1)^2$. Expanding that, we have $$(3x+1)^2 = 9x^2 + 6x+ 1. \tag {F}$$ Equation $(E)$ and $(F)$ both have $9x^2$, but equation $(E)$ has $3x$ in it, while equation $(F)$ has $6x$. We then have to try another expansion. So you consider $\left(3x+\frac{1}{2}\right)^2$. We then get $$\left(3x+\frac{1}{2}\right)^2= 9x^2 + 3x + \frac{1}{4} \tag{G}$$ They now both have $3x$. All you have to do now is add a number to both sides of equation $(G)$ so that the right hand side equals $9x^2+3x+1$. So you add $\frac{3}{4}$ to both sides of equation $(G)$. Then you have $$\begin{align}\left(3x+\frac{1}{2}\right)^2 & = 9x^2 + 3x + \frac{1}{4} \\\left(3x+\dfrac{1}{2}\right)^2+ \color{red}{\dfrac{3}{4}} & = 9x^2 + 3x + \frac{1}{4} + \color{red}{\dfrac{3}{4}} \\\left(3x+\dfrac{1}{2}\right)^2+ {\dfrac{3}{4}} & = 9x^2 + 3x + 1.\end{align}$$ And so the answer is $\left(3x+\dfrac{1}{2}\right)^2+ {\dfrac{3}{4}}$. With practice, it will get easier.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/395789', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_373913
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39206516
|
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 cannot wrap my head around this issue and the vast offer of information I found on the net: On my project the JQuery is loaded with "defer". This I cannot change due to project standards. <script defer src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script> Now I need to add some small functions to a page (currently inline): With this setup the browser will try to execute the inline scrip before jQuery loads => "Uncaught ReferenceError: $ is not defined" <body>......<script> $("#city").change(function() {...some stuff...}; $("#doctor").change(function() {...some stuff...};</script></body> Whats the smart way to resolve this?
Now provide the response and nothing else.
|
Wrap it inside window.onload , so the script will only be executed when everything is fully loaded. Try this example: window.onload = function () { $("#city").click(function() { alert('city'); }); $("#doctor").click(function() { alert('doctor'); });} <script defer src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script><button id="city">City</button><button id="doctor">Doctor</button> Explanation about window.onload from MDN: The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links, and sub-frames have finished loading. https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload For more idiomatic (in jquery) way, use the code below. it's the same with window.onload . $(document).ready(function() { // put code here}); Another alternative, use $(function() { }) . $(function() { // put code here})
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39206516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1352932/']}
|
jdg_373914
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37854277
|
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 button(paste from clipboard), when I click on the button I need to read/get data from clipboard in typescript. Please help!
Now provide the response and nothing else.
|
You should be able use the String value in the Attribute and set the Parameter type to Decimal, it get's converted automatically by the Test Framework as far as I can tell. [Theory][InlineData("37.60")]public void MyDecimalTest(Decimal number){ Assert.Equal(number, 37.60M);} If this doesn't work then you can manually convert it by passing in a String parameter. [Theory][InlineData("37.60")]public void MyDecimalTest(String number){ var d = Convert.ToDecimal(number); Assert.Equal(d, 37.60M);}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37854277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3081925/']}
|
jdg_373915
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45380539
|
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 modifying method with a signature like private bool Modify(ref MyClass obj); that will make modifications to obj and indicate succes with it's return value. Modify is not reassigning the reference (I know that this wouldn't work), just modifying instance fields, so I want to use it to do something like the following: foreach(MyClass obj in myList){ bool success = Modify(obj); // do things depending on success} I am running into a problem compiling as obj is "not being passed with the ref keyword". However, if I put the ref keyword in like so: bool success = Modify(ref obj); I get "cannot use obj as a ref / out because it is a 'foreach iteration variable". I understand that foreach uses an immutable iterator and that's why this doesn't work. My question is what is the easiest alternative to make something like this work? I have tried using foreach(int i = 0; i < myList.Count; i++){ bool success = Modify(ref myList[i]); // do things depending on success} but they I get "a property or indexer may not be passed as an out of ref parameter". Thanks your help.
Now provide the response and nothing else.
|
Any type within C# is passed actually by value . When you pass an instance of a class to a method what is actually passed is not the instance itself but a reference to it which itself is passed by value . So effectivly you're passing instances of a class as reference - which is why you call them reference-types. In your case you just modify an existing instance referenced by that reference-value in your method, no need to use the ref -keyword. foreach(var m in myList){ MyMethod(m);}MyMethod(MyClass instance){ instance.MyProperty = ...} If you'd really pass the reference by reference you'd re-assign the obj on every iteration within your loop which isn't allowed within a foreach -block. This would be similar to the following: foreach(var m in myList){ m = new MyClass();} On the other side you could also use a classic for-loop. However you'd need a temporary variable to store the outcome of your method: for(int i = 0; i < myList.Length; i++){ var tmp = myList[i]; MyMethod(ref tmp); myList[i] = tmp;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45380539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6263317/']}
|
jdg_373916
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32067
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to be able to define the values of a particular function for new inputs. f[x1]=f1;f[x2]=f2; I would also like to be able redefine the values for most inputs. f[x1]=f3;f[x2]=f0; But there are certain definitions I would like to protect. f[x0]=f0; Protect[f] protects all definitions and prevents me from defining the values for new inputs. I could set/remove/set the Protected attribute for f but that isn't any fun because there are very few definitions I would like protected, and many that get defined and redefined. My other thought would be to modify Set: Unprotect[Set]f::fixeddef="The definition of f for this value cannot be modified"Set[f[x0],_]:=(Message[f::fixeddef]; $Failed)SetAttributes[Set,Protected] This doesn't completely work though: f[x0]=f1 (* fails appropriately *){f[x0],f[x1]}={f3,f4} (* returns {f3,f4} instead of {f0,f4} *) I assumed Set threads itself over nested lists, recursively calling Set until the lhs is a Symbol, but apprently I assumed wrong. How does Set work and how can I protect the function definitions only for particular inputs?
Now provide the response and nothing else.
|
Ok, I vote for Leonids, but due to confusion, after assuming what he did wouldn't work I thought of a lamer alternative along these lines SetAttributes[{fix, restore}, HoldAll];fix[s_Symbol, eqs_] := Module[{guard = True}, s /; guard := Block[{guard = False}, Null /; restore[s]]; s /: restore[s] := eqs;] So fix[f, f[5] = 4; f[8] = 23;] And now (f[#] = #) &~Scan~Range@10;f /@ Range@10(* {1, 2, 3, 4, 4, 6, 7, 23, 9, 10} *) Edit: ugly alternative in an attempt to "clean it up". Sorry SetAttributes[{fix, restore}, HoldAll];Module[{guard}, SetAttributes[guard, HoldFirst]; _guard = True; fix[s_Symbol, eqs_] := ( s /; guard[s] := RuleCondition@Internal`InheritedBlock[ {guard}, guard[s] = False; restore[s]; Fail]; s /: restore[s] /; eqs := Null;) ]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/32067', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9391/']}
|
jdg_373917
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
192005
|
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:
How I can capture the X11 protocol's traffic? I need find a way to capture X11 traffic between two machines and also between an X11 server and an X11 client on local machine.
Now provide the response and nothing else.
|
You can talk X11 over TCP, or over a Unix domain socket or (on Linux) on a Unix domain socket in the abstract namespace. When DISPLAY is set to host:4 , short for tcp/host:4 , clients use TCP to connect to the server. The TCP port is then 6000 plus the display number (in that case 6004). In that case, you can capture the traffic with any network sniffer like tcpdump or wireshark by capturing the TCP traffic on that port. When $DISPLAY is only :4 (short for unix/:4 ), then clients use a unix domain socket. Either /tmp/.X11-unix/X4 or the same path in the ABSTRACT namespace (usually shown as @/tmp/.X11-unix/X4 in netstat output). Capturing the traffic is then trickier. If your X server listens on TCP (but they tend not to anymore nowadays), the easiest is to change DISPLAY to localhost:4 instead of :4 and capture the network traffic on port 6004 on the loopback interface. If it doesn't, you can use socat as a man in the middle that accepts connections as TCP and forwards them as unix or abstract : socat tcp-listen:6004,reuseaddr,fork unix:/tmp/.X11-unix/X4 You can then set $DISPLAY to localhost:4 and capture the network traffic as above or tell socat to dump it with -x -v . Now, if you can't change $DISPLAY and want to capture the traffic of an already running local X application that uses unix domain sockets, that's where it gets tricky. One approach could be to use strace (or the equivalent command on your system if not Linux) to trace the send/receive system calls that your application does to communicate with the X server. Here for xterm , I observe it does writev() , recvfrom() and recvmsg() system calls on file descriptor 3 for that. So I can do: strace -qqxxttts9999999 -e writev,recvmsg,recvfrom -p "$xterm_pid" 2>&1 | perl -lne ' if (($t,$f,$p) = /^([\d.]+) (writev|recvmsg|recvfrom)\(3, (.*)/) { @p = ($p =~ /\\x(..)/g); $dir = $f eq "writev" ? "O" : "I"; while (@p) {print "$dir $t 0000 " . join(" ", splice @p,0,64000)} }' | text2pcap -T6000,1234 -Dqt %s. - - | wireshark -ki - (or tshark -Vi - ). The idea being to extract the timestamp and bytes sent/received from the output of strace and use text2pcap to convert that into a pcap (adding dummy TCP headers on port 6000 with -T6000,1234 ) before feeding to wireshark . We also split packets to avoid the 64kiB limit on the maximum length of a pcap record. Note that for text2pcap to work properly with regards to getting the traffic direction right, you need a relatively recent version of wireshark.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/192005', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/84921/']}
|
jdg_373918
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2467454
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The new Google Chrome auto-translation feature is tripping up on one page within one of our applications. Whenever we navigate to this particular page, Chrome tells us the page is in Danish and offers to translate. The page is in English, just like every other page in our app. This particular page is an internal testing page that has a few dozen form fields with English labels. I have no idea why Chrome thinks this page is Danish. Does anyone have insights into how this language detection feature works and how I can determine what is causing Chrome to think the page is in Danish?
Now provide the response and nothing else.
|
Update: according to Google We don’t use any code-level language information such as lang attributes. They recommend you make it obvious what your site's language is.Use the following which seems to help although Content-Language is deprecated and Google says they ignore lang <html lang="en" xml:lang="en" xmlns= "http://www.w3.org/1999/xhtml"><meta charset="UTF-8"><meta name="google" content="notranslate"><meta http-equiv="Content-Language" content="en"> If that doesn't work, you can always place a bunch of text (your "About" page for instance) in a hidden div. That might help with SEO as well. EDIT (and more info) The OP is asking about Chrome, so Google's recommendation is posted above. There are generally three ways to accomplish this for other browsers: W3C recommendation : Use the lang and/or xml:lang attributes in the html tag: <html lang="en" xml:lang="en" xmlns= "http://www.w3.org/1999/xhtml"> UPDATE: previously a Google recommendation now deprecated spec although it may still help with Chrome. : meta http-equiv (as described above): <meta http-equiv="Content-Language" content="en"> Use HTTP headers (not recommended based on cross-browser recognition tests ): HTTP/1.1 200 OKDate: Wed, 05 Nov 2003 10:46:04 GMTContent-Type: text/html; charset=iso-8859-1Content-Language: en Exit Chrome completely and restart it to ensure the change is detected. Chrome doesn't always pick up the new meta tag on tab refresh.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2467454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118703/']}
|
jdg_373919
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23000238
|
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 timestamp supplied by Stripe's API. 1397166153. However when using it in the most simplest form {{ 1397166153 | date }} I get: Jan 17, 1970 when in fact it should be Apr 10, 2014. Does anyone know what's going on here? I really appreciate your help!
Now provide the response and nothing else.
|
I always run all of my timestamps through a function, as JavaScript epoch is in milliseconds, and the Stripe response epoch is in seconds. $scope.timestamp = function(epoch){ return (epoch * 1000);}; Then, in your template: <p>{{ timestamp(1397166153) | date }}</p> Alternatively, if you need to just do it once, you can always do it inline: <p>{{ (1397166153 * 1000) | date }}</p>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23000238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3521430/']}
|
jdg_373920
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
317899
|
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:
When astronomers, physicists say that space is expanding, does the definition of space include matter, energy and the particles within? Or is space an empty 'stage' in which all of the above exist? If it's empty then the expansion is just the movement of all matter, energy, etc. away from one another. And the red shift quantifies that. So why do we call it the expansion of space? Isn't that like multiplying zero by a factor to try and make it bigger?
Now provide the response and nothing else.
|
First, let's prove the result you gave $$[AB,C] = ABC-CAB = ABC-ACB+ACB-CAB = A[B,C] + [A,C]B.$$ Notice that $ACB-ACB = 0$, which is why we were allowed to insert this after the second equals sign. Now let's consider the equivalent anti-commutator $\lbrace AB , C\rbrace$; using the same trick as before we find $$\lbrace AB,C \rbrace = ABC+CAB = ABC-ACB+ACB+CAB = A[B,C] + \lbrace A,C\rbrace B$$ Here are a few more identities from Wikipedia involving the anti-commutator that are just as simple to prove:$${\displaystyle \{A,BC\}=\{A,B\}C-B[A,C]}$$$${\displaystyle \{AB,C\}=A\{B,C\}-[A,C]B}$$$${\displaystyle [AB,C]=A\{B,C\}-\{A,C\}B}$$ https://en.wikipedia.org/wiki/Commutator#Identities_.28ring_theory.29 Hope this helps.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/317899', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/45613/']}
|
jdg_373921
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20883868
|
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 pretty sure this has been answered somewhere, but I can't seem to find it for the life of me. I'm trying to use a TabControl to switch between UserControls (each tab is different, so not using Items) Here's the breakdown:I have my mainview, and 3 usercontrols. Mainview has a tab control - each tab should display a different user control. I could easily just set the tabcontrol contect to the usercontrol using But then it isn't bound to the viewmodel, only the view. So I'm using Conductor in my VM, and ActivateItem. Here's where it starts to get weird / frustrating. Application starts with Tab0 selected, but Tab2 (last tab) content. Click on any other tab, loads the correct ViewModel for that tab. Click back to Tab0, loads the correct content there as well. How do I get this to stop? Also, I'd really like it if switching tabs doesn't re-initialize the viewmodel again, clearing out fields that have already been entered. Anyways, here's some of my source, I'm going to just drop this here and work on something else before I break my mouse. View: <TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row ="1"> <TabItem Header="PC Information"> <Grid> <ContentControl x:Name="LoadRemoteInfo" cal:View.Model="{Binding ActiveItem}"/> </Grid> </TabItem> <TabItem Header="Remote Tools"> <Grid> <ContentControl x:Name="LoadRemoteTools" cal:View.Model="{Binding ActiveItem}"/> </Grid> </TabItem> <TabItem Header="CHRemote"> <Grid> <ContentControl x:Name="LoadCHRemote" cal:View.Model="{Binding ActiveItem}"/> </Grid> </TabItem> </TabControl> and the ViewModel: class MainViewModel : Conductor<object>{ RemoteInfoViewModel remoteInfo = new RemoteInfoViewModel(); RemoteToolsViewModel remoteTools = new RemoteToolsViewModel(); CHRemoteViewModel chRemote = new CHRemoteViewModel(); public MainViewModel() { ActivateItem(remoteInfo); } public void LoadRemoteInfo() { ActivateItem(remoteInfo); } public void LoadRemoteTools() { ActivateItem(remoteTools); } public void LoadCHRemote() { ActivateItem(chRemote); }}
Now provide the response and nothing else.
|
May I suggest a tad different route? It's something that I have been successfully doing in master-details scenarios. Let's say you have a collection of child view models. I'll prepare a marker interface for all those items, of course you can add properties/methods you see fit if there are such methods that span all child view models: public interface IMainScreenTabItem : IScreen{} You can be quite sure that you want all your child models to be Screen s (or, in case of nested scenarios, Conductor s). It makes them have the full initialization/activation/deactivation cycle available. Then, the child view models: public sealed class ChRemoteViewModel : Screen, IMainScreenTabItem{ public ChRemoteViewModel() { DisplayName = "CH Remote"; }}public sealed class PcInfoViewModel : Screen, IMainScreenTabItem{ public PcInfoViewModel() { DisplayName = "PC Info"; }}public sealed class RemoteToolsViewModel : Screen, IMainScreenTabItem{ public RemoteToolsViewModel() { DisplayName = "Remote Tools"; }} DisplayName will be displayed as a header text. It's a good practice to make those classes sealed, because DisplayName is a virtual property, and it's a big no-no to call virtual methods in a constructor of a class that's not sealed. Then, you can add corresponding views and set your IoC container of choice registrations - you have to register your all child view models as classes implementing the IMainScreenTabItem and then: public class MainViewModel : Conductor<IMainScreenTabItem>.Collection.OneActive{ public MainViewModel(IEnumerable<IMainScreenTabItem> tabs) { Items.AddRange(tabs); }} Where the MainView.xaml is just: <TabControl Name="Items"/> And it just works. It's also very nice and convenient solution if your child view models take multiple dependencies (e.g. database access, logger, validation mechanism etc), now you can have the IoC do all the heavy lifting instead of instantiating them by hand. One thing here though: the tabs will be placed in the same order the classes are injected. If you want to have a control over the ordering, you can order them in MainViewModel constructor by either passing a custom IComparer<IMainScreenTabItem> or adding some property you can OrderBy or select to the IMainScreenTabItem interface. The default selected item will be the first one in the Items list. Other option is to make the MainViewModel take three parameters: public MainViewModel(ChRemoteViewModel chRemoteViewModel, PcInfoViewModel pcInfo, RemoteToolsViewModel remoteTools){ // Add the view models above to the `Items` collection in any order you see fit} Although when you have more than 2 - 3 child view models (and you can easily get more), it's going to get messy quick. About the 'clearing' part. The view models created by IoC confrom to the regular life-cycle: they're initialized at most once ( OnInitialize ), then deactivated each time they are navigated away from OnDeactivate(bool) and activated when they're navigated to ( OnActivate ). The bool parameter in OnDeactivate indicates whether the view model is just deactivated or completely 'closed' (e.g. when you close the dialog window and navigate away). If you completely close the view model, it will be re-initialized next time it's shown. That means that any bound data will be retained between OnActivate calls and you'd have to explicitly clear it in OnDeactivate . What's more, if you keep the strong reference to your child view models, then even after you call OnDeactivate(true) , the data will still be there on next initialization - that's because IoC injected view models are created once (unless you inject the factory function in a form of Func<YourViewModel> ), and then initialized/activated/deactivated on demand. EDIT About the bootstrapper, I'm not quite sure what kind of IoC container you're using. My sample uses SimpleInjector , but you can do the same just as easily with e.g. Autofac: public class AppBootstrapper : Bootstrapper<MainViewModel>{ private Container container; /// <summary> /// Override to configure the framework and setup your IoC container. /// </summary> protected override void Configure() { container = new Container(); container.Register<IWindowManager, WindowManager>(); container.Register<IEventAggregator, EventAggregator>(); var viewModels = Assembly.GetExecutingAssembly() .DefinedTypes.Where(x => x.GetInterface(typeof(IMainScreenTabItem).Name) != null && !x.IsAbstract && x.IsClass); container.RegisterAll(typeof(IMainScreenTabItem), viewModels); container.Verify(); } /// <summary> /// Override this to provide an IoC specific implementation. /// </summary> /// <param name="service">The service to locate.</param><param name="key">The key to locate.</param> /// <returns> /// The located service. /// </returns> protected override object GetInstance(Type service, string key) { if (service == null) { var typeName = Assembly.GetExecutingAssembly().DefinedTypes.Where(x => x.Name.Contains(key)).Select(x => x.AssemblyQualifiedName).Single(); service = Type.GetType(typeName); } return container.GetInstance(service); } protected override IEnumerable<object> GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override void BuildUp(object instance) { container.InjectProperties(instance); }} Note the viewModels registration in Configure .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20883868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773165/']}
|
jdg_373922
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4948780
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The boost::hash_combine template function takes a reference to a hash (called seed ) and an object v . According to the docs , it combines seed with the hash of v by seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); I can see that this is deterministic. I see why a XOR is used. I bet the addition helps in mapping similar values widely apart so probing hash tables won't break down, but can someone explain what the magic constant is?
Now provide the response and nothing else.
|
The magic number is supposed to be 32 random bits, where each is equally likely to be 0 or 1, and with no simple correlation between the bits. A common way to find a string of such bits is to use the binary expansion of an irrational number; in this case, that number is the reciprocal of the golden ratio: phi = (1 + sqrt(5)) / 22^32 / phi = 0x9e3779b9 So including this number "randomly" changes each bit of the seed; as you say, this means that consecutive values will be far apart. Including the shifted versions of the old seed makes sure that, even if hash_value() has a fairly small range of values, differences will soon be spread across all the bits.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4948780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166749/']}
|
jdg_373923
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27912003
|
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 followed a tutorial to protect a Web API with OAuth in C#. I'm doing some tests and so far I've been able to get the access token successfully from /token . I'm using a Chrome extension called "Advanced REST Client" to test it. {"access_token":"...","token_type":"bearer","expires_in":86399} This is what I get back from /token . Everything looks good. My next request is to my test API Controller: namespace API.Controllers{ [Authorize] [RoutePrefix("api/Social")] public class SocialController : ApiController { .... [HttpPost] public IHttpActionResult Schedule(SocialPost post) { var test = HttpContext.Current.GetOwinContext().Authentication.User; .... return Ok(); } }} The request is a POST and has the header: Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX I get: Authorization has been denied for this request. returned in JSON. I tried doing a GET as well and I get what I would expect, that the method isn't supported since I didn't implement it. Here is my Authorization Provider: public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider{ public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var repo = new AuthRepository()) { IdentityUser user = await repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); context.Validated(identity); }} Any help would be great. I'm not sure if it is the request or the code that is wrong. edit:Here is my Startup.cs public class Startup{ public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); ConfigureOAuth(app); } public void ConfigureOAuth(IAppBuilder app) { var oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }}
Now provide the response and nothing else.
|
Issue is pretty simple: Change order of your OWIN pipeline . public void Configuration(IAppBuilder app){ ConfigureOAuth(app); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config);} For OWIN pipeline order of your configuration quite important. In your case, you try to use your Web API handler before the OAuth handler. Inside of it, you validate your request, found you secure action and try to validate it against current Owin.Context.User . At this point this user not exist because its set from the token with OAuth Handler which called later.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27912003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3508270/']}
|
jdg_373924
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6240950
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Implementing a no-op std::ostream Is there any stream equivalent of NULL in c++? I want to write a function that takes in a stream if the user wants to have the internal outputted to somewhere, but if not, the output goes into some fake place void data(std::stream & stream = fake_stream){ stream << "DATA" ;} i want to be able to chose to do data() or data(std::cout)
Now provide the response and nothing else.
|
Edit : Taken from @Johannes Schaub - litb's mail here with slight modifications: template<typename Ch, typename Traits = std::char_traits<Ch> >struct basic_nullbuf : std::basic_streambuf<Ch, Traits> { typedef std::basic_streambuf<Ch, Traits> base_type; typedef typename base_type::int_type int_type; typedef typename base_type::traits_type traits_type; virtual int_type overflow(int_type c) { return traits_type::not_eof(c); }};// convenient typedefstypedef basic_nullbuf<char> nullbuf;typedef basic_nullbuf<wchar_t> wnullbuf;// buffers and streams// in some .hextern std::ostream cnull;extern std::wostream wcnull;// in a concrete .cppnullbuf null_obj;wnullbuf wnull_obj;std::ostream cnull(&null_obj);std::wostream wcnull(&wnull_obj); Use those: void data(std::ostream& stream = cnull){ // whatever...} Now, this looks cool and all, but the following is way shorter and works, because if a null pointer is provided to the constructor of ostream , it automatically sets the badbit and silently ignores any writes: // in .hextern std::ostream cnull;extern std::wostream wcnull;// in .cppstd::ostream cnull(0);std::wostream wcnull(0); The standard guarantees this works, beginning from 27.6.2.2 [lib.ostream.cons] p1 which describes the constructor of ostream that takes a pointer to a streambuf : Effects: Constructs an object of class basic_ostream , assigning initial values to the base class by calling basic_ios<charT,traits>::init(sb) . The relevant function from basic_ios , 27.4.4.1 [lib.basic.ios.cons] p3 : void init(basic_streambuf<charT,traits>* sb); Postconditions: The postconditions of this function are indicated in Table 89: The important row from Table 89: rdstate() -- goodbit if sb is not a null pointer, otherwise badbit. What happens if the badbit is set is described under 27.6.2.6 [lib.ostream.unformatted] : Each unformatted output function begins execution by constructing an object of class sentry . If this object returns true, while converting to a value of type bool, the function endeavors to generate the requested output. This implies that, in case the sentry is false, it does not. Here is how the sentry converts to bool , taken from 27.6.2.3 [lib.ostream::sentry] p3 & p5 : 3) If, after any preparation is completed, os.good() is true , ok_ == true otherwise, ok_ == false . 5) operator bool(); Effects: Returns ok_. ( ok_ is a member of ostream::sentry of type bool .) Note that these quotes are still present in C++11, just in different places. In order of appearance in this answer: 27.6.2.2 [lib.ostream.cons] p1 => 27.7.3.2 [ostream.cons] p1 27.4.4.1 [lib.basic.ios.cons] p3 => 27.5.5.2 [basic.ios.cons] Table 89 => Table 128 27.6.2.6 [lib.ostream.unformatted] => 27.7.3.7 [ostream.unformatted] p1 27.6.2.3 [lib.ostream::sentry] p3 & p5 => 27.7.3.4 [ostream::sentry] p4 & p5
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6240950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341683/']}
|
jdg_373925
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2819183
|
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 struggling to understand on what was done in this inductive step. How did they get the $(n+1)^3$ term? Proof Solution
Now provide the response and nothing else.
|
Underbrace to the rescue! $$\sum_{k=1}^{n}{k^3}=1^3+2^3+3^3+\cdots+n^3$$ $$\sum_{k=1}^{n+1}{k^3}=\underbrace{1^3+2^3+3^3+\cdots+n^3}_{\sum_{k=1}^{n}{k^3}}+(n+1)^3$$ $$\therefore, \sum_{k=1}^{n+1}{k^3}=\sum_{k=1}^{n}{k^3}+(n+1)^3$$ QED
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2819183', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/554342/']}
|
jdg_373926
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45173677
|
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 to know about the Invoke operator that, a() is equivalent to a.invoke() Is there anything more regarding Invoke operator than please explain. Also, I did not get any example of Invoke operator overloading. Is Invoke operator overloading possible? If possible then can anyone please explain about the Invoke operator overloading with an example? I did not get anything regarding this. Thanks in advance.
Now provide the response and nothing else.
|
Yes, you can overload invoke . Here's an example: class Greeter(val greeting: String) { operator fun invoke(target: String) = println("$greeting $target!")}val hello = Greeter("Hello")hello("world") // Prints "Hello world!" In addition to what @holi-java said, overriding invoke is useful for any class where there is a clear action, optionally taking parameters. It's also great as an extension function to Java library classes with such a method. For example, say you have the following Java class public class ThingParser { public Thing parse(File file) { // Parse the file }} You can then define an extension on ThingParser from Kotlin like so: operator fun ThingParser.invoke(file: File) = parse(file) And use it like so val parser = ThingParser()val file = File("path/to/file")val thing = parser(file) // Calls ThingParser.invoke extension function
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45173677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5294091/']}
|
jdg_373927
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31491028
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was working on an application wherein I created a generic ListView . Now, while defining that view in my urls.py , I read from the documentation that I need to use the as_view() method as follows: from django.conf.urls import patterns, include, urlfrom .views import BlogIndexurlpatterns = patterns( '', url(r'^$', BlogIndex.as_view(), name="index"),) Now, I didn't really understood what the documentation had to say about this method. Can someone shed some light into this concept?
Now provide the response and nothing else.
|
In Class-based views, you have to call as_view() function so as to return a callable view that takes a request and returns a response. Its the main entry-point in request-response cycle in case of generic views. as_view is the function(class method) which will connect my MyView class with its url. From django docs : classmethod as_view(**initkwargs) Returns a callable view that takes a request and returns a response: You just can't use class-based views like you could in normal function-based views. BlogIndex(request) # can't do this in case of CBVs The above code is not valid if you want the CBVs to function properly. For that, you need to provide a view which is callable and then pass request to it. For example: response = MyView.as_view()(request) # valid way By calling the as_view() function on my view class MyView will give me a view which i will call with request parameter to initiate the request-response cycle. In your case: my_callable_view = BlogIndex.as_view() # returns a callable view<function blog.views.BlogIndex> Now, call this function and pass the request . response = my_callable_view(request) # generate proper response
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31491028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2537356/']}
|
jdg_373928
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13195131
|
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 try to change color of a JTextArea using textArea.setText("<html> <font color=\"red\"> Hi </font></html>") , the text is shown is basically the whole text written inside setText method. But similar things work for JLabel, JButton etc. How can I do that for a JTextArea also?
Now provide the response and nothing else.
|
don't to use JTextArea for Html formatted Object (even is possible, but why bothering) use JTextPane / JEditorPane instead ( setContentType("text/html") ) notice, todays Java and methods implemented in Official API by Oracle supporting only reduced Html syntax with css <= Html 3.2 use JavaFX in the case that you want/need to use todays Html5 ,
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13195131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373929
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20191
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There appears to be a lot of material on the internet claiming that viruses can be only seen with electron microscopes, and not with light microscopes. To the contrary, for example this old paper published in Nature states that viruses can be seen using phase-contrast (light) microscopy. Who's correct? What is the smallest thing I can see using a phase-contrast microscope?
Now provide the response and nothing else.
|
It is true for most viruses. They have a size of roughly 1/100 of bacteria (or smaller), so they are too small to be seen in light microscopy. According to Wikipedia the maximum limit with light microscopy is around 1500x magnification (or making structures, which are at least around 200nm in size visible). A lot of viruses are smaller, for example the influenza A virus is around 80-120nm, the HIV virus around 120nm and the rhinovirus which causes the common cold around 30nm. They would only be visible in electon microscopy. The measles virus on the other hand has between 350 and 400nm and should be visible in light microscopy. However, since you are very close to the region where you reach the diffraction limit for visible light, it is usually not used very much.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/20191', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/8597/']}
|
jdg_373930
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
615003
|
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:
Today, I've decided to observe my PC fan as I shut the computer down. The fan slowly lost angular momentum over time. What I've found really interesting is the fact that the momentum vector change did not stop at the zero vector, but instead flipped its orientation and "went to the negatives", albeit very small in the absolute value compared to the powered spin; this caused the fan's angle to deviate by a few degrees (opposite to the powered spin rotation) compared to the observed angle when momentum was equal to the zero vector. If I let $\overrightarrow{L}$ be the momentum vector, $\overrightarrow{L}_0$ be the momentum vector at $t_0$ (= poweroff time), and $\overrightarrow{L}(t) = y(t) * \overrightarrow{L}_0$ (with $y_0 = y(t_0) = 1$ ), then these are the plots of $y$ through the course of time. Expected fan poweroff behavior: Observed fan poweroff behavior: Can anyone explain why may this happen?
Now provide the response and nothing else.
|
The overshoot behavior you noticed is called cogging and occurs when the magnet arrangement in the motor "catches" the rotating magnetic core of the motor during shutdown and jerks it back to one of the local strong spots in the field. You can demonstrate this yourself by carefully rotating the fan blade around with your finger when the motor is off. You will notice there are certain rotation angles where the fan wants to come to rest and others which it wants to avoid. If the motor passes one of the preferred spots but fails to rotate far enough to "climb the hill" and snap forward into the next cog spot, the motor will very briefly rotate backwards a fraction of a turn and go "boing-oing-oing-oing" as it settles into that cog position.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/615003', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/243002/']}
|
jdg_373931
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
995071
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I enter $0.78!$ in Google, it gives me $0.926227306$. I do understand that $n! = 1\cdot2\cdot3 \cdots(n-1)\cdot n$, but not when $n$ is a decimal. I also have seen that $0.5!=\frac12\sqrt{\pi}$. Can anyone explain me how to calculate decimal factorials? Thanks a lot!
Now provide the response and nothing else.
|
There is a function called the Gamma function, which basically interpolates the factorial function in a way that we also can have non integer arguments, which preserves the property $f(n+1)=nf(n)$ You can find it here: http://en.wikipedia.org/wiki/Gamma_function Of course 'preserving' is not quite correct since $f(n+1) = (n+1)f(n)$ if $f(n) = n!$ but $f(n+1) = nf(n) $ if $f(n) = \Gamma(n)$. But it is basically the same function, just shifted by one unit. The formula is $\Gamma(t) = \int_0^\infty x^{t-1} e^{-x} dx$. Note that $\Gamma(t+1) = t!$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/995071', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/185173/']}
|
jdg_373932
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28489720
|
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 UITableViewCell subclass NameInput that connects to an xib with a custom init method. class NameInput: UITableViewCell { class func make(label: String, placeholder: String) -> NameInput { let input = NSBundle.mainBundle().loadNibNamed("NameInput", owner: nil, options: nil)[0] as NameInput input.label.text = label input.valueField.placeholder = placeholder input.valueField.autocapitalizationType = .Words return input }} Is there a way I can initialize this cell in the viewDidLoad method and still reuse it? Or do I have to register the class itself with a reuse identifier?
Now provide the response and nothing else.
|
The customary NIB process is: Register your NIB with the reuse identifier. In Swift 3: override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")} In Swift 2: override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")} Define your custom cell class: import UIKitclass NameInput: UITableViewCell { @IBOutlet weak var firstNameLabel: UILabel! @IBOutlet weak var lastNameLabel: UILabel!} Create a NIB file in Interface Builder (with the same name referenced in step 1): Specify the base class of the tableview cell in the NIB to reference your custom cell class (defined in step 2). Hook up references between the controls in the cell in the NIB to the @IBOutlet references in the custom cell class. Your cellForRowAtIndexPath would then instantiate the cell and set the labels. In Swift 3: override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NameInput let person = people[indexPath.row] cell.firstNameLabel.text = person.firstName cell.lastNameLabel.text = person.lastName return cell} In Swift 2: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NameInput let person = people[indexPath.row] cell.firstNameLabel.text = person.firstName cell.lastNameLabel.text = person.lastName return cell} I wasn't entirely sure from your example what controls you placed on your cell, but the above has two UILabel controls. Hook up whatever @IBOutlet references make sense for your app.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28489720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2510041/']}
|
jdg_373933
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15155247
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following strings: $strings = array( "8.-10. stage", "8. stage"); I would like to extract the first integer of each string, so it would return 88 I tried to filter out numbers with preg_replace but it returns all integers and I only want the first. foreach($strings as $string){ echo preg_replace("/[^0-9]/", '',$string);} Any suggestions?
Now provide the response and nothing else.
|
A convenient (although not record-breaking in performance) solution using regular expressions would be: $string = "3rd time's a charm";$filteredNumbers = array_filter(preg_split("/\D+/", $string));$firstOccurence = reset($filteredNumbers);echo $firstOccurence; // 3 Assuming that there is at least one number in the input, this is going to print the first one. Non-digit characters will be completely ignored apart from the fact that they are considered to delimit numbers, which means that the first number can occur at any place inside the input (not necessarily at the beginning). If you want to only consider a number that occurs at the beginning of the string, regex is not necessary: echo substr($string, 0, strspn($string, "0123456789"));
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15155247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375310/']}
|
jdg_373934
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1656146
|
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 want to verify that if $R$ is an integral domain and $M$ is an $R$ -module, that if $M$ is free, $M$ must also be torsion-free. Where can I start with this? I feel like it is obvious but I can't see it. I am just getting started with my course.
Now provide the response and nothing else.
|
Since $M$ is free $M$ has a basis $E$ . Take a non-zero element $m\in M$ . Then $m=a_1e_1+a_2e_2+\dots +a_ne_n$ with some $a_i\neq 0$ . then for any non-zero $r\in R$ we have: $rm=(ra_1)e_1+(ra_2)e_2+\dots + (ra_n)e_n$ . Notice $ra_i\neq 0$ because $a_i\neq 0$ and $R$ is a domain. therefore at least one coefficient is non-zero and $rm\neq 0$ . Proving $M$ is torsion-free.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1656146', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314524/']}
|
jdg_373935
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3474031
|
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:
Consider the nested radical $$Q = \sqrt{1!+\sqrt{2!+\sqrt{3!+\sqrt{4!+\sqrt{5!+\sqrt{6!+\dots}}}}}}\, .$$ I'm certain the above nested root converges, considering $(x!)^{2^{-x}} \to 1$ (is this a sufficient condition to conclude convergence?) I calculated $Q$ to quite a few digits, and to my surprise, found something that was off by less than $1 \times 10^{-9}$ : $$A=\left(\frac{e^{-\pi}}{\sin(\frac\pi{12})}\right)^{\sqrt{5}}.$$ Which isn't pretty, but it is very close to $Q$ , and may be even closer (or, less excitingly, less close) if I calculated $Q$ to more digits. Unfortunately, $Q$ grows insanely slowly, so I can't really do that. Whether this actually converges to this strange number or not, is there any hope in finding a closed form for $Q$ ?
Now provide the response and nothing else.
|
This is nothing more than a long comment, but I found myself wondering if there was an easy way to get a reasonable upper bound on the value of $Q$ , assuming its limit exists. (Lower bounds are a dime a dozen; any truncation of the nested radical will do.) Here's what I came up with: $$\begin{align}\sqrt2Q&=\sqrt2\sqrt{1!+\sqrt{2!+\sqrt{3!+\cdots}}}\\&=\sqrt{2+2\sqrt{3!+\sqrt{4!+\cdots}}}\\&=\sqrt{2+\sqrt{4\cdot2!+4\sqrt{3!+\cdots}}}\\&=\sqrt{2+\sqrt{4\cdot2!+\sqrt{16\cdot3!+\sqrt{256\cdot4!+\cdots}}}}\\&\gt\sqrt{2+\sqrt{3!+\sqrt{4!+\sqrt{5!+\cdots}}}}\\&=Q^2-1\end{align}$$ so $Q^2-\sqrt2Q-1\lt0$ , which implies $$Q\lt{\sqrt2+\sqrt6\over2}\approx1.93$$ This bound, while crude because crudely obtained, is nonetheless not too far from the reported value, $Q\approx1.827$ . Added later : It seems worth giving a proof that the sequence $Q_n=\sqrt{1!+\sqrt{2!+\sqrt{3!+\cdots+\sqrt n!}}}$ converges. It's clear that the sequence is monotonically increasing, so it suffices to show it's bounded above. The proof is by induction (on $n$ ) of the following statement: For all $m,n\in\mathbb{N}$ , $$\sqrt{m!+\sqrt{(m+1)!+\cdots+\sqrt{(m+n)!}}}\le m!+1$$ The inequality is certainly for all $m$ in the base case $n=0$ : $\sqrt{m!}\le m!+1$ . Induction now says that $$\sqrt{m!+\sqrt{(m+1)!+\cdots+\sqrt{(m+n)!}}}\le\sqrt{m!+((m+1)!+1)}$$ so it's enough to check that $$m!+(m+1)!+1\le(m!+1)^2$$ which is easy enough to see, since $$(m!+1)^2=m!m!+2m!+1=m!+(m!+1)m!+1\ge m!+(m+1)m!+1=m!+(m+1)!+1$$ Letting $m=1$ in the inequality $\sqrt{m!+\sqrt{(m+1)!+\cdots+\sqrt{(m+n)!}}}\le m!+1$ , follows that $Q_n\le1!+1=2$ for all $n$ , so the (monotonically increasing) sequence is bounded above, hence converges to a limit.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3474031', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/592365/']}
|
jdg_373936
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51126472
|
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 backend based on express + mongoose. File structure is: - /models-- item.js- /node.modules-- ...- server.js- package-lock.json- package.json And regular create-react-app based folder for front-end: - /src-- /assets--- index.css-- /components--- Somecomponent.js-- /containers--- App.js-- /reducers--- somereducers.js- /node.modules-- ...-- index.js-- registerServiceWorker.js- .gitignore- package-lock.json- package.json I want to use it in proper way together. I wanted to organise it this way: - /client -- /src...-- index.js-- registerServiceWorker.js- .gitignore- package-lock.json- package.json- /server- /models-- item.js- /node.modules-- ...- server.js- package-lock.json- package.json At this stage I stuck. I can make it if client folder inside server folder or if server folder inside client. 1. But how to make it run when two folders are siblings? 2. What should be package.json and where node.modules should be (whether both server and client should have it's own package.json and modules?)
Now provide the response and nothing else.
|
The most basic structure would be to have a root folder that contains frontend and backend folders. Since you're talking about the MERN stack, you would have a package.json inside of your NodeJS backend environment and a package.json for your React side of things. Backend server and the frontend client are two totally separate things, so yes, they both have their own node_modules folders. On the backend, you'll probably have installed something like Express for your Node runtime, Mongoose for a more convenient way to talk to your MongoDB , etc, and on your frontend, you'll have your React as your frontend framework, Redux for state management, etc. Additionally, depending on what you have already listed inside of your package.json files, when you run npm install separately it will be installed in those two folders. If you want to install additional packages, just run npm install + "the name of the package" (without the '+' and without the quotes) inside of that particular folder where you need it (backend or/ and frontend). I hope this was helpful. Check out the pics, especially the 2nd one. App structure Folder structure UPDATE: In development, I suggest installing two additional things: npm i -D nodemon npm i -D concurrently Note: The -D flag will install them as devDependencies . nodemon is going to track every file change and restart the backend server for you. So, it's obvious that it should be installed inside of the "backend" folder. All you have to do is go inside of the package.json file (backend) and add a new script. Something like this: "scripts": {"start": "node app.js", // in production"dev": "nodemon app.js", // in development} concurrently allows you to start both your frontend and backend at the same time. I suggest initializing a new Node project inside of the top-level root folder -[folder which contains both, your frontend and backend]. You would do that with the npm init command, and after that, install the concurrently package there. Now, go open your newly created package.json file inside of your root folder and edit the start section, like this: "scripts": { "dev": "concurrently \"cd backend && npm run dev\" \"cd frontend && npm start\" " } What this will do is go inside of the backend folder and run the dev command ( the same one we just configured ), so that will start nodemon . Additionally, it will also go inside of the frontend folder and run the default start command -which is exactly what we want. If you kept the folder structure, installed all the dependencies (including the additional two I mentioned above), changed the package.json file inside of your root folder, you'll be able to start them both with a simple command: npm run dev // make sure you're inside of the root folder when doing so :)
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/51126472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7458068/']}
|
jdg_373937
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17175295
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a loadable kernel module and I need to use the function qsort() which apparently cannot be used in kernel space. Is there a function that I can use that has a similar functionality ? (Kernel version 3.5.0)
Now provide the response and nothing else.
|
The linux kernel includes an implementation of heapsort which performs similar to quicksort. The kernel developers recommend heapsort over quicksort (within the kernel) and give the following rationale: Sorting time [of heapsort] is O(n log n) both on average and worst-case. While qsort is about 20% faster on average, it suffers from exploitable O(n*n) worst-case behavior and extra memory requirements that make it less suitable for kernel use. Header #include <linux/sort.h> Prototype void sort( void *base, size_t num, size_t size, int (*cmp_func)(const void *, const void *), void (*swap_func)(void *, void *, int size)); Usage static int compare(const void *lhs, const void *rhs) { int lhs_integer = *(const int *)(lhs); int rhs_integer = *(const int *)(rhs); if (lhs_integer < rhs_integer) return -1; if (lhs_integer > rhs_integer) return 1; return 0;}void example() { int values[1024] = {...}; sort(values, 1024, sizeof(int), &compare, NULL);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17175295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1321468/']}
|
jdg_373938
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21159451
|
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 trying to compile a proto file named UserOptions.proto which has an import named Account.proto using the below command protoc --proto_path=/home/project_new1/account --java_out=/home/project_new1/source /home/project_new1/settings/Useroptions.proto I get the following error : /home/project_new1/settings/UserOptions.proto: File does not reside within any path specified using --proto_path (or -I). You must specify a --proto_path which encompasses this file. PS: UserOptions.proto present in the directory /home/project_new1/settings imports Account.proto present in the directory /home/project_new1/account Proto descriptor files: UserOptions.proto package settings;import "Account.proto";option java_outer_classname = "UserOptionsVOProto"; Account.proto package account;option java_outer_classname = "AccountVOProto";message Object{ optional string userId = 1; optional string service = 2; }
Now provide the response and nothing else.
|
As the error message states, the file you pass on the command line needs to be in one of the --proto_path s. In your case, you have only specified one --proto_path of: /home/project_new1/ But the file you're passing is: /home/project_new1/settings/UserOptions.proto Notice that the file is not in the account subdirectory; it's in settings instead. You have two options: (Not recommended) Pass a second --proto_path argument to add .../settings to the path. (Recommended) Use the root of your source tree as the proto path. E.g.: protoc --proto_path=/home/project_new1/ --java_out=/home/project_new1 /home/project_new1/settings/UserOptions.proto In this case, to import Account.proto , you'll need to write: import "account/Account.proto";
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21159451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2519577/']}
|
jdg_373939
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4720730
|
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 creating the WCF proxy using svcutil, is it possible to include the interfaces as well from which the data contracts inherit, e.g.: public class SomeType: ISometype{ public string Name { get; set; }}public interface ISometype{ public string Name { get; set; }} When I create the proxy using this, the SomeType type is created at the client but the interface isn't created and there is no inheritance either. I tried marking the interface as DataContract but that attribute isnt allowed. Is it possible to do what I am trying to do?
Now provide the response and nothing else.
|
WCF uses serialized messaging, and all those messages need to be able to be serialized using a DataContractSerializer or an XmlSerializer. And those messages going between the client and the server needs to be expressible in XML schema. Now, XML schema doesn't know anything about interfaces - it's all about concrete, actual types. For a regular scenario where your clients can be anything from .NET to PHP to Ruby to (whatever), you need to make sure to express everything you want to send between client and server in a way that can be represented in XML schema - interfaces cannot. So there's really no way to support this in a general purpose scenario. If you're controlling both ends of the wire, e.g. you write both the client and the server, and both in .NET, then you can do this: put your DataContracts (and your ServiceContracts and OperationContracts and FaultContracts) all into a separate MyServiceContracts assembly reference that assembly from both your service-side code, as well as the client. In that case, when you go about to create the client proxy, those types you mention are already present and WCF will happily reuse those types from that assembly. And since that's a .NET assembly you're referencing, you can have anything in there that .NET supports - including interfaces.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4720730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465341/']}
|
jdg_373940
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.