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
5137042
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using urlib to hit my app not a browser so I can't see the debug screen when an error occurs. What's the best way to send the normal debug info to the console or a file? Edit: I'm already catching the output of the page but when I print that to the screen it's filled with tons of useless html. can I get just the error? Now provide the response and nothing else.
Update - 2016 This post is still getting hits. I recommend using one of the approaches below that use the built in logging system. In the same way exceptions are piped to the admin email handler, you can send the data to a console logger, file logger, or anywhere else (solely, or in addition to the email handler.) Original answer Well, the easiest way is to set debug mode OFF and let django email you the error, since that literally takes 5 seconds: http://docs.djangoproject.com/en/dev/howto/error-reporting/ Otherwise, I'd write a middleware that logs the exception, but it's a little more of a pain if you want the stack trace. Here's the documentation. import tracebackimport sysfrom __future__ import print_functionclass ProcessExceptionMiddleware(object): def process_exception(self, request, exception): # Just print the exception object to stdout print(exception) # Print the familiar Python-style traceback to stderr traceback.print_exc() # Write the traceback to a file or similar myfile.write(''.join(traceback.format_exception(*sys.exc_info())))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5137042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107074/']}
jdg_376141
stackexchange
llm_judgeable_groundtruth_similarity
20622529
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just want to make sure I got how Ack-ing works in Storm.I have 1 spout and 2 bolts chained together. Spout emits tuple to Bolt1 which in turn will emit a tuple to Bolt 2. I want Bolt 2 to ack the initial tuple sent from Spout and I'm not sure how. In order to guarantee fault tolerance (ie: tuples are resent) I want to ack in bolt 2 the tuple emitted by Spout just in case it fails somewhere in the process so it can be resent. Consider this example: Spout: _collector.emit(new Values(queue.dequeue()) Bolt1: def execute(tuple: Tuple) { _collector.emit(tuple, new Values("stuff"))} At this point tuple is the tuple sent by the spout. I can ack it here w no probs. Now add another bolt which listens in on tuples emitted by Bolt1. Bolt2: def execute(tuple2: Tuple) { _collector.emit(tuple2, new Values("foo"))} At this point the tuple in tuple2 is the tuple sent from Bolt1 (the one that has string "stuff" in it). So if I send an ack in Bolt2 this will ack the tuple from Bolt1 not the one sent from Spout. Correct? How can I ack the tuple that was sent from the spout? Should I piggy back the initial spout on all the other spouts so I can retrieve it in the last Bolt and ack it? I read Nathan's tutorials and I got the impression that I could ack the tuple received in Bolt1 (from Spout) right there after emitting tuple2. This would link the newly emitted tuple2 to the original tuple sent by Spout so when Bolt2 acks tuple 2 it actually acks the original tuple from the Spout. Is this true? Let me know if I'm missing something in my explanation. Now provide the response and nothing else.
For those interested, I've found a solution by asking on the storm group. What I need is in Spout to emit tuples the following way (with a unique ID): Spout: //ties in tuple to this UID _collector.emit(new Values(queue.dequeue(), *uniqueID*) Then Bolt1 will ack the tuple only after it emits it to Bolt2 Bolt1: //emit first then ack _collector.emit(tuple, new Values("stuff")) //**anchoring** - read below to see what it means _collector.ack(tuple) At this point tuple from Spout has been acked in Bolt1, but at the same time the newly emitted tuple "stuff" to Bolt2 is "anchored" to the tuple from Spout. What this means is that it still needs to be acked later on otherwise on timeout it will be resent by spout. Bolt2: _collector.ack(tuple) Bolt2 needs to ack the tuple received from Bolt1 which will send in the last ack that Spout was waiting for. If at this point Bolt2 emits tuple, then there must be a Bolt3 which will get it and ack it. If the tuple is not acked at the last point, Spout will time it out and resend it. Each time anchoring is done on an emit statement from bolt to bolt, a new node in a "tree" structure is built... well more like a list in my case since I never send the same tuple to 2 or more tuples, I have a 1 to 1 relationship. All nodes in the tree need to be acked, and only then the tuple is marked as fully arrived. If the tuple is not acked and it is sent with a UID and anchored later on then it will be kept in memory forever (until acked). Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20622529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1007845/']}
jdg_376142
stackexchange
llm_judgeable_groundtruth_similarity
2705583
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 just wondering how I can use JavaScript to simulate a click on an element. Currently I have: function simulateClick(control) { if (document.all) { control.click(); } else { var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); control.dispatchEvent(evObj); }} <a href="http://www.google.com" id="mytest1">test 1</a><br><script type="text/javascript"> simulateClick(document.getElementById('mytest1'));</script> But it's not working :( Any ideas? Now provide the response and nothing else.
[ Edit 2022 ] The answer was really outdated. Modernized it. The original answer is at the bottom. Use element.dispatchEvent with a freshly created Event of the desired type. Here's an example using event delegation . Fork this stackblitz project to play around with it. // Note: {bubbles: true} because of the event delegation ...document.addEventListener(`click`, handle);document.addEventListener(`virtualhover`, handle);// the actual 'trigger' functionconst trigger = (el, etype, custom) => { const evt = custom ?? new Event( etype, { bubbles: true } ); el.dispatchEvent( evt );};// a custom event ;)const vHover = new CustomEvent(`virtualhover`, { bubbles: true, detail: `red` });setTimeout( _ => trigger( document.querySelector(`#testMe`), `click` ), 1000 );function handle(evt) { if (evt.target.id === `clickTrigger`) { trigger(document.querySelector(`#testMe`), `click`); } if (evt.type === `virtualhover`) { evt.target.style.color = evt.detail; return setTimeout( _ => evt.target.style.color = ``, 1000 ); } if (evt.target.id === `testMe`) { document.querySelector(`#testMeResult`) .insertAdjacentHTML(`beforeend`, `<p>One of us clicked #testMe. It was <i>${evt.isTrusted ? `<b>you</b>` : `me`}</i>.</p>`); trigger( document.querySelector(`#testMeResult p:last-child`), `virtualhover`, vHover ); }} body { font: 1.2rem/1.5rem verdana, arial; margin: 2rem;}#testMe { cursor: pointer;}p { margin: 0.2rem 0;} <div id="testMe"> Test me can be clicked</div><p><button id='clickTrigger'>Click #testMe</button></p><div id="testMeResult"></div> The old answer : Here's what I cooked up. It's pretty simple, but it works: function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); }}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2705583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290957/']}
jdg_376143
stackexchange
llm_judgeable_groundtruth_similarity
4909369
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm attempting to match a timecode in the format of "0000" to "2459". How can I match numbers in a specific range, so that I could specifically match all numbers between 0 and 24 and all numbers between 0 and 59, and nothing greater or lesser? I know how to match each individual digit, but that won't do what I want because for example /[0-2][0-4]/ would capture numbers 0-4, 10 - 14, and 20-24, missing those in between. So I want to capture all inclusive for multiple digits. Now provide the response and nothing else.
The following should do the trick: /(?:[01][0-9]|2[0-4])[0-5][0-9]/ Explanation: The ?: makes the parentheses non-capturing. In the parentheses we simply match either 00-19 or 20-24. After that we match 00-59.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4909369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/331892/']}
jdg_376144
stackexchange
llm_judgeable_groundtruth_similarity
364533
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 thinking, maybe a well known problem, of whether there exists a fair gamble game for two persons by tossing one dishonest coin that will always stop(one winner is selected) at no more than $N$ steps for some finite $N$. My intuition is No. Now provide the response and nothing else.
You are correct that this is not always possible. It depends upon $p$. For $N$ flips there are $2^N$ sequences, each with a certain probability that you can figure out if you know the probability the coin shows heads using the binomial distribution. To make a fair game, you need to be able to express $\frac 12$ as the sum of some set of these probabilities. In particular, if $p$ is transcendental, you know it is impossible because if it were possible you would have a polynomial equation with $p$ as a root.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/364533', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16340/']}
jdg_376145
stackexchange
llm_judgeable_groundtruth_similarity
28214913
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two functions, one that tries to get a token from a webservice and may fail, and one that tries to use this token to get the username and may fail. getToken :: IO (Maybe Token)getUsername :: Token -> IO (Maybe String) I would like to take the result of getToken and feed it to getUsername . If there was only IO or Maybe , I could simply use bind, but since there are down nested monads, I can't. How can I write something equivalent to getToken >>= getUsername :: IO (Maybe String) ? More generally, what function has type m1 m2 a -> (a -> m1 m2 b) -> m1 m2 b ? Bonus question: how would I do that using the do notation in an IO context? Now provide the response and nothing else.
I have defined a function useToken showing your use case: type Token = StringgetToken :: IO (Maybe Token)getToken = undefinedgetUsername :: Token -> IO (Maybe String)getUsername = undefineduseToken :: IO (Maybe String)useToken = do token <- getToken case token of Just x -> getUsername x Nothing -> return Nothing If you don't want to use do notation, then you can use: useToken2 :: IO (Maybe String)useToken2 = getToken >>= \token -> maybe (return Nothing) getUsername token Or using monad transformers, your code will become simpler: import Control.Monad.Trans.Maybetype Token = StringgetToken :: MaybeT IO TokengetToken = undefinedgetUsername :: Token -> MaybeT IO StringgetUsername = undefineduseToken :: MaybeT IO String useToken = do token <- getToken getUsername token Note that, you can also directly lift IO operations inside the monad transformer. As @Robedino points out, now the code will be more concise without do notation: useToken :: MaybeT IO String useToken = getToken >>= getUsername
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28214913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981855/']}
jdg_376146
stackexchange
llm_judgeable_groundtruth_similarity
4533681
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: private void RespCallback(IAsyncResult asynchronousResult){ try { WebRequest myWebRequest1 = (WebRequest)asynchronousResult.AsyncState; // End the Asynchronous response. WebResponse webResponse = myWebRequest1.EndGetResponse(asynchronousResult); } catch (Exception) { // TODO:Log the error }} Now having the webResponse object, what is the easiest way to read its contents? Now provide the response and nothing else.
I would simply use the async methods on WebClient - much easier to work with: WebClient client = new WebClient(); client.DownloadStringCompleted += (sender,args) => { if(!args.Cancelled && args.Error == null) { string result = args.Result; // do something fun... } }; client.DownloadStringAsync(new Uri("http://foo.com/bar")); But to answer the question; assuming it is text , something like (noting you may need to specify the encoding): using (var reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); // do something fun... }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4533681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247402/']}
jdg_376147
stackexchange
llm_judgeable_groundtruth_similarity
18304516
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: @RequestMapping(value = "/envinfo", method = RequestMethod.GET)@ResponseBodypublic Map getEnvInfo(){ BasicQuery basicQuery = new BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id': false }"); Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo"); return envinfo;} As you can notice, the code: Retrieves JSON from MongoDB Converts it to a Map object The Map object is then converted to JSON by Spring MongoData before it is returned to the browser. Is it possible to directly return the raw json from MongoDb without going through the intermediate conversion steps? Now provide the response and nothing else.
There's two way's you can do this right now: 1. Using the CollectionCallback on MongoTemplate You can use a CollectionCallback to deal with the returned DBObject directly and simply toString() it: template.execute("jvmInfo", new CollectionCallback<String>() { String doInCollection(DBCollection collection) { DBCursor cursor = collection.find(query) return cursor.next().toString() }} Yo'll still get the exception translation into Spring's DataAccessExceptions . Note, that this is slightly brittle as we expect only a single result to be returned for the query but that's probably something you have to take care of when trying to produce a String anyway. 2. Register a Converter from DBObject to String You can implement a Spring Converter to do the toString() for you. class DBObjectToStringConverter implements Converter<DBObject, String> { public String convert(DBObject source) { return source == null ? null : source.toString(); }} You can then either use the XML configuration or override customConversions() to return a new CustomConversions(Arrays.asList(new DBObjectToStringConverter())) to get it registered with your MongoConverter . You can then simply do the following: String result = mongoTemplate.findOne(basicQuery, String.class, "jvmInfo"); I will add the just showed converter to Spring Data MongoDB and register it by default for the upcoming 1.3 GA release and port the fix back to 1.2.x as part of the fix for DATAMONGO-743 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18304516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14316/']}
jdg_376148
stackexchange
llm_judgeable_groundtruth_similarity
1884054
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 a Silverlight application, the System.Windows.Browser.HtmlPage.Document.DocumentUri object returns a physical file path rather than an HTTP: address. What would cause this? Now provide the response and nothing else.
Well, I'm (almost) sure that without making use of the $_SERVER superglobal keys, providing a alternative way to figure out PATH_INFO is just impossible, that being said lets first list all of the $_SERVER keys that we may possibly use: 'PHP_SELF' 'QUERY_STRING' 'SCRIPT_FILENAME' 'PATH_TRANSLATED' 'SCRIPT_NAME' 'REQUEST_URI' 'PATH_INFO' 'ORIG_PATH_INFO' We obviously need to ignore the last two. Now we should ( I don't know this for a fact, I'm just assuming because you said so ) filter all the keys that exist in the link you provided ( which BTW is offline ATM ), that leaves us with the following keys: 'PHP_SELF' 'SCRIPT_FILENAME' 'REQUEST_URI' Regarding your comment to Anthonys answer : You are just juggling variables now. SCRIPT_FILENAME is a part of the CGI spec. It will not be available if PATH_INFO is unavailable. As for REQUEST_URI , it's apache's mod_rewrite specific. – LiraNuna I'm running LightTPD/1.4.20-1 (Win32) with PHP 5.3.0 as CGI, cgi.fix_pathinfo = 1 and $_SERVER['REQUEST_URI'] is very available to me , I also remember using that same variable back in the days when no one used mod_rewrite so my honest humble guess is that you're plain wrong in this point . Regarding the SCRIPT_FILENAME key I'm unable to test that one out ATM. Still, if we close our eyes really hard and believe that you're right that leaves us with only one variable: 'PHP_SELF' I'm not trying in being harsh here (and I still believe that there are more solutions) but if PHP_SELF is the only key you want us to work with ( assuming there are no impositions on PHP_SELF itself ) there is only one solution left: function PATH_INFO(){ if (array_key_exists('PATH_INFO', $_SERVER) === true) { return $_SERVER['PATH_INFO']; } $whatToUse = basename(__FILE__); // see below return substr($_SERVER['PHP_SELF'], strpos($_SERVER['PHP_SELF'], $whatToUse) + strlen($whatToUse));} This function should work, however there may be some problems using the __FILE__ constant since it returns the path to the file where the __FILE__ constant is declared and not the path to the requested PHP script , so that's why the $whatToUse is there for: sou you can replace it with 'SCRIPT_FILENAME' or if you really believe in what you are saying, just use '.php' . You should also read this regarding why not to use PHP_SELF . If this doesn't work for you, I'm sorry but I can think of anything else. EDIT - Some more reading for you: Drupal request_uri() (why do they keep saying REQUEST_URI is Apache specific?) PHP_SELF vs PATH_INFO vs SCRIPT_NAME vs REQUEST_URI
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1884054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229153/']}
jdg_376149
stackexchange
llm_judgeable_groundtruth_similarity
115114
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: How to solve following recurrence equation $$a_0=2$$$$a_{n+1}=a_n(1-a_n)$$ I tried: sol=RSolve[{a[n + 1] == a[n] (1 - a[n]), a[0] == 2}, a[n], n]ListPlot[{sol}] but it doesn't work. how to find the sequence $a_n$? Now provide the response and nothing else.
Your recurrence is an instance of the logistic map $$x_{n+1} = r x_n(1 - x_n).$$ The first sentence of the Solution in some cases section in the link above says: The special case of r = 4 can in fact be solved exactly, as can the case with r = 2; however the general case can only be predicted statistically. Mathematica is indeed able to solve the $r=2$ and $r=4$ cases: RSolve[a[n + 1] == 2 a[n] (1 - a[n]), a[n], n] {{a[n] -> 1/2 - 1/2 E^(2^n C[1])}} RSolve[a[n + 1] == 4 a[n] (1 - a[n]), a[n], n] {{a[n] -> 1/2 - 1/2 Cos[2^n C[1]]}} So I think no one really knows a proper closed form of your nonlinear recurrence. In fact the wiki link makes it seem like the solution is highly dependent on the initial condition, i.e. a small change in the initial condition will result in a large change in the solution. Edit A quick search on OEIS almost gives us a closed form. A007018 gives the formula $$a(n) = -\left\lfloor c^{2^n} \right\rfloor,$$ where $$c = 1.597910218031873178338070118157\ldots$$ Now the issue here is knowing the precise value of $c$. In fact we need to know many decimal places of $c$ to be able to find the first few values of $a(n)$. A077125 gives the first 105 digits and that's only enough to give us the first $8$ values of $a(n)$: c = 1.59791021803187317833807011815745531236222495318211419659139309422961619562279496876114706281963518250566;SetAttributes[sol, Listable];sol[0] = 2;sol[n_] := -Floor[c^(2^n)]correct = RecurrenceTable[{a[n + 1] == a[n] (1 - a[n]), a[0] == 2}, a[n], {n, 0, 10}]];(* relative error *)1. - sol[Range[0, 10]]/correct {0., 0., 0., 0., 0., 0., 0., 0., 0., 5.92121*10^-103, 1.18326*10^-102} So I guess this is a way to approximate solutions and I imagine that's what the quote from above "can only be predicted statistically" means.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/115114', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30288/']}
jdg_376150
stackexchange
llm_judgeable_groundtruth_similarity
46106582
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 and failing to translate my relatively simple SQL statement into one that will work within Doctrine. This is the SQL statement, which works as required when run against my database: SELECT a.* FROM score a INNER JOIN ( SELECT name, MAX(score) AS highest FROM score GROUP BY name ) b ON a.score = b.highest AND a.name = b.name GROUP BY name ORDER BY b.highest DESC, a.dateCreated DESC Here's the DQL attempt thus far: $kb = $em->createQuery( "SELECT a FROM ShmupBundle:Score a INNER JOIN a.name ShmupBundle:Score b WITH a.score = b.score AND a.name = b.name GROUP BY b.name WHERE a.platform='keyboard' GROUP BY a.name ORDER BY b.score DESC, a.dateCreated DESC"); Which is currently giving this error: [Semantical Error] line 0, col 73 near 'ShmupBundle:Score': Error: Class ShmupBundle\Entity\Score has no association named name The table itself is pretty simple:id, name, score, platform, dateCreated There are multiple entries with the same name, but different scores. I want to show only the "high score" per name. I've been trying on and off for a day or two now, with no luck. Can anyone point me in the right direction? Now provide the response and nothing else.
The query you are trying to do with doctrine is related to greatest-n-per-group . To use a sub query and then join with main query get things complicated to handle with doctrine. So below is the rewritten SQL version to get the same results without use of any aggregate functions: SELECT a.* FROM score a LEFT JOIN score b ON a.name = b.name AND a.score < b.score WHERE b.score IS NULL ORDER BY a.score DESC DEMO To convert above query equivalent to doctrine or DQL is easy, below is the DQL version of above SQL: SELECT a FROM AppBundle\Entity\Score a LEFT JOIN AppBundle\Entity\Score b WITH a.name = b.name AND a.score < b.scoreWHERE b.score IS NULLORDER BY a.score DESC Or with query builder you can write something like i have tested below with symfony 2.8 using the DEMO Schema $DM = $this->get( 'Doctrine' )->getManager();$repo = $DM->getRepository( 'AppBundle\Entity\Score' );$results = $repo->createQueryBuilder( 'a' ) ->select( 'a' ) ->leftJoin( 'AppBundle\Entity\Score', 'b', 'WITH', 'a.name = b.name AND a.score < b.score' ) ->where( 'b.score IS NULL' ) ->orderBy( 'a.score','DESC' ) ->getQuery() ->getResult(); Another idea would be create a view using your query in database and in symfony create an entity put the view name in table annotation and just start calling your entity it will give the results returned by your query but this approach is not recommended just a temporary fix.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46106582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327316/']}
jdg_376151
stackexchange
llm_judgeable_groundtruth_similarity
37437153
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 wonder if there is a reference document that NGINX all variaible usable in log_format section. refer to documentation I have not managed to find such a document allowing to list the name, description and format (or type) thx in advance Now provide the response and nothing else.
Going through NginX documentation, it is indeed unclear what variables can be used in the log format directive or not. Some are usable for sure: http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format The same variables appear with a (ngx_http_log_module) in this alphabetical list: http://nginx.org/en/docs/varindex.html But the one listed in the default combined format (like $remote_addr ) appear without. Still they are usable in the log format directive. Besides, two of them are not present in this alphabetical list: $http_referer and $http_user_agent . I guess this is because they are part of the $http_ variable: $http_name : arbitrary request header field; the last part of a variable 'name' is the field name converted to lower case with dashes replaced by underscores. Maybe all of them are usable? I merged all the variables I could find on the official documentation in this list: $ancient_browser equals the value set by the ancient_browser_value directive, if a browser was identified as ancient$arg_ argument in the request line$args arguments in the request line$binary_remote_addr client address in a binary form, value’s length is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses$body_bytes_sent number of bytes sent to a client, not counting the response header; this variable is compatible with the “%B” parameter of the mod_log_config Apache module$bytes_sent number of bytes sent to a client (1.3.8, 1.2.5)$connection connection serial number (1.3.8, 1.2.5)$connection_requests current number of requests made through a connection (1.3.8, 1.2.5)$connections_active same as the Active connections value$connections_reading same as the Reading value$connections_waiting same as the Waiting value$connections_writing same as the Writing value$content_length “Content-Length” request header field$content_type “Content-Type” request header field$cookie_ the named cookie$date_gmt current time in GMT. The format is set by the config command with the timefmt parameter$date_local current time in the local time zone. The format is set by the config command with the timefmt parameter$document_root root or alias directive’s value for the current request$document_uri same as $uri$fastcgi_path_info the value of the second capture set by the fastcgi_split_path_info directive. This variable can be used to set the PATH_INFO parameter$fastcgi_script_name request URI or, if a URI ends with a slash, request URI with an index file name configured by the fastcgi_index directive appended to it. This variable can be used to set the SCRIPT_FILENAME and PATH_TRANSLATED parameters that determine the script name in PHP. For example, for the “/info/” request with the following directives fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name; the SCRIPT_FILENAME parameter will be equal to “/home/www/scripts/php/info/index.php”$geoip_area_code telephone area code (US only)$geoip_city city name, for example, “Moscow”, “Washington”$geoip_city_continent_code two-letter continent code, for example, “EU”, “NA”$geoip_city_country_code two-letter country code, for example, “RU”, “US”$geoip_city_country_code3 three-letter country code, for example, “RUS”, “USA”$geoip_city_country_name country name, for example, “Russian Federation”, “United States”$geoip_country_code two-letter country code, for example, “RU”, “US”$geoip_country_code3 three-letter country code, for example, “RUS”, “USA”$geoip_country_name country name, for example, “Russian Federation”, “United States”$geoip_dma_code DMA region code in US (also known as “metro code”), according to the geotargeting in Google AdWords API$geoip_latitude latitude$geoip_longitude longitude$geoip_org organization name, for example, “The University of Melbourne”$geoip_postal_code postal code$geoip_region two-symbol country region code (region, territory, state, province, federal land and the like), for example, “48”, “DC”$geoip_region_name country region name (region, territory, state, province, federal land and the like), for example, “Moscow City”, “District of Columbia”$gzip_ratio achieved compression ratio, computed as the ratio between the original and compressed response sizes$host in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request $hostname host name$http2 negotiated protocol identifier: “h2” for HTTP/2 over TLS, “h2c” for HTTP/2 over cleartext TCP, or an empty string otherwise$http_ arbitrary request header field; the last part of the variable name is the field name converted to lower case with dashes replaced by underscores. Examples: $http_referer, $http_user_agent$https “on” if connection operates in SSL mode, or an empty string otherwise$invalid_referer Empty string, if the “Referer” request header field value is considered valid, otherwise “1”$is_args “?” if a request line has arguments, or an empty string otherwise$limit_rate setting this variable enables response rate limiting; see limit_rate$memcached_key Defines a key for obtaining response from a memcached server$modern_browser equals the value set by the modern_browser_value directive, if a browser was identified as modern$msec current time in seconds with the milliseconds resolution (1.3.9, 1.2.6)$msie equals “1” if a browser was identified as MSIE of any version$nginx_version nginx version$pid PID of the worker process$pipe “p” if request was pipelined, “.” otherwise (1.3.12, 1.2.7)$proxy_add_x_forwarded_for the “X-Forwarded-For” client request header field with the $remote_addr variable appended to it, separated by a comma. If the “X-Forwarded-For” field is not present in the client request header, the $proxy_add_x_forwarded_for variable is equal to the $remote_addr variable$proxy_host name and port of a proxied server as specified in the proxy_pass directive$proxy_port port of a proxied server as specified in the proxy_pass directive, or the protocol’s default port$proxy_protocol_addr client address from the PROXY protocol header, or an empty string otherwise (1.5.12). the PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.$proxy_protocol_port client port from the PROXY protocol header, or an empty string otherwise (1.11.0). the PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.$query_string same as $args$realip_remote_addr keeps the original client address (1.9.7)$realip_remote_port keeps the original client port (1.11.0)$realpath_root an absolute pathname corresponding to the root or alias directive’s value for the current request, with all symbolic links resolved to real paths $remote_addr client address$remote_port client port$remote_user user name supplied with the Basic authentication$request full original request line$request_body request bod. The variable’s value is made available in locations processed by the proxy_pass, fastcgi_pass, uwsgi_pass, and scgi_pass directives.$request_body_file name of a temporary file with the request body. At the end of processing, the file needs to be removed. To always write the request body to a file, client_body_in_file_only needs to be enabled. When the name of a temporary file is passed in a proxied request or in a request to a FastCGI/uwsgi/SCGI server, passing the request body should be disabled by the proxy_pass_request_body off, fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off directives, respectively.$request_completion “OK” if a request has completed, or an empty string otherwise$request_filename file path for the current request, based on the root or alias directives, and the request URI$request_id unique request identifier generated from 16 random bytes, in hexadecimal (1.11.0)$request_length request length (including request line, header, and request body) (1.3.12, 1.2.7)$request_method request method, usually “GET” or “POST”$request_time request processing time in seconds with a milliseconds resolution (1.3.9, 1.2.6); time elapsed since the first bytes were read from the client$request_uri full original request URI (with arguments)$scheme request scheme, “http” or “https”$secure_link The status of a link check. The specific value depends on the selected operation mode$secure_link_expires The lifetime of a link passed in a request; intended to be used only in the secure_link_md5 directive$sent_http_ arbitrary response header field; the last part of the variable name is the field name converted to lower case with dashes replaced by underscores$server_addr an address of the server which accepted a request. Computing a value of this variable usually requires one system call. To avoid a system call, the listen directives must specify addresses and use the bind parameter.$server_name name of the server which accepted a request$server_port port of the server which accepted a request$server_protocol request protocol, usually “HTTP/1.0”, “HTTP/1.1”, or “HTTP/2.0”$session_log_binary_id current session ID in binary form (16 bytes)$session_log_id current session ID$slice_range the current slice range in HTTP byte range format, for example, bytes=0-1048575$spdy SPDY protocol version for SPDY connections, or an empty string otherwise$spdy_request_priority request priority for SPDY connections, or an empty string otherwise$ssl_cipher returns the string of ciphers used for an established SSL connection$ssl_client_cert returns the client certificate in the PEM format for an established SSL connection, with each line except the first prepended with the tab character; this is intended for the use in the proxy_set_header directive$ssl_client_fingerprint returns the SHA1 fingerprint of the client certificate for an established SSL connection (1.7.1)$ssl_client_i_dn returns the “issuer DN” string of the client certificate for an established SSL connection$ssl_client_raw_cert returns the client certificate in the PEM format for an established SSL connection$ssl_client_s_dn returns the “subject DN” string of the client certificate for an established SSL connection$ssl_client_serial returns the serial number of the client certificate for an established SSL connection$ssl_client_verify returns the result of client certificate verification: “SUCCESS”, “FAILED”, and “NONE” if a certificate was not present$ssl_protocol returns the protocol of an established SSL connection$ssl_server_name returns the server name requested through SNI (1.7.0)$ssl_session_id returns the session identifier of an established SSL connection$ssl_session_reused returns “r” if an SSL session was reused, or “.” otherwise (1.5.11)$status response status (1.3.2, 1.2.2)$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space information about the client TCP connection; available on systems that support the TCP_INFO socket option$time_iso8601 local time in the ISO 8601 standard format (1.3.12, 1.2.7)$time_local local time in the Common Log Format (1.3.12, 1.2.7)$uid_got The cookie name and received client identifier$uid_reset If the variable is set to a non-empty string that is not “0”, the client identifiers are reset. The special value “log” additionally leads to the output of messages about the reset identifiers to the error_log$uid_set The cookie name and sent client identifier$upstream_addr keeps the IP address and port, or the path to the UNIX-domain socket of the upstream server. If several servers were contacted during request processing, their addresses are separated by commas, e.g. “192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock”. If an internal redirect from one server group to another happens, initiated by “X-Accel-Redirect” or error_page, then the server addresses from different groups are separated by colons, e.g. “192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock : 192.168.10.1:80, 192.168.10.2:80”$upstream_cache_status keeps the status of accessing a response cache (0.8.3). The status can be either “MISS”, “BYPASS”, “EXPIRED”, “STALE”, “UPDATING”, “REVALIDATED”, or “HIT”$upstream_connect_time time spent on establishing a connection with an upstream server$upstream_cookie_ cookie with the specified name sent by the upstream server in the “Set-Cookie” response header field (1.7.1). Only the cookies from the response of the last server are saved$upstream_header_time time between establishing a connection and receiving the first byte of the response header from the upstream server$upstream_http_ keep server response header fields. For example, the “Server” response header field is available through the $upstream_http_server variable. The rules of converting header field names to variable names are the same as for the variables that start with the “$http_” prefix. Only the header fields from the response of the last server are saved$upstream_response_length keeps the length of the response obtained from the upstream server (0.7.27); the length is kept in bytes. Lengths of several responses are separated by commas and colons like addresses in the $upstream_addr variable$upstream_response_time time between establishing a connection and receiving the last byte of the response body from the upstream server$upstream_status keeps status code of the response obtained from the upstream server. Status codes of several responses are separated by commas and colons like addresses in the $upstream_addr variable$uri current URI in request, normalized. The value of $uri may change during request processing, e.g. when doing internal redirects, or when using index files. A page with such a list (of log-usable variables) would be much appreciated in NginX documentation, just like what Apache, uWSGI or Gunicorn documentation have.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37437153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4774055/']}
jdg_376152
stackexchange
llm_judgeable_groundtruth_similarity
2244255
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following task: download a file using HTTPS and authentication. Indy seems the way to go but for some reason it doesn't work so far. I have the following in place: a TIdHTTP component which I use for downloading a TIdURI component used to create the URL a TIdSSLIOHandlerSocketOpenSSL component which should provide the secure connection. The required DLLs are in the binary folder. The site also requires authentication and I included the user/pass in the URL as in the example below. In short this is the code: URI := TIdURI.Create('https://test.example.com/');URI.Username := ParamUserName;URI.Password := ParamPassword;HTTP := TIdHTTP.Create(nil);if URI.Protocol = 'https' thenbegin IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); IOHandler.SSLOptions.Method := sslvSSLv3; HTTP.IOHandler := IOHandler;end;HTTP.Get(URI.GetFullURI([ofAuthInfo]), FileStream); Using this code I get a "Read Timeout" EIdReadTimeout exception very fast. Testing the URL in a browser works without problem. Any ideas on what's missing or what I did wrong? Now provide the response and nothing else.
I finally abandoned Indy and OpenSSL and used WinInet for downloading. This is the code that worked for me: function Download(URL, User, Pass, FileName: string): Boolean;const BufferSize = 1024;var hSession, hURL: HInternet; Buffer: array[1..BufferSize] of Byte; BufferLen: DWORD; F: File;begin Result := False; hSession := InternetOpen('', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0) ; // Establish the secure connection InternetConnect ( hSession, PChar(FullURL), INTERNET_DEFAULT_HTTPS_PORT, PChar(User), PChar(Pass), INTERNET_SERVICE_HTTP, 0, 0 ); try hURL := InternetOpenURL(hSession, PChar(URL), nil, 0, 0, 0) ; try AssignFile(f, FileName); Rewrite(f,1); try repeat InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) ; BlockWrite(f, Buffer, BufferLen) until BufferLen = 0; finally CloseFile(f) ; Result := True; end; finally InternetCloseHandle(hURL) end finally InternetCloseHandle(hSession) end;end;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2244255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108676/']}
jdg_376153
stackexchange
llm_judgeable_groundtruth_similarity
705945
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 have this expression:$$\sum_{\{\vec{S}\}}\prod_{i=1}^{N}e^{\beta HS_{i}}=\prod_{i=1}^{N}\sum_{S_{i}\in\{-1,1\}}e^{\beta HS_{i}} \qquad (1)$$Where $\sum_{\{\vec{S}\}}$ means a sum over all possible vectors $\vec{S}=(S_1,...,S_N)$ with the restriction that $S_i$ can only take the values $\{-1,+1\}$, i.e. the sum is over $2^N$ different vectors: $\{\vec{S}\}$. My question is: How can I be sure that (1) is right? Is there a criteria to interchange sums and products or it's always valid? Now provide the response and nothing else.
The problem was in how to write down the sum $\sum_{\{\vec{S}\}}$. Since this sum is over all the possible vectors $\vec{S}=(S_1,...,S_N)$, (where $S_i\in\{-1,1\}$), we can rewrite this sum like $$\sum_{S_{1}\in\{-1,1\}}\cdots\sum_{S_{N}\in\{-1,1\}}$$i.e.$$\sum_{\{\vec{S}\}}\prod_{i=1}^{N}e^{\beta HS_{i}}=\sum_{S_{1}\in\{-1,1\}}\cdots\sum_{S_{N}\in\{-1,1\}}\prod_{i=1}^{N}e^{\beta HS_{i}} \qquad(1)$$ Clearly this sum has $2^N$ elements of the type $\prod_{i=1}^{N}e^{\beta HS_{i}}$. Now, since $$\prod_{i=1}^{N}e^{\beta HS_{i}}=e^{\beta HS_{1}}\cdots e^{\beta HS_{N}},$$then (1) turns $$\sum_{\{\vec{S}\}}\prod_{i=1}^{N}e^{\beta HS_{i}}=\sum_{S_{1}\in\{-1,1\}}\cdots\sum_{S_{N}\in\{-1,1\}}e^{\beta HS_{1}}\cdots e^{\beta HS_{N}} \qquad(2)$$Since each $S_i$ is independent of the others, we can "factorize" the $\Sigma$'s:$$\sum_{\{\vec{S}\}}\prod_{i=1}^{N}e^{\beta HS_{i}}=\left(\sum_{S_{1}\in\{-1,1\}}e^{\beta HS_{1}}\right)\cdots\left(\sum_{S_{N}\in\{-1,1\}}e^{\beta HS_{N}}\right)$$And finally:$$\sum_{\{\vec{S}\}}\prod_{i=1}^{N}e^{\beta HS_{i}}=\prod_{j=1}^{N}\sum_{S_{j}\in\{-1,1\}}e^{\beta HS_{j}} \qquad Q.E.D.$$ Note. This result can be generalized for vectors $\vec{S}=(S_1,...,S_N)$ with components $S_i\in\{1,...,k\}$ for some integer $k$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/705945', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48197/']}
jdg_376154
stackexchange
llm_judgeable_groundtruth_similarity
44248108
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 create a new field sid on each document in a collection of about 500K documents. Each sid is unique and based on that record's existing roundedDate and stream fields. I'm doing so with the following code: var cursor = db.getCollection('snapshots').find();var iterated = 0;var updated = 0;while (cursor.hasNext()) { var doc = cursor.next(); if (doc.stream && doc.roundedDate && !doc.sid) { db.getCollection('snapshots').update({ "_id": doc['_id'] }, { $set: { sid: doc.stream.valueOf() + '-' + doc.roundedDate, } }); updated++; } iterated++;}; print('total ' + cursor.count() + ' iterated through ' + iterated + ' updated ' + updated); It works well at first, but after a few hours and about 100K records it errors out with: Error: getMore command failed: { "ok" : 0, "errmsg": "Cursor not found, cursor id: ###", "code": 43,}: ... Now provide the response and nothing else.
EDIT - Query performance: As @NeilLunn pointed out in his comments, you should not be filtering the documents manually, but use .find(...) for that instead: db.snapshots.find({ roundedDate: { $exists: true }, stream: { $exists: true }, sid: { $exists: false }}) Also, using .bulkWrite() , available as from MongoDB 3.2 , will be far way more performant than doing individual updates. It is possible that, with that, you are able to execute your query within the 10 minutes lifetime of the cursor. If it still takes more than that, you cursor will expire and you will have the same problem anyway, which is explained below: What is going on here: Error: getMore command failed may be due to a cursor timeout, which is related with two cursor attributes: Timeout limit, which is 10 minutes by default. From the docs : By default, the server will automatically close the cursor after 10 minutes of inactivity, or if client has exhausted the cursor. Batch size, which is 101 documents or 16 MB for the first batch, and 16 MB, regardless of the number of documents, for subsequent batches (as of MongoDB 3.4 ). From the docs : find() and aggregate() operations have an initial batch size of 101 documents by default. Subsequent getMore operations issued against the resulting cursor have no default batch size, so they are limited only by the 16 megabyte message size. Probably you are consuming those initial 101 documents and then getting a 16 MB batch, which is the maximum, with a lot more documents. As it is taking more than 10 minutes to process them, the cursor on the server times out and, by the time you are done processing the documents in the second batch and request a new one , the cursor is already closed: As you iterate through the cursor and reach the end of the returned batch, if there are more results, cursor.next() will perform a getMore operation to retrieve the next batch. Possible solutions: I see 5 possible ways to solve this, 3 good ones, with their pros and cons, and 2 bad one: Reducing the batch size to keep the cursor alive. Remove the timeout from the cursor. Retry when the cursor expires. Query the results in batches manually. Get all the documents before the cursor expires. Note they are not numbered following any specific criteria. Read through them and decide which one works best for your particular case. 1. Reducing the batch size to keep the cursor alive One way to solve that is use cursor.bacthSize to set the batch size on the cursor returned by your find query to match those that you can process within those 10 minutes: const cursor = db.collection.find() .batchSize(NUMBER_OF_DOCUMENTS_IN_BATCH); However, keep in mind that setting a very conservative (small) batch size will probably work, but will also be slower, as now you need to access the server more times. On the other hand, setting it to a value too close to the number of documents you can process in 10 minutes means that it is possible that if some iterations take a bit longer to process for any reason (other processes may be consuming more resources), the cursor will expire anyway and you will get the same error again. 2. Remove the timeout from the cursor Another option is to use cursor.noCursorTimeout to prevent the cursor from timing out: const cursor = db.collection.find().noCursorTimeout(); This is considered a bad practice as you would need to close the cursor manually or exhaust all its results so that it is automatically closed: After setting the noCursorTimeout option, you must either close the cursor manually with cursor.close() or by exhausting the cursor’s results. As you want to process all the documents in the cursor, you wouldn't need to close it manually, but it is still possible that something else goes wrong in your code and an error is thrown before you are done, thus leaving the cursor opened. If you still want to use this approach, use a try-catch to make sure you close the cursor if anything goes wrong before you consume all its documents. Note I don't consider this a bad solution (therefore the ), as even thought it is considered a bad practice...: It is a feature supported by the driver. If it was so bad, as there are alternatives ways to get around timeout issues, as explained in the other solutions, this won't be supported. There are ways to use it safely, it's just a matter of being extra cautious with it. I assume you are not running this kind of queries regularly, so the chances that you start leaving open cursors everywhere is low. If this is not the case, and you really need to deal with these situations all the time, then it does make sense not to use noCursorTimeout . 3. Retry when the cursor expires Basically, you put your code in a try-catch and when you get the error, you get a new cursor skipping the documents that you have already processed: let processed = 0;let updated = 0;while(true) { const cursor = db.snapshots.find().sort({ _id: 1 }).skip(processed); try { while (cursor.hasNext()) { const doc = cursor.next(); ++processed; if (doc.stream && doc.roundedDate && !doc.sid) { db.snapshots.update({ _id: doc._id }, { $set: { sid: `${ doc.stream.valueOf() }-${ doc.roundedDate }` }}); ++updated; } } break; // Done processing all, exit outer loop } catch (err) { if (err.code !== 43) { // Something else than a timeout went wrong. Abort loop. throw err; } }} Note you need to sort the results for this solution to work. With this approach, you are minimizing the number of requests to the server by using the maximum possible batch size of 16 MB, without having to guess how many documents you will be able to process in 10 minutes beforehand. Therefore, it is also more robust than the previous approach. 4. Query the results in batches manually Basically, you use skip() , limit() and sort() to do multiple queries with a number of documents you think you can process in 10 minutes. I consider this a bad solution because the driver already has the option to set the batch size, so there's no reason to do this manually, just use solution 1 and don't reinvent the wheel. Also, it is worth mentioning that it has the same drawbacks than solution 1, 5. Get all the documents before the cursor expires Probably your code is taking some time to execute due to results processing, so you could retrieve all the documents first and then process them: const results = new Array(db.snapshots.find()); This will retrieve all the batches one after another and close the cursor. Then, you can loop through all the documents inside results and do what you need to do. However, if you are having timeout issues, chances are that your result set is quite large, thus pulling everything in memory may not be the most advisable thing to do. Note about snapshot mode and duplicate documents It is possible that some documents are returned multiple times if intervening write operations move them due to a growth in document size. To solve this, use cursor.snapshot() . From the docs : Append the snapshot() method to a cursor to toggle the “snapshot” mode. This ensures that the query will not return a document multiple times, even if intervening write operations result in a move of the document due to the growth in document size. However, keep in mind its limitations: It doesn't work with sharded collections. It doesn't work with sort() or hint() , so it will not work with solutions 3 and 4. It doesn't guarantee isolation from insertion or deletions. Note with solution 5 the time window to have a move of documents that may cause duplicate documents retrieval is narrower than with the other solutions, so you may not need snapshot() . In your particular case, as the collection is called snapshot , probably it is not likely to change, so you probably don't need snapshot() . Moreover, you are doing updates on documents based on their data and, once the update is done, that same document will not be updated again even though it is retrieved multiple times, as the if condition will skip it. Note about open cursors To see a count of open cursors use db.serverStatus().metrics.cursor .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/44248108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3333359/']}
jdg_376155
stackexchange
llm_judgeable_groundtruth_similarity
641290
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 $A=QR$ be a $QR$ -decomposition. Then the wikipedia article regarding $QR$ decomposition states that If $A$ is invertible, then the factorization is unique if we require that the diagonal elements of $R$ are positive. I don't understand the relation of diagonal elements being positive to uniqueness. Can someone explain what happens if they are non-negative, say some of them are zero, and what happens if they are all real. Now provide the response and nothing else.
To convince yourself thatwhen multiplying two matrices, if scale k-th column of the matrix on the left by $\alpha$ and the k-th row of the matrix on the right by $1/\alpha$ then the product does not change. So we can always multiply the column of $Q$ by $-1$ and the corresponding row of $R$ also by $-1$ , the we have another QR factorization. So requiring the diagonal to be positive prevents this ambiguity. By the way, the ambiguity actually comes from taking square roots when calculating the columns of Q. Depending on the sign of the square root, we can end up with either positive value or a negative value on the diagonal of $R$ . Also, if $A$ is singular, then one or more of the diagonal entries of $R$ would be zero. In this case, scaling by $-1$ the column of $Q$ that goes with the diagonal value of zero does not change the diagonal value of $R$ . This is why we need $A$ to be nonsingular.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/641290', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/41541/']}
jdg_376156
stackexchange
llm_judgeable_groundtruth_similarity
15678817
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 started learning Ember.js (bought the PeepCode screencast), and am learning quite smoothly from it, but ran into a problem when trying to write my first Ember app. Here's the (nested) route mapping: App.Router.map(function () { this.resource('bases', { path: '/' }, function () { this.resource('base', { path: ':base_id' }, function () { this.resource('places', function () { this.resource('place', { path: ':place_id' }); }); }); });}); This allows urls like this: domain.com/#/yokota-ab-japan/places/4c806eabd92ea093ea2e3872 yokota-ab-japan is the id of a base (an Air Force base in Japan) 4c806eabd92ea093ea2e3872 is the id of a venue on Foursquare When the places route is hit, I setup the data with a call to the foursquare api, iterate over the JSON to create an array of App.Place objects, and return that array. App.PlacesRoute = Ember.Route.extend({ model: function () { var placesData = Ember.A(); $.getJSON('https://api.foursquare.com/v2/venues/search?ll=35.744771,139.349456&query=ramen&client_id=nnn&client_secret=nnn&v=20120101', function (data) { $.each(data.response.venues, function (i, venues) { placesData.addObject(App.Place.create({ id: venues.id, name: venues.name, lat: venues.location.lat, lng: venues.location.lng })); }); }); return placesData; }}); That seems to work well. I display the placesData array using this template: <script type="text/x-handlebars" data-template-name="places"> <div> {{#each place in controller}} {{#linkTo 'place' place}} {{place.name}} {{/linkTo}} {{/each}} </div> {{outlet}}</script> The linkTo links to the individual place, where I want to show more details about a place. Here's the route I setup to pull data about the single place, populate a single App.Place object, and return it: App.PlaceRoute = Ember.Route.extend({ model: function (params) { console.log('place route called'); var place; $.getJSON('https://api.foursquare.com/v2/venues/' + params.place_id + '?client_id=nnn&client_secret=nnn', function (data) { var v = data.response.venue; place = App.Place.create({ id: v.id, name: v.name, lat: v.location.lat, lng: v.location.lng }); }); return place; }}); My problem is, PlaceRoute doesn't get called when the user clicks a link to it, but it does get called when the page is refreshed on this route. According to the PeepCode Ember.js screencast (at ~12:25 into the video) it states that "controllers rarely ever make calls to data, route objects handle that", so I think I'm correct in putting my ajax calls in the routes (I've seen so many differing tutorials online, but since Peepcode consulted with the Ember.js creators, I went with it as my primary learning source). If this isn't correct, or could be done better, please let me know. Now provide the response and nothing else.
Ember Documentation on the model hook: "A hook you can implement to convert the URL into the model for this route." This explains why the model hook is just called on page refresh. But this confuses a lot of people :-). So, this is not the right hook in this case. I think you should use the setupController hook for this case. Try this: App.PlaceRoute = Ember.Route.extend({ setupController: function (controller, model) { console.log('place route called'); var place; $.getJSON('https://api.foursquare.com/v2/venues/' + model.get('place_id') + '?client_id=nnn&client_secret=nnn', function (data) { var v = data.response.venue; place = App.Place.create({ id: v.id, name: v.name, lat: v.location.lat, lng: v.location.lng }); }); controller.set("model", place); }}); Additional 2 cents from myself: Why is the model hook just executed, when the app is entered via URL/direct browser navigation? Ember has the assumption, that you do not necessarily make a call to the model hook, if you use {{linkTo}} . In your places template you use {{#linkTo 'place' place}} {{place.name}} {{/linkTo}} . You are passing a place object to your route. Ember assumes that this is the same object, that you would get when executing your model hook. So from Embers View there is no need to call the model hook. So if you want to perform retrieval logic even when you use linkTo , use the setupController hook .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15678817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61320/']}
jdg_376157
stackexchange
llm_judgeable_groundtruth_similarity
36568526
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 REST API with Spring Boot and Jersey packaged as jar . When I run my app (using IntelliJ), I can navigate to: http://localhost:8080/clients and I get all the clients. Now, I have made some changes in pom.xml in order to package it as war as I need to deploy it in a external Tomcat. When I package the war (named apirest.war ) and it is deployed in that Tomcat, I navigate to: http://api.mycompany.com/apirest/clients but I get HTTP 404 Error . What is happening? Now provide the response and nothing else.
If you have Apache HTTPComponents HttpClient on your classpath, you can do it like this: mockMvc.perform(post("/some/super/secret/url") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList( new BasicNameValuePair("someparam1", "true"), new BasicNameValuePair("someparam2", "test") ))))); If you don't have HttpClient, you can do it with a simple helper method that constructs the urlencoded form entity: mockMvc.perform(post("/some/super/secret/url") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .content(buildUrlEncodedFormEntity( "someparam1", "value1", "someparam2", "value2" )))); With this helper function: private String buildUrlEncodedFormEntity(String... params) { if( (params.length % 2) > 0 ) { throw new IllegalArgumentException("Need to give an even number of parameters"); } StringBuilder result = new StringBuilder(); for (int i=0; i<params.length; i+=2) { if( i > 0 ) { result.append('&'); } try { result. append(URLEncoder.encode(params[i], StandardCharsets.UTF_8.name())). append('='). append(URLEncoder.encode(params[i+1], StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return result.toString(); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36568526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026283/']}
jdg_376158
stackexchange
llm_judgeable_groundtruth_similarity
11284898
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 QThread which generates a fairly large amount of data regularly (couple of megabytes per second), and it needs to transmit it to the parent (GUI) thread. I'm afraid I'm not that certain in the inner workings of QThread so I would like to ask for a best practice. Obviously, the most direct way to transmit data is to just emit an array. However, how efficient is this? Does Qt know about where it is used and avoids deep copying it when sending and receiving it? If not, I can gladly just allocate the memory in the main thread and give a pointer to the child thread where it will write the data (and only emit short messages about the progress). This does not seem to be the most elegant solution to me, this is why I'm asking. If Qt avoids copying the data in multiple buffers when emitting and receiving, is it guaranteed in all systems? I don't have the resources to try benchmarking it under various OSs. Now provide the response and nothing else.
QThread 's inner workings are irrelevant: they play no role in how the event loops work. When you emit a signal in a QObject that lives in a thread different from the slot's object, the signal will be posted as a QMetaCallEvent to the event queue of the receiving thread. The event loop running in the receiving thread will then act on this event and execute the call into the slot that was connected to the emitted signal. So, no matter what happens, whatever data you send through the signal will eventually end up as a payload in an instance of QEvent-derived class. The meat of the issue is when the QMetaCallEvent reaches the event loop and the container gets passed into the slot as an argument. Of course the copy constructors could be called plenty of times along the way. Below is some simple code that demonstrates how many times the copy constructor and default constructor are in fact called on the elements of the data members of an implicitly shared copy-on-write container (QVector), on a custom class that stands in for a container. You'll be pleasantly surprised :) Since Qt containers are implicitly shared copy-on-write, their copy construction has negligible cost: all that's done is a reference counter is incremented atomically on construction. None of the data members are copied, for example. Alas, pre-11 C++ shows its ugly side: if the slot code modifies the container in any way, there's no way to pass references to the slot in such a way that would let the compiler know that the original container is not needed anymore. Thus: if the slot receives a const reference to the container, you're guaranteed that no copies will be made. If the slot receives a writeable copy of the container and you modify it, there will be a completely unnecessary copy made since the instance alive at the call site is no longer needed. In C++-11 you'd pass an rvalue reference as a parameter. Passing an rvalue reference in a function call ends the lifetime of the passed object in the caller. Sample code output: "Started" copies: 0 assignments: 0 default instances: 0 "Created Foo" copies: 0 assignments: 0 default instances: 100 "Created Bar" copies: 0 assignments: 0 default instances: 100 "Received signal w/const container" copies: 0 assignments: 0 default instances: 100 "Received signal w/copy of the container" copies: 0 assignments: 0 default instances: 100 "Made a copy" copies: 100 assignments: 1 default instances: 101 "Reset" copies: 0 assignments: 0 default instances: 0 "Received signal w/const class" copies: 2 assignments: 0 default instances: 1 "Received signal w/copy of the class" copies: 3 assignments: 0 default instances: 1 //main.cpp#include <QtCore>class Class { static QAtomicInt m_copies; static QAtomicInt m_assignments; static QAtomicInt m_instances;public: Class() { m_instances.fetchAndAddOrdered(1); } Class(const Class &) { m_copies.fetchAndAddOrdered(1); } Class & operator=(const Class &) { m_assignments.fetchAndAddOrdered(1); return *this; } static void dump(const QString & s = QString()) { qDebug() << s << "copies:" << m_copies << "assignments:" << m_assignments << "default instances:" << m_instances; } static void reset() { m_copies = 0; m_assignments = 0; m_instances = 0; }};QAtomicInt Class::m_instances;QAtomicInt Class::m_copies;QAtomicInt Class::m_assignments;typedef QVector<Class> Vector;Q_DECLARE_METATYPE(Vector)class Foo : public QObject{ Q_OBJECT Vector v;public: Foo() : v(100) {}signals: void containerSignal(const Vector &); void classSignal(const Class &);public slots: void sendContainer() { emit containerSignal(v); } void sendClass() { emit classSignal(Class()); }};class Bar : public QObject{ Q_OBJECTpublic: Bar() {}signals: void containerDone(); void classDone();public slots: void containerSlotConst(const Vector &) { Class::dump("Received signal w/const container"); } void containerSlot(Vector v) { Class::dump("Received signal w/copy of the container"); v[99] = Class(); Class::dump("Made a copy"); Class::reset(); Class::dump("Reset"); emit containerDone(); } void classSlotConst(const Class &) { Class::dump("Received signal w/const class"); } void classSlot(Class) { Class::dump("Received signal w/copy of the class"); emit classDone(); //QThread::currentThread()->quit(); }};int main(int argc, char ** argv){ QCoreApplication a(argc, argv); qRegisterMetaType<Vector>("Vector"); qRegisterMetaType<Class>("Class"); Class::dump("Started"); QThread thread; Foo foo; Bar bar; Class::dump("Created Foo"); bar.moveToThread(&thread); Class::dump("Created Bar"); QObject::connect(&thread, SIGNAL(started()), &foo, SLOT(sendContainer())); QObject::connect(&foo, SIGNAL(containerSignal(Vector)), &bar, SLOT(containerSlotConst(Vector))); QObject::connect(&foo, SIGNAL(containerSignal(Vector)), &bar, SLOT(containerSlot(Vector))); QObject::connect(&bar, SIGNAL(containerDone()), &foo, SLOT(sendClass())); QObject::connect(&foo, SIGNAL(classSignal(Class)), &bar, SLOT(classSlotConst(Class))); QObject::connect(&foo, SIGNAL(classSignal(Class)), &bar, SLOT(classSlot(Class))); QObject::connect(&bar, SIGNAL(classDone()), &thread, SLOT(quit())); QObject::connect(&thread, SIGNAL(finished()), &a, SLOT(quit())); thread.start(); a.exec(); thread.wait();}#include "main.moc"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11284898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788824/']}
jdg_376159
stackexchange
llm_judgeable_groundtruth_similarity
5524744
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem with the following code: template <typename U>class lamePtr{public: typedef U* ptr;};template <typename U>class smarterPointer{ public: void funFun() { typedef lamePtr<U> someType; someType::ptr query; }}; As you see, I have a typedef inside lamePtr. Inside smarterPointer class I have a function funFun(). What am I trying to do is to make another typedef someType. Till that line, everything works fine until we get to the line with someType::ptr query. What I want here to happen is that "query" will become lamePtr< U >::ptr (a simple value, not a typedef ;). However, I get compilation errors (with gcc 4.4.3): temp.cpp: In member function ‘void smarterPointer&ltU>::funFun()’:temp.cpp:15: error: expected ‘;’ before ‘query’ What am I doing wrong here? Now provide the response and nothing else.
someType , as lamePtr<U> is a "dependant name". It depends on what U is as to whether or not there is a member ptr and, if so, what kind of "thing" that member is. Of course, you know that for all T , lamePtr<T>::ptr is a type, but at this stage of compilation the parser does not know that. Use the typename keyword to hint to the parser that it's a type. The rest will be resolved later in the compilation process. Just a little C++ quirk. template <typename U>class lamePtr{public: typedef U* ptr;};template <typename U>class smarterPointer{ public: void funFun() { typedef lamePtr<U> someType; typename someType::ptr query; }};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5524744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689106/']}
jdg_376160
stackexchange
llm_judgeable_groundtruth_similarity
24185921
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 notify adapters of listviews of main class in onPostExecute but I receive the error: java.lang.IllegalMonitorStateException:object not locked by thread before notify() @Overrideprotected void onPostExecute(String result) { popularfragment.adapter.notifyDataSetChanged(); recentfragment.adapter.notifyDataSetChanged();} Now provide the response and nothing else.
The .notify() method has to be called from within a synchronized context, ie from inside a synchronized block. The java.lang.IllegalMonitorStateException is thrown when you call .notify() on an object that is not used as the lock for the synchronized block in which you call notify. For example, the following works; synchronized(obj){ obj.notify();} But this will throw the exception; synchronized(obj){ // notify() is being called here when the thread and // synchronized block does not own the lock on the object. anotherObj.notify(); } Reference; IllegalMonitorStateException API How to use wait & notify
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24185921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2900777/']}
jdg_376161
stackexchange
llm_judgeable_groundtruth_similarity
3091913
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As we know that $\sin 15^o$ , $\sin 30^o$ , $\sin 45^o$ have simple closed form expressions as these are multiples of 3, but i have never seen any simple closed form expression for $\sin 10^o$ or simply sine for any non-multiple of 3, if there exists a closed form expression, do help me, PS. I know $\sin 10^o$ is solution of $8x^3-6x+1=0$ but i can't solve it as its too tedious . Why is being multiple of 3 such a great thing for an angle??? Now provide the response and nothing else.
Being a multiple of $3°$ isn't a great thing, as degrees are an arbitrary unit. It matters much more to be a small fraction of a full turn, as this leads to polynomial equations of a low degree. E.g. $$\sin 3x=-4\sin^3x+3\sin x=0$$ leads to the well-known $$\sin\frac\pi3=\frac{\sqrt3}2.$$ Some other fractions lead to closed-form expressions, but most others not, as explained by the Abel-Ruffini theorem. In particular, angle trisection (dividing by three) involves a cubic equation which is in general not solvable (the above case being an exception). It is interesting to note that there are analytical formulas to solve cubics, but for some values of the coefficients (the so-called casus irreductibilis ), the solution requires… trigonometric functions, with angle trisection, and you are circling in rounds.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3091913', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/452208/']}
jdg_376162
stackexchange
llm_judgeable_groundtruth_similarity
38132510
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 load some Jade content into a certain div on button click. I have found how to do this with jquery, there are several posts on it, and essentially what I want to do is $('#div').load('/somePage'); However, I am unable to use jQuery in my project. Is there an equivalent function in vanilla javascript? Now provide the response and nothing else.
I think you can do this with the following; var request = new XMLHttpRequest();request.open('GET', '/somepage', true);request.onload = function() { if (request.status >= 200 && request.status < 400) { var resp = request.responseText; document.querySelector('#div').innerHTML = resp; }};request.send(); By the way, you can do this with fetch API too. fetch('/somepage') .then(function(response) { return response.text(); }) .then(function(body) { document.querySelector('#div').innerHTML = body; }); By the way, you can read this blog post for learning something about fetch API.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38132510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3796088/']}
jdg_376163
stackexchange
llm_judgeable_groundtruth_similarity
12009367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone explaine and help me with this. My webpage is slugish because the scroll function is dragging it down. I need to add a delay but don't understand how to do this. $(window).scroll(handleScroll); Now provide the response and nothing else.
You could write a simple throttle debounce function to limit the times per second the scroll event will be handled. function debounce(method, delay) { clearTimeout(method._tId); method._tId= setTimeout(function(){ method(); }, delay);}$(window).scroll(function() { debounce(handleScroll, 100);}); This will make sure there's at least 100ms between each call to handleScroll (or, in other words, it's called at most 10 times per second). As zzzzBov pointed out, what Zakas describes as a throttle function is actually a debounce function. The difference is that debounce discards the superfluous scroll events, while a throttle function should queue them up to be handled later (but at a given maximum rate). In the case of scroll events, you don't want real throttling.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12009367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1540479/']}
jdg_376164
stackexchange
llm_judgeable_groundtruth_similarity
16140986
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I've got the following functions: def xplusy(x, y): return x+ydef xplus1(x): xplusy = xplusy(x, 1) return xplusy Now if I call a = xplus1(4) it throws the following error: UnboundLocalError: local variable 'xplusy' referenced before assignment The error is because of the naming conflict, if I redefine xplus1 as follows: def xplus1(x): s = xplusy(x, 1) return s it works fine. Why is it so: can't compiler properly distinguish between a variable and a function call? Any ways around it? Now provide the response and nothing else.
In Python, functions are data, and typing is dynamic. This means that the following lines are valid Python: def func(x): return x + 3func = 3 func is now an int. The original function func is no longer referenced. The fact that func was originally a function doesn't have any bearing on what types of data can be assigned to it in the future. (This is what "dynamic typing" means.) Therefore, since there's no static typing, and "function" is a valid data type, it wouldn't make sense for the Python interpreter to distinguish between a function and a piece of data referenced by the same name. Therefore, within a given scope, there's no way to use the same unqualified variable name to mean two different things. In your particular case, if the code in your xplus1 function meant anything, it would mean "compute the value of xplusy(x,1) and assign that value to the variable xplusy -- thereby losing the reference to the function xplusy ." However, within the scope of a function, the interpreter won't let you make an assignment to a variable outside of that scope, so it assumes that by writing an assignment statement, you're introducing a new local variable xplusy . The local variable, however, hasn't been defined yet, so your attempt to call it, xplusy(x,1) , fails. The globally defined function is not called as a fall-back because, again, you can't have two unqualified names be identical and point to different data in the same scope. Another example demonstrating the "no duplication of variable names within one scope" rule (which I actually only just discovered while playing around with the prompt in my attempt to construct this answer): >>> def f1():... a = xplusy(3,4)... xplusy = 5... print xplusy...>>> f1()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f1UnboundLocalError: local variable 'xplusy' referenced before assignment>>> def f1():... a = xplusy(3,4)... print a...>>> f1()7 This demonstrates that it really is the scope , not the statement that requires unique names. EDIT: This is a really cool post that explains this and other scoping-related behavior: http://me.veekun.com/blog/2011/04/24/gotcha-python-scoping-closures/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16140986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1564449/']}
jdg_376165
stackexchange
llm_judgeable_groundtruth_similarity
4762538
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 use IIS Express with VS2010 to host a silverlight application. I modified my applicationhost.config file to allow for modification of the proper configuration settings. I have the following in my web.config: <location path=""> <system.webServer> <security> <authentication> <anonymousAuthentication enabled="false" /> <windowsAuthentication enabled="true" /> </authentication> </security> </system.webServer></location> I am not being authenticated and my domain service call returns a null record as the user. I was able to get this to work after installing VS2010 SP1 BETA but I'm trying to get this to work with only IIS Express. How do I enable Windows Authentication to work with IIS Express. Is there a configuration setting that I am missing? Now provide the response and nothing else.
option-1 : edit \My Documents\IISExpress\config\applicationhost.config file and enable windowsAuthentication, i.e: <system.webServer>... <security>... <authentication> <windowsAuthentication enabled="true" /> </authentication>... </security>...</system.webServer> option-2 : Unlock windowsAuthentication section in \My Documents\IISExpress\config\applicationhost.config as follows <add name="WindowsAuthenticationModule" lockItem="false" /> Alter override settings for the required authentication types to 'Allow' <sectionGroup name="security"> ... <sectionGroup name="system.webServer"> ... <sectionGroup name="authentication"> <section name="anonymousAuthentication" overrideModeDefault="Allow" /> ... <section name="windowsAuthentication" overrideModeDefault="Allow" /> </sectionGroup></sectionGroup> Add following in the application's web.config <?xml version="1.0" encoding="UTF-8"?><configuration> <system.webServer> <security> <authentication> <windowsAuthentication enabled="true" /> </authentication> </security> </system.webServer></configuration> Below link may help: http://learn.iis.net/page.aspx/376/delegating-configuration-to-webconfig-files/ After installing VS 2010 SP1 applying option 1 + 2 may be required to get windows authentication working. In addition, you may need to set anonymous authentication to false in IIS Express applicationhost.config: <authentication> <anonymousAuthentication enabled="false" userName="" /> for VS2015, the IIS Express applicationhost config file may be located here: $(solutionDir)\.vs\config\applicationhost.config and the <UseGlobalApplicationHostFile> option in the project file selects the default or solution-specific config file.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4762538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/584800/']}
jdg_376166
stackexchange
llm_judgeable_groundtruth_similarity
7751247
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between following 2 ways of subscribing for an event? receiver.ConfigChanged += Config_ConfigChanged;receiver.ConfigChanged += new EventHandler(Config_ConfigChanged); It seems that both of them work the same way but if so, what is the point of using the second one? What about unsubscribing, will both following methods work also the same way? receiver.ConfigChanged -= Config_ConfigChanged;receiver.ConfigChanged -= new EventHandler(Config_ConfigChanged); Now provide the response and nothing else.
The verbose way works in all versions of C#, the short way only in C# 2 and later. So I see no reason to use the long way nowadays. There are some situations where you still need to use new DelegateType(methodGroup) , but event subscribing isn't one of them. These situations usually involve generic type inference or method overloading. Unsubscribing will work either way since it is based on value equality, not referential equality. If I recall correctly both the implicit conversion from a method group and the explicit new get translated to the same IL code. The implicit conversion is just syntax sugar.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7751247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291427/']}
jdg_376167
stackexchange
llm_judgeable_groundtruth_similarity
39336235
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 my Swift iOS app, I want to download some dynamic HTML pages from a remote server, save them in the document directory, and display those pages from document directory. I was using this to load the page: var appWebView:WKWebView?...appWebView!.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: htmlPath))) Everything works on the simulator, but when I moved to real phones, it just showed a blank page. I then connected to the app using Safari, and found it complained with "Failed to load resource". I then tried to first read the content of the page at htmlPath , then use appWebView!.loadHTMLString() to load the page. It works when the HTML page is simple. But if the HTML references something else, i.e. a JavaScript file also in the document directory (with an absolute path like <script src="file:////var/mobile/Containers/Data/Application/762035C9-2BF2-4CDD-B5B1-574A0E2B0728/Documents/xxxxx.js"> ), it will fail to load. Does anyone know why this happens, and how to resolve the issue? More info: XCode version: 7.3.1 Deployment Target: 8.1 (I tried to use 9.3 too, but that didn't help.) Now provide the response and nothing else.
This is a simplified version of what I have used to load local files in a project of mine (iOS 10, Swift 3). I have just updated my code (7.5.2017) after testing it out again on iOS 10.3.1 and iPhone 7+ as requested by Raghuram and Fox5150 in the comments. I just created a completely new project and this is the folder structure: Update 19.04.2018: Added a new feature to download a .zip with HTML, CSS, JS files, unzip it in /Documents/ (Alamofire + Zip) and then load those files into the webView. You can find it in the GitHub sample project as well. Again, feel free to fork & star! :) Update 08.02.2018: finally added a GitHub sample project , which also includes a local JavaScript file. Feel free to fork & star! :) Version 1 with webView.loadFileURL() ViewController.swift import UIKitimport WebKitclass ViewController: UIViewController, WKNavigationDelegate { override func viewDidLoad() { super.viewDidLoad() let webView = WKWebView() let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false) webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl) webView.navigationDelegate = self view = webView }} Version 2 with webView.loadHTMLString() ViewController.swift import UIKitimport WebKitclass ViewController: UIViewController, WKNavigationDelegate { override func viewDidLoad() { super.viewDidLoad() let webView = WKWebView() let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") let folderPath = Bundle.main.bundlePath let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true) do { let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue) webView.loadHTMLString(htmlString as String, baseURL: baseUrl) } catch { // catch error } webView.navigationDelegate = self view = webView }} Gotchas to look out for: Make sure that your local html/js/css files are in Project -> Target -> Build Phases -> Copy Bundle Resources Make sure that your html files don't reference relative paths e.g. css/styles.css because iOS will flatten your file structure and styles.css will be on the same level as index.html so write <link rel="stylesheet" type="text/css" href="styles.css"> instead Given the 2 versions and the gotchas here are my html/css files from the project: web/index.html <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>Offline WebKit</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <h1 id="webkit-h1">Offline WebKit!</h1> </body></html> web/css/styles.css #webkit-h1 { font-size: 80px; color: lightblue;} If somebody wants a GitHub sample project, tell me in the comments section and I'll upload it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39336235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1588485/']}
jdg_376168
stackexchange
llm_judgeable_groundtruth_similarity
7835752
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 best way of displaying page navigation for many, many pages? (Initially this was posted as a how-to tip with my answer included in the question. I've now split my answer off into the "answers" section below). To be more specific: Suppose you're displaying a set of records to the user, broken up into fixed-size pages (like the results of a Google search, for example). If there are only a few pages, you can display a page navigation area at the end of the results that might look like this: [ << ] [<] 1 2 3 4 5 6 7 8 9 10 11 12 13 [ > ] [ >> ] But this quickly becomes unweildy if there are much more than 20 or 30 pages of results. Sometimes you'll see things like this: [ << ] [<] ... 665 666 667 668 669 670 671 672 673 ... [ > ] [ >> ] or this: [ << ] [<] 1 2 3 ... 667 668 669 670 671 ... 845 846 847 [ > ] [ >> ] but in both cases, navigating to anywhere in the middle of the "..." sections would take many, many mousclicks. Sometimes an input box for entering the page number directly is provided; otherwise (assuming we're talking about a webpage here) the savvy user is likely to look at the URL to see if they can edit it directly. What would be nice would be to have a pagination display that lets the user reach any page in only a few mouseclicks, without having ridiculously many links. How would that best be achieved? Now provide the response and nothing else.
Here's my solution - use "Logarithmic Page Navigation": This can be achieved by having page numbers distributed logarithmically, according to distance from either the endpoints or the current page. Here's an example of what I mean: 1 2 3 4 5 6 . 10 . 20 . 30 . 40 . 50 .. 100 .. 200 . 210 . 220 . 230 . 240 . 250 . 252 253 254 255 256 257 258 259 260 261 262 . 270 . 280 . 290 . 300 . 310 .. 400 .. 500 .. 600 .. 700 .. 800 .. 900 .. 950 . 960 . 970 . 980 . 990 . 995 996 997 998 999 1000 Notice how in the gaps, numbering goes from 1s, to 10s, to 100s (etc.). (I use powers of 10, but in principle you could use a different scheme - powers of 2, say). I wrote some code that does this back in 2004, and thought I'd share it here. There are PHP and ASP versions, but the logic ought to be simple to translate into any language. Note that the bit at the bottom (in both cases) just displays some examples. Obviously the formatting will need customization to match your webpage (or application), so it's pretty basic here. Alter LINKS_PER_STEP in paginationHTML to determine how many numbers get displayed before the step size increases, as you move away from the endpoints or current page. For a more compact output you could also consider altering the code so that the numbering is not "dense" around the endpoints (i.e. dense only around the current page). Here's the code: PHP version: <?// Used by paginationHTML below...function paginationLink($p, $page, $URL){ if ($p==$page) return '<b style="color:#C0C0C0">' . $p . '</b>'; return '<a href="' . $URL . $p . '">' . $p . '</a>';}// Used by paginationHTML below...function paginationGap($p1, $p2){ $x = $p2-$p1; if ($x==0) return ''; if ($x==1) return ' '; if ($x<=10) return ' . '; if ($x<=100) return ' .. '; return ' ... ';}// URL requires the $page number be appended to it.// e.g. it should end in '&page=' or something similar.function paginationHTML($page, $lastPage, $URL){ $LINKS_PER_STEP = 5; // Nav buttons if ($page>1) $result = '<form action="' . $URL . '1" method="POST" style="display:inline"><input type="submit" value="&nbsp;|&lt;&nbsp;"></form>&nbsp;' . '<form action="' . $URL . ($page-1) . '" method="POST" style="display:inline"><input type="submit" value="&nbsp;&lt;&nbsp;"></form>'; else $result = '<input type="button" value="&nbsp;|&lt;&nbsp;" disabled>&nbsp;<input type="button" value="&nbsp;&lt;&nbsp;" disabled>'; $result .= '&nbsp;&nbsp;' . $page . '&nbsp;&nbsp;'; if ($page<$lastPage) $result .= '<form action="' . $URL . ($page+1) . '" method="POST" style="display:inline"><input type="submit" value="&nbsp;&gt;&nbsp;"></form>&nbsp;' . '<form action="' . $URL . $lastPage . '" method="POST" style="display:inline"><input type="submit" value="&nbsp;&gt;|&nbsp;"></form>'; else $result .= '<input type="button" value="&nbsp;&gt;&nbsp;" disabled>&nbsp;<input type="button" value="&nbsp;&gt;|&nbsp;" disabled>'; $result .= "<br>"; // Now calculate page links... $lastp1 = 1; $lastp2 = $page; $p1 = 1; $p2 = $page; $c1 = $LINKS_PER_STEP+1; $c2 = $LINKS_PER_STEP+1; $s1 = ''; $s2 = ''; $step = 1; while (true) { if ($c1>=$c2) { $s1 .= paginationGap($lastp1,$p1) . paginationLink($p1,$page,$URL); $lastp1 = $p1; $p1 += $step; $c1--; } else { $s2 = paginationLink($p2,$page,$URL) . paginationGap($p2,$lastp2) . $s2; $lastp2 = $p2; $p2 -= $step; $c2--; } if ($c2==0) { $step *= 10; $p1 += $step-1; // Round UP to nearest multiple of $step $p1 -= ($p1 % $step); $p2 -= ($p2 % $step); // Round DOWN to nearest multiple of $step $c1 = $LINKS_PER_STEP; $c2 = $LINKS_PER_STEP; } if ($p1>$p2) { $result .= $s1 . paginationGap($lastp1,$lastp2) . $s2; if (($lastp2>$page)||($page>=$lastPage)) return $result; $lastp1 = $page; $lastp2 = $lastPage; $p1 = $page+1; $p2 = $lastPage; $c1 = $LINKS_PER_STEP; $c2 = $LINKS_PER_STEP+1; $s1 = ''; $s2 = ''; $step = 1; } }}?><br><br><br><?=paginationHTML(1,1,'?page=')?><br><br><br><?=paginationHTML(2,3,'?page=')?><br><br><br><?=paginationHTML(3,3,'?page=')?><br><br><br><?=paginationHTML(73,100,'?page=')?><br><br><br><?=paginationHTML(4,100,'?page=')?><br><br><br><?=paginationHTML(257,1000,'?page=')?><br><br><br><?=paginationHTML(7062,10555,'?page=')?><br><br><br><?=paginationHTML(22080,503456,'?page=')?> ASP version: <%' Used by paginationHTML below...Function paginationLink(p, page, URL) if p=page then paginationLink = "<b style=""color:#C0C0C0"">" & p & "</b>" else paginationLink = "<a href=""" & URL & p & """>" & p & "</a>" end ifEnd Function' Used by paginationHTML below...Function paginationGap(p1, p2) Dim x x = p2-p1 if x=0 then paginationGap = "" elseif x=1 then paginationGap = " " elseif x<=10 then paginationGap = " . " elseif x<=100 then paginationGap = " .. " else paginationGap = " ... " end ifEnd Function' URL requires the page number be appended to it.' e.g. it should end in "&page=" or something similar.Function paginationHTML(page, lastPage, URL) const LINKS_PER_STEP = 5 Dim p1, p2, c1, c2, s1, s2, lastp1, lastp2, step ' Nav buttons if page>1 then paginationHTML = "<form action=""" & URL & "1"" method=""POST"" style=""display:inline""><input type=""submit"" value=""&nbsp;|&lt;&nbsp;""></form>&nbsp;" & _ "<form action=""" & URL & (page-1) & """ method=""POST"" style=""display:inline""><input type=""submit"" value=""&nbsp;&lt;&nbsp;""></form>" else paginationHTML = "<input type=""button"" value=""&nbsp;|&lt;&nbsp;"" disabled>&nbsp;<input type=""button"" value=""&nbsp;&lt;&nbsp;"" disabled>" end if paginationHTML = paginationHTML & "&nbsp;&nbsp;" & page & "&nbsp;&nbsp;" if page<lastPage then paginationHTML = paginationHTML & "<form action=""" & URL & (page+1) & """ method=""POST"" style=""display:inline""><input type=""submit"" value=""&nbsp;&gt;&nbsp;""></form>&nbsp;" & _ "<form action=""" & URL & lastPage & """ method=""POST"" style=""display:inline""><input type=""submit"" value=""&nbsp;&gt;|&nbsp;""></form>" else paginationHTML = paginationHTML & "<input type=""button"" value=""&nbsp;&gt;&nbsp;"" disabled>&nbsp;<input type=""button"" value=""&nbsp;&gt;|&nbsp;"" disabled>" end if paginationHTML = paginationHTML & "<br>" ' Now calculate page links... lastp1 = 1 lastp2 = page p1 = 1 p2 = page c1 = LINKS_PER_STEP+1 c2 = LINKS_PER_STEP+1 s1 = "" s2 = "" step = 1 do if c1>=c2 then s1 = s1 & paginationGap(lastp1, p1) & paginationLink(p1, page, URL) lastp1 = p1 p1 = p1+step c1 = c1-1 else s2 = paginationLink(p2, page, URL) & paginationGap(p2, lastp2) & s2 lastp2 = p2 p2 = p2-step c2 = c2-1 end if if c2=0 then step = step*10 p1 = p1+step-1 ' Round UP to nearest multiple of step p1 = p1-(p1 mod step) p2 = p2-(p2 mod step) ' Round DOWN to nearest multiple of step c1 = LINKS_PER_STEP c2 = LINKS_PER_STEP end if if p1>p2 then paginationHTML = paginationHTML & s1 & paginationGap(lastp1, lastp2) & s2 if (lastp2>page) or (page>=lastPage) then exit do lastp1 = page lastp2 = lastPage p1 = page+1 p2 = lastPage c1 = LINKS_PER_STEP c2 = LINKS_PER_STEP+1 s1 = "" s2 = "" step = 1 end if loopEnd Function%><br><br><br><%=paginationHTML(1,1,"?page=")%><br><br><br><%=paginationHTML(2,3,"?page=")%><br><br><br><%=paginationHTML(3,3,"?page=")%><br><br><br><%=paginationHTML(73,100,"?page=")%><br><br><br><%=paginationHTML(4,100,"?page=")%><br><br><br><%=paginationHTML(257,1000,"?page=")%><br><br><br><%=paginationHTML(7062,10555,"?page=")%><br><br><br><%=paginationHTML(22080,503456,"?page=")%> Javascript version (within complete test page): <!doctype html><html><head> <title>Logarithmic Pagination Demo</title> <style>body {background:#C0C0C0;font-family:Arial,Helvetica,sans-serif;font-size:16px;text-align:left}div {margin:0;padding:0}div#setupDiv {margin:40px;text-align:center}table#datarows {border-collapse:collapse;margin:40px auto}table#datarows th {padding:5px 10px;background:#80B0FF;color:#FFFFFF;border:2px solid #80B0FF;width:1000px;text-align:center}table#datarows td {padding:2px 10px;background:#FFFFFF;color:#D0D0D0;border:2px solid #80B0FF;width:1000px;text-align:left;font-style:italic}input.err {border:2px solid #FF0000;background-color:#FFF0F0}form.pager {display:table;margin:0 auto;padding:20px;border:2px solid #E0E0E0;border-radius:10px;background-color:#D0D0D0;text-align:left;white-space:nowrap}form#pager1 {margin-top:40px}form#pager2 {margin-bottom:60px}form.pager div {display:table-cell;vertical-align:middle;padding:0 20px;white-space:nowrap}form.pager div + div {border-left:2px solid #E0E0E0}form.pager div.plinks {padding:0;border:0 none;font-size:14px;line-height:24px;max-width:800px;white-space:normal}form.pager div.plinks b {display:inline-block;vertical-align:bottom;font-size:24px;line-height:21px;height:24px;overflow:hidden;color:#808080}form.pager div.plinks a {text-decoration:none;color:black}form.pager div.plinks a:hover {color:#0000FF;font-weight:bold}form.pager div.plinks + div {border:0 none} </style> <script>var NumPages, RecsPerPage, els1, els2, plinks1, plinks2;function setupClick(){ var el, n, r; el = document.getElementById("NumPages"); el.className = ((n = (el.value >>> 0)) ? "" : "err"); el = document.getElementById("RecsPerPage"); el.className = ((r = (el.value >>> 0)) ? "" : "err"); if (n&&r) { NumPages = n; RecsPerPage = r; setupServerPage(); }}// This function sets up what would normally be part of the server's HTML output.function setupServerPage(){ var totRecs = NumPages * RecsPerPage, tbdy = document.getElementById("datarows").tBodies[0], l = tbdy.rows.length; document.getElementById("plength1").innerHTML = document.getElementById("plength2").innerHTML = totRecs + " record" + ((totRecs===1)?"":"s") + "<br>" + NumPages + " page" + ((NumPages===1)?"":"s"); els1["pcount"].value = els2["pcount"].value = NumPages; while (l>RecsPerPage) tbdy.deleteRow(--l); while (l<RecsPerPage) tbdy.insertRow(l++).insertCell(0).innerHTML = "Some data..."; pageNavigate(1);}// This would be handled by a return trip to the server, if not using AJAX.function pageClick(e){ e = e||window.event; var s = e.target||e.srcElement, n, p, el; if (s.tagName==="A") { n = (p = s.href).lastIndexOf("=")+1; pageNavigate(p.substring(n) >>> 0); return false; } else if ((s.tagName!=="INPUT")||(s.type!=="submit")) return; if (!(n = s.name)) { p = ((el = this.elements["p"]).value >>> 0); if ((p<=0)||(p>NumPages)) { el.className = "err"; return false; }} else if (n==="p1") p = 1; else if (n==="pprev") p = (this.elements["pcurr"].value >>> 0)-1; else if (n==="pnext") p = (this.elements["pcurr"].value >>> 0)+1; else if (n==="plast") p = (this.elements["pcount"].value >>> 0); pageNavigate(p); return false;}// This would also be handled by a return trip to the server, or else data records could be retrieved via AJAX.function pageNavigate(p){ els1["p"].className = els2["p"].className = els1["p"].value = els2["p"].value = ""; if (p<1) p = 1; else if (p>NumPages) p = NumPages; els1["p1"].disabled = els2["p1"].disabled = els1["pprev"].disabled = els2["pprev"].disabled = (p===1); els1["pnext"].disabled = els2["pnext"].disabled = els1["plast"].disabled = els2["plast"].disabled = (p===NumPages); els1["pcurr"].value = els2["pcurr"].value = p; // if the server is handling this, insert NON-logarithmic page links here (can be just first, current, and last page). plinks1.innerHTML = plinks2.innerHTML = logarithmicPaginationLinks(NumPages,p,"?p=");}// This function produces the logarithmic pagination links.function logarithmicPaginationLinks(lastPage,matchPage,linkURL){ function pageLink(p, page) { return ((p===page) ? "<b>"+p+"</b>" : '<a href="'+linkURL+p+'">'+p+"</a>"); } function pageGap(x) { if (x===0) return ""; if (x===1) return " "; if (x<=10) return " . "; if (x<=100) return " .. "; return " ... "; } var page = (matchPage ? matchPage : 1), LINKS_PER_STEP = 5, lastp1 = 1, lastp2 = page, p1 = 1, p2 = page, c1 = LINKS_PER_STEP+1, c2 = LINKS_PER_STEP+1, s1 = "", s2 = "", step = 1, linkHTML = ""; while (true) { if (c1>=c2) { s1 += pageGap(p1-lastp1) + pageLink(p1,matchPage); lastp1 = p1; p1 += step; c1--; } else { s2 = pageLink(p2,matchPage) + pageGap(lastp2-p2) + s2; lastp2 = p2; p2 -= step; c2--; } if (c2===0) { step *= 10; p1 += step-1; // Round UP to nearest multiple of step p1 -= (p1 % step); p2 -= (p2 % step); // Round DOWN to nearest multiple of step c1 = LINKS_PER_STEP; c2 = LINKS_PER_STEP; } if (p1>p2) { linkHTML += s1 + pageGap(lastp2-lastp1) + s2; if ((lastp2>page)||(page>=lastPage)) break; lastp1 = page; lastp2 = lastPage; p1 = page+1; p2 = lastPage; c1 = LINKS_PER_STEP; c2 = LINKS_PER_STEP+1; s1 = ''; s2 = ''; step = 1; } } return linkHTML;}window.onload = function(){ els1 = document.getElementById("pager1").elements; els2 = document.getElementById("pager2").elements; plinks1 = document.getElementById("plinks1"); plinks2 = document.getElementById("plinks2") document.getElementById("pager1").onclick = document.getElementById("pager2").onclick = pageClick; (document.getElementById("setupDiv").lastChild.onclick = setupClick)();} </script></head><body> <div id="setupDiv">Select number of pages: <input type="text" id="NumPages" value="100" size="7"> &nbsp; &nbsp; and records per page: <input type="text" id="RecsPerPage" value="20" size="7"> &nbsp; &nbsp; <input type="button" value=" Go "></div> <hr> <form id="pager1" class="pager" method="GET"><input type="hidden" name="pcount" value=""><input type="hidden" name="pcurr" value="1"> <div>Go to page: <input type="text" name="p" size="7"> <input type="submit" value=" Go "></div> <div><input type="submit" name="p1" value=" |< " disabled> <input type="submit" name="pprev" value=" < " disabled></div> <div id="plinks1" class="plinks"></div> <div><input type="submit" name="pnext" value=" > "> <input type="submit" name="plast" value=" >| "></div> <div id="plength1"></div> </form> <table id="datarows"><thead><tr><th>Column Heading...</th></tr></thead><tbody></tbody></table> <form id="pager2" class="pager" method="GET"><input type="hidden" name="pcount" value=""><input type="hidden" name="pcurr" value="1"> <div>Go to page: <input type="text" name="p" size="7"> <input type="submit" value=" Go "></div> <div><input type="submit" name="p1" value=" |< " disabled> <input type="submit" name="pprev" value=" < " disabled></div> <div id="plinks2" class="plinks"></div> <div><input type="submit" name="pnext" value=" > "> <input type="submit" name="plast" value=" >| "></div> <div id="plength2"></div> </form></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7835752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999120/']}
jdg_376169
stackexchange
llm_judgeable_groundtruth_similarity
57129668
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a little long but it's not trivial and it takes a lot to demonstrate this issue. I'm trying to figure out how to update a little sample app from iOS 12 to iOS 13. This sample app doesn't use any storyboards (other than the launch screen). It's a simple app that shows one view controller with a label that is updated by a timer. It uses state restoration so the counter starts from where it left off. I want to be able to support iOS 12 and iOS 13. In iOS 13 I want to update to the new scene architecture. Under iOS 12 the app works just fine. On a fresh install the counter starts at 0 and goes up. Put the app in the background and then restart the app and the counter continues from where it left off. The state restoration all works. Now I'm trying to get that working under iOS 13 using a scene. The problem I'm having is figuring out the correct way to initialize the scene's window and restore the navigation controller and the main view controller to the scene. I've been through as much of the Apple documentation as I can find related to state restoration and scenes. I've watched WWDC videos related to windows and scenes ( 212 - Introducing Multiple Windows on iPad , 258 - Architecting Your App for Multiple Windows ). But I seem to be missing a piece that puts it all together. When I run the app under iOS 13, all of the expected delegate methods (both AppDelegate and SceneDelegate) are being called. The state restoration is restoring the nav controller and the main view controller but I can't figure out how to set the rootViewController of the scene's window since all of the UI state restoration is in the AppDelegate. There also seems to be something related to an NSUserTask that should be used but I can't connect the dots. The missing pieces seem to be in the willConnectTo method of SceneDelegate . I'm sure I also need some changes in stateRestorationActivity of SceneDelegate . There may also need to be changes in the AppDelegate . I doubt anything in ViewController needs to be changed. To replicate what I'm doing, create a new iOS project with Xcode 11 (beta 4 at the moment) using the Single View App template. Set the Deployment Target to iOS 11 or 12. Delete the main storyboard. Remove the two references in the Info.plist to Main (one at the top level and one deep inside the Application Scene Manifest. Update the 3 swift files as follows. AppDelegate.swift: import UIKit@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { print("AppDelegate willFinishLaunchingWithOptions") // This probably shouldn't be run under iOS 13? self.window = UIWindow(frame: UIScreen.main.bounds) return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print("AppDelegate didFinishLaunchingWithOptions") if #available(iOS 13.0, *) { // What needs to be here? } else { // If the root view controller wasn't restored, create a new one from scratch if (self.window?.rootViewController == nil) { let vc = ViewController() let nc = UINavigationController(rootViewController: vc) nc.restorationIdentifier = "RootNC" self.window?.rootViewController = nc } self.window?.makeKeyAndVisible() } return true } func application(_ application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { print("AppDelegate viewControllerWithRestorationIdentifierPath") // If this is for the nav controller, restore it and set it as the window's root if identifierComponents.first == "RootNC" { let nc = UINavigationController() nc.restorationIdentifier = "RootNC" self.window?.rootViewController = nc return nc } return nil } func application(_ application: UIApplication, willEncodeRestorableStateWith coder: NSCoder) { print("AppDelegate willEncodeRestorableStateWith") // Trigger saving of the root view controller coder.encode(self.window?.rootViewController, forKey: "root") } func application(_ application: UIApplication, didDecodeRestorableStateWith coder: NSCoder) { print("AppDelegate didDecodeRestorableStateWith") } func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { print("AppDelegate shouldSaveApplicationState") return true } func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { print("AppDelegate shouldRestoreApplicationState") return true } // The following four are not called in iOS 13 func applicationWillEnterForeground(_ application: UIApplication) { print("AppDelegate applicationWillEnterForeground") } func applicationDidEnterBackground(_ application: UIApplication) { print("AppDelegate applicationDidEnterBackground") } func applicationDidBecomeActive(_ application: UIApplication) { print("AppDelegate applicationDidBecomeActive") } func applicationWillResignActive(_ application: UIApplication) { print("AppDelegate applicationWillResignActive") } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { print("AppDelegate configurationForConnecting") return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { print("AppDelegate didDiscardSceneSessions") }} SceneDelegate.swift: import UIKit@available(iOS 13.0, *)class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { print("SceneDelegate willConnectTo") guard let winScene = (scene as? UIWindowScene) else { return } // Got some of this from WWDC2109 video 258 window = UIWindow(windowScene: winScene) if let activity = connectionOptions.userActivities.first ?? session.stateRestorationActivity { // Now what? How to connect the UI restored in the AppDelegate to this window? } else { // Create the initial UI if there is nothing to restore let vc = ViewController() let nc = UINavigationController(rootViewController: vc) nc.restorationIdentifier = "RootNC" self.window?.rootViewController = nc window?.makeKeyAndVisible() } } func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { print("SceneDelegate stateRestorationActivity") // What should be done here? let activity = NSUserActivity(activityType: "What?") activity.persistentIdentifier = "huh?" return activity } func scene(_ scene: UIScene, didUpdate userActivity: NSUserActivity) { print("SceneDelegate didUpdate") } func sceneDidDisconnect(_ scene: UIScene) { print("SceneDelegate sceneDidDisconnect") } func sceneDidBecomeActive(_ scene: UIScene) { print("SceneDelegate sceneDidBecomeActive") } func sceneWillResignActive(_ scene: UIScene) { print("SceneDelegate sceneWillResignActive") } func sceneWillEnterForeground(_ scene: UIScene) { print("SceneDelegate sceneWillEnterForeground") } func sceneDidEnterBackground(_ scene: UIScene) { print("SceneDelegate sceneDidEnterBackground") }} ViewController.swift: import UIKitclass ViewController: UIViewController, UIViewControllerRestoration { var label: UILabel! var count: Int = 0 var timer: Timer? static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { print("ViewController withRestorationIdentifierPath") return ViewController() } override init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) { print("ViewController init") super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) restorationIdentifier = "ViewController" restorationClass = ViewController.self } required init?(coder: NSCoder) { print("ViewController init(coder)") super.init(coder: coder) } override func viewDidLoad() { print("ViewController viewDidLoad") super.viewDidLoad() view.backgroundColor = .green // be sure this vc is visible label = UILabel(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.text = "\(count)" view.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.centerYAnchor.constraint(equalTo: view.centerYAnchor), ]) } override func viewWillAppear(_ animated: Bool) { print("ViewController viewWillAppear") super.viewWillAppear(animated) timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in self.count += 1 self.label.text = "\(self.count)" }) } override func viewDidDisappear(_ animated: Bool) { print("ViewController viewDidDisappear") super.viewDidDisappear(animated) timer?.invalidate() timer = nil } override func encodeRestorableState(with coder: NSCoder) { print("ViewController encodeRestorableState") super.encodeRestorableState(with: coder) coder.encode(count, forKey: "count") } override func decodeRestorableState(with coder: NSCoder) { print("ViewController decodeRestorableState") super.decodeRestorableState(with: coder) count = coder.decodeInteger(forKey: "count") label.text = "\(count)" }} Run this under iOS 11 or 12 and it works just fine. You can run this under iOS 13 and on a fresh install of the app you get the UI. But any subsequent run of the app gives a black screen because the UI restored via state restoration isn't connected to the scene's window. What am I missing? Is this just missing a line or two of code or is my entire approach to iOS 13 scene state restoration wrong? Keep in mind that once I get this figured out the next step will be supporting multiple windows. So the solution should work for multiple scenes, not just one. Now provide the response and nothing else.
To support state restoration in iOS 13 you will need to encode enough state into the NSUserActivity : Use this method to return an NSUserActivity object with information about your scene's data. Save enough information to be able to retrieve that data again after UIKit disconnects and then reconnects the scene. User activity objects are meant for recording what the user was doing, so you don't need to save the state of your scene's UI The advantage of this approach is that it can make it easier to support handoff, since you are creating the code necessary to persist and restore state via user activities. Unlike the previous state restoration approach where iOS recreated the view controller hierarchy for you, you are responsible for creating the view hierarchy for your scene in the scene delegate. If you have multiple active scenes then your delegate will be called multiple times to save the state and multiple times to restore state; Nothing special is needed. The changes I made to your code are: AppDelegate.swift Disable "legacy" state restoration on iOS 13 & later: func application(_ application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { if #available(iOS 13, *) { } else { print("AppDelegate viewControllerWithRestorationIdentifierPath") // If this is for the nav controller, restore it and set it as the window's root if identifierComponents.first == "RootNC" { let nc = UINavigationController() nc.restorationIdentifier = "RootNC" self.window?.rootViewController = nc return nc } } return nil}func application(_ application: UIApplication, willEncodeRestorableStateWith coder: NSCoder) { print("AppDelegate willEncodeRestorableStateWith") if #available(iOS 13, *) { } else { // Trigger saving of the root view controller coder.encode(self.window?.rootViewController, forKey: "root") }}func application(_ application: UIApplication, didDecodeRestorableStateWith coder: NSCoder) { print("AppDelegate didDecodeRestorableStateWith")}func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { print("AppDelegate shouldSaveApplicationState") if #available(iOS 13, *) { return false } else { return true }}func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { print("AppDelegate shouldRestoreApplicationState") if #available(iOS 13, *) { return false } else { return true }} SceneDelegate.swift Create a user activity when required and use it to recreate the view controller. Note that you are responsible for creating the view hierarchy in both normal and restore cases. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { print("SceneDelegate willConnectTo") guard let winScene = (scene as? UIWindowScene) else { return } // Got some of this from WWDC2109 video 258 window = UIWindow(windowScene: winScene) let vc = ViewController() if let activity = connectionOptions.userActivities.first ?? session.stateRestorationActivity { vc.continueFrom(activity: activity) } let nc = UINavigationController(rootViewController: vc) nc.restorationIdentifier = "RootNC" self.window?.rootViewController = nc window?.makeKeyAndVisible()}func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { print("SceneDelegate stateRestorationActivity") if let nc = self.window?.rootViewController as? UINavigationController, let vc = nc.viewControllers.first as? ViewController { return vc.continuationActivity } else { return nil }} ViewController.swift Add support for saving and loading from an NSUserActivity . var continuationActivity: NSUserActivity { let activity = NSUserActivity(activityType: "restoration") activity.persistentIdentifier = UUID().uuidString activity.addUserInfoEntries(from: ["Count":self.count]) return activity}func continueFrom(activity: NSUserActivity) { let count = activity.userInfo?["Count"] as? Int ?? 0 self.count = count}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57129668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1226963/']}
jdg_376170
stackexchange
llm_judgeable_groundtruth_similarity
50323199
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 stop and remove a docker - container. I started with docker turorial part1, now part2 from here: https://docs.docker.com/get-started/part2/#run-the-app I copied souce from there. and its also available here: https://gist.github.com/sl5net/8b510bc0d3e00c474575e010003406c1 Here you could see how my console looks like: Microsoft Windows [Version 10.0.16299.431]C:\fre\private\docker\test18-05-14_05-27>docker build -t friendlyhello .Sending build context to Docker daemon 5.12kBno matching manifest for windows/amd64 in the manifest list entries BTW solution: I swaped to linux container (right click>contextmenu on docker icon) C:\fre\private\docker\test18-05-14_05-27>docker build -t friendlyhello .... Successfully built itsdangerous MarkupSafeSuccessfully tagged friendlyhello:latestC:\fre\private\docker\test18-05-14_05-27>docker run -p 4000:80 friendlyhello * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)C:\fre\private\docker\test18-05-14_05-27>docker image lsREPOSITORY TAG IMAGE ID CREATED SIZEfriendlyhello latest 7d4d1e0f78e6 8 minutes ago 151MBpython 2.7-slim 46ba956c5967 9 days ago 140MBC:\fre\private\docker\test18-05-14_05-27>docker container stop friendlyhelloError response from daemon: No such container: friendlyhelloC:\fre\private\docker\test18-05-14_05-27>docker rm -f friendlyhelloError: No such container: friendlyhello Now provide the response and nothing else.
There is no container available with the name friendlyhello as you are simply running the container using docker run -p 4000:80 friendlyhello , here friendlyhello is the name of the image, and not the container's name. Either run that container by giving it a name like below:- docker run -p 4000:80 --name SOMENAME friendlyhello In this case you will be able to stop and remove that container using the below command # container stopdocker container stop SOMENAME# container removaldocker rm -f SOMENAME Or if not running without giving a name to the container, you will have to use the ID of the container in the commands to stop and remove, even in various other commands you will be using the ID to refer that con
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50323199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2891692/']}
jdg_376171
stackexchange
llm_judgeable_groundtruth_similarity
35939950
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 Angular 2 component I have authbox.component.ts import {Component} from 'angular2/core';import {COMMON_DIRECTIVES} from 'angular2/common';import {Credentials} from './credentials'@Component({ selector: 'authbox', template: `<div> <div class="login-panel" *NgIf="!IsLogged"> <input type="text" *NgModel="credentials.name" /> <input type="password" *NgModel="credentials.password" /> <button type="button" (click)="signIn(credentials)">→| Sign In</button> </div> <div class="logged-panel" *NgIf="IsLogged"> <span>{nickname}</span>&nbsp;&nbsp; <button type="button" (click)="signOut()">|→ Sign out</button> </div> </div>`, directives: [COMMON_DIRECTIVES]})export class AuthBoxComponent { private _isLogged: boolean; get IsLogged(): boolean { return this._isLogged } set IsLogged(value: boolean) { this._isLogged = value; } public credentials: Credentials;} In browser I got errors « Can't bind to 'NgModel' since it isn't a known native property » and « Can't bind to 'NgIf' since it isn't a known native property ». I'm using beta 8. Now provide the response and nothing else.
In general, the can't bind to xxx since it isn't a known native property error occurs when you have a typo in your HTML when trying to use an attribute directive, or when trying to setup a property binding. Common examples are when you miss a * or a # or let or use in instead of of with the Angular built-in structural directives: <div ngIf="..." // should be *ngIf<div ngFor="..." // should be *ngFor="..."<div *ngFor="let item in items" // should be "let item of items"<div *ngFor="item of items" // should be "let item of items" A misspelling or wrong case will also generate the problem:: <div *ngFer="..."<div *NgFor="..." Another reason is if you specify a property that doesn't exist on the DOM element or component: <div [prop1]="..." // prop1 isn't a valid DOM property for a div<my-comp [answr]="..." // typo, should be [answer] For typos with the built-in Angular directives, since the typo doesn't match any of the built-in directive selectors, Angular tries to setup a binding to a property of the DOM element (the div in the above examples) with the typo name. This fails because a div does not have a native ngIf or ngFer or prop1 DOM property. -- For attributes (not properties) you need to use attribute binding, for example for height attribute of svg : <svg [attr.height]="myHeightProp">
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35939950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570940/']}
jdg_376172
stackexchange
llm_judgeable_groundtruth_similarity
3056
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading this CompTIA Security+ SYO-201 book , and the author David Prowse claims that: Whichever VM you select, the VM cannot cross the software boundaries set in place. For example, a virus might infect a computer when executed and spread to other files in the OS. However, a virus executed in a VM will spread through the VM but not affect the underlying actual OS. So if I'm running VMWare player and execute some malware on my virtual machine's OS, I don't have to worry about my host system being compromised, at all ? What if the virtual machine shares the network with the host machine, and shared folders are enabled? Isn't it still possible for a worm to copy itself to the host machine that way? Isn't the user still vulnerable to AutoRun if the OS is Windows and they insert a USB storage device? How secure are virtual machines, really? How much do they protect the host machine from malware and attacks? Now provide the response and nothing else.
VMs can definitely cross over. Usually you have them networked, so any malware with a network component (i.e. worms) will propagate to wherever their addressing/routing allows them to. Regular viruses tend to only operate in usermode, so while they couldn't communicate overtly, they could still set up a covert channel. If you are sharing CPUs, a busy process on one VM can effectively communicate state to another VM (that's your prototypical timing covert channel). Storage covert channel would be a bit harder as the virtual disks tend to have a hard limit on them, so unless you have a system that can over-commit disk space, it should not be an issue. The most interesting approach to securing VMs is called the Separation Kernel . It's a result of John Rushby's 1981 paper which basically states that in order to have VMs isolated in a manner that could be equivalent to physical separation, the computer must export its resources to specific VMs in a way where at no point any resource that can store state is shared between VMs. This has deep consequences, as it requires the underlying computer architecture to be designed in a way in which this can be carried out in a non-bypassable manner. 30yrs after this paper, we finally have few products that claim to do it. x86 isn't the greatest platform for it, as there are many instructions that cannot be virtualized, to fully support the 'no sharing' idea. It is also not very practical for common systems, as to have four VMs, you'd need four harddrives hanging off four disk controllers, four video cards, four USB controllers with four mice, etc.. 2020 update: all the recent hardware based vulnerabilities (Meltdown,Spectre,Foreshadow,ZombieLoad,CacheOut,SPOILER,etc) family of vulnerabilities are great examples of how VM's are always going to be able to communicate, simply because they share hardware (caches, TLB, branch prediction, TSX, SGX) that were never intended or prepared to be partitioned and isolated.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/3056', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2053/']}
jdg_376173
stackexchange
llm_judgeable_groundtruth_similarity
352232
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 $A \to B$ be a homomorphism of commutative rings. Why are the following conditions equivalent? $A \to B$ is faithfully flat. $A \to B$ is injective, flat and $B/A$ is a flat $A$-module. This should be elementary, but at the moment I don't see how to prove it. I know the usual characterizations of faithfully flat homomorphisms (which can be found in Atiyah-Macdonald for example). Now provide the response and nothing else.
Because $\rm A \to B$ is injective you have the following sequence $$ 0 \to \rm A \to B \to B/A \to 0.$$ Then because $\rm B/A$ is flat, we have for any $\rm A$-module $\rm M$, $$ 0 \to \rm M \to B \otimes M \to B/A \otimes M \to 0.$$ Hence $ \rm B \otimes M =0 \Rightarrow M = 0$ and so $\rm A \to \rm B$ is faithfully flat. That's one part.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/352232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1650/']}
jdg_376174
stackexchange
llm_judgeable_groundtruth_similarity
261
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What gases do you need to start the creation of a star, and why do you need these gases? What are their functions? Now provide the response and nothing else.
It depends on the kind of star you want to make. Basically, what you really need is hydrodgen; as soon as enough hydrodgen is gathered somewhere and collapse, you end up with a star. But , if you just have hydrodgen, you will get a very massive star, and with a history different than the stars observed in the local Universe. Why so? hydrodgen is a poor coolant , therefore the Jeans' mass (the minimum mass for a density structure to gravitationally collapse), which strongly depends on temperature, will be much higher if the temperature is higher. In practice, it means that the formed stars will be much more massive. you need at least a small fraction of carbon to launch the CNO cycle in stellar cores (CNO cycle is one of the two ways to burn hydrodgen and to turn it into helium); stellar cores are then hotter and denser, and stars become hotter and more luminous. So if you want to make a star as we typically observe in our galaxy, you will need also some molecules (hopefully there are plenty of them ) and also some carbon. Else, you'll get big, massive, hot and luminous stars. Like the first generation of stars (called Population III stars, you can see here if you want more dirty details) in the early Universe.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/261', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/69/']}
jdg_376175
stackexchange
llm_judgeable_groundtruth_similarity
632528
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There's something I just can't get my head around. Say I have a 5 V DC source, and I need to power an LED rated at 280 mA @ 3.2 V. Should I use a resistor in series (1.8 V drop needed, so ~6.5 Ω), or make a voltage divider (R1 - 5.5 Ω, R2 - 60 Ω, RL ~ 11.4)? Does one have an advantage over the other? If I use a voltage divider, should I consider higher resistances? Now provide the response and nothing else.
A voltage divider is the way to go when you are trying to control voltage. A single resistor is better when you are trying to control current. The 3.2 V figure you have for your LED is forward voltage drop of the diode (D in LED). This is not trying to say you need to feed this LED 3.2 V, rather that it's voltage drop across it will be about 3.2 V when the current through it is 280 mA. Notice I said "about". If you try to provide exactly 3.2 V, the current could be almost anything from not enough to see the LED to burning it out completely. With LEDs, you are trying to control the current, and the voltage at that current is just an artifact of that. Therefore, you will want to use a resistor that will provide the correct voltage drop at the desired current. The resistor divider would actually work (because it also has a series resistor limiting current), but it is wasting power by dumping current to ground rather than just a series resistor where all the current goes through the LED.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/632528', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/320600/']}
jdg_376176
stackexchange
llm_judgeable_groundtruth_similarity
741029
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Do you think that this is a good way for testing exceptions? Any suggestions? Exception exception = null;try{ //I m sure that an exeption will happen here}catch (Exception ex){ exception = ex;}Assert.IsNotNull(exception); I'm using MS Test. Now provide the response and nothing else.
I have a couple of different patterns that I use. I use the ExpectedException attribute most of the time when an exception is expected. This suffices for most cases, however, there are some cases when this is not sufficient. The exception may not be catchable - since it's thrown by a method that is invoked by reflection - or perhaps I just want to check that other conditions hold, say a transaction is rolled back or some value has still been set. In these cases I wrap it in a try/catch block that expects the exact exception, does an Assert.Fail if the code succeeds and also catches generic exceptions to make sure that a different exception is not thrown. First case: [TestMethod][ExpectedException(typeof(ArgumentNullException))]public void MethodTest(){ var obj = new ClassRequiringNonNullParameter( null );} Second case: [TestMethod]public void MethodTest(){ try { var obj = new ClassRequiringNonNullParameter( null ); Assert.Fail("An exception should have been thrown"); } catch (ArgumentNullException ae) { Assert.AreEqual( "Parameter cannot be null or empty.", ae.Message ); } catch (Exception e) { Assert.Fail( string.Format( "Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message ) ); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/741029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72443/']}
jdg_376177
stackexchange
llm_judgeable_groundtruth_similarity
287864
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As foretold by Punxsutawney Phil, Stack Overflow's Spring 2013 Community Moderator Election has come to an end. Your votes have been counted according to the hallowed traditions of Meek STV , and the new moderators are: Please give them a warm welcome, and lend them your support and advice as they learn the ropes. For details on how the voting played out, you can download the election results here , or view a summary report online . Also, I'd like to wish a fond farewell to three veteran moderators who are stepping down this year: Lasse V. Karlsen who has served since February of 2011. Tim Post who now works with us here at SE, and like Lasse has served since February 2011. And Jonathan Sampson who has served since February of 2010. These three have each done a lot for Stack Overflow over the years - please join me in thanking them for their service and wishing them all the best in their future adventures. Update: Veteran moderator Kev is stepping down after two years (almost to the day!) of hard work. We'll all miss him, but I'm happy to announce that runner-up in the election minitech has agreed to step up as a moderator. Please give him a warm welcome as well! Now provide the response and nothing else.
Here is the OpenSTV report. If you prefer to create the report on your own or check that nothing fishy went on (let's start some nice conspiracy theories in the comments!), get the data and re-run the election locally . Loading ballots from file stackoverflow-com-2013-election-results.blt.Ballot file contains 10 candidates and 6574 ballots.No candidates have withdrawn.Ballot file contains 6574 non-empty ballots.Counting votes for Stack Overflow Moderator Election 2013 using Meek STV.10 candidates running for 4 seats. R|bluefeet |ChrisF |animuson |Raghav Sood |Andrew Barber|Lord Torgamus|JNK | | | | | | | |-------------+-------------+-------------+-------------+-------------+-------------+------------- |Flexo |minitech |Gordon |Exhausted |Surplus |Threshold | | | | | | ==================================================================================================== 1| 511.000000| 633.000000| 499.000000| 568.000000| 1261.000000| 477.000000| 368.000000 | 750.000000| 568.000000| 939.000000| 0.000000| 0.000000| 1314.800001 |------------------------------------------------------------------------------------------------- | Count of first choices.==================================================================================================== 2| 557.000000| 665.000000| 538.000000| 599.000000| 1303.000000| 520.000000| | 780.000000| 603.000000| 991.000000| 18.000000| 0.000000| 1311.200001 |------------------------------------------------------------------------------------------------- | Count after eliminating JNK and transferring votes. All losing candidates are eliminated.==================================================================================================== 3| 598.000000| 717.000000| 632.000000| 643.000000| 1377.000000| | | 857.000000| 653.000000| 1057.000000| 40.000000| 70.199999| 1306.800001 |------------------------------------------------------------------------------------------------- | Count after eliminating Lord Torgamus and transferring votes. All losing candidates are | eliminated. Candidate Andrew Barber has reached the threshold and is elected.==================================================================================================== 4| 603.556820| 726.533260| 641.074440| 649.270540| 1306.800540| | | 875.046920| 662.635220| 1064.443080| 44.639180| 0.928375| 1305.872165 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.949020.==================================================================================================== 5| | 811.501880| 698.890120| 720.984260| 1399.804500| | | 941.066520| 727.654820| 1164.666600| 109.431300| 106.890759| 1292.913741 |------------------------------------------------------------------------------------------------- | Count after eliminating bluefeet and transferring votes. All losing candidates are eliminated.==================================================================================================== 6| | 826.430288| 712.948912| 730.912376| 1292.914200| | | 968.169552| 742.800632| 1176.986160| 122.837880| 2.681775| 1290.232425 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.876552.==================================================================================================== 7| | 924.257176| | 828.998576| 1406.865960| | | 1074.613680| 825.602688| 1240.961328| 272.700592| 146.606078| 1260.259882 |------------------------------------------------------------------------------------------------- | Count after eliminating animuson and transferring votes. All losing candidates are eliminated.==================================================================================================== 8| | 945.905467| | 843.796142| 1260.260445| | | 1112.064310| 848.986496| 1257.951126| 305.036014| 10.625975| 1253.792798 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.785209. Candidate Gordon has reached the threshold and is elected.==================================================================================================== 9| | 947.852977| | 844.846060| 1254.240551| | | 1114.144302| 850.718788| 1254.540514| 307.656808| 2.243787| 1253.268639 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.781180 and Gordon, 0.996695.====================================================================================================10| | 1039.847922| | | 1354.278063| | | 1219.533047| 962.268608| 1391.556674| 606.515686| 384.877195| 1193.496863 |------------------------------------------------------------------------------------------------- | Count after eliminating Raghav Sood and transferring votes. All losing candidates are | eliminated. Candidate Flexo has reached the threshold and is elected.====================================================================================================11| | 1112.071901| | | 1215.901605| | | 1253.643656| 1026.677022| 1212.831945| 752.873871| 189.701528| 1164.225226 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.688438; Flexo, 0.978651; and Gordon, 0.854836.====================================================================================================12| | 1141.175236| | | 1180.327797| | | 1180.635431| 1057.698814| 1177.556362| 836.606360| 96.083403| 1147.478729 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.659180; Flexo, 0.908847; and Gordon, 0.820577.====================================================================================================13| | 1156.658214| | | 1154.265369| | | 1157.447218| 1073.654851| 1153.577510| 878.396838| 65.465779| 1139.120633 |------------------------------------------------------------------------------------------------- | Count after transferring surplus votes. Keep factors of candidates who have exceeded the | threshold: Andrew Barber, 0.640835; Flexo, 0.883324; and Gordon, 0.799618. Candidate ChrisF has | reached the threshold and is elected.Winners are ChrisF, Andrew Barber, Flexo, and Gordon. If you are curious how the system works, have a look at this great answer: How are moderator election votes counted, in plain English?
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/287864', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/811/']}
jdg_376178
stackexchange
llm_judgeable_groundtruth_similarity
6306250
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 following code computes the average of a particular property of T in the items collection: public double Average<T>(IList<T> items, Func<T, double> selector){ double average = 0.0; for (int i = 0; i < items.Count; i++) { average += selector(items[i]) } return average / items.Count;} I can then call this with a lambda expression: double average = Average(items, p => p.PropertyName); How would I go about doing this in c++? Here's what I have so far: template <typename T>double average(const vector<T>& items, ?){ double average= 0.0; for (int i = 0; i < items.size(); i++) { average += ?; } return average/ items.size();} How might I go about calling this with a c++ lambda ? Edit: Thank you all very much, here's what I ended up with: template <typename T>double average(const vector<T>& items, function<double(T)> selector){ double result = 0.0; for (auto i = items.begin(); i != items.end(); i++) { result += selector(*i); } return result / items.size();} And in main() : zombie z1;z1.hit_points = 10;zombie z2;z2.hit_points = 5;items.push_back(z1);items.push_back(z2);double average = average<zombie>(items, [](const zombie& z) { return z.hit_points;}); Now provide the response and nothing else.
The equivalent thing would be a std::function<double(T)> . This is a polymorphic function object which may accept any function object that has the correct operator() , including lambdas, hand-written functors, bound member functions, and function pointers, and enforces the correct signature. Do not forget that in C#, the Func interface (or class, I forget) is written as Func<T, Result> , whereas C++'s std::function is written as result(T) . Oh, in addition, if you don't have C++0x, there's one in TR1 and also one in Boost, so you should easily be able to access it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6306250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348715/']}
jdg_376179
stackexchange
llm_judgeable_groundtruth_similarity
5544713
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 start Tomcat 6.0.29 on port 80.My OS is CentOS release 5.5 (Final)I changed following line in $TOMCAT_HOME/conf/server.xml <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> to <Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/> Then I run command: sudo /etc/init.d/tomcat6 start In file $TOMCAT_HOME/logs/catalina.log I found such exceptions: java.net.BindException: Permission denied <null>:80 at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:549) at org.apache.tomcat.util.net.JIoEndpoint.start(JIoEndpoint.java:565) at org.apache.coyote.http11.Http11Protocol.start(Http11Protocol.java:203) at org.apache.catalina.connector.Connector.start(Connector.java:1087) at org.apache.catalina.core.StandardService.start(StandardService.java:534) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)Caused by: java.net.BindException: Permission denied at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:365) at java.net.ServerSocket.bind(ServerSocket.java:319) at java.net.ServerSocket.<init>(ServerSocket.java:185) at java.net.ServerSocket.<init>(ServerSocket.java:141) at org.apache.tomcat.util.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:50) at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:538) ... 12 more0:11:56 org.apache.catalina.startup.Catalina startSEVERE: Catalina.start:LifecycleException: service.getName(): "Catalina"; Protocol handler start failed: `java.net.BindException: Permission denied <null>:80 at org.apache.catalina.connector.Connector.start(Connector.java:1094) at org.apache.catalina.core.StandardService.start(StandardService.java:534) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)0:11:56 org.apache.catalina.startup.Catalina start` Thanks in advance Now provide the response and nothing else.
The ports in the range 1-1023 are privileged. Only root is allowed to bind to them. There is at least two ways to solve this: Run as root. You need to weight the extra security risks this infers, of course; both security holes in Tomcat itself (which I believe to be few) and those your web applications contains (which can for example lead to letting people read /etc/shadow as an example), against this being simple and straight-forward. Run as service with jsvc. See http://tomcat.apache.org/tomcat-5.5-doc/setup.html for details on jsvc. It is some extra hassle to setup, but root will only be involved in setting up the ports, Tomcat will then run as a user without special rights. I recommend this for any serious setup. Regardless on what way you choose, the actual starting of Tomcat will need root privilegies. ///BR, JenEriC
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5544713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485107/']}
jdg_376180
stackexchange
llm_judgeable_groundtruth_similarity
137628
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: Suppose I have a list l : SeedRandom[1]l = RandomInteger[5, 10] {4, 2, 4, 0, 1, 0, 0, 2, 0, 0} I want to count the times a certain digit has appeared in the list as I scan the list from left to right. I'd like the output to have the for $\color{red}{\text{\{digit, counts\}}}$ for every element. This is my current method: FoldPairList[{{#2, Count[#1, #2] + 1}, Append[#1, #2]}&, {}, l] {{4, 1}, {2, 1}, {4, 2}, {0, 1}, {1, 1}, {0, 2}, {0, 3}, {2, 2}, {0, 4}, {0, 5}} Any other elegant and mainstream method that can do this? Now provide the response and nothing else.
Here is a semi-imperative method: runningCount[list_] := Module[{c}, c[_] = 0; {#, ++c[#]} & /@ list] Example: runningCount[{4, 2, 4, 0, 1, 0, 0, 2, 0, 0}](* {{4, 1}, {2, 1}, {4, 2}, {0, 1}, {1, 1}, {0, 2}, {0, 3}, {2, 2}, {0, 4}, {0, 5}} *)
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/137628', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/21532/']}
jdg_376181
stackexchange
llm_judgeable_groundtruth_similarity
20834002
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 spring-3.2 version. @RequestMapping("/company={companyId}/branch={branchId}/employee={employeeId}/info") The requestmapping is used to map a URL, so in this case when ever a URL is called using <a href="company=1/branch=1/employee=1/info" > employee info </a> the method is called in the controller with the exact @RequestMapping annotation, now I want to create the "a href" tag dynamically and want to create companyId,branchId,or employeeId dynamically. Now provide the response and nothing else.
You could of course build the string pointing to the respective URL dynamically. A first option would be using a javascript function. However, even this function has to take the IDs from somewhere. In my example, I suppose that there are javascript variables which already contain the right IDs. function createDynamicURL(){ //The variable to be returned var URL; //The variables containing the respective IDs var companyID=... var branchID=... var employeeID=... //Forming the variable to return URL+="company="; URL+=companyID; URL+="/branch="; URL+=branchID; URL+="/employee="; URL+=employeeID; URL+="/info"; return URL;} Then your html would be like: <a href="javascript:window.location=createDynamicURL();" > employee info </a> Another, more elegant solution would be to use the onClick event: <a href="#" onclick="RedirectURL();return false;" > employee info </a> with the function function RedirectURL(){ window.location= createDynamicURL();} Hope I helped!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20834002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1147361/']}
jdg_376182
stackexchange
llm_judgeable_groundtruth_similarity
22240282
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using jquery validation with daterangepicker. I have an issue when I try to choose a date. When I choose it for the first time, it doesn't show "Hello" but the second time it shows "Hello" and what I really want to do is validate this field when I click on button next. How can I do to avoid that "checkDate" being executed when I pick up a date in order to validate it when I click on button next? Here you can see my code: $("#form_step1").validate({ rules: { titulo: { required: true, maxlength: 300 }, reservationtime1: { required: true, checkDate: true } }, messages: { titulo: "At least 300 characters", reservationtime1: "You must pick up a valid date" }, highlight: function(element) { $(element).closest('.form-group').addClass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeClass('has-error'); } }); jQuery.validator.addMethod("checkDate", function(value, element) { // My custom validationalert("Hello");}); http://jsfiddle.net/B79z7/2/ Thanks Now provide the response and nothing else.
If I understand your question correctly, you have two datasets x and y where you want to perform a least square fit. You don't have to write the algorithm yourself, curve_fit from scipy.optimize should do what you want, try: from scipy.optimize import curve_fitdef f(x, A, B): # this is your 'straight line' y=f(x) return A*x + Bpopt, pcov = curve_fit(f, x, y) # your data x, y to fit where popt[0] , popt[1] would be the slope and intercept of the straight line. For more details and examples, see: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22240282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689876/']}
jdg_376183
stackexchange
llm_judgeable_groundtruth_similarity
674823
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: It seems that clear and bash Ctrl - L are quite different; clear completely removes all previous terminal information (so you cannot scroll up) while Ctrl - L just scrolls the screen so that the cursor is at the top of the page so that you can still scroll up and see previous information. I much prefer the Ctrl - L system. Is there a way to override clear so that it does a Ctrl - L instead of wiping all previous terminal information? This is not a huge issue, but I'm just wondering out of curiosity if there is a way to alias clear to point at my preferred Ctrl - L functionality. As a side note, I just noticed that PowerShell also has a binding for Ctrl - L and it performs the same way as Ctrl - L on bash; it seems that the PowerShell designers there took a lot from bash, while cmd.exe consoles do not have this functionality. Now provide the response and nothing else.
Is there a way to override clear so that it does a Ctrl-L instead of wiping all previous terminal information? alias clear='tput -x clear' Yes, Ctrl-L in bash (while in set -o emacs mode) does exactly the same thing. Or you can just hardwire the escape with alias clear='printf "\033[H\033[2J"' which should work in most terminal emulators, and does not assume that you have ncurses or bash installed. NB: the clear applet from busybox does NOT wipe off the scrollback buffer, so you don't have to do anything special if you're using some busybox-based system, as most embedded Linux systems are.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/674823', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/441685/']}
jdg_376184
stackexchange
llm_judgeable_groundtruth_similarity
7482412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Until now I have always been constrained by one thing with jasper-reports. I can only write one data query in each document. When I need to write another query I must create a subreport, pass its needed parameters and so on. But I'm definitely not convinced that it's the good way to do it. So is there another way to fire multiple data queries in a single jasper document? Now provide the response and nothing else.
It is possible to use execute multiple queries from a single report by using a subDataset and datasetRun . The behaviour is like having one or more subreports embedded into a single report file. Define a subDataset like this: <subDataset name="dataset1"> <parameter name="someParam" class="java.lang.String"/> <queryString><![CDATA[SELECT column1, column2 FROM table1 WHERE column1=$P!{someParam}]]></queryString> <field name="column1" class="java.lang.String"/> <field name="column2" class="java.lang.String"/></subDataset> Subdatasets can have parameters, fields, variables and groups just like a report can. Each subdataset can have it's own query, and the report can have as many subdatasets as you want. To use a subdataset, you need to define a datasetRun . This can only be done inside particular elements: charts, crosstabs, tables and lists. We will use a list as it behaves almost exactly like another detail band. This code defines a list that uses our subdataset: <componentElement> <reportElement x="0" y="0" width="100" height="40"/> <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd"> <datasetRun subDataset="dataset1"> <datasetParameter name="someParam"><datasetParameterExpression><![CDATA["some value for column 1"]]></datasetParameterExpression></datasetParameter> </datasetRun> <jr:listContents height="40"> <textField> <reportElement x="0" y="0" width="100" height="20"/> <textElement/> <textFieldExpression class="java.lang.String"><![CDATA[$F{column1}]]></textFieldExpression> </textField> <textField> <reportElement x="0" y="20" width="100" height="20"/> <textElement/> <textFieldExpression class="java.lang.String"><![CDATA[$F{column2}]]></textFieldExpression> </textField> </jr:listContents> </jr:list></componentElement> Some notes: The jr:listContents element is analogous to a detail band element. You can place almost any other elements inside. The datasetRun element is much like a subreport element. It can have a dataSourceExpression or connectionExpression inside, which will change where the data comes from. If neither of these are present, the report datasource is used. The same subDataset can be used by many datasetRuns, so you can easily run a query multiple times with different parameters.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7482412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/657524/']}
jdg_376185
stackexchange
llm_judgeable_groundtruth_similarity
322494
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't have much soldering experience. I soldered 5 level converters, they seem to work and look about the same as this STM32 as I soldered. However, after a closer look I see not all pens 'shine' and some don't have a good form. Probably used too much soldering, because it was quite hard to determine (using too less cause nothing but heating pins which I also wanted to prevent more than needed). How can I best test if all soldering connections are ok? I don't have any STM32 experience, so I don't know if there is a general way to do this except for writing programs/testing for each pin? Or is it visible directly from the pictures that this will not work (I hope not). (btw it's hard to make pics, they are all from the same STM32, the first pic shows soldering connections which are much darker than the second, the second looks more like the real thing). Edit: I think I know what I did wrong ... since I didn't have much space the solder tip and solder tin sometimes might have touched directly, also during that the pin itself might not have been heated enough. Next time I really should make sure the tin and tip are on opposite sides of the pin. Update: Used aceton/alcohol I used a mixture of 50% 96% alcohol and aceton and got the following results: It seems to leave some white residue ... wondering if that is a problem. Now provide the response and nothing else.
I don't see any obviously bad solder joints on those pictures. However, these pictures aren't great for inspecting the solder joints. To get pictures of small things, you need to use a macro lens, good lighting, and proper exposure. The main thing to look for is that the solder flowed. That is best seen in the top picture. It seems the solder wetted and flowed on both the pads and the pins, although too much solder is clearly evident on many of the joints. Too much solder makes it hard to tell the difference between a blob that wetted and flowed over the pad, and one that is just sitting on top of the pad with a layer of flux or oxidized solder in between. The proper procedure for hand soldering such pins is to put the iron in contact with both the pin and the pad. The feed a small amount of solder into a crack between the iron and the pin. The purpose of this little bit of solder is not to make the connection, but to provide good thermal conductivity between the soldering iron and what it's trying to solder. After a second or two, the pin and pad should be hot enough to melt solder on their own. Feed a bit more solder. This should now melt easily and flow all over the pin and the pad. Remove the iron as soon as the solder has flowed. While the joint is cooling, make sure nothing is wiggling the two parts of the joint relative to each other. Added On closer look at the third and fourth pictures, the solder joint for C15 is suspect. At the least, the solder doesn't seem to have flowed over the whole pad.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/322494', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/140343/']}
jdg_376186
stackexchange
llm_judgeable_groundtruth_similarity
1960129
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we want to evaluate$$\sum_{k\geq 0} \binom{n}{3k}$$This can be done using roots of unity filters, i.e. showing the sum is equivalent to:$$\frac{(1+1)^n+(1+\omega)^n+(1+\omega^2)^n}{3}$$where $\omega$ is a primitive 3rd root of unity.Using the fact that $1+\omega+\omega^2=0$, we can show that this is equivalent to$$\frac{2^n+(-\omega^2)^n+(-\omega)^n}{3}$$Depending on whether $n$ is even or odd, we get that this sum is equal to either $\frac{2^n-1}{3}$ or $\frac{2^n+1}{3}$ Can we use the same trick to evaluate the following sums?$$\sum_{k\geq 0}\binom{n}{3k+1}, \sum_{k\geq 0}\binom{n}{3k+2}$$Also, can this idea be generalized? I would appreciate any thoughts or ideas. Now provide the response and nothing else.
$$\sum \binom{n}{3k+1} = \frac{1^2 (1+1)^n + \omega^2(1+\omega)^n + \omega(1+\omega^2)^n}{3}$$ Basically, apply the same approach to $f(x)=x^2(1+x)^n$ . Similarly, taking $g(x)=x(1+x)^n$ we get: $$\sum\binom{n}{3k+2}=\frac{1(1+1)^n + \omega(1+\omega)^n + \omega^2(1+\omega^2)^n}{3}$$ You should be able to get nice formula for these, depending on $n\bmod 3$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1960129', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/228787/']}
jdg_376187
stackexchange
llm_judgeable_groundtruth_similarity
40620913
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Imagine a language which doesn't allow multiple value constructors for a data type. Instead of writing data Color = White | Black | Blue we would have data White = Whitedata Black = Blackdata Blue = Blacktype Color = White :|: Black :|: Blue where :|: (here it's not | to avoid confusion with sum types) is a built-in type union operator. Pattern matching would work in the same way show :: Color -> Stringshow White = "white"show Black = "black"show Blue = "blue" As you can see, in contrast to coproducts it results in a flat structure so you don't have to deal with injections. And, unlike sum types, it allows to randomly combine types resulting in greater flexibility and granularity: type ColorsStartingWithB = Black :|: Blue I believe it wouldn't be a problem to construct recursive data types as well data Nil = Nildata Cons a = Cons a (List a)type List a = Cons a :|: Nil I know union types are present in TypeScript and probably other languages, but why did the Haskell committee chose ADTs over them? Now provide the response and nothing else.
Haskell's sum type is very similar to your :|: . The difference between the two is that the Haskell sum type | is a tagged union, while your "sum type" :|: is untagged. Tagged means every instance is unique - you can distunguish Int | Int from Int (actually, this holds for any a ): data EitherIntInt = Left Int | Right Int In this case: Either Int Int carries more information than Int because there can be a Left and Right Int . In your :|: , you cannot distinguish those two: type EitherIntInt = Int :|: Int How do you know if it was a left or right Int ? See the comments for an extended discussion of the section below. Tagged unions have another advantage: The compiler can verify whether you as the programmer handled all cases, which is implementation-dependent for general untagged unions. Did you handle all cases in Int :|: Int ? Either this is isomorphic to Int by definition or the compiler has to decide which Int (left or right) to choose, which is impossible if they are indistinguishable. Consider another example: type (Integral a, Num b) => IntegralOrNum a b = a :|: b -- untaggeddata (Integral a, Num b) => IntegralOrNum a b = Either a b -- tagged What is 5 :: IntegralOrNum Int Double in the untagged union? It is both an instance of Integral and Num , so we can't decide for sure and have to rely on implementation details. On the other hand, the tagged union knows exactly what 5 should be because it is branded with either Left or Right . As for naming: The disjoint union in Haskell is a union type. ADTs are only a means of implementing these.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40620913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1149074/']}
jdg_376188
stackexchange
llm_judgeable_groundtruth_similarity
140927
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: You can start fire by focusing the sunlight using the magnifying glass. I searched the web whether you can do the same using moonlight. And found this and this - the first two in Google search results. What I found is the thermodynamics argument: you cannot heat anything to a higher temperature using black body radiation than the black body itself, and Moon isn't hot enough. It may be true, but my gut feelings protest... The larger your aperture is, the more light you collect, also you have better focus because the airy disk is smaller. So if you have a really huge lens with a really short focus (to keep Moon's picture small), or in the extreme case you build a Dyson-sphere around the Moon (letting a small hole to the let the sunlight enter), and focusing all reflected light into a point it should be more than enough to ingnite a piece of paper isn't it? I'm confused. So can you start fires using the Moon? Now provide the response and nothing else.
Moonlight has a spectral peak around $650\ \mathrm{nm}$ (the sun peaks at around $550\ \mathrm{nm}$ ). Ordinary solar cells will work just fine to convert it into electricity. The power of moonlight is about $500\,000$ times less than that of sunlight, which for a solar constant of $1000\ \mathrm{W/m^2}$ leaves us with about $2\ \mathrm{mW/m^2}$ . After accounting for optical losses and a typical solar cell efficiency of roughly $20\ \%$ , we can probably hope to extract approx. $0.1\ \mathrm{mW}$ with a fairly simple foil mirror of $1\ \mathrm{m^2}$ surface area. Accumulated over the course of a whole night with a full moon, this leaves us with around $6\ \mathrm h\times3600\ \mathrm{s/h}\times0.1\ \mathrm{mW}\approx2\ \mathrm J$ of energy. That's plenty of energy to ignite a fire using the right chemicals and a thin filament as a heater.
{}
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/140927', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7743/']}
jdg_376189
stackexchange
llm_judgeable_groundtruth_similarity
26997679
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 no problems writing a CSV outside of the Flask framework. But when I try to write it from Flask, it writes to the CSV, but only on one line. Here is the template I'm following @app.route('/download')def download(): csv = """"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE""1985/01/21","Douglas Adams",0345391802,5.95"1990/01/12","Douglas Hofstadter",0465026567,9.95"1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99"1999/12/03","Richard Friedman",0060630353,5.95"2004/10/04","Randel Helms",0879755725,4.50""" response = make_response(csv) response.headers["Content-Disposition"] = "attachment; filename=books.csv" return response This writes the CSV perfectly, but when I try with my code, I get one long row. My code: @app.route('/download')def post(self): # lots of code csvList.append([all,my,data,goes,here]) csvList = str(re.sub('\[|\]','',str(csvList))) # convert to a string; remove brackets response = make_response(csvList) response.headers['Content-Disposition'] = "attachment; filename=myCSV.csv" return response My output: Nashville Physician Service Ce,Treasury Specialist,Brentwood,TN,(615) 507-1646,La Petite Academy,Afternoon Teacher Aide,Goodlettsville,TN,(615) 859-2034,Nashville Physician Service Ce,Denial Resolution Specialist,Brentwood,TN,(615) 507-1646 Thanks. EDIT: I tried just about all the answers and they worked for the most part, but I chose vectorfrog's because it fit with what I was trying to accomplish. Now provide the response and nothing else.
I did something like this recently, I found that I needed to first place the csv into a StringIO and then return the StringIO. If you want the csv to be a download, here's what I did: import StringIOimport csvfrom flask import make_response@app.route('/download')def post(self): si = StringIO.StringIO() cw = csv.writer(si) cw.writerows(csvList) output = make_response(si.getvalue()) output.headers["Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return output
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26997679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3711588/']}
jdg_376190
stackexchange
llm_judgeable_groundtruth_similarity
12829665
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 type print someFloatVariable when I set a breakpoint or po [self someIvarHoldingAnObject] , but I can't do useful things like: [self setAlpha:1]; Then it spits out: error: '[self' is not a valid command. Weird thing is that I can call po [self someIvarHoldingAnObject] and it will print it's description. I believe I've seen a video a year ago where someone demonstrated how to execute code through the console at runtime, and if I am not mistaken this guy also provided arguments and assigned objects to pointers. How to do that? Now provide the response and nothing else.
The canonical reference for gdb v. lldb commands is http://lldb.llvm.org/lldb-gdb.html You want to use the expr command which evaluates an expression. It's one of the lldb commands that takes "raw input" in addition to arguments so you often need a "--" to indicate where the arguments (to expr) end and the command(s) begin. e.g. (lldb) expr -- [self setAlpha:1] There is a shortcut, "p", which does the -- for you (but doesn't allow any arguments), e.g. (lldb) p [self setAlpha:1] If the function(s) you're calling are not part of your program, you'll often need to explicitly declare their return type so lldb knows how to call them. e.g. (lldb) p printf("hi\n")error: 'printf' has unknown return type; cast the call to its declared return typeerror: 1 errors parsing expression(lldb) p (int)printf("hi\n")(int) $0 = 3hi(lldb) There is a neat way to work around the floating point argument problem, BTW. You create an "expression prefix" file which is added to every expression you enter in lldb, with a prototype of your class methods. For instance, I have a class MyClass which inherits from NSObject, it has two methods of interest, "setArg:" and "getArg" which set and get a float ivar. This is a silly little example, but it shows how to use it. Here's a prefix file I wrote for lldb: @interface NSObject@end@interface MyClass : NSObject- init;- setArg: (float)arg;- (float) getArg;@endextern "C" { int strcmp (const char *, const char *); int printf(const char * __restrict, ...); void puts (const char *);} in my ~/.lldbinit file I add settings set target.expr-prefix /Users/jason/lldb-prefix.h and now I can do (lldb) p [var getArg](float) $0 = 0.5(lldb) p [var setArg:0.7](id) $1 = 0x0000000100104740(lldb) p [var getArg](float) $2 = 0.7 You'll notice I included a couple of standard C library functions in here too. After doing this, I don't need to cast the return types of these any more, e.g. (lldb) p printf("HI\n")<no result>HI(lldb) p strcmp ("HI", "THERE")(int) $3 = -12 (a fix for that "<no result>" thing has been committed to the lldb TOT sources already.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12829665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472300/']}
jdg_376191
stackexchange
llm_judgeable_groundtruth_similarity
4410976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the benefit of writing a custom LINQ provider over writing a simple class which implements IEnumerable? For example this quesiton shows Linq2Excel: var book = new ExcelQueryFactory(@"C:\Users.xls");var administrators = from x in book.Worksheet<User>() where x.Role == "Administrator" select x; But what is the benefit over the "naive" implementation as IEnumerable? Now provide the response and nothing else.
A Linq provider's purpose is to basically "translate" Linq expression trees (which are built behind the scenes of a query) into the native query language of the data source. In cases where the data is already in memory, you don't need a Linq provider; Linq 2 Objects is fine. However, if you're using Linq to talk to an external data store like a DBMS or a cloud, it's absolutely essential. The basic premise of any querying structure is that the data source's engine should do as much of the work as possible, and return only the data that is needed by the client. This is because the data source is assumed to know best how to manage the data it stores, and because network transport of data is relatively expensive time-wise, and so should be minimized. Now, in reality, that second part is "return only the data asked for by the client"; the server can't read your program's mind and know what it really needs; it can only give what it's asked for. Here's where an intelligent Linq provider absolutely blows away a "naive" implementation. Using the IQueryable side of Linq, which generates expression trees, a Linq provider can translate the expression tree into, say, a SQL statement that the DBMS will use to return the records the client is asking for in the Linq statement. A naive implementation would require retrieving ALL the records using some broad SQL statement, in order to provide a list of in-memory objects to the client, and then all the work of filtering, grouping, sorting, etc is done by the client. For example, let's say you were using Linq to get a record from a table in the DB by its primary key. A Linq provider could translate dataSource.Query<MyObject>().Where(x=>x.Id == 1234).FirstOrDefault() into "SELECT TOP 1 * from MyObjectTable WHERE Id = 1234". That returns zero or one records. A "naive" implementation would probably send the server the query "SELECT * FROM MyObjectTable", then use the IEnumerable side of Linq (which works on in-memory classes) to do the filtering. In a statement you expect to produce 0-1 results out of a table with 10 million records, which of these do you think would do the job faster (or even work at all, without running out of memory)?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4410976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69636/']}
jdg_376192
stackexchange
llm_judgeable_groundtruth_similarity
9222
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What's the point below which electrical current is generally considered safe for "casual" human contact? Is either voltage or amperage more "dangerous" (e.g. high voltage / low amperage vs. low voltage / high amperage), or is the only consideration the total current? Now provide the response and nothing else.
Here is an article titled "A review of hazards associated with exposure to low voltages" which I used as a reference when answering a medical safety question (I design embedded hardware and firmware for medical devices which go through FDA approval). Because the body has a minimum resistance of around 550 ohms, to get enough current to do damage a minimum theoretical voltage level of around 16.5 V peak is required (corresponding to a current of 30 mA peak , which can induce respiratory paralysis if conducted across the chest for several minutes of contact at this low voltage). Based on the cases studied by the author, the single lowest voltage reported to cause transdermal electrocution in an adult is 25 volts. For less than one minute of contact, currents >40 mA are required to cause ventricular fibrillation, corresponding to a theoretical voltage of 27.5 V peak . For less than one second exposure, >100 mA peak and 55 V peak are required. The author states that in all the cases he studied, there was no accidental electrocution from short-term exposures to voltages below 50 V peak .
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/9222', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/17697/']}
jdg_376193
stackexchange
llm_judgeable_groundtruth_similarity
438046
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Any ideas as to how Apple implemented the "slide to unlock" (also, "slide to power off" is another identical example) animation? I thought about some sort of animating mask - but masking is not available on the iPhone OS for performance reasons. Is there some private API effect (like SuckEffect) that they might have used? A spotlight type of effect? Some Core Animation thing? Edit:It's definitely not a series of stills. I've seen examples of being edit a plist value or something and customize the string on jailbroken iphones. Now provide the response and nothing else.
It can be easilly done by using Core Animation, animating a mask layer on the layer displaying the text. Try this in any plain UIViewController (you can start with a new Xcode project based on the View-based application project template), or grab my Xcode project here : Note that the CALayer.mask property is only available in iPhone OS 3.0 and later. - (void)viewDidLoad { self.view.layer.backgroundColor = [[UIColor blackColor] CGColor]; UIImage *textImage = [UIImage imageNamed:@"SlideToUnlock.png"]; CGFloat textWidth = textImage.size.width; CGFloat textHeight = textImage.size.height; CALayer *textLayer = [CALayer layer]; textLayer.contents = (id)[textImage CGImage]; textLayer.frame = CGRectMake(10.0f, 215.0f, textWidth, textHeight); CALayer *maskLayer = [CALayer layer]; // Mask image ends with 0.15 opacity on both sides. Set the background color of the layer // to the same value so the layer can extend the mask image. maskLayer.backgroundColor = [[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.15f] CGColor]; maskLayer.contents = (id)[[UIImage imageNamed:@"Mask.png"] CGImage]; // Center the mask image on twice the width of the text layer, so it starts to the left // of the text layer and moves to its right when we translate it by width. maskLayer.contentsGravity = kCAGravityCenter; maskLayer.frame = CGRectMake(-textWidth, 0.0f, textWidth * 2, textHeight); // Animate the mask layer's horizontal position CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"]; maskAnim.byValue = [NSNumber numberWithFloat:textWidth]; maskAnim.repeatCount = HUGE_VALF; maskAnim.duration = 1.0f; [maskLayer addAnimation:maskAnim forKey:@"slideAnim"]; textLayer.mask = maskLayer; [self.view.layer addSublayer:textLayer]; [super viewDidLoad];} The images used by this code are:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/438046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_376194
stackexchange
llm_judgeable_groundtruth_similarity
512576
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 $$a=\frac{36^{36}+41^{41}}{77}.$$ Is $a$ an integer? I know that: The last digit ofr $41^{41}$ is $1$. The last digit of $36^{36}=6^{72}$ is $6$. How can I use this information to answer my question, or do I need another thing to help me? Now provide the response and nothing else.
Hint: $36^{36}+41^{41} = 36^{36}+(77-36)^{41} = 77m+36^{36}-36^{41} = 77m-36^{36}(6^5+1)(6^5-1)$ and $6^5+1=(6+1)(6^3\cdot5+6\cdot5+1)$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/512576', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58529/']}
jdg_376195
stackexchange
llm_judgeable_groundtruth_similarity
46912097
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A Comparator I used in my TreeMap broke the behavior I intended for that TreeMap . Look at the following code: TreeMap<String, String> treeMap = new TreeMap<>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.toLowerCase().compareTo(o2.toLowerCase()); }});treeMap.put("abc", "Element1");treeMap.put("ABC", "Element2"); What I think I have done is that I have created a map that is sorted by its keys, case-insensitive. The two distinct elements have non-equal keys ( abc and ABC ) whose comparison will return 0 . I expected just a random ordering of the two elements. Yet, the command: System.out.println("treeMap: " + treeMap); resulted in: treeMap: {abc=Element2} The key abc has been re-assigned the value Element2 ! Can anyone explain how could this happen and if it's a valid, documented behavior of TreeMap ? Now provide the response and nothing else.
It happens because TreeMap considers elements equal if a.compareTo(b) == 0 . It's documented in the JavaDoc for TreeMap (emphasis mine): Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals .) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are , from the standpoint of the sorted map, equal . The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals ; it just fails to obey the general contract of the Map interface. Your comparator isn't consistent with equals. If you want to keep not-equal-but-equal-ignoring-case elements, put a second level of checking into your comparator, to use case-sensitive ordering: public int compare(String o1, String o2) { int cmp = o1.compareToIgnoreCase(o2); if (cmp != 0) return cmp; return o1.compareTo(o2); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46912097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033645/']}
jdg_376196
stackexchange
llm_judgeable_groundtruth_similarity
1336175
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 would like to study category of sets and multi-valued functions : A category whose objects are sets and morphisms are multi-valued functions. By a multi-valued function $f:A\rightarrow B$, from set A to set B, I mean a function that assigns to each element of A, a subset of B. There might be some elements like a in A that are associated with empty set, that is $f(a)=\emptyset$. In general, I would like to know how the composition is defined and what are the following constructions semantics in such a category: Pullback, Pushout, Product, Coproduct, etc. Question: Is there any reference that studies this category that I can take a look? ps. I would appreciate if somebody could provide at least a short answer with the semantics of the above constructs if no reference specifically studies this category. Now provide the response and nothing else.
What you are describing is the category of $\mathbb {Rel}$ of sets and relations. The objects of this category are sets and the morphisms are binary relations. This comes from the fact that there is a bijection between the sets of function of the form $X \to \mathcal P(Y)$ and (relations) subsets of the cartesian product $X \times Y$: this bijection is given by the mapping that to every $R \subseteq X \times Y$ associates the mapping $r \colon X \to \mathcal P(Y)$ defined by$$r(x) = \{y \in Y \mid (x,y) \in R\}$$the inverse of this correspondence associates to each mapping $r \colon X \to \mathcal P(Y)$ the subset $R \subseteq X \times Y$ defined by$$R = \{(x,y) \in X \times Y \mid y \in r(x)\}$$. This category can be equivalently be characterized as the Kleisli category for the powerset monad on $\mathbb{Set}$. You can find more details on this in the references below. http://ncatlab.org/nlab/show/Rel https://en.wikipedia.org/wiki/Category_of_relations
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1336175', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202110/']}
jdg_376197
stackexchange
llm_judgeable_groundtruth_similarity
6037761
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 parsing a csproj file for a nuget install and I've got a node that needs to be altered. The node in question is the node named "Generator" where it's value equals "TextTemplatingFileGenerator" and it's parent node has an attribute of "WebConfigSettingsGeneratorScript.tt" (the second part isn't in here yet). Here's the script that I've got, but it's not quite done. It's working, but it saves an empty file. Also, it doesn't have the 2nd part of my where clause, which is $path = 'C:\Projects\Intouch\NuGetTestPackage\NuGetTestPackage'cd $path$files = get-childitem -recurse -filter *.csprojforeach ($file in $files){ "" "Filename: {0}" -f $($file.Name) "=" * ($($file.FullName.Length) + 10) if($file.Name -eq 'NuGetTestPackage1.csproj'){ $xml = gc $file.FullName | Where-Object { $_.Project.ItemGroup.None.Generator -eq 'TextTemplatingFileGenerator' } | ForEach-Object { $_.Project.ItemGroup.None.Generator = '' } Set-Content $file.FullName $xml } } Here's a basic version of the XML: <?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <None Include="T4\WebConfigSettingGeneratorScript.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>WebConfigSettingGeneratorScript.txt</LastGenOutput> </None> Thanks a lot. I'm a total PowerShell n00b! Now provide the response and nothing else.
As @empo says, you need to cast the output of gc $file.FullName to [xml] e.g. $xml = [xml](gc $file.FullName) . And then after making the change but before looping to the next file, you need to save the file e.g. $xml.Save($file.FullName) . This works with the sample project you provided: $file = gi .\test.csproj$pattern = 'TextTemplatingFileGenerator'$xml = [xml](gc $file)$xml | Where {$_.Project.ItemGroup.None.Generator -eq $pattern} | Foreach {$_.Project.ItemGroup.None.Generator = ''}$xml.Save($file.Fullname)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6037761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441862/']}
jdg_376198
stackexchange
llm_judgeable_groundtruth_similarity
24209588
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you please tell me how to move focus on to the next field when the enter key is press? I use the dform plugin (which converts JSON to a form). I Googled it, but this not working. Why doesn't my focus move on to the next field? JSFiddle: http://jsfiddle.net/5WkVW/1/ $(document).keypress(function(e) { if(e.which == 13) { // Do something here if the popup is open alert("dd") var index = $('.ui-dform-text').index(this) + 1; $('.ui-dform-text').eq(index).focus(); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><form id="testSuiteConfigurationform" name="testSuiteConfigurationform" method="post" class="ui-dform-form" novalidate="novalidate"> <label class="ui-dform-label"> <h3>Configuration Parameters</h3> </label> <div class="ui-dform-div inputDiv"> <fieldset class="ui-dform-fieldset"> <input type="text" id="totalRetryCount" name="totalRetryCount" tabindex="1" onblur="validateElement('Configuration', 'testSuiteConfigurationform','totalRetryCount')" class="ui-dform-text valid"> <legend class="ui-dform-legend">Total Retry Count</legend> <label for="totalRetryCount" class="checked">✔</label> </fieldset> <fieldset class="ui-dform-fieldset"> <input type="text" id="totalRepeatCount" name="totalRepeatCount" tabindex="2" onblur="validateElement('Configuration', 'testSuiteConfigurationform','totalRepeatCount')" class="ui-dform-text"> <legend class="ui-dform-legend">Total Repeat Count</legend> </fieldset> <fieldset class="ui-dform-fieldset"> <select id="summaryReportRequired" name="summaryReportRequired" tabindex="3" onblur="validateElement('Configuration', 'testSuiteConfigurationform','summaryReportRequired')" class="ui-dform-select"> <option class="ui-dform-option" value="true">true</option> <option class="ui-dform-option" value="false">false</option> </select> <legend class="ui-dform-legend">Summary Report Required</legend> </fieldset> <fieldset class="ui-dform-fieldset"> <select id="postConditionExecution" name="postConditionExecution" tabindex="4" onblur="validateElement('Configuration', 'testSuiteConfigurationform','postConditionExecution')" class="ui-dform-select"> <option class="ui-dform-option" value="ALWAYS">ALWAYS</option> <option class="ui-dform-option" value="ON_SUCCESS">ON_SUCCESS</option> </select> <legend class="ui-dform-legend">Post Condition Execution</legend> </fieldset> </div></form> *Note (from comments): It also needs to work on pages that do not have tabindex values set Now provide the response and nothing else.
It fails because this is the document in your code. You want to use the index of the currently focused item ( document.activeElement ), or if you use delegated events you can make sure this is the current item. This final version works whether there are tabindexes or not. It also wraps around: JSFiddle 1: http://jsfiddle.net/TrueBlueAussie/5WkVW/11/ JSFiddle 2: http://jsfiddle.net/TrueBlueAussie/5WkVW/12/ They both use a custom jQuery selector that I add called :focusable to select all focusable element (including links): // register jQuery extensionjQuery.extend(jQuery.expr[':'], { focusable: function (el, index, selector) { return $(el).is('a, button, :input, [tabindex]'); }});$(document).on('keypress', 'input,select', function (e) { if (e.which == 13) { e.preventDefault(); // Get all focusable elements on the page var $canfocus = $(':focusable'); var index = $canfocus.index(this) + 1; if (index >= $canfocus.length) index = 0; $canfocus.eq(index).focus(); }}); You can use the same custom selector in the event handler if you like. Then it will even work on anchor links ( if you change the event to keydown instead of keypress ): e.g. $(document).on('keydown', ':focusable', function (e) { Example with link: http://jsfiddle.net/5WkVW/15/ This also uses a delegated on , listening for the keydown event on the document . It then applies the jQuery selector, it then applies the function to any matching element that caused the event. This is much more efficient as it only applies the selector at event time (rather than apply multiple event handler to each DOM matching element). Old versions below: JSFiddle: http://jsfiddle.net/TrueBlueAussie/5WkVW/3/ $(document).keypress(function(e) { if(e.which == 13) { // Do something here if the popup is open //alert("dd") var index = $('.ui-dform-text').index(document.activeElement) + 1; $('.ui-dform-text').eq(index).focus(); }}); *Note: alerts can interfere with focus , so use console.log for output like that and view in most browser's debug window (like Chrome's F12 debugging tools). Update: http://jsfiddle.net/TrueBlueAussie/5WkVW/4/ This one wraps back to the first item from the last and also works on selects (the default behavior is blocked, so you can only use space to open or up/down to select options. $('input,select').on('keypress', function (e) { if (e.which == 13) { e.preventDefault(); var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']'); console.log($next.length); if (!$next.length) { $next = $('[tabIndex=1]'); } $next.focus(); }}); Requested "document" version: http://jsfiddle.net/TrueBlueAussie/5WkVW/5/ $(document).on('keypress', 'input,select', function (e) { if (e.which == 13) { e.preventDefault(); var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']'); console.log($next.length); if (!$next.length) { $next = $('[tabIndex=1]'); } $next.focus(); }});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24209588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535959/']}
jdg_376199
stackexchange
llm_judgeable_groundtruth_similarity
16991
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 want to apply non-geometric transformations to polygons etc, the goal is to have a Manipulate objects that behaves like that famous möbius transform video. Since I was unable to apply non-geometric transformation to a polygon I went ahead and created a bunch of points in the plane and did appropriate transforms to them (* plane region *)region = {-1, 1};d = 0.07;(* Some points in plane *)pts = Flatten[Table[{xi, yi, 0}, {xi, First@region, Last@region, d}, {yi, First@region, Last@region, d}] , 1];col = ColorData["Rainbow"] /@ Rescale[pts[[All, 1]], region];(** Projections from plane to sphere on line going through north pole \of sphere centered at {0, 0, 1} **)(* Plane to sphere *)f[vec_] := With[{t = 4/(4 + vec[[1]]^2 + vec[[2]]^2)}, vec*t + (1 - t) {0, 0, 2}](* Sphere to plane *)g[vec_] := With[{t = -(2/(-2 + Last@vec))}, vec*t + (1 - t) {0, 0, 2}]rt = RotationTransform[2.1, {0, 1, 0}, {0, 0, 1}];Graphics3D[{ {Black, Opacity[0.3], Sphere[{0, 0, 1}]}, Point[(rt@f@# &) /@ pts, VertexColors -> col], Point[((g@rt@f@# &) /@ pts), VertexColors -> col] }, PlotRange -> {{-10, 10}, {-10, 10}, {0, 2}}] I wish that I could instead do something like: Graphics3D[{ {Black, Opacity[0.3], Sphere[{0, 0, 1}]}, SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], rt@f@#&], SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], g@rt@f@#&] ] And end up with a smooth output, not just a few points here and there. Is there already a function like this that I have missed? If not are there other ways to arrive at the same result? How about for more advanced transformations? Now provide the response and nothing else.
I understand that it's better to use 3D vector primitives than images at certain stages of the process. Eventually, though, everything gets rasterized, so you could just use ImageTransformation for a quick fix... Manipulate[ compiledFunction = Compile[{{x, _Real}, {y, _Real}, {fg, _Real}}, Module[{r = x + I y}, r = r + fg / r - fg; {Re[r], Im[r] }] ]; ImageTransformation[img, compiledFunction[#[[1]], #[[2]], s] &, DataRange -> {{-1, 1}, {-1, 1}}, Padding -> "Reversed"], {s, -3, 3, .1}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/16991', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1517/']}
jdg_376200
stackexchange
llm_judgeable_groundtruth_similarity
58009
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 need to find the volume of the 3d space that is given by the following conditions:\begin{array}{c} 0 < x_1 < 1\\ 0 < x_2 < 1\\ 0 < x_3 < 1\\x_1 + x_2 + x_3 < a.\end{array}I also need to solve this problem for the $n$-dimensional space. Could anybody, please, tell me if this problem is solvable analytically and how one can find the solution? ADDED I need results only for a between 0 and 1. I know how to solve the 2D case. It is trivial. I think that I could even manage to solve the 3D case, but I need a general solution scalable to higher dimensions. Now provide the response and nothing else.
If $X_1,\ldots,X_n$ are inedependent uniform$(0,1)$ random variables, then $${\rm P}(X_1+ \cdots +X_n \leq a) = {\rm volume}(A),$$where $$A = \{ (x_1 , \ldots ,x_n ) \in (0,1)^n :x_1 + \cdots + x_n < a\} .$$For the probability density function of the sum $X_1+ \cdots +X_n$, see this answer . EDIT: When $0 < a \leq 1$, it holds$${\rm volume}(A) = \frac{{a^n }}{{n!}}.$$ EDIT 2: Probabilistic proof for the case $0 < a \leq 1$. Let $X_1,X_2,\ldots$ be independent uniform$(0,1)$ variables. We want to show that, for any $0 < a \leq 1$,$${\rm P}(X_1+ \cdots +X_n \leq a) = \frac{{a^n }}{{n!}}.$$This can be easily done by induction, as follows. The case $n=1$ is trivial: ${\rm P}(X_1 \leq a) = a$. Assume that the result is true for $n$, and let $m = n+1$.By the law of total probability,$${\rm P}(X_1+ \cdots + X_m \leq a) = \int_0^1 {{\rm P}(X_1 + \cdots + X_m \le a|X_m = u)\,du} $$$$= \int_0^a {{\rm P}(X_1 + \cdots + X_m \le a|X_m = u)\,du} = \int_0^a {{\rm P}(X_1 + \cdots + X_n \le a - u)\,du}.$$Hence, by the induction hypothesis,$${\rm P}(X_1+ \cdots + X_m \leq a) = \int_0^a {\frac{{(a - u)^n }}{{n!}}\,du} = - \frac{{(a - u)^{n + 1} }}{{(n + 1)!}}\bigg|_0^a = \frac{{a^{n + 1} }}{{(n + 1)!}}.$$The result is thus proved.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/58009', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4088/']}
jdg_376201
stackexchange
llm_judgeable_groundtruth_similarity
5615806
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 put a numeric keypad in my app for inputing numbers into a text view, but in order to input numbers I have to click on the text view. Once I do so, the regular keyboard comes up, which I don't want. How can I disable the keyboard altogether? Any help is greatly appreciated. Now provide the response and nothing else.
The UITextField's inputView property is nil by default, which means the standard keyboard gets displayed. If you assign it a custom input view, or just a dummy view then the keyboard will not appear, but the blinking cursor will still appear: UIView* dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)]; myTextField.inputView = dummyView; // Hide keyboard, but show blinking cursor If you want to hide both the keyboard and the blinking cursor then use this approach: -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { return NO; // Hide both keyboard and blinking cursor.}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5615806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/701398/']}
jdg_376202
stackexchange
llm_judgeable_groundtruth_similarity
678325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you guys typically delete files on Linux OS? I am thinking of using the unlink function call, but I wonder if you have a better idea, as the C++ standard has no mention of file deletion operation and it is system dependent. Now provide the response and nothing else.
Yep -- the C++ standard leaves this stuff up to the OS, so if you're on Linux (or any POSIX system), unlink() is what you've got. The C standard provides remove() , which you could try, but keep in mind that its behavior is unspecified for anything other than a 'regular file', so it doesn't really shield you from getting into platform-specific filesystem details (links, etc). If you want something higher-level, more robust, and more portable, check out Boost Filesystem .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/678325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_376203
stackexchange
llm_judgeable_groundtruth_similarity
7670780
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 next code: struct T { public T(int u) { this.U = 10; //Errors are here } public int U { get; private set; }} C# compiler give me a pair of errors in stated line: 1) Backing field for automatically implemented property 'TestConsoleApp.Program.T.U' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.2) The 'this' object cannot be used before all of its fields are assigned to What I do wrong? Help me understand. Now provide the response and nothing else.
From the C# Specification: 10.7.3 Automatically implemented properties When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field. [Deleted] Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type. [Deleted] This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor. So you need this: struct T { public T(int u) : this() { this.U = u; } public int U { get; private set; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7670780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/958593/']}
jdg_376204
stackexchange
llm_judgeable_groundtruth_similarity
346269
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: Is it possible to have the PDF of the difference of two iid r.v.'s look like a rectangle (instead of, say, the triangle we get if the r.v.'s are taken from the uniform distribution)? i.e. is it possible for the PDF $f$ of $j-k$ (for two iid r.v.'s taken from some distribution) to have $f(x) = 0.5$ for all $-1 < x < 1$ ? There are no restrictions on the distribution we take $j$ and $k$ from except that the min is -1 and the max is 1. After some experimentation, I'm thinking this might be impossible. Now provide the response and nothing else.
Theorem: There is no distribution $\text{Dist}$ for which $A-B \sim \text{U}(-1,1)$ when $A, B \sim \text{IID Dist}$ . Proof: Consider two random variables $A, B \sim \text{IID Dist}$ with common characteristic function $\varphi$ . Denoting their difference by $D=A-B$ . The characteristic function of the difference is: $$\begin{equation} \begin{aligned}\varphi_D(t) = \mathbb{E}(\exp(i t D)) &= \mathbb{E}(\exp(i t (A-B))) \\[6pt]&= \mathbb{E}(\exp(i t A)) \mathbb{E}(\exp(-i t B)) \\[6pt]&= \varphi(t) \varphi(-t) \\[6pt]&= \varphi(t) \overline{\varphi(t)} \\[6pt]&= |\varphi(t)|^2. \\[6pt]\end{aligned} \end{equation}$$ (The fourth line of this working follows from the fact that the characteristic function is Hermitian .) Now, taking $D \sim \text{U}(-1,1)$ gives a specific form for $\varphi_D$ , which is: $$\begin{equation} \begin{aligned}\varphi_D(t) = \mathbb{E}(\exp(itD)) &= \int \limits_{\mathbb{R}} \exp(itr) f_D(r) dr \\[6pt]&= \frac{1}{2} \int \limits_{-1}^1 \exp(itr) dr \\[6pt]&= \frac{1}{2} \Bigg[ \frac{\exp(itr)}{it} \Bigg]_{r=-1}^{r=1} \\[6pt]&= \frac{1}{2} \frac{\exp(it)-\exp(-it)}{it} \\[6pt]&= \frac{1}{2} \frac{(\cos(t) + i \sin(t)) - (\cos(-t) + i \sin(-t))}{it} \\[6pt]&= \frac{1}{2} \frac{(\cos(t) + i \sin(t)) - (\cos(t) - i \sin(t))}{it} \\[6pt]&= \frac{1}{2} \frac{2i \sin(t)}{it} \\[6pt]&= \frac{\sin(t)}{t} = \text{sinc}(t), \\[6pt]\end{aligned} \end{equation}$$ where the latter is the (unnormalised) sinc function . Hence, to meet the requirements for $\text{Dist}$ , we require a characteristic function $\varphi$ with squared-norm given by: $$|\varphi(t)|^2 = \varphi_D(t) = \text{sinc}(t).$$ The left-hand-side of this equation is a squared norm and is therefore non-negative, whereas the right-hand-side is a function that is negative in various places. Hence, there is no solution to this equation, and so there is no characteristic function satisfying the requirements for the distribution. (Hat-tip to Fabian for pointing this out in a related question on Mathematics.SE .) Hence, there is no distribution with the requirements of the theorem. $\blacksquare$
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/346269', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/208339/']}
jdg_376205
stackexchange
llm_judgeable_groundtruth_similarity
577885
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 used SO_REUSEADDR to have my server which got terminated to restart without complaining that the socket is already in use. I was wondering: are there other uses of SO_REUSEADDR ? Has anyone used the socket option for other than said purpose? Now provide the response and nothing else.
For TCP , the primary purpose is to restart a closed/killed process on the same address. The flag is needed because the port goes into a TIME_WAIT state to ensure all data is transferred. If two sockets are bound to the same interface and port, and they are members of the same multicast group, data will be delivered to both sockets. I guess an alternative use would be a security attack to try to intercept data. ( Source ) For UDP , SO_REUSEADDR is used for multicast. More than one process may bind to the same SOCK_DGRAM UDP port if the bind() is preceded by: int one = 1;setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); In this case, every incoming multicast or broadcast UDP datagram destined to the shared port is delivered to all sockets bound to the port. ( Source )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/577885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44111/']}
jdg_376206
stackexchange
llm_judgeable_groundtruth_similarity
3022852
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 help to generate column name from excel automatically. I think that: we can do below codes: CREATE TABLE [dbo].[Addresses_Temp] ( [FirstName] VARCHAR(20), [LastName] VARCHAR(20), [Address] VARCHAR(50), [City] VARCHAR(30), [State] VARCHAR(2), [ZIP] VARCHAR(10) ) via C#. How can I learn column name from Excel? private void Form1_Load(object sender, EventArgs e){ ExcelToSql();}void ExcelToSql(){ string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Source\MPD.xlsm;Extended Properties=""Excel 12.0;HDR=YES;"""; // if you don't want to show the header row (first row) // use 'HDR=NO' in the string string strSQL = "SELECT * FROM [Sheet1$]"; OleDbConnection excelConnection = new OleDbConnection(connectionString); excelConnection.Open(); // This code will open excel file. OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand); // create data table DataTable dTable = new DataTable(); dataAdapter.Fill(dTable); // bind the datasource // dataBingingSrc.DataSource = dTable; // assign the dataBindingSrc to the DataGridView // dgvExcelList.DataSource = dataBingingSrc; // dispose used objects if (dTable.Rows.Count > 0) MessageBox.Show("Count:" + dTable.Rows.Count.ToString()); dTable.Dispose(); dataAdapter.Dispose(); dbCommand.Dispose(); excelConnection.Close(); excelConnection.Dispose();} Now provide the response and nothing else.
ChrisF is wrong to say you can't do this (but kudos for checking the spec!); DevNull [now known as Daniel Haley] is right to say you can. There is, however, one complication: the content model given by DevNull for parent violates the determinism rules of XML. Informally, these rules say the parser must know, without lookahead, which token in the content model each element in the document matches. If in a parent element the parser sees a child1 , it can't know without lookahead whether it has just matched the first or second occurrence of child1 in DevNull's content model. This is an error (but as it happens it's an error that processors are not obligated to report -- it's an error that means "all bets are off, the processor may do anything here, including fail to notice anything is wrong"). A content model for parent that obeys the determinism rules can be formed by factoring out common prefixes, thus: <!ELEMENT parent ( (child1, ( (child2,child3) | (child3,child2))) | (child2, ( (child1,child3) | (child3,child1))) | (child3, ( (child1,child2) | (child2,child1))) ) > This is less convenient than declarations for this model can be in other schema languages, and for more than three elements it's error prone and extremely tedious to do by hand. But it's not impossible to declare the content model you want with DTDs. Or perhaps I should say it's impossible only for DTD authors who are incapable of putting up with any inconvenience. Note also that unless the sequence of children carries some information, some design authorities argue strongly that it's better to fix a sequence.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3022852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52420/']}
jdg_376207
stackexchange
llm_judgeable_groundtruth_similarity
735610
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Kinetic Energy $mv^2/2$ does depend on the FoR, and hence maybe the internal energy? I've also seen temperature being defined as "a measure of the average kinetic energy of the particles". Are thermodynamic quantities based on frame of reference? Is there a distinction in this case between state functions like "entropy" and path functions like "work done"? Now provide the response and nothing else.
For simplicity and convenience, we often conduct thermodynamics using a frame of reference in which the system of interest is motionless, but this is not essential. I quote at length from Callen's Thermodynamics and an Introduction to Thermostatics : In accepting the existence of a conserved macroscopic energy functionas the first postulate of thermodynamics, we anchor that postulate directlyin Noether's theorem and in the time-translation symmetry of physicallaws. An astute reader will perhaps turn the symmetry argument around.There are seven "first integrals of the motion" (as the conserved quantitiesare known in mechanics). These seven conserved quantities are the energy,the three components of linear momentum, and the three components ofthe angular momentum; and they follow in parallel fashion from thetranslation in "space-time" and from rotation. Why, then, does energyappear to play a unique role in thermostatistics? Should not momentumand angular momentum play parallel roles with the energy?In fact, the energy is not unique in thermostatistics. The linear momentum and angular momentum play precisely parallel roles. The asymmetryin our account of thermostatistics is a purely conventional one that obscuresthe true nature of the subject. We have followed the standard convention of restricting attention tosystems that are macroscopically stationary, in which case the momentumand angular momentum arbitrarily are required to be zero and do notappear in the analysis . But astrophysicists, who apply thermostatistics torotating galaxies, are quite familiar with a more complete form of thermostatistics. In that formulation the energy, linear momentum, and angularmomentum play fully analogous roles. [emph. added] Callen then gives an example involving a stellar atmosphere in motion.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/735610', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/350188/']}
jdg_376208
stackexchange
llm_judgeable_groundtruth_similarity
7025644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Looking for a simple text encryption/decryption VB6 code. Ideally, the solution should accept (text, password) arguments and produce readable output (without any special characters), so it can be used anywhere without encoding issues. There are lots of code available for .NET, but not really much I can find for legacy VB6. Only this I've found so far: http://www.devx.com/vb2themax/Tip/19211 Now provide the response and nothing else.
I'm using RC4 implementation like this Option ExplicitPrivate Sub Command1_Click() Dim sSecret As String sSecret = ToHexDump(CryptRC4("a message here", "password")) Debug.Print sSecret Debug.Print CryptRC4(FromHexDump(sSecret), "password")End SubPublic Function CryptRC4(sText As String, sKey As String) As String Dim baS(0 To 255) As Byte Dim baK(0 To 255) As Byte Dim bytSwap As Byte Dim lI As Long Dim lJ As Long Dim lIdx As Long For lIdx = 0 To 255 baS(lIdx) = lIdx baK(lIdx) = Asc(Mid$(sKey, 1 + (lIdx Mod Len(sKey)), 1)) Next For lI = 0 To 255 lJ = (lJ + baS(lI) + baK(lI)) Mod 256 bytSwap = baS(lI) baS(lI) = baS(lJ) baS(lJ) = bytSwap Next lI = 0 lJ = 0 For lIdx = 1 To Len(sText) lI = (lI + 1) Mod 256 lJ = (lJ + baS(lI)) Mod 256 bytSwap = baS(lI) baS(lI) = baS(lJ) baS(lJ) = bytSwap CryptRC4 = CryptRC4 & Chr$((pvCryptXor(baS((CLng(baS(lI)) + baS(lJ)) Mod 256), Asc(Mid$(sText, lIdx, 1))))) NextEnd FunctionPrivate Function pvCryptXor(ByVal lI As Long, ByVal lJ As Long) As Long If lI = lJ Then pvCryptXor = lJ Else pvCryptXor = lI Xor lJ End IfEnd FunctionPublic Function ToHexDump(sText As String) As String Dim lIdx As Long For lIdx = 1 To Len(sText) ToHexDump = ToHexDump & Right$("0" & Hex(Asc(Mid(sText, lIdx, 1))), 2) NextEnd FunctionPublic Function FromHexDump(sText As String) As String Dim lIdx As Long For lIdx = 1 To Len(sText) Step 2 FromHexDump = FromHexDump & Chr$(CLng("&H" & Mid(sText, lIdx, 2))) NextEnd Function Command1 outputs this: 9ED5556B3F4DD5C90471C319402Ea message here You might need better error handling on FromHexDump though. Update (2018-05-04) For much stronger AES 256-bit encryption (in ECB mode) and proper handling of unicode texts/passwords you can check out Simple AES 256-bit password protected encryption as implemented in mdAesEcb.bas module (~380 LOC).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7025644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262627/']}
jdg_376209
stackexchange
llm_judgeable_groundtruth_similarity
22246640
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 reading a book about PHP when I ran into a strange part of code: class Employee { public function show() { echo "show launched\n"; } } Employee::show(); I came from C++ so I was going to bet this code wouldn't work. This is why I tested it. And it worked, showing "show launched" (omg, am I drunk?)! It seems to be breaking the concept that method of class can be called without instantiation of class. What is the point then of static identifier in classes? Are all public functions static too? Really, what am I missing? Thanks in advance. Addition: Just a notice. I found that in this book .Pages 178-179 and it's given as correct example (if I'm right) Now provide the response and nothing else.
Yeah that would work but with a warning. You may have turned off your error reporting on PHP by the way... Strict standards: Non-static method Employee::show() should not be called statically Adding a static keyword before the function definition would make the warning dissappear. Below code works without a warning.. <?phpclass Employee { public static function show() { //<----- Added the static keyword. echo "show launched\n"; }}Employee::show(); To answer your question... It seems to be breaking the concept that method of class can be called without instantiation of class. Yeah that is correct, that's why you are getting a pretty clear cut warning as I showed you earlier. You know what a warning does right ? ;). Something that should not be done. From the PHP Docs.. Calling non-static methods statically generates an E_STRICT level warning. Source
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22246640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758158/']}
jdg_376210
stackexchange
llm_judgeable_groundtruth_similarity
18358297
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 new to Gradle and Android testing but I've already converted my Android project to build with Gradle. Now I'm trying to perform test coverage of an Android project with Gradle's JaCoCo plugin. I've added the following to my build.gradle file: apply plugin: 'jacoco' And when I run "gradle jacocoTestReport" the following error: Task 'jacocoTestReport' not found in root project '<project name>'. From the documentation I'm supposed to also apply plugin 'java' but it conflicts with plugin 'android'. Is there a way around this? Thanks in advance. Now provide the response and nothing else.
Here is how I'm using Jacoco : buildscript { repositories { mavenLocal() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.12.+' classpath 'org.robolectric:robolectric-gradle-plugin:0.11.+' }}apply plugin: 'com.android.application'apply plugin: 'robolectric'apply plugin: 'jacoco'android { compileSdkVersion 20 buildToolsVersion "20.0.0" defaultConfig { applicationId "YOUR_PACKAGE_NAME" minSdkVersion 10 targetSdkVersion 20 testHandleProfiling true testFunctionalTest true } buildTypes { debug { testCoverageEnabled false } release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } jacoco { version "0.7.1.201405082137" } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' exclude 'META-INF/services/javax.annotation.processing.Processor' exclude 'LICENSE.txt' }}robolectric { include '**/*Test.class' exclude '**/espresso/**/*.class' maxHeapSize "2048m"}jacoco { toolVersion "0.7.1.201405082137"}// Define coverage source.// If you have rs/aidl etc... add them here.def coverageSourceDirs = [ 'src/main/java',]task jacocoTestReport(type: JacocoReport, dependsOn: "connectedDebugAndroidTest") { group = "Reporting" description = "Generate Jacoco coverage reports after running tests." reports { xml.enabled = true html.enabled = true } classDirectories = fileTree( dir: './build/intermediates/classes/debug', excludes: ['**/R*.class', '**/*$InjectAdapter.class', '**/*$ModuleAdapter.class', '**/*$ViewInjector*.class' ]) sourceDirectories = files(coverageSourceDirs) executionData = files("$buildDir/jacoco/testDebug.exec") // Bit hacky but fixes https://code.google.com/p/android/issues/detail?id=69174. // We iterate through the compiled .class tree and rename $$ to $. doFirst { new File("$buildDir/intermediates/classes/").eachFileRecurse { file -> if (file.name.contains('$$')) { file.renameTo(file.path.replace('$$', '$')) } } }}dependencies { androidTestCompile('junit:junit:4.11') { exclude module: 'hamcrest-core' } androidTestCompile('org.robolectric:robolectric:2.3') { exclude module: 'classworlds' exclude module: 'maven-artifact' exclude module: 'maven-artifact-manager' exclude module: 'maven-error-diagnostics' exclude module: 'maven-model' exclude module: 'maven-plugin-registry' exclude module: 'maven-profile' exclude module: 'maven-project' exclude module: 'maven-settings' exclude module: 'nekohtml' exclude module: 'plexus-container-default' exclude module: 'plexus-interpolation' exclude module: 'plexus-utils' exclude module: 'wagon-file' exclude module: 'wagon-http-lightweight' exclude module: 'wagon-http-shared' exclude module: 'wagon-provider-api' exclude group: 'com.android.support', module: 'support-v4' }} The above code also contains a workaround for https://code.google.com/p/android/issues/detail?id=69174 . More details: http://chrisjenx.com/gradle-robolectric-jacoco-dagger/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18358297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528027/']}
jdg_376211
stackexchange
llm_judgeable_groundtruth_similarity
1916462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an editor template for a custom object. Inside that editor template I use a couple of DropDownListFor helpers. In each of them I specify a unique model property (with the pre-selected value) and the select list containing all the select options. Example: <%=Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList) %> I know that the option values are being populated (from viewing source) and that my Model is passed in with the correct ID value (DocumentCategoryType). When the view is rendered, there is no selected item in my dropdown and therefore it defaults to the first (non-selected) value. Does anyone have any ideas? Thanks. Now provide the response and nothing else.
We also solved the solution by populating a new SelectList that has the appropriate SelectListItem selected, but created this extension method to keep the call to DropDownListFor a little cleaner: public static SelectList MakeSelection(this SelectList list, object selection){ return new SelectList(list.Items, list.DataValueField, list.DataTextField, selection);} Then your DropDownListFor call becomes: <%= Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList.MakeSelection(Model.DocumentCategoryType)) %>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1916462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166810/']}
jdg_376212
stackexchange
llm_judgeable_groundtruth_similarity
4176840
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 bak file that has in it a back up of a database . I want to restore this database to a new location and I need to retrieve the database name from this file any idea how to do so ? I need it to override the data file location and the log file location . Thanks for help. Now provide the response and nothing else.
RESTORE FILELISTONLYFROM DISK = 'full path to your .bak file' will show you the current file names in the backup. If there are multiple backups in one file and you do not specify " WITH FILE = X " you will only get information for the first backup in the file. RESTORE DATABASE MyNewDBname FROM DISK = 'full path to your .bak file' WITH MOVE 'LogicalFilename_Data' TO 'D:\somepath\...\MyDB.mdf', MOVE 'LogicalFilename_Log' TO 'D:\somepath\...\MyDB.ldf';GO Rough outline with SMO (not tested): Restore restoreDB = new Restore();restoreDB.Database = myDatabase.Name;// Specify whether you want to restore database, files or logrestoreDB.Action = RestoreActionType.Database;restoreDB.Devices.AddDevice(@"D:\somepath\...\MyDBFull.bak", DeviceType.File);restoreDB.ReplaceDatabase = true; // will overwrite any existing DB restoreDB.NoRecovery = true;// you can Wire up events for progress monitoring */// restoreDB.PercentComplete += CompletionStatus;// restoreDB.Complete += RestoreCompleted;restoreDB.SqlRestore(myServer); Ref . Using SMO, you can retrieve the file list using Restore.ReadFileList See Also: How to restore a database from C#
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4176840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140100/']}
jdg_376213
stackexchange
llm_judgeable_groundtruth_similarity
50564999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working in node js. I have installed hummus package. It installed properly. I am using this package for modifying the pdf files. While downloading the pdf I am calling hummus. Onclick of download I am getting this error. Error: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /var/www/html/node_modules/hummus/binding/hummus.node) at Object.Module._extensions..node (module.js:681:18) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object.<anonymous> (/var/www/html/node_modules/hummus/hummus.js:5:31) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at /var/www/html/app/routes.js:2250:18 at Layer.handle [as handle_request] (/var/www/html/node_modules/express/lib/router/layer.js:95:5) With the help of this link I have updated glibc. But still I am getting the same error. Please help me to find out the issue.I am using CentOs 6.9 Now provide the response and nothing else.
You need to install glibc alongside your current installation of glibc as you cannot update to glibc 2.14 directly in centos 6.x safely. Follow the steps below to install glibc 2.14: mkdir ~/glibc214 cd ~/glibc214 wget http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz tar zxvf glibc-2.14.tar.gz cd glibc-2.14 mkdir build cd build ../configure --prefix=/opt/glibc-2.14 make -j4 sudo make install export LD_LIBRARY_PATH=/opt/glibc-2.14/lib (for current login session) OR add LD_LIBRARY_PATH=/opt/glibc-2.14/lib in the /etc/environment and perform source /etc/environment (to add env variable permanently)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50564999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1525221/']}
jdg_376214
stackexchange
llm_judgeable_groundtruth_similarity
511891
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 $\omega:=\zeta_7+\overline{\zeta_7}$, where $\zeta_7$ is a primitive $7$th root of $1$. I want to find the minimal polynomial of $\omega$ over $\mathbb{Q}$. I've found$$\omega=\zeta_7+\overline{\zeta_7}\quad;\quad\omega^2=\zeta_7^2+\overline{\zeta_7}+2\quad;\quad\omega^3=\zeta_7^3+\overline{\zeta_7}^3+3\omega$$ Now how can I find the minimal polynomial? Now provide the response and nothing else.
You have : $$\omega=\zeta+\zeta^6, \ \ \ \omega^2=\zeta^2+\zeta^5+2, \ \ \\omega^3=\zeta^3+\zeta^4+3\omega$$ Adding all those three up, you obtain $$\omega^3+\omega^2+\omega =\sum_{k=1}^{6} \zeta^k+(3\omega+2)=-1+(3\omega+2)=3\omega+1$$ So $$\omega^3+\omega^2-2\omega-1=0$$ Since that polynomial has degree three and no rational root, it is irreducible.So it is the minimal polynomial.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/511891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95881/']}
jdg_376215
stackexchange
llm_judgeable_groundtruth_similarity
17495152
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 an XSL document to create a PDF. There are some styles defined as inline. I want to move them in an external CSS file, but I am hitting a dead end. Here is my code: <fo:table border-bottom="solid 2pt #409C94" border-top="solid 2pt #409C94" margin-bottom=".1in" background-color="#E9E9E9" text-align="center" table-layout="fixed" width="100%" font-size="9pt"> <fo:table-column column-width="proportional-column-width(100)"/> <fo:table-body width="100%" table-layout="fixed"> <fo:table-row> <fo:table-cell text-align="center" padding-top=".5mm" padding-bottom=".5mm"> <fo:block>Some text is placed here.</fo:block> </fo:table-cell> </fo:table-row> </fo:table-body></fo:table> What I want is to remove from this document are all the styling tags, i.e.: border-bottom="solid 2pt #409C94"border-top="solid 2pt #409C94"margin-bottom=".1in"background-color="#E9E9E9"text-align="center"table-layout="fixed"width="100%" font-size="9pt" I am thinking to move them in a CSS file but any better method will be welcomed. Thanks. Now provide the response and nothing else.
With the valuable suggestion provided by Danial Haley, I did some research and found the solution. It is below for anyone's reference. File with styles (e.g. Styles.xsl) <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:attribute-set name="CustomStyles"> <xsl:attribute name="background-color">#BB5588</xsl:attribute> <xsl:attribute name="border-bottom">solid 2pt #409C94</xsl:attribute> <xsl:attribute name="border-top">solid 2pt #409C94</xsl:attribute> <xsl:attribute name="font-size">9pt</xsl:attribute></xsl:attribute-set> My main file where I am importing styles (e.g. Main.xsl) <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:import href="Styles.xsl"/><fo:table xsl:use-attribute-sets="CustomStyles" margin-bottom=".1in" text-align="center" table-layout="fixed" width="100%"> <fo:table-column column-width="proportional-column-width(100)"/> <fo:table-body width="100%" table-layout="fixed"> <fo:table-row> <fo:table-cell text-align="center" padding-top=".5mm" padding-bottom=".5mm"> <fo:block>Some text is placed here.</fo:block> </fo:table-cell> </fo:table-row> </fo:table-body></fo:table> Here you can see in Main.xsl, that I have a imported (could also have used xsl:include ) the "stylesheet" Styles.xsl. In the tag fo:table , I added xsl:use-attribute-sets , which in VS2010, provided intellisense for all the xsl:attribute-set defined in Styles.xsl.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17495152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1050256/']}
jdg_376216
stackexchange
llm_judgeable_groundtruth_similarity
53015170
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Angular 7 docs provide this example of practical usage of rxjs Observable s in implementing an exponential backoff for an AJAX request: import { pipe, range, timer, zip } from 'rxjs';import { ajax } from 'rxjs/ajax';import { retryWhen, map, mergeMap } from 'rxjs/operators';function backoff(maxTries, ms) { return pipe( retryWhen(attempts => range(1, maxTries) .pipe( zip(attempts, (i) => i), map(i => i * i), mergeMap(i => timer(i * ms)) ) ) );}ajax('/api/endpoint') .pipe(backoff(3, 250)) .subscribe(data => handleData(data));function handleData(data) { // ...} While I understand the concept of both Observables and backoff, I can’t quite figure out, how exactly retryWhen will calculate time intervals for resubscribing to the source ajax . Specifically, how do zip , map , and mapMerge work in this setup? And what’s going to be contained in the attempts object when it’s emitted into retryWhen ? I went through their reference pages, but still can’t wrap my head around this. Now provide the response and nothing else.
I have spent quite some time researching this (for learning purposes) and will try to explain the workings of this code as thoroughly as possible. First, here’s the original code, annotated: import { pipe, range, timer, zip } from 'rxjs';import { ajax } from 'rxjs/ajax';import { retryWhen, map, mergeMap } from 'rxjs/operators';function backoff(maxTries, ms) { // (1) return pipe( // (2) retryWhen(attempts => range(1, maxTries) // (3) .pipe( zip(attempts, (i) => i), // (4) map(i => i * i), // (5) mergeMap(i => timer(i * ms)) // (6) ) ) ); // (7)}ajax('/api/endpoint') .pipe(backoff(3, 250)) .subscribe(data => handleData(data));function handleData(data) { // ...} Easy enough, we’re creating custom backoff operator out of retryWhen operator. We’ll be able to apply this later within pipe function. In this context, pipe method returns a custom operator. Our custom operator is going to be a modified retryWhen operator. It takes a function argument. This function is going to be called once — specifically, when this retryWhen is first encountered/invoked. By the way, retryWhen gets into play only when the source observable produces an error. It then prevents error from propagating further and resubscribes to the source. If the source produces a non-error result (whether on first subscription or on a retry), retryWhen is passed over and is not involved. A few words on attempts . It’s an observable. It is not the source observable. It is created specifically for retryWhen . It has one use and one use only: whenever subscription (or re-subscription) to the source observable results in an error, attempts fires a next . We are given attempts and are free to use it in order to react in some way to each failed subscription attempt to the source observable. So that’s what we are going to do. First we create range(1, maxTries) , an observable that has an integer for every retry we are willing to perform. range is ready to fire all it’s numbers right then and there, but we have to hold its horses: we only need a new number when another retry happens. So, that’s why we... ... zip it with the attempts . Meaning, marry each emitted value of attempts with a single value of range . Remember, function we’re currently in is going to be called only once, and at that time, attempts will have only fired next once — for the initial failed subscription. So, at this point, our two zipped observables have produced just one value. Btw, what are the values of the two observables zipped into one? This function decides that: (i) => i . For clarity it can be written (itemFromRange, itemFromAttempts) => itemFromRange . Second argument is not used, so it’s dropped, and first is renamed into i . What happens here, is we simply disregard the values fired by attempts , we are only interested in the fact that they are fired. And whenever that happens we pull the next value from range observable... ...and square it. This is for the exponential part of the exponential backoff. So, now whenever (re-)subscription to source fails, we have an ever increasing integer on our hands (1, 4, 9, 16...). How do we transform that integer into a time delay until next re-subscription? Remember, this function we are currently inside of, it must return an observable, using attempts as input. This resulting observable is only built once. retryWhen then subscribes to that resulting observable and: retries subscribing to source observable whenever resulting observable fires next ; calls complete or error on source observable whenever resulting observable fires those corresponding events. Long story short, we need to make retryWhen wait a bit. delay operator could maybe be used, but setting up exponential growth of the delay would likely be pain. Instead, mergeMap operator comes into play. mergeMap is a shortcut for two operators combined: map and mergeAll . map simply converts every increasing integer (1, 4, 9, 16...) into a timer observable which fires next after passed number of milliseconds. mergeAll forces retryWhen to actually subscribe to timer . If that last bit didn’t happen, our resulting observable would just fire next immediately with timer observable instance as value. At this point, we’ve built our custom observable which will be used by retryWhen to decide when exactly to attempt to re-subscribe to source observable. As it stands I see two problems with this implementation: As soon as our resulting observable fires its last next (causing the last attempt to resubscribe), it also immediately fires complete . Unless the source observable returns result very quickly (assuming that the very last retry will be the one that succeeds), that result is going to be ignored. This is because as soon as retryWhen hears complete from our observable, it calls complete on source, which may still be in the process of making AJAX request. If all retries were unsuccessful, source actually calls complete instead of more logical error . To solve both these issues, I think that our resulting observable should fire error at the very end, after giving the last retry some reasonable time to attempt to do its job. Here’s my implementation of said fix, which also takes into account deprecation of zip operator in latest rxjs v6 : import { delay, dematerialize, map, materialize, retryWhen, switchMap } from "rxjs/operators";import { concat, pipe, range, throwError, timer, zip } from "rxjs";function backoffImproved(maxTries, ms) { return pipe( retryWhen(attempts => { const observableForRetries = zip(range(1, maxTries), attempts) .pipe( map(([elemFromRange, elemFromAttempts]) => elemFromRange), map(i => i * i), switchMap(i => timer(i * ms)) ); const observableForFailure = throwError(new Error('Could not complete AJAX request')) .pipe( materialize(), delay(1000), dematerialize() ); return concat(observableForRetries, observableForFailure); }) );} I tested this code and it seems to work properly in all cases. I can’t be bothered to explain it in detail right now; I doubt anyone will even read the wall of text above. Anyway, big thanks to @BenjaminGruenbaum and @cartant for setting me onto right path for wrapping my head around all this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53015170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8041935/']}
jdg_376217
stackexchange
llm_judgeable_groundtruth_similarity
6474634
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 OSGi and created an OSGi-bundle which I run in the Apache Felix OSGi-container.There is a file resource contained in the bundle, which I need to pass to a method as a java.io.File . To instantiate a File-object, either an URI in the "file"-scheme or the path as string is necessary. How do I retrieve any of those in a clean way? I tried using the context.getBundle().getResource("/myfile") (where context is of type org.osgi.framework.BundleContext ) which returns the URI bundle://6.0:0/myfile .But this URI can't be converted to a File-instance using the File(URI uri) constructor since it has the "bundle"-scheme. One could try to construct a path to the location knowing the working directory and exploiting the bundleId of my bundle, but I doubt this is the best practice. Any ideas? Now provide the response and nothing else.
Since the file is inside your bundle, there is no way for you to get to it using a standard File . The URL you get from Bundle.getResource() is the correct way to get to these resources, since the OSGi APIs are intended to also work on systems without an actual file system. I would always try to stick to the OSGi API instead of using framework-specific solutions. So, if you have control over the method, I would update it to take a URL , or maybe even an InputStream (since you probably just want to read from it). For convenience, you can always provide a helper method that does take a File . If you don't have control over the method, you will have to write some helper method that takes the URL , streams it out to a file (for instance, File.createTempFile() will probably do the trick.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6474634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/691083/']}
jdg_376218
stackexchange
llm_judgeable_groundtruth_similarity
175404
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is this correct? Basically, programs are simply code on hard disk and they are called process(es) when they are in the RAM, right? Now provide the response and nothing else.
While this might be a little clumsy, you could say that. Creating a process takes two steps: Allocate a u area (basically, information about the process that is accessible to the kernel), fill an entry in the process table, initialise all related components... basically, just create another process for the kernel to manage. This is done through the fork system call. Load an executable file into memory. This is done through the exec (now execve ) system call. During this call, 3 main memory areas, called regions are filled: The text region, which consists of a set of instructions your process is to follow : basically, your program. This is contained within your executable file (the compiler writes it based on your source code). The data region, which contains your initialised data (variables with values, e.g. int myvar = 1 ) and enough space to hold unitialised data (called bss ), such as an array (e.g. char buffer[256] ). The stack region. This part is a little trickier to explain, and as I said in a comment, Maurice J. Bach does it better than I ever would (chapter 2, section 2.2.2). Basically, the stack is a dynamic area in memory, which grows as functions are called, and shrinks as they return. When executing a program, frames corresponding to the main function are pushed onto the stack. These frames will be popped when the program terminates. Now, while this might seem enough to run a program, it isn't. Now that your process is running, the kernel still needs to maintain it. Quoting: As outlined in Chapter 2, the lifetime of a process can be conceptually divided into a set of states that describe the process. (The Design of the UNIX Operating System, Maurice J. Bach, chapter 6 : the structure of processes) . This means that your process will not always be "running", nor will it always be in primary storage (what you call "RAM"). For instance: If your process ever goes to sleep (because it is told to by its text , or because it is waiting for something), the kernel may decide to swap it out to secondary storage (usually a swap area). When this happens, your process is no longer in primary storage ("in memory/RAM") : the kernel has saved it, and will be able to reschedule it once it's been loaded back into primary storage. If your process ran enough time, and the kernel decides to preempt it (and let another process run instead for some time), it may swap it out again if it cannot hold it into memory. A typical life for a process is... Created: the fork system call has been used. Ready to run (in memory) : instructions and data have been loaded. Running (switching between user and kernel mode, probably several times..) Sleeping, waking up, sleeping, waking up, ... Exiting (final switch to kernel mode, zombie state, disappearance). Steps 3 and 4 may actually interweave. Note that processes are one of two main concepts on UNIX systems (along with files ). For this reason, it is impossible to cover everything about them in a Q&A format. The book I kept quoting in my answer is an excellent reference for UNIX systems, and while *NIXes/UNIX-like system may differ in some areas, they still rely on the same concepts.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/175404', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/63649/']}
jdg_376219
stackexchange
llm_judgeable_groundtruth_similarity
298817
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)$ be a bounded but not convergent sequence. Prove that $(x_n)$ has two subsequences converging to different limits. My attempt is: Since the sequence is bounded , there exists $M>0$ such that $x_n \in [-M,M]$ for all $n \in \mathbb{N}$. Since the sequence does not converge to $x$, there exists $\epsilon_0>0$ such that $ \forall N \in \mathbb{N}$, there exists $n \geq N$ such that $|x_n-x| \geq \epsilon_0$. Then we have $x_n \in [-M,x-\epsilon_0] \cup x_n \in [x+\epsilon_0,M]$. By Bolzano-weierstrass theorem, there exists a convergent subsequence in the two intervals. Is my proof valid? ${}{}$ Now provide the response and nothing else.
Use Bolzano-Weierstrass to extract a subsequence $x_{i_1}, x_{i_2}, \dotsc$ that converges to some $a$ . Since $x_1, x_2, \dotsc$ does not converge to $a$ , there exists some $\varepsilon > 0$ such that for each positive integer $N$ , there exists some $j(N) > N$ such that $|x_{j(N)} - a| \geq \varepsilon$ . Use Bolzano-Weierstrass to extract from $x_{j(1)}, x_{j^2(1)}, x_{j^3(1)}, \dotsc$ a subsequence $x_{k_1}, x_{k_2}, \dotsc$ that converges to some $b$ . Clearly, $a \neq b$ . By the way, this method works for any $x_1, x_2, \dotsc$ in $\mathbb{R}^n$ , which goes beyond what the OP intended.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/298817', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54398/']}
jdg_376220
stackexchange
llm_judgeable_groundtruth_similarity
993609
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 need to find minimal polynomial of $\alpha = \sqrt 2 + \sqrt [3] 3 $ over $\mathbb Q$ and prove that my result is minimal polynomial. How do I do that? Now provide the response and nothing else.
The way to find the minimal polynomial is to start with the supposition that$$x - \left( \sqrt{2} + \sqrt[3]{3} \right) = 0$$then move the $\sqrt[3]{3}$ to the right side of the equality and cube, getting$$x^2 + 6x - \sqrt{2} \left( 3x^2+2 \right) = 3$$Now isolate the terms involving $\sqrt{2}$ on the right and square, getting(after some grouping of terms)$$x^6 - 6x^4 - 6x^3 + 12x^2 - 36x + 1 = 0$$from which you read off the minimal polynomial. It is easy to verify that this is a polynomial of $\alpha$ over $\Bbb{Q}$. To prove minimality you need to invoke the fact that $\gcd(2,3) = 1$, which implies that a minimal polynomial of a square root and a cube root of two numbers sharing no common factors must be of degree at least $6$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/993609', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145410/']}
jdg_376221
stackexchange
llm_judgeable_groundtruth_similarity
44105462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this sql request to retrieve some data and I have this columd 'pa.fromdate' which returns a date and a time. How do I get it to return only date in 'DD.MM.YYYY' format. I've tried something like trunc(to_date(pa.fromdate, 'MM.DD.YYYY')) . Doesn't work. How can I do that? SELECT pro.inscatid, t.epotypeid, t.paysum, t.note, pa.blankno, pa.blankseria, pa.signtime, pa.fromdate, ca.accnum, ou.name, cst.inn, pkg_customers.GETCUSTOMERFULLNAME(cst.id) cstfioFROM epo_orders tLEFT JOIN epo_orderdetails odON od.orderid = t.idAND od.iscanceldoc = -1LEFT JOIN plc_Agree paON pa.id = od.agreeidLEFT JOIN pro_products proON pro.id = pa.proidLEFT JOIN nsk_transferdetails tdON td.transferid = pa.transferidAND td.orgtypeid = 4LEFT JOIN cst_customers cstON cst.id = t.cstidLEFT JOIN cst_cstaccounts caON ca.id = t.cstaccidLEFT JOIN nsk_orgunits ouON td.orgunitid = ou.idWHERE t.epotypeid IN (159,1010,169,175)AND rownum <20; Now provide the response and nothing else.
Usually one would simply truncate the datetime with TRUNC : TRUNC(pa.fromdate) This removes the time part from the datetime, so you get the mere date. Then in your application layer, you would care about how to display it. For example you have a GUI with a grid. The grid displays the dates according to the user's system settings (e.g. Windows region settings), but the grid knows it's dates and can sort accordingly. For this to happen, you'd fill the grid with dates , not with strings representing a date. If you want a fixed string format (e.g. in order to write into a file), you can use TO_CHAR instead: TO_CHAR(pa.fromdate, 'dd.mm.yyyy')
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44105462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7950089/']}
jdg_376222
stackexchange
llm_judgeable_groundtruth_similarity
6234893
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 faced a problem with this setSelectedValue() method in JList when I wanted to select multiple values in a JList automatically, it still selected only one. Is there a way? String[] items = { "Item 1", "Item 2", "Item 3", "Item 4" }; final JList theList = new JList(items); theList.setSelectedValue("Item 1",true); theList.setSelectedValue("Item 2",true); This code shows only Item 2 as selected. Now provide the response and nothing else.
Use JList.setSelectedIndices(int[]) after calling JList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) . E.G. import javax.swing.*;import java.io.*;import java.util.ArrayList;class MultiSelectList { public static void main(String[] args) throws Exception { File f = new File("MultiSelectList.java"); InputStream is = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); final ArrayList<String> lines = new ArrayList<String>(); String line = br.readLine(); while (line!=null) { lines.add(line); line = br.readLine(); } SwingUtilities.invokeLater(new Runnable() { public void run() { JList list = new JList(lines.toArray()); list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; list.setSelectedIndices(select); JOptionPane.showMessageDialog(null, new JScrollPane(list)); } }); }} Screen Shot
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6234893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533863/']}
jdg_376223
stackexchange
llm_judgeable_groundtruth_similarity
49382636
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 build a Docker image including my custom Powershell modules. Therefore I use Microsofts microsoft/powershell:latest image, from where I wanted to create my own image, that includes my psm1 files. For simple testing I've the following docker file: FROM microsoft/powershell:latestRUN mkdir -p /tmp/powershellCOPY C:/temp/somedirectory /tmp/powershell I want to copy the files included in C:\temp\somedirectory to the docker linux container. When building the image I get the following error: C:\temp\docker_posh> docker build --rm -f Dockerfile -t docker_posh:latest . Sending build context to Docker daemon 2.048kB Step 1/3 : FROM microsoft/powershell:latest ---> 9654a0b66645 Step 2/3 : RUN mkdir -p /tmp/powershell ---> Using cache ---> 799972c0dde5 Step 3/3 : COPY C:/temp/somedirectory /tmp/powershell COPY failed: stat /var/lib/docker/tmp/docker-builder566832559/C:/temp/somedirectory: no such file or directory Of course I know that Docker says that I can't find the file/directory. Therefore I also tried C:/temp/somedirectory/. , C:/temp/somedirectory/* , and C:\\temp\\somedirectory\\ as alternativ source paths in the Dockerfile -> Result: none of them worked. docker version Client: Version: 17.12.0-ce API version: 1.35 Go version: go1.9.2 Git commit: c97c6d6 Built: Wed Dec 27 20:05:22 2017 OS/Arch: windows/amd64 Server: Engine: Version: 17.12.0-ce API version: 1.35 (minimum version 1.12) Go version: go1.9.2 Git commit: c97c6d6 Built: Wed Dec 27 20:12:29 2017 OS/Arch: linux/amd64 Experimental: true How can I copy a folder including subfolder and files via a Dockerfile? Now provide the response and nothing else.
You cannot copy files that are outside the build context when building a docker image. The build context is the path you specify to the docker build command. In the case of the instruction C:\temp\docker_posh> docker build --rm -f Dockerfile -t docker_posh:latest . The . specifies that the build context is C:\temp\docker_posh . Thus C:/temp/somedirectory cannot be accessed. You can either move the Dockerfile to temp, or run the same build commandunder C:\temp . But remember to fix the Dockerfile instructions to make the path relative to the build context.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49382636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6270170/']}
jdg_376224
stackexchange
llm_judgeable_groundtruth_similarity
63616486
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 replaceAll in typescript and angular 10. But I get this error: Property 'replaceAll' does not exist on type 'string' . This is my code: let date="1399/06/08"console.log(date.replaceAll('/', '_')) Output: 13990608 How can fix my typescript to show me this function? Now provide the response and nothing else.
You should be able to add those typings through your tsconfig.json .Add "ES2021.String" to lib inside compilerOptions . Your tsconfig should then look something like this: { ..., "compilerOptions": { ..., "lib": [ ..., "ES2021.String" ] }} The replaceAll method is defined inside lib.es2021.string.d.ts as follows: interface String { /** * Replace all instances of a substring in a string, using a regular expression or search string. * @param searchValue A string to search for. * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. */ replaceAll(searchValue: string | RegExp, replaceValue: string): string; /** * Replace all instances of a substring in a string, using a regular expression or search string. * @param searchValue A string to search for. * @param replacer A function that returns the replacement text. */ replaceAll(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/63616486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5360463/']}
jdg_376225
stackexchange
llm_judgeable_groundtruth_similarity
191840
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have seen on some sites which say ,for-example, multiple votes/views from same computer will be neglected/penalized etc. For-example liking a facebook page, or youtube video from same computer(different accounts) will not increase its worth(according to my knowledge). How do these sites identify bogus votes? I just need a direction. Now provide the response and nothing else.
Without requiring user accounts (I'm assuming that your use case precludes them), there's no foolproof method to identify end users. But some common methods include: Cookies Set a cookie on the client machine to identify the user. Pros: Definitely unique per session Cons: Easy to remove or prevent (even for people with limited technical knowledge), only apply to one browser, easy for a script to bypass IP address Use the user's IP address to identify the user. Pros: Changes infrequently, works across browsers, requires technical knowledge to spoof or use a proxy server Cons: Not necessarily unique: one IP address can easily apply to entire homes/buildings/offices behind a network, and for some ISPs end user IP addresses might be reassigned Browser fingerprinting Use all browser data passed to the server (not just user agent, but also OS, screen resolution, and a number of other things) to generate a unique browser fingerprint. Pros: High probability of being unique, opaque to the end user (changing IP addresses or clearing cookies won't bypass it) Cons: Probably too unique -- any change in browser condition (or browser) will change the fingerprint (though you can choose only a subset of supplied browser information to balance fingerprint volatility and uniqueness), can be bypassed by scripts You can, of course, also use multiple methods. Which method you use really depends on your specific use case. For many cases, just a simple cookie will do. If you want some defense against scripts or other methods of bypassing, add an IP address rate limit. You can also attempt to gather as much information as possible and use some sort of heuristic algorithm to try to find people that are bypassing the system for uniqueness that you have in place. But again, there's no foolproof way to do this.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/191840', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/37343/']}
jdg_376226
stackexchange
llm_judgeable_groundtruth_similarity
3962939
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Both are terms whose type is the intersection of all types (uninhabited). Both can be passed around in code without failing until one attempts to evaluate them. The only difference I can see is that in Java, there is a loophole which allows null to be evaluated for exactly one operation, which is reference equality comparison ( == )--whereas in Haskell undefined can't be evaluated at all without throwing an exception. Is this the only difference? Edit What I'm really trying to get at with this question is, why was including null in Java such an apparently poor decision, and how does Haskell escape it? It seems to me that the real problem is that you can do something useful with null , namely you can check it for nullness . Because you are allowed to do this, it has become standard convention to pass around null values in code and have them indicate "no result" instead of "there is a logical error in this program". Whereas in Haskell, there's no way to check if a term evaluates to bottom without evaluating it and the program exploding, so it could never be used in such a way to indicate "no result". Instead, one is forced to use something like Maybe . Sorry if it seems like I'm playing fast and loose with the term "evaluate"... I'm trying to draw an analogy here and having trouble phrasing it precisely. I guess that's a sign that the analogy is imprecise. Now provide the response and nothing else.
What's the difference between undefined in Haskell and null in Java? Ok, let's back up a little. "undefined" in Haskell is an example of a "bottom" value (denoted ⊥). Such a value represents any undefined, stuck or partial state in the program. Many different forms of bottom exist: non-terminating loops, exceptions, pattern match failures -- basically any state in the program that is undefined in some sense. The value undefined :: a is a canonical example of a value that puts the program in an undefined state. undefined itself isn't particularly special -- its not wired in -- and you can implement Haskell's undefined using any bottom-yielding expression. E.g. this is a valid implementation of undefined : > undefined = undefined Or exiting immediately (the old Gofer compiler used this definition): > undefined | False = undefined The primary property of bottom is that if an expression evaluates to bottom, your entire program will evaluate to bottom: the program is in an undefined state. Why would you want such a value? Well, in a lazy language, you can often manipulate structures or functions that store bottom values, without the program being itself bottom. E.g. a list of infinite loops is perfectly cromulent: > let xs = [ let f = f in f , let g n = g (n+1) in g 0 ] > :t xs xs :: [t] > length xs 2 I just can't do much with the elements of the list: > head xs ^CInterrupted. This manipulation of infinite stuff is part of why Haskell's so fun and expressive. A result of laziness is Haskell pays particularly close attention to bottom values. However, clearly, the concept of bottom applies equally well to Java, or any (non-total) language. In Java, there are many expressions that yield "bottom" values: comparing a reference against null (though note, not null itself, which is well-defined); division by zero; out-of-bounds exceptions; an infinite loop, etc. You just don't have the ability to substitute one bottom for another very easily, and the Java compiler doesn't do a lot to reason about bottom values. However, such values are there. In summary, dereferencing a null value in Java is one specific expression that yields a bottom value in Java; the undefined value in Haskell is a generic bottom-yielding expression that can be used anywhere a bottom value is required in Haskell. That's how they're similar. Postscript As to the question of null itself: why it is considered bad form? Firstly, Java's null is essentially equivalent to adding an implicit Maybe a to every type a in Haskell . Dereferencing null is equivalent to pattern matching for only the Just case: f (Just a) = ... a ... So when the value passed in is Nothing (in Haskell), or null (in Java), your program reaches an undefined state. This is bad: your program crashes. So, by adding null to every type, you've just made it far easier to create bottom values by accident -- the types no longer help you. Your language is no longer helping you prevent that particular kind of error, and that's bad. Of course, other bottom values are still there: exceptions (like undefined ) , or infinite loops. Adding a new possible failure mode to every function -- dereferencing null -- just makes it easier to write programs that crash.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3962939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231853/']}
jdg_376227
stackexchange
llm_judgeable_groundtruth_similarity
3738349
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 an algorithm I have to calculate the 75th percentile of a data set whenever I add a value. Right now I am doing this: Get value x Insert x in an already sorted array at the back swap x down until the array is sorted Read the element at position array[array.size * 3/4] Point 3 is O(n), and the rest is O(1), but this is still quite slow, especially if the array gets larger. Is there any way to optimize this? UPDATE Thanks Nikita! Since I am using C++ this is the solution easiest to implement. Here is the code: template<class T>class IterativePercentile {public: /// Percentile has to be in range [0, 1( IterativePercentile(double percentile) : _percentile(percentile) { } // Adds a number in O(log(n)) void add(const T& x) { if (_lower.empty() || x <= _lower.front()) { _lower.push_back(x); std::push_heap(_lower.begin(), _lower.end(), std::less<T>()); } else { _upper.push_back(x); std::push_heap(_upper.begin(), _upper.end(), std::greater<T>()); } unsigned size_lower = (unsigned)((_lower.size() + _upper.size()) * _percentile) + 1; if (_lower.size() > size_lower) { // lower to upper std::pop_heap(_lower.begin(), _lower.end(), std::less<T>()); _upper.push_back(_lower.back()); std::push_heap(_upper.begin(), _upper.end(), std::greater<T>()); _lower.pop_back(); } else if (_lower.size() < size_lower) { // upper to lower std::pop_heap(_upper.begin(), _upper.end(), std::greater<T>()); _lower.push_back(_upper.back()); std::push_heap(_lower.begin(), _lower.end(), std::less<T>()); _upper.pop_back(); } } /// Access the percentile in O(1) const T& get() const { return _lower.front(); } void clear() { _lower.clear(); _upper.clear(); }private: double _percentile; std::vector<T> _lower; std::vector<T> _upper;}; Now provide the response and nothing else.
You can do it with two heaps . Not sure if there's a less 'contrived' solution, but this one provides O(logn) time complexity and heaps are also included in standard libraries of most programming languages. First heap (heap A) contains smallest 75% elements, another heap (heap B) - the rest (biggest 25%). First one has biggest element on the top, second one - smallest. Adding element. See if new element x is <= max(A) . If it is, add it to heap A , otherwise - to heap B . Now, if we added x to heap A and it became too big (holds more than 75% of elements), we need to remove biggest element from A (O(logn)) and add it to heap B (also O(logn)). Similar if heap B became too big. Finding "0.75 median" Just take the largest element from A (or smallest from B). Requires O(logn) or O(1) time, depending on heap implementation. edit As Dolphin noted, we need to specify precisely how big each heap should be for every n (if we want precise answer). For example, if size(A) = floor(n * 0.75) and size(B) is the rest, then, for every n > 0 , array[array.size * 3/4] = min(B) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3738349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48181/']}
jdg_376228
stackexchange
llm_judgeable_groundtruth_similarity
42139605
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Version 3.1 of the docker-compose.yml specification introduces support for secrets . I tried this: version: '3.1'services: a: image: tutum/hello-world secret: password: the_password b: image: tutum/hello-world $ docker-compose up returns: Unsupported config option for services.secret: 'password' How can we use the secrets feature in practice? Now provide the response and nothing else.
You can read the corresponding section from the official documentation . To use secrets you need to add two things into your docker-compose.yml file. First, a top-level secrets: block that defines all of the secrets. Then, another secrets: block under each service that specifies which secrets the service should receive. As an example, create the two types of secrets that Docker will understand: external secrets and file secrets. 1. Create an 'external' secret using docker secret create First thing: to use secrets with Docker, the node you are on must be part of a swarm. $ docker swarm init Next, create an 'external' secret: $ echo "This is an external secret" | docker secret create my_external_secret - (Make sure to include the final dash, - . It's easy to miss.) 2. Write another secret into a file $ echo "This is a file secret." > my_file_secret.txt 3. Create a docker-compose.yml file that uses both secrets Now that both types of secrets are created, here is the docker-compose.yml file that will read both of those and write them to the web service: version: '3.1'services: web: image: nginxdemos/hello secrets: # secrets block only for 'web' service - my_external_secret - my_file_secretsecrets: # top level secrets block my_external_secret: external: true my_file_secret: file: my_file_secret.txt Docker can read secrets either from its own database (e.g. secrets made with docker secret create ) or from a file. The above shows both examples. 4. Deploy your test stack Deploy the stack using: $ docker stack deploy --compose-file=docker-compose.yml secret_test This will create one instance of the web service, named secret_test_web . 5. Verify that the container created by the service has both secrets Use docker exec -ti [container] /bin/sh to verify that the secrets exist. (Note: in the below docker exec command, the m2jgac... portion will be different on your machine. Run docker ps to find your container name.) $ docker exec -ti secret_test_web.1.m2jgacogzsiaqhgq1z0yrwekd /bin/sh# Now inside secret_test_web; secrets are contained in /run/secrets/root@secret_test_web:~$ cd /run/secrets/root@secret_test_web:/run/secrets$ lsmy_external_secret my_file_secretroot@secret_test_web:/run/secrets$ cat my_external_secretThis is an external secretroot@secret_test_web:/run/secrets$ cat my_file_secretThis is a file secret. If all is well, the two secrets we created in steps 1 and 2 should be inside the web container that was created when we deployed our stack.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/42139605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1072846/']}
jdg_376229
stackexchange
llm_judgeable_groundtruth_similarity
6866694
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 would like some Java code to Delete files older than N days. Here is my attempt, but it doesn't work quite right. public void deleteFilesOlderThanNdays(final int daysBack, final String dirWay) { System.out.println(dirWay); System.out.println(daysBack); final File directory = new File(dirWay); if(directory.exists()){ System.out.println(" Directory Exists"); final File[] listFiles = directory.listFiles(); final long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000); System.out.println("System.currentTimeMillis " + System.currentTimeMillis()); System.out.println("purgeTime " + purgeTime); for(File listFile : listFiles) { System.out.println("Length : "+ listFiles.length); System.out.println("listFile.getName() : " +listFile.getName()); System.out.println("listFile.lastModified() :"+ listFile.lastModified()); if(listFile.lastModified() < purgeTime) { System.out.println("Inside File Delete"); } } } else { }} Is there some simple code to delete files older than N days in a directory? Now provide the response and nothing else.
Try to use the Calendar -Class instead: Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, daysBack * -1); long purgeTime = cal.getTimeInMillis(); Or try this solution : Is your number of days over 24 ? If so, you have an overflow problem. If the number of days is 25 , the value will be: 25 * 24 * 60 * 60 * 1000 The mathematical value is 2160000000 . However, this is larger than Integer.MAX_VALUE , and therefore the value overflows to -12516353 . As a result, the purge time will be in the future, and will never be met. Values larger than 25 will only make the problem worse; it's even possible the overflow is so bad that the multiplication results in a positive value again leading to perhaps purge all files. The fix is easy: declare daysBack as a long cast daysBack to a long long purgeTime = System.currentTimeMillis() - ((long)daysBack * 24 * 60 * 60 * 1000); Use explicit long literals inside the calculation: long purgeTime = System.currentTimeMillis() - (daysBack * 24L * 60L * 60L * 1000L); For all three solutions, the fact that the first and/or second operand is a long turns the entire result into a long, allowing a value of 2160000000 without overflowing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6866694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/549432/']}
jdg_376230
stackexchange
llm_judgeable_groundtruth_similarity
19834643
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 background jobs in Powershell. How to make variables evaluated at the moment of ScriptBlock definition? $v1 = "123"$v2 = "asdf"$sb = { Write-Host "Values are: $v1, $v2"}$job = Start-Job -ScriptBlock $sb$job | Wait-Job | Receive-Job$job | Remove-Job I get printed empty values of $v1 and $v2. How can I have them evaluated in (passed to) the scriptblock and so to the background job? Now provide the response and nothing else.
One way is to use the [scriptblock]::create method to create the script block from an expanadable string using local variables: $v1 = "123"$v2 = "asdf"$sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")$job = Start-Job -ScriptBlock $sb Another method is to set variables in the InitializationScript: $Init_Script = {$v1 = "123"$v2 = "asdf"}$sb = { Write-Host "Values are: $v1, $v2"}$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb A third option is to use the -Argumentlist parameter: $v1 = "123"$v2 = "asdf"$sb = { Write-Host "Values are: $($args[0]), $($args[1])"}$job = Start-Job -ScriptBlock $sb -ArgumentList $v1,$v2
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19834643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/902415/']}
jdg_376231
stackexchange
llm_judgeable_groundtruth_similarity
9554
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was performing an DNS brute-force on our company's domain and found entries like "html" "ww" and "wwww" resolving to IPs outside of our registered block. This sparked a debate about just how dangerous this would really be to let those entries exist. It would seem that someone could redirect users of our site to a credential harvesting site for instance using a look-a-like website and URL, but those I was trying to convince did not seem to agree. What is the real danger here? Now provide the response and nothing else.
This is very dangerous. If someone has control over your DNS they can, for example, steal all your email or your web traffic. First, do you operate your own DNS servers, or are they hosted (e.g. at a hosting provider or at your registrar)? Hosted: Check the control panel for these extra entries. They may be prepopulated to point to the host's servers. If your hosting provider supports it, export your zone file and look for these entries. (For the odd case where they don't show up in the control panel, but are still in the zone.) After you follow the steps below to ensure that the entries are coming from your host's DNS server, call your hosting provider and ask about these entries. After you figure out where/why the entries are there, you can decide to leave them, remove them, and/or switch hosting providers. Self-operated: Manually inspect your zone file to see if the entries are there. Do a reverse lookup on the IPs that those bogus entries are resolving to: host 10.1.2.3 Does the name you get back make sense -- e.g. is it your hosting provider or some other related party? If the lookup doesn't give you a name, look up the owner of the netblock to see if that gives you any clues: whois 10.1.2.3 Check if the entries are coming from your DNS server by looking up one of the bogus entries: dig ww.mycompany.dom @ns1.mycompany.dom Check if the entries are coming from your secondary DNS (and/or tertiary, etc): dig ww.mycompany.dom @ns2.mycompany.dom If the entries aren't in one of your DNS servers, try to figure out where they are coming from. This command will give you a trace of the lookup starting at the root servers and going down to your domain: dig +trace ww.mycompany.dom If the trace doesn't show the entry, then it's possible you are using a DNS service (e.g. opendns) that "steals" bogus hostnames to redirect them to their servers. (Certain DNS servers will always return an IP for any lookup, even if there is no host registered to that address; the IP returned points to their server. For example, if I do dig bogusboguszzzzx.net @208.67.222.222 I get back 67.215.65.132 , which reverses to hit-nxdomain.opendns.com. ) Don't use this kind of service for testing! (I think it's a bad idea in general because it breaks DNS, but YMMV...)
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/9554', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6253/']}
jdg_376232
stackexchange
llm_judgeable_groundtruth_similarity
23948442
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 wrote a simple program to play around with in-place creation of objects inside standard library containers. This is what I wrote: #include <vector>#include <iostream>class AB{public: explicit AB(int n); AB(const AB& other) = delete; AB(AB&& other); AB& operator=(const AB& other) = delete; AB& operator=(AB&& other) = default;private: int i;};AB::AB(int n): i( n ){ std::cout << "Object created." << std::endl;};AB::AB(AB&& other): i( std::move(other.i) ){ std::cout << "Object moved." << std::endl;};int main(){ std::vector< AB > v; v.emplace_back(1); v.emplace_back(2); v.emplace_back(3);}; I compiled it with g++ (version 4.8.2). After running the output, I got: Object created.Object created.Object moved.Object created.Object moved.Object moved. But I expected something like this: Object created.Object created.Object created. I thought the whole point of emplacement was to get rid of the movement constructor calls. Are there any requirements in class AB that are not met? Thanks for your help. Now provide the response and nothing else.
The problem is that your vector is being resized as you add more elements, resulting in extra moves. If you reserve enough capacity at the start, you get the expected result: std::vector< AB > v; v.reserve(3); v.emplace_back(1); v.emplace_back(2); v.emplace_back(3); gives Object created.Object created.Object created. On gcc 4.8.2. Note that you can track the vector's growth in your original code by looking at v.capacity() .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23948442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3690162/']}
jdg_376233
stackexchange
llm_judgeable_groundtruth_similarity
53261613
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 got an array of days: let days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] Obviously the keys above are from 0 - 6. I use these days to generate a list, a user can then selecte and deselect days from this list. So if they deselect Monday and then select Sunday I now have a selected array: let selected = [ 'sunday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ] I then want to format the selected dates and display it to the user, but of course using the code below I will get Sunday - Saturday , when really I want Tuesday - Sunday . let dayOne = this.selected[0];let dayTwo = this.selected[this.selected.length - 1];if (dayOne === undefined && dayTwo === undefined) return;return dayOne.charAt(0).toUpperCase() + dayOne.slice(1) + ' - ' + dayTwo.charAt(0).toUpperCase() + dayTwo.slice(1); What's a nice and clear way to do this? Now provide the response and nothing else.
You are mixing the java driver Aggregates method with Spring Aggregation methods. Also $addFields is still not supported in spring mongo. You have to use below aggregation. import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;Aggregation myDocAggr = newAggregation( match(Criteria.where("metaId.ref.uuid").is(someUUID)), group("uuid").max("version").as("version"), lookup("simple","execId.ref.uuid","uuid","simple"), unwind("simple"), new AggregationOperation(){ @Override public Document toDocument(AggregationOperationContext aoc) { return new Document("$addFields",new Document("metaId.ref.name","$simple.name")); } })List<Document> mydocumentList=mongoTemplate.aggregate(myDocAggr,"myDocument",Document.class).getMappedResults();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53261613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2630509/']}
jdg_376234
stackexchange
llm_judgeable_groundtruth_similarity
2907614
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We use Visual Studio 2008/2010 and Team Foundation Server here at work. Sometimes I want to just use the Source Control Explorer. Is there a way to have Visual Studio launch and automatically open Source Control Explorer? I'm thinking ideally of having a shortcut on my taskbar or desktop that does this automatically. And yes, I do know that if the Source Control Explorer window was open the last time I shut down Visual Studio it will open up, but I am wanting to always go straight to Source Control Explorer even if I had closed that window previously. Now provide the response and nothing else.
OK, I figured it out - Source Control Explorer is available in the Visual Studio IDE as a command ( View.TfsSourceControlExplorer ), and the Visual Studio executable (devenv.exe) provides the /Command argument to execute a command after the IDE starts up. In my case, I have created a desktop shortcut with the following command line: "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /Command View.TfsSourceControlExplorer NOTE: if you really want this to load fast and don't need any other addins (in my case ReSharper and .NET Reflector Pro ) then you can also add the /SafeMode argument to the command line.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2907614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35133/']}
jdg_376235
stackexchange
llm_judgeable_groundtruth_similarity
49984134
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 wonder the count operation in mongodb for large collection. When I do db.collection.count() without any criteria in a collection with ten million rows, it just take no more than 100ms. Why so fast, is it just read from the stat value of db.collection.stats().count ? Now provide the response and nothing else.
A count() without a query predicate is a fast/estimated count read from the collection statistics, so should return in constant time regardless of the total number of documents. This is the same value returned by db.collection.stats().count and the $collStats aggregation stage (MongoDB 3.6+). Note: with the WiredTiger storage engine, collection statistics are persisted periodically and may not be accurate after unclean shutdown . A count() with query criteria will provide a more accurate result, but will need to iterate a suitable index (or perform a collection scan if there are no candidate indexes). You can confirm the query planning outcome by reviewing the explain() output for a count. The winning plan for a fast count only has a COUNT stage: > db.zipcodes.explain().count().queryPlanner.winningPlan{ "stage" : "COUNT" } The winning plan for a count using an index will have a COUNT_SCAN input stage: > db.zipcodes.explain().count({city:'Sydney'}).queryPlanner.winningPlan{ "stage" : "COUNT", "inputStage" : { "stage" : "COUNT_SCAN", "keyPattern" : { "city" : 1 }, "indexName" : "city_1", "isMultiKey" : false, "multiKeyPaths" : { "city" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "indexBounds" : { "startKey" : { "city" : "Sydney" }, "startKeyInclusive" : true, "endKey" : { "city" : "Sydney" }, "endKeyInclusive" : true } }} The winning plan for a count requiring a collection scan will have a COLLSCAN input stage: > db.zipcodes.explain().count({cityx:'Sydney'}).queryPlanner.winningPlan{ "stage" : "COUNT", "inputStage" : { "stage" : "COLLSCAN", "filter" : { "cityx" : { "$eq" : "Sydney" } }, "direction" : "forward" }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49984134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3630822/']}
jdg_376236
stackexchange
llm_judgeable_groundtruth_similarity
26213998
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 Sdk is on Android studio.I tried to select this repository in eclipse: /applications/Android Studio.app/sdk , but i haven't the effects that i hoped.How can i do this? Now provide the response and nothing else.
Get the public key from the client phone (adb host) cat /data/.android/adbkey.pub copy the above public key to the target phone's /data/misc/adb/adb_keys location. (you may need to stop the adb daemon first with stop adbd ) cat /data/misc/adb/adb_keys verify both cat outputs match. try restarting adb daemon on target start adbd or just reboot them. If you are having problems reading or writing to ADB KEYS in above steps, try setting environment variable ADB_KEYS_PATH with a temporary path (eg: /data/local/tmp ). Refer to that link it goes into more details "On the host, the user public/private key pair is automatically generated, if it does not exist, when the adb daemon starts and is stored in $HOME/.android/adb_key(.pub) or in $ANDROID_SDK_HOME on windows. If needed, the ADB_KEYS_PATH env variable may be set to a :-separated (; under Windows) list of private keys, e.g. company-wide or vendor keys. On the device, vendors public keys are installed at build time in /adb_keys. User-installed keys are stored in /data/misc/adb/adb_keys"
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26213998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4067311/']}
jdg_376237
stackexchange
llm_judgeable_groundtruth_similarity
10079
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm curious as to why dual-slope analog to digital converters are used in most digital voltmeters, like one of these when a delta-sigma converter like one of these easily exceeds the specifications of any of the other dual-slope converters sold by Microchip, and in fact many other suppliers, especially given the low price point of the chip (about $4 in low quantities.) Is there a reason I am missing? Now provide the response and nothing else.
With a dual-slope ADC you effectively get free averaging as the run-up integration phase will have this effect. The output is also extremely simple, just a pulse that needs to be timed which can be done with even the simplest micro controllers. $4 is a really big deal when your making 50,000 of something and trying to sell it for $50. The dual-slope part you linked is $1.64 in a PDIP for 5000+. The sigma-delta's cheapest package is $2.88 in its cheapest package. Saving ~$1.20 on a single part AND being able to use a more basic microcontroller is a big cost win. I think you'll find the more expensive multimeters do use higher end ADCs.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/10079', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1225/']}
jdg_376238
stackexchange
llm_judgeable_groundtruth_similarity
821341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can add an attribute to items in a RadioButtonList item like so: PaymentMethodDropDownList.Items[0].Attributes.Add("onclick", "javascript:showNoMethods();");PaymentMethodDropDownList.Items[1].Attributes.Add("onclick", "javascript:showCreditCardMethod();");PaymentMethodDropDownList.Items[2].Attributes.Add("onclick", "javascript:showSendPaymentMethod();"); However, when I try to add the attributes to a DropDownList control it doesn't seem to work. I would expect it to be similar. Now provide the response and nothing else.
This cannot be done in the same way as a radioButtonList, for a dropdownlist, the correct attribute event name is "onchange" instead of "onclick".The event should be attached to DropDownList Itself and not the items as follows: PaymentMethodDropDownList.Attributes.Add("onchange", "showCreditCardMethod();"); Also, this is a little bit more complicated and requires a custom javascript function to perform a different action depending on the option selected. Here's an example: PaymentMethodDropDownList.Attributes.Add("onchange", "handleDropDownEvents(this);"); Custom Javascript function: this assumes that values for the dropdown items are "CreditCard" and "SendPayment". <script type="text/javascript"> function handleDropDownEvents(e){ if(e.value == "CreditCard"){ showCreditCardMethod(); } else if(e.value == "SendPayment"){ showSendPaymentMethod(); } }</script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/821341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/86191/']}
jdg_376239
stackexchange
llm_judgeable_groundtruth_similarity
7697640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been developing a gui for some time, which requires the creation of common control objects that Mathematica lacks (e.g. spinner, treeview, openerbar, etc.). One is the multipanel, i.e. a pane object that is split into two (or more) subpanes, where the divider can be set by the mouse. Here is my version of a dual pane. I would like to hear your opinion and ideas about how to expand it to handle not just 2 but any number of subpanes, and also how to optimize it. At present, for heavily loaded subpanes, it lags terribly, no idea why. Options[SplitPane] = {Direction -> "Vertical", DividerWidth -> Automatic, Paneled -> {True, True}};SplitPane[opts___?OptionQ] := Module[{dummy}, SplitPane[Dynamic[dummy], opts]];SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];SplitPane[val_, content_, opts___?OptionQ] := SplitPane[val, content, {100, 50}, opts];SplitPane[Dynamic[split_, arg___], {expr1_, expr2_}, {maxX_, maxY_}, opts___?OptionQ] := DynamicModule[{temp, dir, d, panel, coord, max, fix, val}, {dir, d, panel} = {Direction, DividerWidth, Paneled} /. {opts} /. Options[SplitPane]; dir = dir /. {Bottom | Top | "Vertical" -> "Vertical", _ -> "Horizontal"}; d = d /. Automatic -> 2; split = If[NumberQ[split], split, max/2]; val = Clip[split /. {_?NumberQ -> split, _ -> maxX/2}, {0, maxX}]; {coord, max, fix} = Switch[dir, "Vertical", {First, maxX, maxY}, "Horizontal", {(max - Last[#]) &, maxY, maxX}]; panel = (# /. {None | False -> Identity, _ -> (Panel[#, ImageMargins -> 0, FrameMargins -> -1] &)}) & /@ panel; Grid[If[dir === "Vertical", {{ Dynamic[ panel[[1]]@ Pane[expr1, ImageSize -> {split - d, fix}, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, AppearanceElements -> None], TrackedSymbols :> {split}], Deploy@EventHandler[ MouseAppearance[ Pane[Null, ImageSize -> {d*2, fix}, ImageMargins -> -1, FrameMargins -> -1], "FrameLRResize"], "MouseDown" :> (temp = coord@MousePosition@"CellContentsAbsolute"; split = If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, split]), "MouseDragged" :> (temp = coord@MousePosition@"CellContentsAbsolute"; split = If[0 <= temp <= max, temp, split])], Dynamic@ panel[[2]]@ Pane[expr2, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, AppearanceElements -> None, ImageSize -> {max - split - d, fix}] }}, { List@ Dynamic[panel[[1]]@ Pane[expr1, ImageSize -> {fix, split - d}, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, AppearanceElements -> None], TrackedSymbols :> {split}], List@Deploy@EventHandler[ MouseAppearance[ Pane[Null, ImageSize -> {fix, d*2}, ImageMargins -> -1, FrameMargins -> -1], "FrameTBResize"], "MouseDown" :> (temp = coord@MousePosition@"CellContentsAbsolute"; split = If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, split]), "MouseDragged" :> (temp = coord@MousePosition@"CellContentsAbsolute"; split = If[0 <= temp <= max, temp, split])], List@ Dynamic[panel[[2]]@ Pane[expr2, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, ImageSize -> {fix, max - split - d}, AppearanceElements -> None], TrackedSymbols :> {split}] } ], Spacings -> {0, -.1}] ];SplitPane[val_, arg___] /; NumberQ[val] := Module[{x = val}, SplitPane[Dynamic[x], arg]];pos = 300;SplitPane[ Dynamic[pos], {Manipulate[ Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], Factorial[123]}, {500, 300}] Now provide the response and nothing else.
The key to generalizing to several panels was to refactor your code. In its present form, while very nice, it was mixing visualization / UI primitives and options with the split logic, and had lots of duplicate code. This made generalization hard. Here is the refactored version: ClearAll[SplitPane];Options[SplitPane] = { Direction -> "Vertical", DividerWidth -> Automatic, Paneled -> True};SplitPane[opts___?OptionQ] := Module[{dummy}, SplitPane[Dynamic[dummy], opts]];SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];SplitPane[val_, content_, opts___?OptionQ] := SplitPane[val, content, {100, 50}, opts];SplitPane[sp_List, {cont__}, {maxX_, maxY_}, opts___?OptionQ] /; Length[sp] == Length[Hold[cont]] - 1 := Module[{scrollablePane, dividerPane, onMouseDownCode, onMouseDraggedCode, dynPane, gridArg, split, divider, panel}, With[{paneled = Paneled /. {opts} /. Options[SplitPane],len = Length[Hold[cont]]}, Which[ TrueQ[paneled ], panel = Table[True, {len}], MatchQ[paneled, {Repeated[(True | False), {len}]}], panel = paneled, True, Message[SplitPane::badopt]; Return[$Failed, Module] ] ]; DynamicModule[{temp, dir, d, coord, max, fix, val}, {dir, d} = {Direction, DividerWidth}/.{opts}/.Options[SplitPane]; dir = dir /. { Bottom | Top | "Vertical" -> "Vertical", _ -> "Horizontal" }; d = d /. Automatic -> 2; val = Clip[sp /. {_?NumberQ -> sp, _ -> maxX/2}, {0, maxX}]; {coord, max, fix} = Switch[dir, "Vertical", {First, maxX, maxY}, "Horizontal", {(max - Last[#]) &, maxY, maxX} ]; Do[split[i] = sp[[i]], {i, 1, Length[sp]}]; split[Length[sp] + 1] = max - Total[sp] - 2*d*Length[sp]; panel = (# /. { None | False -> Identity, _ -> (Panel[#, ImageMargins -> 0,FrameMargins -> -1] &) }) & /@ panel; scrollablePane[args___] := Pane[args, ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, AppearanceElements -> None]; dividerPane[size : {_, _}] := Pane[Null, ImageSize -> size, ImageMargins -> -1,FrameMargins -> -1]; onMouseDownCode[n_] := Module[{old}, temp = coord@MousePosition@"CellContentsAbsolute"; If[Abs[temp - split[n]] <= d \[And] 0 <= temp <= max, old = split[n]; split[n] = temp-Sum[split[i], {i, n - 1}]; split[n + 1] += old - split[n]; ]]; onMouseDraggedCode[n_] := Module[{old}, temp = coord@MousePosition@"CellContentsAbsolute"; If[0 <= temp <= max, old = split[n]; split[n] = temp -Sum[split[i], {i, n - 1}]; split[n + 1] += old - split[n]; ] ; ]; SetAttributes[dynPane, HoldFirst]; dynPane[expr_, n_, size_] := panel[[n]]@scrollablePane[expr, ImageSize -> size]; divider[n_, sizediv_, resizeType_] := Deploy@EventHandler[ MouseAppearance[dividerPane[sizediv], resizeType], "MouseDown" :> onMouseDownCode[n], "MouseDragged" :> onMouseDraggedCode[n] ]; SetAttributes[gridArg, HoldAll]; gridArg[{content__}, sizediv_, resizeType_, sizeF_] := Module[{myHold, len = Length[Hold[content]] }, SetAttributes[myHold, HoldAll]; List @@ Map[ Dynamic, Apply[Hold, MapThread[Compose, { Range[len] /. { len :> Function[ exp, myHold[dynPane[exp, len, sizeF[len]]], HoldAll ], n_Integer :> Function[exp, myHold[dynPane[exp, n, sizeF[n]], divider[n, sizediv, resizeType] ], HoldAll] }, Unevaluated /@ Unevaluated[{content}] }] (* MapThread *) ] /. myHold[x__] :> x ] (* Map *) ]; (* Module *) (* Output *) Grid[ If[dir === "Vertical", List@ gridArg[{cont}, {d*2, fix},"FrameLRResize",{split[#] - d, fix} &], (* else *) List /@ gridArg[{cont}, {fix, d*2},"FrameTBResize", {fix, split[#] - d} &] ], Spacings -> {0, -.1}]]];SplitPane[val_, arg___] /; NumberQ[val] := Module[{x = val}, SplitPane[Dynamic[x], arg]]; Here is how it may look: SplitPane[{300, 300}, { Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], Factorial[123], CompleteGraph[5] }, {900, 300}] Can't comment of performance problems you mentioned. Also, when you start dragging with the mouse, the real cursor position is often quite off with respect to the divider position. This is both for your and my versions, perhaps some more precise scaling is needed. Just want to emphasize once again - generalization became only possible after I did the refactoring, to separate the splitting logic from the visualization-related things. As to the optimization, I also think that it will be much easier to attempt optimizing this version than the original one, for the same reasons. EDIT I hesitated a bit to add this note, but it must be mentioned that my solution above, while working, shows one practice which is considered bad by expert UI mma programmers. Namely, it uses Module - generated variables inside Dynamic inner to that Module (in particular, split in the code above, also various auxiliary functions). The reasons I used it are that I wasn't able to make this work with only DynamicModule - generated variables, plus Module - generated variables always worked for me before. However, please see the post by John Fultz in this MathGroup thread, where he states that this practice should be avoided.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7697640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712498/']}
jdg_376240