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
23836846
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I had an issue where my db scheme change wasn't being reflected on Heroku PG. I double checked to see that both migration and seed succeeded. What was even weirder was that the db scheme change worked fine on a staging heroku deployment (after the exact same migration/seed). After some searching around, I learned that you are supposed to restart heroku after migrations via: heroku restart --app=app_name I've never had to do this (I'm not exactly a veteran, but I've run a good amount of migrations before and have never had to restart heroku for this particular reason). Do I actually need to be restarting heroku after each migration? Or is this more of a case by case thing? Now provide the response and nothing else.
If you make changes to your DB via migrations then you will need to restart the application on Heroku. When Rails starts in production mode it caches the DB schema. Migrations run in one off processes which the running web process is not aware of. So for it to pick up the changes you need to restart at least your web processes. If your application was idling when you deployed and you ran the migrations it would pick up the new schema as the app started.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23836846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1497315/']}
jdg_379341
stackexchange
llm_judgeable_groundtruth_similarity
45989148
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to keep a Grpc server running as a console daemon. This gRPC server is a microservice that runs in a docker container. All of the examples I can find make use of the following: Console.ReadKey(); This does indeed block the main thread and keeps it running but does not work in docker with the following error: "Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read." Now I could probably try to find a workaround for docker specifically, but this still doesn't feel right. Does anyone know of a good "production ready" way to keep the service running? Now provide the response and nothing else.
You can now use Microsoft.Extensions.Hosting pacakge which is a hosting and startup infrastructures for both asp.net core and console application. Like asp.net core, you can use the HostBuilder API to start building gRPC host and setting it up. The following code is to get a console application that keeps running until it is stopped (for example using Control-C): using System;using System.Threading.Tasks;using Microsoft.Extensions.Hosting;public class Program{ public static async Task Main(string[] args) { var hostBuilder = new HostBuilder(); // register your configuration and services. .... await hostBuilder.RunConsoleAsync(); }} In order to run the gRPC service, you need to start/stop Grpc.Core.Server in a hosted service. A hosted service is basically a piece of code that is run by the host when the host itself is started and the same for when it is stopped. This is represented in the IHostedService interface. That's to say, implement a GrpcHostedService to override the interface: using System.Threading;using System.Threading.Tasks;using Grpc.Core;using Microsoft.Extensions.Hosting;namespace Grpc.Host{ public class GrpcHostedService: IHostedService { private Server _server; public GrpcHostedService(Server server) { _server = server; } public Task StartAsync(CancellationToken cancellationToken) { _server.Start(); return Task.CompletedTask; } public async Task StopAsync(CancellationToken cancellationToken) => await _server.ShutdownAsync(); }} It's simple really. We get an GrpcHostedService instance injected through dependency injection and run StartAsync on it when host is started. When the host is stopped we run StopAsync so that we can gracefully shut everything down including Grpc server. Then go back to the Program.cs and make some changes: public class Program{ public static async Task Main(string[] args) { var hostBuilder = new HostBuilder() // Add configuration, logging, ... .ConfigureServices((hostContext, services) => { // Better to use Dependency Injection for GreeterImpl Server server = new Server { Services = {Greeter.BindService(new GreeterImpl())}, Ports = {new ServerPort("localhost", 5000, ServerCredentials.Insecure)} }; services.AddSingleton<Server>(server); services.AddSingleton<IHostedService, GrpcHostedService>(); }); await hostBuilder.RunConsoleAsync(); }} By doing this, the generic host will automatically run StartAsync on our hosted service, which in turn will call StartAsync on the Server instance, essentially start the gRPC server. When we shut down the host with Control-C, the generic host will automatically call StopAsync on our hosted service, which again will call StopAsync on the Server instance which will do some clean up. For other configuration in HostBuilder, you can see this blog .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45989148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1475874/']}
jdg_379342
stackexchange
llm_judgeable_groundtruth_similarity
27689220
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 came across varargs while learning android( doInBackground(Type... params) ) , SO posts clarified the use of it My question is why can't we just use Arrays instead of varargs public void foo(String...strings) { } I can replace this type of a call by packing my variable number of arguments in an array and passing it to a method such as this public void foo(String[] alternativeWay){ } Also does main(String[] args) in java use varargs , if not how are we able to pass runtime parameters to it Please suggest the benefits or use of varargs and is there there anything else important to know about varargs Now provide the response and nothing else.
The only difference between foo(String... strings) and foo(String[] strings) is for the calling code. Consider this call: foo("a", "b"); That's valid with the first declaration of foo , and the compiler will emit code to create an array containing references to "a" and "b" at execution time. It's not valid with the second declaration of foo though, because that doesn't use varargs. In either case, it's fine for the caller to explicitly create the array: for(new String[] { "a", "b" }); // Valid for either declaration Also does main(String[] args) in java use varargs , if not how are we able to pass runtime parameters to it When it's written as main(String[] args) it doesn't; if you write main(String... args) then it does. It's irrelevant to how the JVM treats it though, because the JVM initialization creates an array with the command line arguments . It would only make a difference if you were writing your own code to invoke main explicitly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27689220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3725998/']}
jdg_379343
stackexchange
llm_judgeable_groundtruth_similarity
8765605
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 form in Django that looks like this class FooForm(forms.ModelForm): foo_field = forms.ModelChoiceField(widget=FooWidget(def_arg=self.data)) Where I call self.data , Python throws the exception name 'self' is not defined . How can I access self there? Now provide the response and nothing else.
As others have answered, there is no self to refer to at that point. Something like this does work though: class FooForm(forms.ModelForm): foo_field = forms.ModelChoiceField() def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) self.fields['foo_field'].initial = self.data You can also access the widget in __init__ through self.fields['foo_field'].widget
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8765605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272096/']}
jdg_379344
stackexchange
llm_judgeable_groundtruth_similarity
13239040
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 hibernate to insert to a mysql table on which all columns are defined as not null. It has a unique primary key and another unique index on several columns. I'm getting the following error: org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into MY_TABLE(col1, col2, col3, col4, ID_) values (?, ?, ?, ?, ?)]; constraint [null] This error is in customer logs and I can't reproduce the problem myself, so I can't put in debugging to see what the values are in the insert statement. My understanding is that "constraint [null]" means a "not null" constraint is being violated. However, looking at my code, I cannot see any possible way that any of the data could be null at the time of the insert, unless hibernate is trying to insert a null ID (which would be a very bad bug in hibernate and so seems unlikely). However, I can see how it could happen that a unique constraint is being violated. Is it possible that the message is misleading and I'm actually getting a unique key violation? Does "constraint[null]" always mean a not null constraint was violated? Now provide the response and nothing else.
If you search for the callers of the constructor of DataIntegrityViolationException in the Spring source code, you'll find that it's called in org.springframework.orm.hibernate3.SessionFactoryUtils : return new DataIntegrityViolationException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]; constraint [" + jdbcEx.getConstraintName() + "]", ex); So the exception is caused by a violated constraint, and null is the name of the constraint as returned by the JDBC exception. So you should blame the MySQL driver for not populating the violated constraint name in the JDBC exception. But the violated constraint could be any constraint, and not necessarily a not null constraint.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13239040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1255843/']}
jdg_379345
stackexchange
llm_judgeable_groundtruth_similarity
3589065
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 to be able to group similar methods and have them appear in my Outline view in Eclipse. This makes navigating large swaths of code a little easier on the eye, and easier to find methods you need. In Objective-C there was a pragma mark command that you could set. Anything like that for java/eclipse? Now provide the response and nothing else.
I use the Coffee Bytes plugin for code folding, specifically configuring it for folding code that has start and end tags. Although the plugin is not downloadable off the page listed on the Google Code page, it has been recompiled against Eclipse 3.5 and made available elsewhere ; the version appears to work against Eclipse 3.6 and 3.7 as well. It is also available in the Yoxos marketplace . I use the following notation to group getters and setters of properties along with declaration of the property, although the same notation could be extended for your use. // {{ Idprivate String id;public String getId() { return id;}public void setId(final String id) { this.id = id;}// }} Configuration of the same needs to be done by setting appropriate preference in the code folding section available via Windows > Preferences > Java > Editor > Folding . Remember to choose Coffee Bytes Java Folding, and enable support for User Defined Regions. Although the support for grouping/folding is restricted to the editor, the natural order of the methods within the fold can be retain in the outline view. I'm afraid that I'm unaware of any grouping capabilities beyond this plug-in.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3589065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19875/']}
jdg_379346
stackexchange
llm_judgeable_groundtruth_similarity
27168
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Hi everybody!!I am studing cohomology of sheaves on schemes. I have a question for you. Let $X$ be a noetherian scheme. Do you know if the cathegory QCoh(X) has enough injectives? I know that it has "enough flasque" and that Mod(X) has enough injective but what about QCoh(X)?Thank you Now provide the response and nothing else.
First of all, let me quote the famous paper by Grothendieck "Sur quelques points d'algebre homologique" (Tohoku Math part 1 & part 2 ). According to Theorem 1.10.1 there, every abelian category satisfying (AB5) (equivalent to exactness of filtered direct limits) and with a generator has enough injectives, For every scheme $X$ it is well known that $Qco(X)$ is abelian and satisfies (AB5), see, for instance, EGA I, new edition, Corollaire (2.2.2)(iv) where it is proved that such a limit preserves quasi-coherence. So, the only issue is the existence of a generator. For some time it was known that over a quasi-compact quasi-separated scheme, $Qco(X)$ has a generator. For a nice geometric argument, consult the proof of Theorem (4) in Kleiman's " Relative duality for quasi-coherent sheaves ". Note that any noetherian scheme $X$ is quasi-compact and quasi-separated, EGA I, (6.1.1) and (6.1.13). Surprisingly, using techniques from relative homological algebra, Enochs and Estrada proved in 2005 the existence of a generator for any scheme. See their paper " Relative homological algebra in the category of quasi-coherent sheaves ". (There was a previous unpublished proof by O. Gabber). Summing up, for any scheme $X$, the category $Qco(X)$ has enough injectives.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/27168', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6571/']}
jdg_379347
stackexchange
llm_judgeable_groundtruth_similarity
16094679
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 <DataGridCheckBoxColumn Binding="{Binding Path=Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> And public bool Foo{ get; set; } Checking/Unchecking sets Foo , but setting Foo in code does not change the Checkbox state. Any Suggesitons? Now provide the response and nothing else.
You need to raise the PropertyChanged event when you set Foo in your DataContext . Normally, it would look something like: public class ViewModel : INotifyPropertyChanged{ private bool _foo; public bool Foo { get { return _foo; } set { _foo = value; OnPropertyChanged("Foo"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }} If you call Foo = someNewvalue , the PropertyChanged event will be raised and your UI should be updated
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16094679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/608667/']}
jdg_379348
stackexchange
llm_judgeable_groundtruth_similarity
31912000
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While trying to parse json string to android, HTML values are passed.Before a day all was working good, and suddenly my app start crashing when trying to fetch database with the help of php files. When I checked noticed that html values..see logcat 08-10 01:09:55.814: E/result(6744): <html><body><h2>Checking your browser..<h2><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("7965e114a1dccaf35af3756261f75ad8");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://realroom.byethost24.com/medical/stokist.php?ckattempt=1";</script></body></html>08-10 01:09:55.814: E/JSON Parser(6744): Error parsing data org.json.JSONException: Value <html><body><h2>Checking of type java.lang.String cannot be converted to JSONObject08-10 01:09:55.816: E/AndroidRuntime(6744): FATAL EXCEPTION: AsyncTask #108-10 01:09:55.816: E/AndroidRuntime(6744): Process: com.example.medionline, PID: 674408-10 01:09:55.816: E/AndroidRuntime(6744): java.lang.RuntimeException: An error occured while executing doInBackground()08-10 01:09:55.816: E/AndroidRuntime(6744): at android.os.AsyncTask$3.done(AsyncTask.java:304)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.FutureTask.run(FutureTask.java:242)08-10 01:09:55.816: E/AndroidRuntime(6744): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.lang.Thread.run(Thread.java:818)08-10 01:09:55.816: E/AndroidRuntime(6744): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference08-10 01:09:55.816: E/AndroidRuntime(6744): at com.example.medionline.All_supplier_list$FetchMFG.doInBackground(All_supplier_list.java:182)08-10 01:09:55.816: E/AndroidRuntime(6744): at com.example.medionline.All_supplier_list$FetchMFG.doInBackground(All_supplier_list.java:1)08-10 01:09:55.816: E/AndroidRuntime(6744): at android.os.AsyncTask$2.call(AsyncTask.java:292)08-10 01:09:55.816: E/AndroidRuntime(6744): at java.util.concurrent.FutureTask.run(FutureTask.java:237)08-10 01:09:55.816: E/AndroidRuntime(6744): ... 4 more This is happening to all the pages that I have hosted on byethost server, while the pages that are hosted on other server are working well and fine. I tried moving one of my file to other server and on that it is returning proper json string. Also when I check the url in browser it is returning proper json string without any exception or error with byethost.. but in android giving html values.. Here's my JSONfunction class package com.example.medionline;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse; import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONException;import org.json.JSONObject;import android.util.Log;public class JSONfunctions{ static InputStream is = null; static String result = ""; static JSONObject jArray = null;public static JSONObject getJSONfromURL(String url) { // Download JSON data from URL try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 "); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { Log.e("jsonnnnnnn", line); sb.append(line + "\n"); } is.close(); result = sb.toString(); Log.e("result", result); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return jArray;}public static JSONObject makeHttpRequest(String loginUrl, String post, List<NameValuePair> para){ try { if(post == "POST") { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(loginUrl); httpPost.setEntity(new UrlEncodedFormEntity(para)); httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 "); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if(post == "GET") { HttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(para, "utf-8"); loginUrl += "?" + paramString; HttpGet httpGet = new HttpGet(loginUrl); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; if (is != null) { while ((line = reader.readLine()) != null) { //Log.e("jsonnnnnnn", line); sb.append(line + "\n"); } is.close(); result = sb.toString(); Log.e("result", result); } } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jArray;}} And this is my PHP file <?phpinclude('config.php');date_default_timezone_set("Asia/Calcutta");$result1 = mysqli_query($con,"SELECT * FROM `pj_medionline_mst_stockist` ORDER BY `pj_medionline_mst_stockist`.`ID` ASC ");$response = array();$posts = array();while($row=mysqli_fetch_array($result1)){ $id =$row["ID"]; $stkcode =$row["stkcode"]; $comName =$row["ComName"]; $operatorid =$row["operatorid"]; $password =$row["Password"]; $posts[] = array('id'=>$id, 'stkcode'=>$stkcode, 'stkname'=>$comName, 'operatorid'=>$operatorid, 'password'=>$password);}$response['stokist'] = $posts;print(json_encode($response));?> Now provide the response and nothing else.
Solved! I had the same issue using Byethost to retrieve JSON data from my PHP server. We just need to add a cookie to the HTTP request to pass the testcookie-nginx-module As Richard's answer says: The main problem is that Byet Host implement a simple security antibots module >named testcookie-nginx-module https://kyprizel.github.io/testcookie-nginx-module/ On the link he provided we can see that the testcookie-nginx-module makes a 2-steps validation: The first time that a HTTP request is done, the module returns a javascript instead of the JSON we are expecting. This script is executed on the client (tipically a web browser) and generates a validation cookie containing an AES key. Here's the script I've received form my server: <html><body> <script type="text/javascript" src="/aes.js" ></script> <script> function toNumbers(d){ var e=[]; d.replace(/(..)/g,function(d){ e.push(parseInt(d,16))}); return e } function toHex(){ for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++) e+=(16>d[f]?"0":"")+d[f].toString(16); return e.toLowerCase() } var a=toNumbers("f655ba9d09a112ffff8c63579db590b4"), b=toNumbers("98344c2eee86c3ffff90592585b49f80"), c=toNumbers("1286963467aa92ffff8323bdca0d7be9"); document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://myserver.byethost8.com/myPhpPage.php?i=1"; </script> <noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body> The script adds the validation cookie to the document and redirects it to the url we actually want to access. The testcookie-nginx-module validates the cookie AES key and and let the request hit the url that will response with the JSON data we want to access. On the following HTTP requests the client will have stored the cookie and will add it to the request skipping the step 1. Solution for our Android App We are going to skip the cookie generation by getting it from a web browser and add it directly to our Android HTTP request (Unless of course you want to get involved in generating it). Before you get the cookie from the web browser make sure you accessed the url at least once with the browser to generate it. Getting the cookie key from the web browser. I used Google Chrome for it: From the Chrome menu in the top right corner of the browser, select Settings . At the bottom of the page, click Show advanced settings... . Under Privacy, select Content settings... . select All cookies and site data... . Search for you website name. By searching "byethost" you'll find it. Open the cookie named __test and copy the values of content , path and expires Setting the cookie on our Android app. On your code should be something like: try { if(post == "POST") { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(loginUrl); httpPost.setEntity(new UrlEncodedFormEntity(para)); httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 "); httpPost.addHeader("Cookie", "__test=THE_CONTENT_OF_YOUR_COOKIE_HERE; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent();}else if(post == "GET"){ HttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(para, "utf-8"); loginUrl += "?" + paramString; HttpGet httpGet = new HttpGet(loginUrl); httpGet.addHeader("Cookie", "__test=THE_CONTENT_OF_YOUR_COOKIE_HERE; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent();}} And that's it. Now every time the app makes an HTTP request it will include the cookie to pass the testcookie-nginx-module and will be retrieving your JSON data. I hope this helps and is not too late. Regards
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31912000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4180170/']}
jdg_379349
stackexchange
llm_judgeable_groundtruth_similarity
23500481
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 question was asked for MySQL already, but for Transact-SQL, what is the default JOIN behaviour? That is, is simply writing JOIN in a query synonymous with writing INNER JOIN (as is the case with MySQL), or something else, like perhaps FULL OUTER JOIN ? Now provide the response and nothing else.
JOIN defaults to INNER JOIN behaviour. To verify this, I ran the following code: DECLARE @A TABLE (x INT)INSERT INTO @A SELECT 1 UNION ALL SELECT 2DECLARE @B TABLE (x INT)INSERT INTO @B SELECT 2 UNION ALL SELECT 3SELECT A.x AS 'A.x', B.x AS 'B.x'FROM @A AJOIN @B B ON A.x = B.x This produces just one row, consistent with INNER JOIN behaviour: A.x | B.x-----+-----2 | 2 Contrast this with a FULL OUTER JOIN : ...SELECT A.x AS 'A.x', B.x AS 'B.x'FROM @A AFULL OUTER JOIN @B B ON A.x = B.x This of course shows all three rows: A.x | B.x-----+-----1 | NULL2 | 2NULL | 3
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23500481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1832942/']}
jdg_379350
stackexchange
llm_judgeable_groundtruth_similarity
1362481
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If today is Wednesday, what day of the week will it be $100$ days from now?Going forward $1,8,15,\dots,92,99$ days all result in Wednesday. So the $100$th day will be Thursday. But the solution given by PASCAL contest of University of Waterloo says Friday. Can somebody explain please? Now provide the response and nothing else.
Today is Wednesday $1$ day from now it is Thursday. $2$ days from now it is Friday. $3$ days from now it is Saturday. $4$ days from now it is Sunday. $5$ days from now it is Monday. $6$ days from now it is Tuesday. $7$ days from now it is Wednesday. $14 = 7\cdot 2$ days from now it is Wednesday. ... $70 = 7\cdot 10$ days from now it is Wednesday. ... $98 = 7\cdot 14$ days from now it is Wednesday. $99 = 7\cdot 14 + 1$ days from now it is Thursday. $100 = 7\cdot 14 + 2$ days from now it is Friday.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1362481', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/124537/']}
jdg_379351
stackexchange
llm_judgeable_groundtruth_similarity
48830316
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 ReactJS component contains an iframe. In response to an event in the outer page, I need to reload the iframe. If the user has navigated to another page in the iframe, I need to reset it to the URL that it had when I first loaded the page. This URL is available in this.props . I've tried using forceUpdate() . I can see that this causes the render method to run, but the iframe doesn't get reset - presumably because React can't tell that anything has changed. At the moment I'm appending some random text to the iframe's querystring: this URL change forces React to re-render the iframe. However this feels a bit dirty: the page within the iframe is beyond my control so who knows what this extra querystring value might do? resetIframe() { console.log("==== resetIframe ===="); this.forceUpdate();}public render() { console.log("==== render ===="); // How can I use just this.props.myUrl, without the Math.random()? let iframeUrl = this.props.myUrl + '&random=' + Math.random().toString(); return <div> <button onClick={() => { this.resetIframe(); }}>Reset</button> <iframe src={iframeUrl}></iframe> </div>} (I'm using TypeScript too, if that makes a difference.) Now provide the response and nothing else.
I'd create a state variable with the random, and just update it on resetIframe : state = { random: 0}resetIframe() { this.setState({random: this.state.random + 1});}public render() { return <div> <button onClick={() => { this.resetIframe(); }}>Reset</button> <iframe key={this.state.random} src={this.props.myUrl}></iframe> </div>} Here is a fiddle working: https://codesandbox.io/s/pp3n7wnzvx
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48830316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15825/']}
jdg_379352
stackexchange
llm_judgeable_groundtruth_similarity
4014036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider two extension methods: public static T MyExtension<T>(this T o) where T:classpublic static T MyExtension<T>(this T o) where T:struct And a class: class MyClass() { ... } Now call the extension method on a instance of the above class: var o = new MyClass(...);o.MyExtension(); //compiler error here..o.MyExtension<MyClass>(); //tried this as well - still compiler error.. The compiler says that calling the method is an ambiguous call when I call it on a class. I would have thought that it could determine which extension method to call, as MyClass is a class, not a struct? Now provide the response and nothing else.
EDIT: I've now blogged about this in more detail. My original (and I now believe incorrect) thought: generic constraints aren't taken into account during the overload resolution and type inference phases - they're only used to validate the result of the overload resolution. EDIT: Okay, after a lot of going round on this, I think I'm there. Basically my first thought was almost correct. Generic type constraints only act to remove methods from a candidate set in a very limited set of circumstances... in particular, only when the type of a parameter itself is generic; not just a type parameter, but a generic type which uses a generic type parameter. At that point, it's the constraints on the type parameters of the generic type which are validated, not the constraints on the type parameters of the generic method you're calling. For example: // Constraint won't be considered when building the candidate setvoid Foo<T>(T value) where T : struct// The constraint *we express* won't be considered when building the candidate// set, but then constraint on Nullable<T> willvoid Foo<T>(Nullable<T> value) where T : struct So if you try to call Foo<object>(null) the above method won't be part of the candidate set, because Nullable<object> value fails to satisfy the constraints of Nullable<T> . If there are any other applicable methods, the call could still succeed. Now in the case above, the constraints are exactly the same... but they needn't be. For example, consider: class Factory<TItem> where TItem : new()void Foo<T>(Factory<T> factory) where T : struct If you try to call Foo<object>(null) , the method will still be part of the candidate set - because when TItem is object , the constraint expressed in Factory<TItem> still holds, and that's what's checked when building up the candidate set. If this turns out to be the best method, it will then fail validation later, near the end of 7.6.5.1: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints (§4.4.4) declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on the type parameter, a binding-time error occurs. Eric's blog post contains more detail on this.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4014036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77318/']}
jdg_379353
stackexchange
llm_judgeable_groundtruth_similarity
2180181
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the value of $\sum_{k=1}^{n}k\binom{n}{k}$ ? I know that $\sum_{k=0}^{n}\binom{n}{k}= 2^{n}$ and so, $\sum_{k=1}^{n}\binom{n}{k}= 2^{n}-1$ but how to deal with $k$ ? Now provide the response and nothing else.
From the binomial theorem, we have $$(1+x)^n=\sum_{k=0}^n\binom{n}{k}x^k\tag 1$$ Differentiating $(1)$ reveals $$n(1+x)^{n-1}=\sum_{k=0}^n\binom{n}{k}kx^{k-1}\tag2$$ Setting $x=1$ in $(2)$ yields $$n2^{n-1}=\sum_{k=0}^n\binom{n}{k}k$$ And we are done! Interestingly, I showed in THIS ANSWER , that for $m<n$, we have $$\sum_{k=0}^n\binom{n}{k}(-1)^k k^m=0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2180181', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/382333/']}
jdg_379354
stackexchange
llm_judgeable_groundtruth_similarity
47714
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 didn't know how to phrase the question properly so I am going to explain how this came about. I know Math is a very rigorous subject and there are proofs for everything we know and use. In fact, I am sure that if there was anything that we couldn't prove Mathematically, then we wouldn't use it any where in Math or Science. Anyway, here is the story:Not to long ago I was having a conversation with someone who insisted in telling me that any human knowledge based on Math is a sham, this of course includes Science. He then proceed to tell me that he thought this was the case because according to him there is no proof that zero is a number and second he insisted even if we were to say that zero is a number, that there is no proof that the distance from 0 to 1 is the same as the distance from 1 to 2. According to this guy, there is no way to measure the distance from something that doesn't exist to something that does. If I understood him correctly he said that is because he just can't see how we can measure from non-existence to something that does exist. In this case, he said that there is now way to know for sure that the length or distance from zero or non-existent number to one would be the same as the distance or length from 1 to 2. No matter what I said to him, he just disregarded offhandedly. I am so upset that I want to punch him in the face, but I would rather get the proofs and show him that he is completely wrong. To me this would be the equivalent of slapping him on the face with a gauntlet and I would have the satisfaction of knowing that Math and Science are in solid ground and that Mathematicians and/or Scientist haven't pulled a fast one on us. So please post links to where I can read the Mathematical Proofs for these. Or links that show that to be a fallacy. Thanks. The question was, is there a place where I can get proofs for both of those things. First, for Zero being a number whether an integer, complex or any other kind. And second, for a proof that would show that the distance from 0 to 1 is equal to the distance from 1 to 2. But I guess what I should really have asked is whether or not these proof exist and where I can find them. Now provide the response and nothing else.
I am so upset that I want to punch him in the face This would be an understandable (although inadvisable) reaction. Here are a few responses I recommend you give to him: "Define what you mean by 'exists'." "Define what you mean by '1'." "Define what you mean by 'distance'." "Prove that 1 exists." "Prove that the distance from 1 to 2 is 1." "What is the distance from 1 to 1?" These questions are designed to get him a) actually thinking about what he's saying, and b) quiet. In response to "Define what you mean by '1'" and "Prove that 1 exists", he will undoubtedly point to "one rock" or "one bird" or "one airplane", etc., and then you can respond,"Ah, but those are all one of something . I am talking about the number 1." Here is where he will be a bit confused. The number 1 is a human abstraction from our experiences with one < object >, but it does not exist as a physical object. Here is my favorite quote regarding this (from Linear Algebra by Fraleigh and Beauregard): "Numbers exist only in our minds. There is no physical entity that is the number 1. If there were, 1 would be in a place of honor in some great museum of science, and past it would file a steady stream of mathematicians gazing at 1 in wonder and awe." There are several fundamental issues that your adversary is missing: Firstly, there is no agreed-upon definition of what it means for something to be a "number" . If someone said "I am only going to call even integers "numbers", the odd integers don't count", they are just as correct as someone who calls every mathematical construction humans have ever come up with a "number". Mathematicians have decided on definitions of "integer", "complex number", etc., and the statements that "0 is an integer" or " $\sqrt{2}$ is not an integer" are true because "integer" actually means something. The word "number" is a vague word that has no mathematical content. Secondly, mathematics is a human construction : "The mathematician is entirely free, within the limits of his imagination, to construct what worlds he pleases. What he is to imagine is a matter for his own caprice; he is not thereby discovering the fundamental principles of the universe nor becoming acquainted with the ideas of God." - John William Navin Sullivan "Mathematics is a game played according to certain rules with meaningless marks on paper." - David Hilbert "[Mathematics] is an independent world/ Created out of pure intelligence." - William Wordsworth So, what "exists" and what "doesn't exist" depends entirely on what we've set up for ourselves. Mathematicians pick a certain set of axioms, then follow them to logical conclusions. It makes no sense to say, separate from a previous decision about what axioms we're using , that "0 doesn't exist". Only after you've decided what axioms you are using, and what exactly it is that would characterize the object "0", can you decide whether your system includes such an object. If you really want to get at him, here is a recommendation: Tell him, "I am going to prove directly to you that 0 exists." For several seconds, pretend to be deep in thought, trying to remember the details of the proof. Surely he will look on with anticipation, eager to attack whatever you are going to present. Then, appear to have recalled the key step, and very slowly and deliberately draw a massive "0" taking up the entire piece of paper. Look extremely pleased with yourself, as if you had made a difficult and convoluted argument. The fact is, that is exactly what "0", or indeed anything in mathematics, is: a symbol we write down . What "0" means in mathematics can vary widely; perhaps it is the zero element of $\mathbb{Z}$ (the integers), or the function from $\mathbb{R}$ (the real numbers) to $\mathbb{R}$ that is the constant 0 function. Within a given context , e.g. specific axioms and structures, it makes sense to decide what properties an object you want to call the symbol "0" might have (for example, if there is a notion of "addition", you would probably ask for an object "0" to satisfy " $a+0=a$ " for all objects $a$ ), and then, having decided what "0" should refer to if it did exist, actually find out whether it does, within your axioms / structures. But without deciding what "0" means beforehand (and remember, 0 isn't something like "no airplanes", since physical objects are irrelevant), all "0" means is the symbol 0, and it is quite easy to prove that that exists - just draw it! Of course, this won't be satisfying to your adversary at all, but I guess I'm just trying to think of ways you can get your just revenge by making equally absurd arguments :) Good luck confronting him, perhaps comment back to let us know how it goes!
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/47714', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12581/']}
jdg_379355
stackexchange
llm_judgeable_groundtruth_similarity
29980
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Below is a figure from a TIME magazine edition. I have a few questions regarding this representation of quantum computing: Is saying "0 and 1 at the same time" a correct statement? Isn't the qubit just in a superposition of both states, not "both at the same time"? It is ultimately either 0 or 1 once observed, and it has a certain probability of being 0 or 1 once observed. Is it ever "0 and 1 at the same time"? "Perform multiple operations simultaneously" seems to imply that the benefit of quantum computers comes from their ability to do computations in paralell. How accurate is that statement? Are computations happening in parallel? Now provide the response and nothing else.
This figure is not accurate at all about quantum computers. This "try-every-case" thing is the standard boilerplate everyone puts in their popsci articles. But it's not at all how quantum algorithms work, it doesn't give any sense of what quantum computers are actually good at, and it doesn't give any sense of what they're not good at. The way quantum computers do things like factor numbers is nothing at all like trying all the answers. It's quite frustrating; Scott Aaronson puts this in the header of his blog https://scottaaronson.blog/ because it's such a widespread misconception.
{}
{'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/29980', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/20941/']}
jdg_379356
stackexchange
llm_judgeable_groundtruth_similarity
31733
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to fix a large .bib file where all proper names are in ALL CAPITALS (thanks ProQuest!) Is there an elisp function that searches a buffer/region for words in all capitals and turns all characters except the first one into lowercase letters? E.g. DOE, JOHN --> Doe, John I found a couple of functions on Xah Lee's excellent site that work on cases ( Toggle cases , Title cases ), but I don't know enough elisp to turn either of them into what I need. Now provide the response and nothing else.
How about using keyboard macros: <f3> -- start recording C-M-s \b[A-Z]\{2,\}\b RET -- find the next word of only upper-case letters and at least 2 letters. M-- M-c -- Call capitalize-word on the word before point M-0 <f4> -- Stop recording and run the macro repeatedly until error n.b. If that's catching non-upper-case words as well, you'd need to set isearch-case-fold-search . Or more directly (and you could run this via M-: as a one-time thing, or make a new interactive function if you want to re-use it): (let ((case-fold-search nil)) (while (re-search-forward "\\b[A-Z]\\{2,\\}\\b" nil :noerror) (capitalize-word -1))) Regarding comments, some corner cases may well need custom attention, but Emacs does have you covered on the matter of diacritics, as we can simply use [[:upper:]] in place of [A-Z] . The following kind of modification might be worth trying to catch the other elements: (let ((case-fold-search nil) (pattern "\\(?:\\b\\|Ma?c\\|'\\)\\([[:upper:]]\\{2,\\}\\)\\b")) (while (re-search-forward pattern nil :noerror) (save-restriction (narrow-to-region (match-beginning 1) (match-end 1)) (capitalize-word -1)))) but perhaps it's good enough to simply relax the pattern to: "\\([[:upper:]]\\{2,\\}\\)\\b"
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/31733', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/15351/']}
jdg_379357
stackexchange
llm_judgeable_groundtruth_similarity
4515099
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 writing a C# winform application for an archiving system. The system has a huge database where some tables would have more than 1.5 million records. What i need is an algorithm that indexes the content of these records. Mainly, the files are Microsoft office, PDF and TXT documents. anyone can help? whether with ideas, links, books or codes, I appreciate it :) example: if i search for the word "international" in a certain folder in the database, i get all the files that contain that word ordered by a certain criteria such as relevance, modifying date...etc Now provide the response and nothing else.
You need to create, what is known as an inverted index - which is at the core of how search engines work (a la Google). Apache Lucene is arguably the best library for inverted indexing. You have 2 options: Lucene.net - a .NET port of the Java Lucene library. Apache Solr - a full-fledged search server built using Lucene libs and easily integrable into your .NET application because it has a RESTful API. Comes out-of-the-box with several features such as caching, scaling, spell-checking, etc. You can make life easier for your app-to-Solr interaction using the excellent SolrNet library. Apache Tika offers a very extensive data/metadata extraction toolkit working with PDFs, HTMLs, MS Office docs etc. A simpler option would be to the IFilter API. See this article for more details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4515099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420689/']}
jdg_379358
stackexchange
llm_judgeable_groundtruth_similarity
3391184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Friends How do I implement following complex logic? flag1 can be "N" or "A" or "I" flag2 can be "N" or "A" or "I" flag3 can be "N" or "A" or "I" function (string flag1, string flag2, string flag3)begin The function needs to return: return "None" if flag1, flag2 and flag3 are "N" else return "Active" if flag1, flag2 and flag3 are "A" else return "Inactive" if flag1, flag2 and flag3 are "I" else return "both" if flag1, flag2 and flag3 are either "A" AND "I" (OR "N") e.g. 1) flag1 is "A" and flag2 is "I" and flag3 is "I" e.g. 2) flag1 is "I" and flag2 is "A" and flag3 is "I" e.g. 2) flag1 is "A" and flag2 is "N" and flag3 is "I" retrun result end Thanks for reply but none of post gives answer. I know if else constrauct and looking for logic to implement above psedocode. All four are possibel conditions specially #4 is complex and need to know how to implement that. Now provide the response and nothing else.
Your logic for point 4 is confusing... I would use an enum value for this, rather than strings - it is much more type-safe (eg what if someone passed "WIBBLEWOBBLE" to your method? What should it return?) enum Value { None, Active, Inactive, Both }private Value GetValue(Value flag1, Value flag2, Value flag3) { if (flag1 == flag2 && flag2 == flag3) // they are all the same return flag1; else return Value.Both; // there is a difference}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3391184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408990/']}
jdg_379359
stackexchange
llm_judgeable_groundtruth_similarity
38675428
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 GitHub file browser lists a file's name and info about the last commit: Is there a way to add each file's size to these listings? Now provide the response and nothing else.
If there is no official way to do this, here is a bookmarklet which uses GitHub's API to add size info ( won't work in IE ): javascript:(function(){function f(a){var g=document.querySelector('div[role="rowheader"] a[title="'+a.name+'"]').closest('div[role="row"]').lastElementChild,c=document.createElement("div");c.style.width="5em";"file"===a.type&&(c.textContent=(a.size/1024).toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})+" KB",c.style.textAlign="right",c.style.whiteSpace="nowrap");g.insertAdjacentElement("beforebegin",c)}var b=window.location.pathname.split("/"),d=b[1],h=b[2],e=b[4];b=b.slice(5);d=["https://api.github.com/repos",d,h,"contents"].concat(b||[]).join("/")+(e?"?ref="+e:"");console.log(d);fetch(d).then(function(a){return a.json()}).then(function(a){return Array.isArray(a)?a.forEach(f):console.warn(a)})})(); Unminified source: (function () { "use strict"; //Parse the current GitHub repo url. Examples: // Repo root: /Sphinxxxx/vanilla-picker // Subfolder: /Sphinxxxx/vanilla-picker/tree/master/src/css // Subfolder at commit: /Sphinxxxx/vanilla-picker/tree/382231756aac75a49f046ccee1b04263196f9a22/src/css // Subfolder at tag: /Sphinxxxx/vanilla-picker/tree/v2.2.0/src/css // //If applicable, the name of the commit/branch/tag is always the 4th element in the url path. //Here, we put that in the "ref" variable: const [/* Leading slash */, owner, repo, /* "tree" */, ref, ...path] = window.location.pathname.split('/'); //Create the URL to query GitHub's API: https://developer.github.com/v3/repos/contents/#get-contents //Example: // https://api.github.com/repos/Sphinxxxx/vanilla-picker/contents/src/css?ref=382231756aac75a49f046ccee1b04263196f9a22 const query = ['https://api.github.com/repos', owner, repo, 'contents'].concat(path || []), url = query.join('/') + (ref ? '?ref=' + ref : ''); console.log(url); //https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch fetch(url).then(r => r.json()) .then(j => Array.isArray(j) ? j.forEach(handleFileInfo) : console.warn(j)); function handleFileInfo(info) { //console.log(info); const link = document.querySelector(`div[role="rowheader"] a[title="${info.name}"]`); const timeCol = link.closest('div[role="row"]').lastElementChild; const sizeCol = document.createElement('div'); sizeCol.style.width = '5em'; if(info.type === 'file') { //http://stackoverflow.com/a/17663871/1869660 //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Parameters sizeCol.textContent = (info.size/1024).toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' KB'; sizeCol.style.textAlign = 'right'; sizeCol.style.whiteSpace = 'nowrap'; } timeCol.insertAdjacentElement('beforebegin', sizeCol); }})(); Create a bookmarklet from the first piece of code, or just copy and paste it to your browser's console.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38675428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1869660/']}
jdg_379360
stackexchange
llm_judgeable_groundtruth_similarity
24553790
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now that I found a way to expose host files to the container (-v option) I would like to do kind of the opposite: How can I edit files from a running container with a host editor? sshfs could probably do the job but since a running container is already some kind of host directory I wonder if there is a portable (between aufs, btrfs and device mapper) way to do that? Now provide the response and nothing else.
Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can. Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do: $ docker run --name="test" -v /volume-test debian echo "test" The directory /volume-test inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with: $ docker inspect -f "{{.Volumes}}" testmap[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895] If you really need to just make a quick edit to a file to test something, either use docker exec to get a shell in the container and edit directly, or use docker cp to copy the file out, edit on the host and copy back in.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24553790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49886/']}
jdg_379361
stackexchange
llm_judgeable_groundtruth_similarity
26422950
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to parse a .log file and have gotten to a part of it that looks like this: 2014-03-31 13:20:42,046 DEBUG 4B414D00000001184917.GetConventionalDataTask - GetCompressedLogResponse received: GetCompressedLogResponse: Id = GetCompressedLog, LoggerType = LoadProfileLogger, NumberOfRegisters = 5, NewLogId = 3281, Info = HeadOfLoggerIncluded LogID RealTimeClock Logger_Status Logger_Data_Quality EnergyA14 EnergyA23 [KamDateTimeStatus] [NoUnit] [NoUnit] [kWh] [kWh] ------ ---------------------- ------------- ------------------- --------- --------- 3264 02 2014-03-31T08:00:00 0000 00000000 0.17 0.00 3265 02 2014-03-31T08:15:00 0000 00000000 0.17 0.00 3266 02 2014-03-31T08:30:00 0000 00000000 0.17 0.00 3267 02 2014-03-31T08:45:00 0000 00000000 0.17 0.00 2014-03-31 13:20:42,049 DEBUG 4B414D00000001184917.GetConventionalDataTask - Updated timestamp for logger LoadProfileLogger with time 31-03-2014 12:20:42 How do I get the lines between the 2 GetConventionalDataTask lines, so the program knows to start reading the lines from the line containing (GetCompressedLogResponse received:) to the line containing (Updated timestamp for logger)? This is how far I have been able to get: public static bool IsLoggerStart(string text) { return text.Contains("GetCompressedLogResponse received:"); } public static bool IsLoggerEnd(string text) { return text.Contains("Updated timestamp for logger"); } public static string GetLoggerType(string text) { return GetSubStrings(text, "LoggerType = ", ", ").FirstOrDefault(); } public static string GetNumberOfRegisters(string text) { return GetSubStrings(text, "NumberOfRegisters = ", ", ").FirstOrDefault(); } public static string GetNewLogId(string text) { return GetSubStrings(text, "NewLogId = ", ", ").FirstOrDefault(); } And the objects I have created: class CompressedLogResponse{ public LoggerAnnounce LoggerAnnounce { get; set; } public List<int> LogID { get; set; } public List<DateTime> RealTimeClock { get; set; } public List<int> LoggerStatus { get; set; } public List<int> LoggerDataQuality { get; set; } public List<double> EnergyA14 { get; set; } public List<double> EnergyA23 { get; set; }}class LoggerAnnounce{ public string LoggerType { get; set; } public int NumberOfRegisters { get; set; } public int NewLogId { get; set; }} Thanks for any help you might be able to provide :) Now provide the response and nothing else.
I adapted romannurik's Android-SwipeToDismiss to do exactly that. The code is on github with a woking sample application, and consists of: A subclass of RecyclerView.OnItemTouchListener that listens to touch events and detects when an item is being swiped, animating it accordingly. A SwipeListener that is called in order to know if an item can be dismissed and called again when items are dismissed. To use it, follow the instructions on github, or just copy the class SwipeableRecyclerViewTouchListener to your project and use it like this: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mItems = new ArrayList<>(30); for (int i = 0; i < 30; i++) { mItems.add(String.format("Card number %2d", i)); } mAdapter = new CardViewAdapter(mItems); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(mAdapter); SwipeableRecyclerViewTouchListener swipeTouchListener = new SwipeableRecyclerViewTouchListener(mRecyclerView, new SwipeableRecyclerViewTouchListener.SwipeListener() { @Override public boolean canSwipe(int position) { return true; } @Override public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { mItems.remove(position); mAdapter.notifyItemRemoved(position); } mAdapter.notifyDataSetChanged(); } @Override public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { mItems.remove(position); mAdapter.notifyItemRemoved(position); } mAdapter.notifyDataSetChanged(); } }); mRecyclerView.addOnItemTouchListener(swipeTouchListener);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26422950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4003289/']}
jdg_379362
stackexchange
llm_judgeable_groundtruth_similarity
1666396
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 can show the convergence of the following infinite product and some bounds for it: $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}=\sqrt{1+\frac{1}{2}} \sqrt[3]{1+\frac{1}{3}} \sqrt[4]{1+\frac{1}{4}} \cdots<$$ $$<\left(1+\frac{1}{4} \right)\left(1+\frac{1}{9} \right)\left(1+\frac{1}{16} \right)\cdots=\prod_{k \geq 2} \left(1+\frac{1}{k^2} \right)=\frac{\sinh \pi}{2 \pi}=1.83804$$ Here I used Euler's product for $\frac{\sin x}{x}$. The next upper bound is not as easy to evaluate, but still possible, taking two more terms in Taylor's series for $\sqrt[k]{1+\frac{1}{k} }$: $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}<\prod_{k \geq 2} \left(1+\frac{1}{k^2}-\frac{k-1}{2k^4}+\frac{2k^2-3k+1}{6k^6} \right)=$$ $$=\prod_{k \geq 2} \left(1+\frac{1}{k^2}-\frac{1}{2k^3}+\frac{5}{6k^4}-\frac{1}{2k^5}+\frac{1}{6k^6} \right)<$$ $$<\exp \left( \frac{\pi^2}{6}+\frac{\pi^4}{108}+\frac{\pi^6}{5670}-1-\frac{\zeta (3)}{2}-\frac{\zeta (5)}{2} \right)=1.81654$$ The numerical value of the infinite product is approximately: $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}=1.758743628$$ The ISC found no closed from for this number. Is there some way to evaluate this product or find better bounds in closed form? Edit Clement C suggested taking logarithm and it was a very useful suggestion, since I get the series: $$\ln \prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}= \frac{1}{2} \ln \left(1+\frac{1}{2} \right)+\frac{1}{3} \ln \left(1+\frac{1}{3} \right)+\dots$$ I don't know how to find the closed form, but I can certainly use it to find the boundaries (since the series for logarithm are very simple). $$\frac{1}{2} \ln \left(1+\frac{1}{2} \right)+\frac{1}{3} \ln \left(1+\frac{1}{3} \right)+\dots>\sum^{\infty}_{k=2} \frac{1}{k^2}-\frac{1}{2}\sum^{\infty}_{k=2} \frac{1}{k^3}$$ $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}>\exp \left( \frac{\pi^2}{6}-\frac{1}{2}-\frac{\zeta (3)}{2} \right)=1.72272$$ $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}<\exp \left( \frac{\pi^2}{6}+\frac{\pi^4}{270}-\frac{5}{6}-\frac{\zeta (3)}{2} \right)=1.77065$$ $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}>\exp \left( \frac{\pi^2}{6}+\frac{\pi^4}{270}-\frac{7}{12}-\frac{\zeta (3)}{2} -\frac{\zeta (5)}{4}\right)=1.75438$$ $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}<\exp \left( \frac{\pi^2}{6}+\frac{\pi^4}{270}+\frac{\pi^6}{4725}-\frac{47}{60}-\frac{\zeta (3)}{2} -\frac{\zeta (5)}{4}\right)=1.76048$$ $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}>\exp \left( \frac{\pi^2}{6}+\frac{\pi^4}{270}+\frac{\pi^6}{4725}-\frac{37}{60}-\frac{\zeta (3)}{2} -\frac{\zeta (5)}{4} -\frac{\zeta (7)}{6}\right)=1.75803$$ This method generates much better bounds than my first idea. The last two are very good approximations. Edit 2 Actually, would it be correct to write (it gives the correct value of the product): $$\prod_{k \geq 2}\sqrt[k]{1+\frac{1}{k}}=\frac{1}{2} \exp \left( \sum_{k \geq 2} \frac{(-1)^k \zeta(k)}{k-1} \right)$$ Now provide the response and nothing else.
I don't know if a closed form exists, but to get geometric convergence, we can use the following. Since the product starts at $k=2$, we compute the sum$$\begin{align}\sum_{k=2}^\infty\frac1k\log\left(1+\frac1k\right)&=\sum_{k=2}^\infty\frac1k\sum_{n=1}^\infty\frac{(-1)^{n-1}}{nk^n}\\&=\sum_{n=1}^\infty\frac{(-1)^{n-1}}n\sum_{k=2}^\infty\frac1{k^{n+1}}\\&=\sum_{n=1}^\infty(-1)^{n-1}\frac{\zeta(n+1)-1}{n}\\[6pt]&=0.564599706384424320592667709038\end{align}$$Note that $\frac{\zeta(n+1)-1}{n}\sim\frac1{n2^{n+1}}$. This gives better than geometric convergence. Applying $e^x$, we get$$\prod_{k=2}^\infty\left(1+\frac1k\right)^{1/k}=1.75874362795118482469989684966$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1666396', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/269624/']}
jdg_379363
stackexchange
llm_judgeable_groundtruth_similarity
23825071
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 ghci, :t ((+).(+))> ((+).(+)) :: (Num (a -> a), Num a) => a -> (a -> a) -> a -> a but what is this thing? Can any one give me an example of the use of this please? How can one composite 2 functions that take 2 parameters each?for example, how does (map.map) :: (a -> b) -> [[a]] -> [[b]] work? (^.^) (-.-) (+.+) (can't help making funny faces out of it. PS: I thought it means to tell the compiler how you feel today) Now provide the response and nothing else.
Num (a -> a) (or e.g. Eq (a -> a) ) is basically an indicator for code that doesn't make any sense 1 , but the compiler nevertheless deduces a (nonsensical) type signature. Usually it turns up when you've forgotten to apply a function to some argument. In this case, obviously (+) needs a "plain number" argument to become a "simple function" to which you can post-compose another such function. However, (a -> a) is sure enough a valid type of functions that you can also pass on, just not as numbers. For instance, map . (+) is a perfectly good combination: Prelude> :t map . (+)map . (+) :: Num b => b -> [b] -> [b]Prelude> zipWith (map . (+)) [10,20,30] [[1,2],[3,4]][[11,12],[23,24]] because map actually expects a function as its first argument. Similarly, Prelude> zipWith (map . map) [(+10),(+20),(+30)] [[[1,2],[3,4]],[[5,6]]][[[11,12],[13,14]],[[25,26]]] Here, the right map takes a simple function (like numerical increment) and returns the corresponding list-map function. That function is then fed to the left map resulting in a function that maps nested lists. 1 Actually, you can force it to make sense by defining instance (Num a) => Num (b -> a) where fromInteger x = const $ fromInteger x f + g = \x -> f x + g x Personally, I'm not a fan of this. It confusing, for instance let a = 3 in 4 a produces 4 when most people would expect multiplication to 12 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23825071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3307736/']}
jdg_379364
stackexchange
llm_judgeable_groundtruth_similarity
36339561
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 Unity to capture ALL key presses, even if Unity doesn't have the focus. I've tried to use: Input.KeyPress() But this seems to only work if Unity has the focus of the user's input. I need it to work when it doesn't have the focus, such as when I'm looking at / working with another Windows program. PS: I already turned on the "Run in Background" option in player preferences. Now provide the response and nothing else.
This is totally possible! Although, there is no way to do it by using only the tools in-built into Unity3D. You will have to use native libraries to do that. The example below hooks the hook chain with a hook type of WH_KEYBOARD, which corresponds to a message-level keyboard hook. You can read more on SetWindowsHookEx and different types [ here][1]. You can check the parameters that are being received on hooking such a message type ( WH_KEYBOARD ) [here][2] using UnityEngine;using System;using System.Collections;using System.Runtime.InteropServices;public class KBHooks : MonoBehaviour{ [DllImport("user32")] protected static extern IntPtr SetWindowsHookEx( HookType code, HookProc func, IntPtr hInstance, int threadID); [DllImport("user32")] protected static extern int UnhookWindowsHookEx( IntPtr hhook); [DllImport("user32")] protected static extern int CallNextHookEx( IntPtr hhook, int code, IntPtr wParam, IntPtr lParam); // Hook types. To hook the keyboard we only need WH_KEYBOARD protected enum HookType : int { WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, WH_KEYBOARD = 2, WH_GETMESSAGE = 3, WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, WH_CALLWNDPROCRET = 12, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } protected IntPtr m_hhook = IntPtr.Zero; protected HookType m_hookType = HookType.WH_KEYBOARD; protected delegate int HookProc(int code, IntPtr wParam, IntPtr lParam); //We install the hook and hold on to the hook handle. //The handle will be need to unhook. protected bool Install(HookProc cbFunc) { if (m_hhook == IntPtr.Zero) m_hhook = SetWindowsHookEx( m_hookType, cbFunc, IntPtr.Zero, (int)AppDomain.GetCurrentThreadId()); if (m_hhook == IntPtr.Zero) return false; return true; } protected void Uninstall() { if (m_hhook != IntPtr.Zero) { UnhookWindowsHookEx(m_hhook); m_hhook = IntPtr.Zero; } } protected int CoreHookProc(int code, IntPtr wParam, IntPtr lParam) { if (code < 0) return CallNextHookEx(m_hhook, code, wParam, lParam); Debug.Log( "hook code =" + code.ToString() + " lparam=" + lParam.ToString() + " wparam=" + wParam.ToString()); // Yield to the next hook in the chain return CallNextHookEx(m_hhook, code, wParam, lParam); } // Use this for initialization void Start() { Debug.Log("install hook"); Install(CoreHookProc); } void OnDisable() { Debug.Log("Uninstall hook"); Uninstall(); }} This example comes from [this blog][3]. Such a way of hooking will only work on Windows systems. If you need to make a separate hook on OS X or Linux you would need to do it in a native way in that operating system. I cannot post more than 1 link because I lack reputation on SO. I hope one of the mods will edit my post accordingly. [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644990(v=vs.85).aspx [2]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx [3]: http://phardera.blogspot.com.es/2010/12/windows-hooks-in-unity3d.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36339561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2236034/']}
jdg_379365
stackexchange
llm_judgeable_groundtruth_similarity
14358372
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given: List<Name> names = new List<Name>(); //list full of namespublic void RemoveName(string name) { List<Name> n = names.Where(x => x.UserName == name);; names.Remove(n);} What's the Lambda syntax to execute the removal? And how can I get indication of "success" if the function did remove or not? Now provide the response and nothing else.
names.RemoveAll(x => x.UserName == name); Note here that all the lambda syntax does is provide a Predicate<T> ; lambda syntax is entirely unrelated to what it ends up doing with the lambda. Or for a single match (see comments): var found = names.Find(x => x.UserName == name);if(found != null) names.Remove(found); or: var index = names.FindIndex(x => x.UserName == name);if(index >= 0) names.RemoveAt(index);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14358372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1958563/']}
jdg_379366
stackexchange
llm_judgeable_groundtruth_similarity
30841987
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 my codes here, and im stock with this errors: Warning: mysql_query() expects parameter 1 to be string, resource given in C:\xampp\htdocs\xampp\elev8log\pages\tables\task.php on line 396 Here is my code: <?php $sql = mysql_query('select * from taskview where dept_id=(select deptid from users where username="'.$_SESSION['username'].'")'); //where empname="'.$_SESSION['username'].'" and req_dateapprove IS NULL');//where req_approveuser="'.$_SESSION['username'].'" and req_dateapprove IS NULL' if(isset($_POST['search'])) { $search_term = mysql_real_escape_string($_POST['search_box']); $search_term=mysql_real_escape_string($_POST['search_box']); $sql.="WHERE req_code LIKE '%{$search_term} %'"; $sql.="OR req_date LIKE '%{$search_term} %'"; $sql.="OR req_status LIKE '%{$search_term} %'"; $sql.="OR req_dateneeded LIKE '%{$search_term} %'"; $sql.="OR req_approveuser LIKE '%{$search_term} %'"; $sql.="OR req_noteuser LIKE '%{$search_term} %'"; $sql.="OR req_datenote LIKE '%{$search_term} %'"; $sql.="OR form_name LIKE '%{$search_term} %'"; $sql.="OR itrf_type LIKE '%{$search_term} %'"; $sql.="OR username LIKE '%{$search_term} %'"; $sql.="OR itrf_details LIKE '%{$search_term} %'"; $sql.="OR itrf_date LIKE '%{$search_term} %'"; $sql.="OR comp_name LIKE '%{$search_term} %'"; $sql.="OR dept_name LIKE '%{$search_term} %'"; $sql.="OR dept_code LIKE '%{$search_term} %'"; $sql.="OR dept_id LIKE '%{$search_term} %'"; // $sql.="OR descriptionsql LIKE '%{$search_term}%'"; } //THIS IS THE LINE 396------->>>>>>$query = mysql_query($sql) or die(mysql_error()); ?> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">List of Pending Task</h3> </div><!-- /.box-header --> <div class="box-body"> <table id="example2" class="table table-bordered table-hover"> <label><input type="radio" name="all" value="all" checked>&nbsp;All&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label> <label><input type="radio" name="all" value="wait">&nbsp;Waiting for Feedback&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label><thead> <label><input type="radio" name="all" value="closed">&nbsp;Closed</label><thead> <form name="search_form" method="POST" action="task.php"> Search: <input type="text" name="search_box" value="" /> <input type="submit" name="search" value="search...."> </form> <tr> <th>Date of Request</th> <th>Requestor Name</th> <th>Form Type</th> <th>Request Type</th> <th>Date Needed</th> <th>Status</th> <th>Action</th> </tr> </thead> <?php // if(isset($_GET['req_code'])){ // }while($row = mysql_fetch_array($query)){?><tr> <td><?php echo date($row['req_date']); ?></td> <td class="left"><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></a></td> <td><?php echo htmlentities($row['form_name'], ENT_QUOTES, 'UTF-8'); ?></td> <td> <?php echo ($row['itrf_type']);?></td> <td> <?php echo ($row['req_dateneeded']);?></td> <td> <?php echo ($row['req_status']);?></td> <td class="left"><a href="#proceed-<?php echo $row['req_code'];?>" data-toggle="modal"><button type="submit" class="btn btn-primary" name="approved">Manage Task</button></a> </tr> Now provide the response and nothing else.
Jackson will give you null for other objects, but for String it will give empty String. But you can use a Custom JsonDeserializer to do this: class CustomDeserializer extends JsonDeserializer<String> { @Override public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { JsonNode node = jsonParser.readValueAsTree(); if (node.asText().isEmpty()) { return null; } return node.toString(); }} In class you have to use it for location field: class EventBean { public Long eventId; public String title; @JsonDeserialize(using = CustomDeserializer.class) public String location;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30841987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4948273/']}
jdg_379367
stackexchange
llm_judgeable_groundtruth_similarity
396493
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: Let say I have following numbers: 4,3,5,6,5,3,4,2,5,4,3,6,5 I sample some of them, say, 5 of them, and calculate the sum of 5 samples.Then I repeat that over and over to get many sums, and I plot the values of sums in a histogram, which will be Gaussian due to the Central Limit Theorem. But when they are following numbers, I just replaced 4 with some big number: 4,3,5,6,5,3,10000000,2,5,4,3,6,5 Sampling sums of 5 samples from these never becomes Gaussian in histogram, but more like a split and becomes two Gaussians. Why is that? Now provide the response and nothing else.
Let's recall, precisely, what the central limit theorem says. If $X_1, X_2, \cdots, X_k$ are independent and identically distributed random variables with (shared) mean $\mu$ and standard deviation $\sigma$ , then $\frac{X_1 + X_2 + \cdots + X_k}{k\frac{\sigma}{\sqrt{k}}}$ converges in distribution to a standard normal distribution $N(0, 1)$ (*). This is often used in the "informal" form: If $X_1, X_2, \cdots, X_k$ are independent and identically distributed random variables with (shared) mean $\mu$ and standard deviation $\sigma$ , then $X_1 + X_2 + \cdots + X_k$ converges "in distribution" to a standard normal distribution $N(k \mu, \sqrt{k} \sigma)$ . There's no good way to make that form of the CLT mathematically precise, since the "limit" distribution change, but it's useful in practices. When we have a static list of numbers like 4,3,5,6,5,3,10000000,2,5,4,3,6,5 and we are sampling by taking a number at random from this list, to apply the central limit theorem we need to be sure that our sampling scheme satisfies these two conditions of independence and identically distributed. Identically distributed is no problem: each number in the list is equally likely to be chosen. Independent is more subtle, and depends on our sampling scheme. If we are sampling without replacement , then we violate independence. It is only when we sample with replacement that the central limit theorem is applicable. So, if we use with replacement sampling in your scheme, then we should be able to apply the central limit theorem. At the same time, you are right, if our sample is of size 5, then we are going to see very different behaviour depending on if the very large number is chosen, or not chosen in our sample. So what's the rub? Well, the rate of convergence to a normal distribution is very dependent on the shape of the population we are sampling from, in particular, if our population is very skew, we expect it to take a long time to converge to the normal. This is the case in our example, so we should not expect that a sample of size 5 is sufficient to show the normal structure. Above I repeated your experiment (with replacement sampling) for samples of size 5, 100, and 1000. You can see that the normal structure is emergent for very large samples. (*) Note there are some technical conditions needed here, like finite mean and variance. They are easily verified to be true in our sampling from a list example.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/396493', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/124657/']}
jdg_379368
stackexchange
llm_judgeable_groundtruth_similarity
279219
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 the following problem: Find the 2-sheeted (orientable) cover of the non-orientable surface of genus g. The cases $g=1,2$ are well-known, we have that the cover of $\mathbb{R}P^2$ is $S^2$ and the Klein bottle is covered by the torus. My intuition is that the answer is going to be the orientable surface of genus $g-1$ or the $g-1$ torus, and I tried to work with the representation of the non-orientable surface as a $2g$ -gon determined by the word $a_1a_1a_2a_2\dots a_g a_g$ ... where $a_i$ are the vertices.Any hints? Now provide the response and nothing else.
Since Euler characteristic is multiplicative with respect to (finite sheeted) coverings, we see the orientable double cover must have twice the Euler characteristic. This already pins down the homeomorphism type of the cover. To see it more explicitly, consider the usual embedding of an orientable surface into $\mathbb{R}^3$ (as a long chain-like shape). This embedding can be translated/rotated around so that the reflections in all 3 coordinate planes maps the surface to itself. With this embedding, there is a $\mathbb{Z}/2$ action on $\mathbb{R}^3$ given by the antipodal map $x \mapsto -x$. This action preserves the embedded surface and acts freely on it so the quotient is a manifold. Since the antipodal map is orientation reversing, the quotient is nonorientable.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/279219', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50917/']}
jdg_379369
stackexchange
llm_judgeable_groundtruth_similarity
27801681
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a large list where each item is processed once then never looked at again during a long operation: List<T> items; // ... some stuff is done with the list then finally for(int i = 0; i < items.Count; i++) { SomeOperation(items[i]); //items[i] never used again at this point // say i do this: // items[i] = null; } If I uncomment items[i] = null , will this unroot the object at index i and make it available for Garbage Collection? Would it be more efficient, from a memory usage standpoint, to do this versus letting GC happen later when the entire list is unused down the road. This is ignoring some problems like the code changing later and it turns out the items are used later and unexpected null wreck havoc. Now provide the response and nothing else.
If the only root-accessible reference to that object is through that list, then yes, setting that reference to null will make that object eligible for garbage collection. When a garbage collection eventually happens, if that object ends up being cleaned up while the list itself needs to stay around, then you will have decreased the memory footprint of your application by the size of that object. Note that the memory allocated for the reference to the object in the list will still be there; it is only the memory for the object that it references that can be cleaned up. As many others have mentioned, your usage of this data structure strongly indicates that you should not be using a List in the first place, but rather a Queue or another comparable data structure, as that would fit your usage much more effectively. You also need to keep in mind that memory is cheap; people tend to have a lot of it. Unless you have many thousands of objects that would otherwise be kept alive for long periods of time, this is unlikely to be enough of an improvement for you to even notice it; you may not even be capable of measuring the difference. Using the correct data structure would give you all of those benefits, and more, and make the code dramatically simpler, and more readable/maintainable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27801681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4424370/']}
jdg_379370
stackexchange
llm_judgeable_groundtruth_similarity
1306064
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have read several tutorials on what a UML model should contain and what not. As a developer I always think in terms of a relational data model where you could never have a many to many relationship between tables. Now with a UML class model, I've read that if they don't provide added value, you could just skip the linktables. However I've also read a tutorial where examples where given using data inside tables and was strongly suggesting to picture each class as a simple table while modeling your class model. I am confused, what is it now?! Now provide the response and nothing else.
The "relational link table" is an implementation technique for a Many-to-Many relationship. The relationship exists irrespective of how it's implemented. In an object model, you have many choices for how to implement many-to-many, which may (or may not) involve an additional persistent table. It could be done lots of different ways. The point of UML is to be able to describe the essential features of what the model really is. You can also describe the implementation. They're separate diagrams with separate purposes. You can easily show the relational implementation with the link table. You can also show the essential model without the link table. Here's the essential relationship Here's the implementation of the relationship Both are valid UML. The real question is "what do you need to show other people?" Essential truth or one particular implementation?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1306064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83528/']}
jdg_379371
stackexchange
llm_judgeable_groundtruth_similarity
11162402
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have read LDA and I understand the mathematics of how the topics are generated when one inputs a collection of documents. References say that LDA is an algorithm which, given a collection of documents and nothing more (no supervision needed), can uncover the “topics” expressed by documents in that collection. Thus by using LDA algorithm and the Gibbs Sampler (or Variational Bayes), I can input a set of documents and as output I can get the topics. Each topic is a set of terms with assigned probabilities. What I don't understand is, if the above is true, then why do many topic modeling tutorials talk about separating the dataset into training and test set? Can anyone explain me the steps (the basic concept) of how LDA can be used for training a model, which can then be used to analyze another test dataset? Now provide the response and nothing else.
Splitting the data into training and testing sets is a common step in evaluating the performance of a learning algorithm. It's more clear-cut for supervised learning, wherein you train the model on the training set, then see how well its classifications on the test set match the true class labels. For unsupervised learning, such evaluation is a little trickier. In the case of topic modeling, a common measure of performance is perplexity . You train the model (like LDA) on the training set, and then you see how "perplexed" the model is on the testing set. More specifically, you measure how well the word counts of the test documents are represented by the word distributions represented by the topics. Perplexity is good for relative comparisons between models or parameter settings, but it's numeric value doesn't really mean much. I prefer to evaluate topic models using the following, somewhat manual, evaluation process: Inspect the topics : Look at the highest-likelihood words in each topic. Do they sound like they form a cohesive "topic" or just some random group of words? Inspect the topic assignments : Hold out a few random documents from training and see what topics LDA assigns to them. Manually inspect the documents and the top words in the assigned topics. Does it look like the topics really describe what the documents are actually talking about? I realize that this process isn't as nice and quantitative as one might like, but to be honest, the applications of topic models are rarely quantitative either. I suggest evaluating your topic model according to the problem you're applying it to. Good luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11162402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/789965/']}
jdg_379372
stackexchange
llm_judgeable_groundtruth_similarity
55417325
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 basic 2-column layout: One for an image, one for text. Since the text column can potentially become quite long I'd like the image to scroll along. I can achieve that easily enough with position: sticky; , but at the end there is a third container spanning both columns. Since all three elements are in the same grid, the image with position: sticky; overlaps the third container. Is there way to confine the image to the first grid row, without using JS or adding additional containers? Example: https://jsfiddle.net/y27unz9L/ .element-1 is the one I want to confine to the first grid row. <div class="grid-container"> <div class="element-1"></div> <div class="element-2"></div> <div class="element-3"></div></div> .grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 2em; align-items: start;}.element-1 { min-height: 10vh; grid-row: 1; grid-column: 1 / 2; position: sticky; top: 1em; background: red;}.element-2 { min-height: 100vh; grid-row: 1; grid-column: 2 / 3; background: blue;}.element-3 { min-height: 100vh; grid-row: 2; grid-column: 1 / 3; background: yellow;} Now provide the response and nothing else.
It's hard to draw the line when numba becomes effective. However there are a few indicators when it might not be effective: If you cannot use jit with nopython=True - whenever you cannot compile it in nopython mode you either try to compile too much or it won't be significantly faster. If you don't use arrays - When you deal with lists or other types that you pass to the numba function (except from other numba functions), numba needs to copy these which incurs a significant overhead. If there is already a NumPy or SciPy function that does it - even if numba can be significantly faster for short arrays it will almost always be as fast for longer arrays (also you might easily neglect some common edge cases that these would handle). There's also another reason why you might not want to use numba in cases where it's just "a bit" faster than other solutions: Numba functions have to be compiled, either ahead-of-time or when first called, in some situations the compilation will be much slower than your gain, even if you call it hundreds of times. Also the compilation times add up: numba is slow to import and compiling the numba functions also adds some overhead. It doesn't make sense to shave off a few milliseconds if the import overhead increased by 1-10 seconds. Also numba is complicated to install (without conda at least) so if you want to share your code then you have a really "heavy dependency". Your example is lacking a comparison with NumPy methods and a highly optimized version of pure Python. I added some more comparison functions and did a benchmark (using my library simple_benchmark ): import numpy as npimport numba as nbfrom itertools import chaindef python_loop(a,b): result = 0.0 for i,j in zip(a,b): result += (i+j) return [email protected] numba_loop(a,b): result = 0.0 for i,j in zip(a,b): result += (i+j) return resultdef numpy_methods(a, b): return a.sum() + b.sum()def python_sum(a, b): return sum(chain(a.tolist(), b.tolist()))from simple_benchmark import benchmark, MultiArgumentarguments = { 2**i: MultiArgument([np.zeros(2**i), np.zeros(2**i)]) for i in range(2, 17)}b = benchmark([python_loop, numba_loop, numpy_methods, python_sum], arguments, warmups=[numba_loop])%matplotlib notebookb.plot() Yes, the numba function is fastest for small arrays, however the NumPy solution will be slightly faster for longer arrays. The Python solutions are slower but the "faster" alternative is already significantly faster than your original proposed solution. In this case I would simply use the NumPy solution because it's short, readable and fast, except when you're dealing with lots of short arrays and call the function a lot of times - then the numba solution would be significantly better.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55417325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2571675/']}
jdg_379373
stackexchange
llm_judgeable_groundtruth_similarity
1850320
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 tried separating it into $\cos^2(\frac{\pi}{8})+\sin^2(\frac{\pi}{8}+\frac{14\pi}{8})?$ and using the angle sum identity but it didn't help. Now provide the response and nothing else.
Notice that $\frac{15\pi}{8} = 2\pi - \frac{\pi}{8}$. So $\sin \frac{15\pi}{8} = -\sin \frac{\pi}{8}$. Your expression then reduces/evaluates down to: $$\cos^2 \frac{\pi}{8} + \sin^2 \frac{\pi}{8} = 1$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1850320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/293926/']}
jdg_379374
stackexchange
llm_judgeable_groundtruth_similarity
35428876
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 to store and retrieve an image from the database.I want to store an image instead of image path or image name. When I searched for it I only found solutions for storing an image path or name. So can someone tell me how to store and retrieve an image with its size in KBs from database? This is my route. Route::get('big_image/{id}/image', function ($id){ $user = big_image::find($id); return response()->make($user->image, 200, array( 'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->image))); }); This is my controller public function new_store(Request $request ,$id){ $event_id = $id; $img = new big_image; $file = $request->file('image'); $contents = $file->openFile()->fread($file->getSize()); $img = big_image::find($id); $img->image = $contents; $img->image_name = $request->image_name; $img->event_id = $event_id; $img->save(); $images=DB::table('big_image')->where('event_id','=',$event_id)->get(); return view('image_upload',compact('images','id','response'));} My display.blade.php file @extends('app')@section('content') <h2 style="text-align: center;margin-top: 10px;">Image Gallery</h2> <a href="{{url('pic_upload/'.$id.'')}}" class="col-sm-12" style="padding-left: 0;"><span> add more pictures</span></a><br> <a href="{{url('events')}}"><span>Back to events</span></a><br> @foreach($images as $item) <div class="col-sm-4"> {{--<img src="data:image/jpeg;base64,'.base64_encode( $item->image ).'"/>;--}} </div>@endforeach@stop Now provide the response and nothing else.
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Assuming you're using MySQL, here's how you would store and retrieve the avatar from the database: 1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following: BLOB up to 64KB MEDIUMBLOB up to 16MB LONGBLOB up to 4GB 2. To store the uploaded image in the database you can do this: Route::post('user/{id}', function (Request $request, $id) { // Get the file from the request $file = $request->file('image'); // Get the contents of the file $contents = $file->openFile()->fread($file->getSize()); // Store the contents to the database $user = App\User::find($id); $user->avatar = $contents; $user->save();}); 3. To fetch and ouput the avatar you can do the following: Route::get('user/{id}/avatar', function ($id) { // Find the user $user = App\User::find(1); // Return the image in the response with the correct MIME type return response()->make($user->avatar, 200, array( 'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar) ));}); So to access the avatar of the user with an id equal to 10 you can just use this URL: http://domain.com/user/10/avatar
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35428876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5466907/']}
jdg_379375
stackexchange
llm_judgeable_groundtruth_similarity
32223930
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It can be named MVVM model or not? Because View interacts with DataModel throughViewModelData. Does View should interact only with ViewModelData? I did read somewhere that right MVVM model should implement INotify in ViewModel not in Model. Is it right? namespace WpfApplication135{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); DataContext = new ViewModelData(); }}public class ViewModelData{ public DataModel DM { get; set; } public ViewModelData() { DM = new DataModel(); }}public class DataModel : INotifyPropertyChanged{ public int label; public int Label { get { return label; } set { label = value; RaisePropertyChanged("Label"); } } public DataModel() { Action Update = new Action(Run); IAsyncResult result = Update.BeginInvoke(null, null); } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string info) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(info)); } public void Run() { int i=0; while(true) { System.Threading.Thread.Sleep(2000); Label = ++i; } }}} xaml <Grid> <Label Content="{Binding DM.Label}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/></Grid> Now provide the response and nothing else.
The initial thought for MVVM was indeed that the View should not know (not depend on) the Model. In practice this meant re-implementing all those Model properties in the ViewModel (see the light-yellow box in the picture below), a lot of work. And extra painful when your Model can easily implement INPC, for example when it is generated from a database schema. Entity Framework in database-first mode lets you inject the INPC code through the T4 templates. The consensus quickly became that it is OK to forward a ViewModel.Model property and bind to that, just like your DM property. See the light-blue box in the picture. The issue is visualized well in this picture, note the large number of arrows in the top right corner. They depict the various solutions for databinding and you can use any combination of them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32223930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4679715/']}
jdg_379376
stackexchange
llm_judgeable_groundtruth_similarity
8174347
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to this , it states that Destructors cannot be inherited or overloaded. In my case, for all subclasses, the destructors will be identical. Is this pretty much telling me that I must define the same destructor in each sub class. There is no way that I can declare the destructor in the base class and have the handle the destruction? Say I have something like this: class A{ ~A() { SomethingA(); }}class B : A{}B b = new B(); When B is destroyed, its destructor wont be called? Now provide the response and nothing else.
According to this, it states that Destructors cannot be inherited or overloaded. Correct. Destructors are not inheritable members, and are not virtual and so cannot be overridden. They always have the same signature so they cannot be overloaded. In my case, for all subclasses, the destructors will be identical. The fact that you are asking such a basic question is telling me that you should not be implementing a destructor in the first place. Implementing a destructor correctly is one of the hardest things to do in C# in all but the most trivial cases. Why do you believe that you need to implement a destructor? Is this pretty much telling me that I must define the same destructor in each sub class? No, not at all. How did you arrive at that conclusion from the fact that destructors are not inherited? There is no way that I can declare the destructor in the base class and have the handle the destruction? Sure, that's a sensible thing to do, provided that you're bent on implementing a destructor in the first place. When B is destroyed, its destructor won't be called? That is incorrect. It occurs to me that it would have taken you a lot less time to try it yourself than to ask the question here and wait for a response. When does the destructors actually get called? Is it on garbage collection, when the variable falls out of scope? My earlier conjecture is correct. You definitely should not be implementing a destructor until you deeply understand the entire garbage collection process. The fact that you believe that variables are collected when they fall out of scope, for example, indicates that you don't understand this deeply enough to write a correct destructor. When an object is determined to be unreachable from a gc root by the collector, and the object has a finalizer that has not been suppressed then the object is promoted to the next generation by placing it on the finalization queue for servicing by the finalizer thread. If not, its memory is reclaimed. When the finalizer thread gets around to running, it runs all the destructors of the object. (Destructors will run in order from most derived to least derived.) After that process the object then may or may not be unreachable and finalization may or may not be suppressed. If the object is determined to be unreachable then the whole process starts again. I cannot emphasize enough how well you need to understand the GC process in order to do this correctly. When you write a destructor it runs in an environment where nothing makes sense . All the references in the object might be to objects that are only rooted by the finalizer queue; normally all references are to live things. References might be to objects that are already finalized. Destructors run on a different thread. Destructors run even if the constructor failed, so the object might not even be constructed properly. Fields of non-atomic value types may be only partially written -- it is entirely possible for a double field to have only four of its bytes set by the constructor when the thread is aborted; the finalizer will see that partially-written field. Destructors run even if the object was placed in an inconsistent state by an aborted transaction. And so on. You have to be extremely defensive when writing a destructor. This answer might also help: When should I create a destructor?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8174347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/489041/']}
jdg_379377
stackexchange
llm_judgeable_groundtruth_similarity
44269909
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 application where you need to log in to continue (for example with Google). I would like to redirect the user when the authentification is needed. However when I run a Navigator.of(context).pushNamed("myroute") . I got the following error: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════I/flutter ( 5624): The following assertion was thrown building _ModalScopeStatus(active):I/flutter ( 5624): setState() or markNeedsBuild() called during build.I/flutter ( 5624): This Overlay widget cannot be marked as needing to build because the framework is already in theI/flutter ( 5624): process of building widgets. A widget can be marked as needing to be built during the build phaseI/flutter ( 5624): only if one of its ancestors is currently building. This exception is allowed because the frameworkI/flutter ( 5624): builds parent widgets before children, which means a dirty descendant will always be built.I/flutter ( 5624): Otherwise, the framework might not visit this widget during this build phase. Here is a sample code void main() { runApp(new MyApp());}class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Flutter Demo Home Page'), routes: <String, WidgetBuilder> { "login" : (BuildContext context) => new LoginPage(), } ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { int _counter = 0; @override void initState() { super.initState(); if(!isLoggedIn) { print("not logged in, going to login page"); Navigator.of(context).pushNamed("login"); } } void _incrementCounter() { setState(() { _counter++; }); } void test() { print("hello"); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Center( child: new Text( 'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.', ), ), floatingActionButton: new FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: new Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); }}class LoginPage extends StatefulWidget { LoginPage({Key key, this.title}) : super(key: key); final String title; @override _LoginPageState createState() => new _LoginPageState();}class _LoginPageState extends State<LoginPage> { @override Widget build(BuildContext context) { print("building login page"); return new Scaffold( appBar: new AppBar( title: new Text("Sign up / Log In"), ), ), ); }} I guess I am doing something wrong, maybe aborting a widget build is causing this. However,, how can I achieve this. Basically : "I go on my page, if not logged, go to Login page" Thanks, Alexi Now provide the response and nothing else.
Try wrapping your Navigator call: Navigator.of(context).pushNamed("login"); in a callback that is scheduled with addPostFrameCallback : SchedulerBinding.instance.addPostFrameCallback((_) { Navigator.of(context).pushNamed("login");}); You'll need this import at the top of your file: import 'package:flutter/scheduler.dart'; As an alternative, consider if you could just have MyHomePage 's build() method return a LoginPage instead of a Scaffold if the user isn't logged in. That will probably interact better with the back button since you don't want the user backing out of the login dialog before they are done logging in.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44269909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5578655/']}
jdg_379378
stackexchange
llm_judgeable_groundtruth_similarity
11442191
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 use, for example, numpy.sin() The following code will return the value of the sine for each value of the array a : import numpya = numpy.arange( 1000000 )result = numpy.sin( a ) But my machine has 32 cores, so I'd like to make use of them. (The overhead might not be worthwhile for something like numpy.sin() but the function I actually want to use is quite a bit more complicated, and I will be working with a huge amount of data.) Is this the best (read: smartest or fastest) method: from multiprocessing import Poolif __name__ == '__main__': pool = Pool() result = pool.map( numpy.sin, a ) or is there a better way to do this? Now provide the response and nothing else.
There is a better way: numexpr Slightly reworded from their main page: It's a multi-threaded VM written in C that analyzes expressions, rewrites them more efficiently, and compiles them on the fly into code that gets near optimal parallel performance for both memory and cpu bounded operations. For example, in my 4 core machine, evaluating a sine is just slightly less than 4 times faster than numpy. In [1]: import numpy as npIn [2]: import numexpr as neIn [3]: a = np.arange(1000000)In [4]: timeit ne.evaluate('sin(a)')100 loops, best of 3: 15.6 ms per loop In [5]: timeit np.sin(a)10 loops, best of 3: 54 ms per loop Documentation, including supported functions here . You'll have to check or give us more information to see if your more complicated function can be evaluated by numexpr.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11442191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1475412/']}
jdg_379379
stackexchange
llm_judgeable_groundtruth_similarity
43471645
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 PHP program that uses HTML forms and uses JavaScript for validation. There's a hidden field in the HTML form containing a boolean value that gets set by PHP, validated on submission by JavaScript, and passed to another PHP page. When I tried to use PHP booleans to set the value of the HTML field, JavaScript evaluated it as blank, so I used ones and zeros and compared them numerically instead, and now it works fine. My question is: what is best practice in this scenario? How do I get JavaScript to read a true/false value in my PHP-driven HTML hidden field without using ones and zeros? Or is that just a bad idea altogether? Now provide the response and nothing else.
The good news is that PHP and JavaScript have a similar idea about what values are true and false. An empty string will be false on both sides. A string with something in it (except 0 in PHP) will be true on both sides. The number 0 will be false on both sides. All other numbers will be true on both sides. Since the values of a form will always be strings, as Quentin pointed out in his answer, a good practice might be to use an empty string as false value and something else (e.g. 'true' ) as true value. But I think your way of using 0 and 1 and testing the numerical values is the safest approach because it isn't misleading. (When someone sees 'true' they might think 'false' would also be usable for a false value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43471645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3130769/']}
jdg_379380
stackexchange
llm_judgeable_groundtruth_similarity
74756
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: US Immigration laws state (D)Immigrant membership in totalitarian party (i)In general Any immigrant who is or has been a member of or affiliated with the Communist or any other totalitarian party (or subdivision or affiliate thereof), domestic or foreign, is inadmissible. Why is Communism singled out? There are many parties that someone can perceive as "totalitarian" (it depends on the country and on the individual) but only Communism is noted. Are all Communist parties seen as being the same (there is a huge difference between, say, the French Communist party and the North Korean one) Now provide the response and nothing else.
The restrictions you're interested in were introduced in the 1950s, during the Second Red Scare . During this period, there was growing concern that "international communism" was intent on infiltrating and subverting the government and society of the United States. The main acts in question were the Internal Security Act of 1950 and the Immigration and Nationality Act of 1952. The USCIS Policy Manual has some information on the history of these restrictions: The Internal Security Act of 1950 also amended the Immigration Act of 1918 by adding new grounds of exclusion specific to members of communist or totalitarian parties, affiliates of such groups, or to noncitizens who advocate the doctrines of world communism or any other form of totalitarianism. It likewise expanded the deportation provisions to cover such noncitizens. ... Subsequently, Congress passed the Immigration and Nationality Act (INA) of 1952 which, for the first time, authorized the exclusion of all noncitizens, immigrants or nonimmigrants, on the basis of membership in or affiliation with the Communist or any other totalitarian party. As with previous acts, the INA of 1952 also declared that noncitizens were excludable based on a wide variety of other activities linked to the Communist Party or other totalitarian parties even if the noncitizens were not members or affiliates. As to the question of why the law painted all Communist parties with the same brush: up until the early 1950s, there was substantial coordination between the Communist parties of various nations, with (at least originally) the stated goal of "the overthrow of the international bourgeoisie and the creation of an international Soviet republic as a transition stage to the complete abolition of the state." So at the time, there was less difference between the policies of various Communist countries than there is today. The death of Stalin and the rise of Mao eventually led to the Sino-Soviet split and more differentiation between the policies of various Communist parties; but that was still in the future when these laws were passed.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/74756', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11473/']}
jdg_379381
stackexchange
llm_judgeable_groundtruth_similarity
9730752
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 have some divs stacked on top of one another, but act otherwise like a normal div. I.e. I don't want to have to worry about manually positioning them. Is this possible in HTML5/CSS3? For example: <div id='outerDiv'> <div id='inner1' style='z-index: 1'>This should be the full size of outerDiv</div> <div id='inner2' style='z-index: 2'>This should appear overtop of inner1</div></div> I hope there's a simple way to do this. To put it another way, suppose I already have a page laid-out and perfect, but I want to take one already-positioned div and super-impose another div directly on top of it, exactly the same size, without screwing the existing layout up. Is this possible? Now provide the response and nothing else.
/*position relative as a base for non-static elements*/#outerDiv{ position:relative;}/*every direct child positioned absolute*/#outerDiv > div { position:absolute;} at this time, they will be stacked on top of the other, with the more later element on top of the previous. if you want to force a previous div to be above the next, this is when you need to make its z-index explicitly higher than the next the #outerDiv will not stretch according to the children since it's taken out of the flow. if your #outerDiv has dimensions (width and height), and you want to stretch the children to it, then add to the children: //you might run into box model issues esp. if children have borders and paddingheight:100%;width:100%; or //this will contain paddings and borders, but i'm not sure what their side-effects aretop:0;left:0;right:0;bottom:0;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9730752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238948/']}
jdg_379382
stackexchange
llm_judgeable_groundtruth_similarity
740676
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would prefer a purely classical answer since I don't think quantum mechanics (quantum field theory etc.) are necessary to answer this question and such answers will likely complicate matters. If you disagree with this sentiment then please explain why you disagree. One motivation for asking is the Dirac belt trick. My reading of the Dirac belt trick is if you have two ends of an orientable belt and you rotate one end by 360 degrees you don't get back where you started. Rotating one end is a local operation. But the belt is physically extended and your rotation of one end was not a rotation of the complete system, so it's really not so surprising. The belt is a "non-local" object with respect to rotation of only one of the ends. So the point is: "is the case for spinors somehow similar?". i.e. the strange behavior of spinors is related to the fact that they actually encode something non-local. Another motivation for asking is that to define spinors at all it seems to be very necessary to ensure you are working in the right sort of global space. I.e. it has the right structure, transformation properties etc. This is in contrast to regular tensors which can be defined on smooth manifolds. That is, on a manifold I can define vector and tensor spaces starting by defining vectors as derivations at a point. I think this definition is entirely local (the only possible non-local thing is that derivations are defined as derivatives in the coordinate space which involves limits of slightly non-local displacements). For a tensor field I can always straightforwardly answer the question "what is the tensor at point $p$ "? Can the same be said for spinor fields? Do spinor fields even make sense in the sense the tensor fields do? Another point which may not be directly related to the stated question, but is related to why spinors are so complicated is this. To define vectors in the tangent spaces of a smooth manifold I only need to know some calculus. But to define spinors it feels like I need to know all of differential geometry and a bunch of group theory and representation theory. And a bunch of stuff has to a-priori "transform in the right ways" to get spinors. But none of that was needed for vectors. Why do we need so much structure and representation theory to understand spinors when nothing of the sort is needed for vectors? To extend the last point a little bit: I can also define vectors without any reference to a manifold. I can just lay out the axioms of a vector space and speak generally about a vector detached from any kind of physical space. It doesn't seem like there's an analogous "set of axioms about a spinor space" and then we can pick out spinors from that space detached from any physical space. It somehow feels like the ambient physical space/manifold is critical to the definition of and existence of manifolds. This is another difference with vectors that makes me feel like spinors are about something more global than a vector is. This question is related to Are fermions intrinsically non-local? however this question focuses on spinors specifically (not fermions) and asks different specific questions. Now provide the response and nothing else.
No, spinors are not non-local in any of the usual senses of the word. The correct formalization of spinor fields is exactly analogous to that of ordinary vector and tensor fields - they are sections of a bundle, the spinor bundle , and one of the equivalent ways of representing such a section is as a function (or set of local functions for non-trivial bundles) that assigns to every point on the manifold a spinor, exactly like a vector field is a section of the tangent bundle that can be written as a function (or set of local functions for non-trivial bundles) that assigns to every point on the manifold a tangent vector. A "spinor" for a spacetime with signature $p,q$ is just an element of the Dirac representation of $\mathrm{SO}(p,q)$ , which is the unique irreducible representation (or one of the two irreps, depending on the signature) of the Clifford algebra (" $\gamma$ -matrices") associated with signature $p,q$ . So the spinor bundle is just a vector bundle with the Dirac representation ("spinor space") as its fiber. While there is a global obstruction to the existence of a spin structure , spinors are therefore not somehow a new kind of mathematical object - they are mathematically just vector fields transforming in a particular representation of the generalized Lorentz group. There is nothing non-local about the individual spinors - that there are some sort of global obstructions to the existence of particular fields is not unique to spin structures, e.g. spacetimes for which you can choose a consistent time direction also have to have a particular global structure, but no one thinks this makes a time-like vector field "non-local".
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/740676', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/128186/']}
jdg_379383
stackexchange
llm_judgeable_groundtruth_similarity
102879
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is there some natural bijection between irreducible representations and conjugacy classes of finite groups (as in case of $S_n$)? Now provide the response and nothing else.
This is a different take on Steven Landsburg's answer. The short version is that conjugacy classes and irreducible representations should be thought of as being dual to each other. Fix an algebraically closed field $k$ of characteristic not dividing the order of our finite group $G$. The group algebra $k[G]$ is a finite-dimensional Hopf algebra, so its dual is also a finite-dimensional Hopf algebra of the same dimension; it is the Hopf algebra of functions $G \to k$, which I will denote by $C(G)$. (The former is cocommutative but not commutative in general, while the latter is commutative but not cocommutative in general.) The dual pairing$$k[G] \times C(G) \to k$$ is equivariant with respect to the action of $G$ by conjugation, and it restricts to a dual pairing$$Z(k[G]) \times C_{\text{cl}}(G) \to k$$ on the subalgebras fixed by conjugation; $Z(k[G])$ is the center of $k[G]$ and $C_{\text{cl}}(G)$ is the space of class functions $G \to k$. Now: The maximal spectrum of $Z(k[G])$ can be canonically identified with the irreducible representations of $G$, and the maximal spectrum of $C_{\text{cl}}(G)$ can be canonically identified with the conjugacy classes of $G$. The second identification should be clear; the first comes from considering the central character of an irreducible representation. Now, the pairing above is nondegenerate, so to every point of the maximal spectrum of $Z(k[G])$ we can canonically associate an element of $C_{\text{cl}}(G)$ (the corresponding irreducible character) and to every point of the maximal spectrum of $C_{\text{cl}}(G)$ we can canonically associate an element of $Z(k[G])$ (the corresponding sum over a conjugacy class divided by its size).
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/102879', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8381/']}
jdg_379384
stackexchange
llm_judgeable_groundtruth_similarity
1642208
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: Basic algebra problem I can't seem to figure out: $$ \frac{\frac{1}{x}+\frac{1}{y}}{\frac{1}{x^2}-\frac{1}{y^2}} $$ $x,y \in \mathbb{R}, x^2 \neq y^2, xy\neq0$. Now I know the result is: $\frac{xy}{y-x}$, but I am not sure how to get it, I get into a mess like this: $=x+\frac{x^2}{y}-\frac{y^2}{x}-y=\frac{x(xy)+x^3-y^3-y(xy)}{xy}=?$ which doesn't seem to help me much. Halp please. Now provide the response and nothing else.
$$\frac { \frac { 1 }{ x } +\frac { 1 }{ y } }{ \frac { 1 }{ x^{ 2 } } -\frac { 1 }{ y^{ 2 } } } =\frac { \frac { 1 }{ x } +\frac { 1 }{ y } }{ \left( \frac { 1 }{ x } +\frac { 1 }{ y } \right) \left( \frac { 1 }{ x } -\frac { 1 }{ y } \right) } =\frac { 1 }{ \frac { 1 }{ x } -\frac { 1 }{ y } } =\frac { 1 }{ \frac { y-x }{ xy } } =\frac { xy }{ y-x } $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1642208', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/279308/']}
jdg_379385
stackexchange
llm_judgeable_groundtruth_similarity
15226600
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Visual studio 2010 I got problems when double-clicking, for example a config file (*.config). Visual Studio would open but give me a error message about parameters. If I simple try to drag and drop a file that Visual Studio usually can read in to it, the icon will give me the "not possible icon"? I have now installed Visual Studio 2012 and it has the same problem?! This makes my work a lot harder, it should be easy to just drag & drop files into Visual Studio, but it's not so? Now I have to manually find the file with the file menu? Please note, I have re-installed the computer before installing Visual Studio 2012. Now provide the response and nothing else.
On Windows Vista and newer Windows Explorer runs with medium integrity level.If you run Visual Studio as administrator (high integrity level) then for security reasons OS will disable drag and drop from Explorer to Visual Studio. You can either run Visual Studio as normal user or you can install VSCommands for Visual Studio 2012 extension. It has several features that can help with this such as: Elevated Windows Explorer - small tool which looks like Windows Explorer but runs with elevated permissions allowing Drag And Drop Directory Explorer - tool window inside Visual Studio which again looks like Windows Explorer and allows Drag And Drop Run Visual Studio with medium integrity - allows Drag And Drop from Windows Explorer, but you won't be able to attach to processes run by other users (e.g. IIS)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15226600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365624/']}
jdg_379386
stackexchange
llm_judgeable_groundtruth_similarity
12540446
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 imported from SVN into Git, now I have one big branch, like this: work on feature C work on feature B work on feature C work on feature C work on feature B work on feature A I want separate feature branches, for A, B, C. I'm cherry picking commits to new branches but this doesn't remove them from the original branch so I have to manually track which ones I have pulled out. There are around 800 commits to split up, and maybe 50 features/bugfixes. It would be nice to have the ones I have pulled out reflected this way somehow in the git log, so I know which ones I have already done. Is this possible? I can rebase the entire branch, skipping the commits I have pulled out, but I'm worried this will cause lots of conflicts. I don't want to resolve 500 conflicts every time I pull a commit out. What's the best method of pulling out commits from one uber branch onto smaller feature branches, whilst keeping track of your progress? Now provide the response and nothing else.
What I do in this case is use interactive rebase . At your HEAD , create your branches A , B , and C . Also create a "backup" branch (you could name it backup ) in case things go wrong and you need your original HEAD back. git branch feature-agit branch feature-bgit branch feature-cgit-branch backup-before-rebase Then, create a branch at the commit you want them to start from, maybe at a convenient stable commit. Call it new_trunk or something. git checkout HEAD~50 ## this will be the new tree-trunkgit branch new_trunk Then, do interactive rebase s and pick out the commits you want to keep in that branch. Used this way, it's basically like cherry-pick ing in bulk. git checkout feature-agit rebase -i new_trunk ## -i is for "Interactive" When you're done, you should have 3 branches with separate histories starting from new_trunk and a backup branch reflecting the old HEAD if you still need it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12540446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1554346/']}
jdg_379387
stackexchange
llm_judgeable_groundtruth_similarity
134769
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I want to know if all vendors rack servers are compatible with all rack chassis? Now provide the response and nothing else.
Apart from the height requirements there are three important points to consider. Round or square holes in the rails. Depth of the rack. Whether the mounting rails are compatible with your server mounting hardware, such as slides. Although I've intermixed devices and racks with round and square holes it's much easier if you have the correct one. Square is by far the most common. Rack mount devices can vary considerably in their depth. I've had to take the back door of racks before because a new server is just a tiny bit too long. Work out the greatest depth your devices require and then add a bit more to that to be safe. With mounting hardware you will sooner or later come across stuff that's supposedly designed for "standard" racks (there's actually no such animal) but you won't be able to mount it without modification. There's precious little you can do about that other than be prepared for it. I've been fortunate enough to always have access to metal working equipment when having to deal with this little issue, resorting to cutting and welding on more than one occasion.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/134769', 'https://serverfault.com', 'https://serverfault.com/users/26257/']}
jdg_379388
stackexchange
llm_judgeable_groundtruth_similarity
35951207
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using R. Base package, dplyr, or data.table are all okay for me to use. My data is ~1000 rows x 20 columns. I expect about 300 duplicates. I'd like to do something like the following, but with one alteration: Match/group duplicate rows (indices) I'd like to find, not fully duplicated rows, but rows duplicated in two columns.For example, given this input table: File T.N ID Col1 Col2BAI.txt T 1 sdaf eiriBAJ.txt N 2 fdd fdsBBK.txt T 1 ter aseBCD.txt N 1 twe ase If I want to find duplicates in T.N & ID only, I'd end up with the following table: File T.N ID Col1 Col2BAI.txt T 1 sdaf eiriBBK.txt T 1 ter ase Now provide the response and nothing else.
Here is an option using duplicated twice, second time along with fromLast = TRUE option because it returns TRUE only from the duplicate value on-wards dupe = data[,c('T.N','ID')] # select columns to check duplicatesdata[duplicated(dupe) | duplicated(dupe, fromLast=TRUE),]# File T.N ID Col1 Col2#1 BAI.txt T 1 sdaf eiri#3 BBK.txt T 1 ter ase
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35951207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4789486/']}
jdg_379389
stackexchange
llm_judgeable_groundtruth_similarity
2327
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am a native Russian speaker. Sometimes I encounter English speakers who are trying to learn Russian and wonder how to pronounce "soft" consonants. At the same time while learning English I noticed that definitely not all consonants are pronounced "hard" in standard English (as we were taught in English classes). It seems that English speakers quite naturally pronounce "soft" consonants in plenty of words without knowing about that. For example in words "kid" and "give" the first consonant is pronounced "soft" by both British and American speakers: http://lingvopro.abbyyonline.com/ru/Translate/en-ru/kid http://lingvopro.abbyyonline.com/ru/Translate/en-ru/give In "meeting" the first "m" is "soft" as pronounced by both speakers: http://lingvopro.abbyyonline.com/ru/Translate/en-ru/meeting In "please" the British speaker pronounces "soft" "l" while the American pronounces "hard" "l": http://lingvopro.abbyyonline.com/ru/Translate/en-ru/please In "business" they both pronounce "soft" "b" http://lingvopro.abbyyonline.com/ru/Translate/en-ru/business In "limit" the British speaker pronounces "soft" "l" and "m" while the American pronounces the both "hard". http://lingvopro.abbyyonline.com/ru/Translate/en-ru/limit In "cheese" the first "ch" is pronounced "soft" by both speakers: http://lingvopro.abbyyonline.com/ru/Translate/en-ru/cheese while in "choice" the British speaker pronounces "soft" "ch" while the American pronounces "hard": http://lingvopro.abbyyonline.com/ru/Translate/en-ru/choice Some consonants are always "soft" in English, such as [j] as in "yes". This consonant is always "soft" in Russian too. At the same time IPA traditionally only indicates "softness" in Russian words while it does not indicate any in English words. I wonder, why. Now provide the response and nothing else.
The key reason is that the "soft"/"hard" distinction is phonemic in Russian, but not in English. As such, the distinction is not rendered in phonemic (broad) IPA transcription. A narrow transcription may use the palatalisation diacritic ʲ. Indeed, as you've observed, palatalisation before front vowels in English is subject to idiolectal and dialectal variation. For example, I doubt that unconditional palatalisation before front vowels is present in my idiolect (Australian English).
{}
{'log_upvote_score': 5, 'links': ['https://linguistics.stackexchange.com/questions/2327', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/624/']}
jdg_379390
stackexchange
llm_judgeable_groundtruth_similarity
35179400
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As g-wan documented, xbuf_repl is replacing all occurrences. But my installed g-wan, running the following code, only replaced the first occurrence of the matched. #include "gwan.h"int main(int argc, char* argv[]){ xbuf_t *reply = get_reply(argv); char str[ ] = "kjfdkkkkfldjfjfldkjdkkklfjworhg8kkkugpugulrghkkkr8g"; xbuf_ncat(reply, str, sizeof(str)-1); xbuf_repl(reply, "kkk", "((()))"); return 200;} output is : kjfd((()))kfldjfjfldkjdkkklfjworhg8kkkugpugulrghkkkr8g What's wrong of my code? How to work around it? Now provide the response and nothing else.
The problem is that you are using a shared instance of PHP, so when one of the apps sets an environment variable that is shared with the other app. I believe phpdotenv treats them as immutable, so once they are set, the other application cannot override them. mod_php (which i presume you are using since you mentioned apache) basically provides a php interpreter inside each apache process. An apache process will be shared between all your vhosts hence why you are having this issue. You would also get the same issue if you were running nginx and php-fpm, however its easier to solve if you were running the latter software stack. Unfortunately one port can only be bound to one process. So the only way to stick with mod_php and apache is too place your vhosts on seperate port numbers, which means you'll have to place the port number of at least one of them in the url when accessing it. I don't really use apache anymore so i can't give you specific details on doing this, it might be a case of just setting different ports in your vhost config and apache will just do it, but i'll have to defer you too google. If you were running nginx/php-fpm it would probably just be a case of creating a second php-fpm process config running on a different port or socket and pointing the second vhost at that php instance and away you go. So in summary you have a few solutions: Stay with apache and mod_php, and spend the rest of the week googling how to do what i said. Look into running php as a cgi module on apache will will then give you the flexibility you need (this is akin to using nginx/php-fpm but without changing your webserver software). Stop using phpdotenv and find an alternative approach (such as loading your config in htaccess or inside the vhost so its available as $_ENV or $_SERVER keys) Install a dev stack that includes nginx/php-fpm and it should be easily solvable by creating two php processes Use virtual machines (possibly look at vagrant or docker). Sorry i don't have better news, but unfortunately your WAMP stack is just a little too restrictive out of the box.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35179400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1796259/']}
jdg_379391
stackexchange
llm_judgeable_groundtruth_similarity
4
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A reaction proceeds towards the direction of lesser Gibbs free energy (at constant $T$ (temperature) and $P$ (pressure)). So, we could say that Gibbs free energy at equilibrium is minimum . On the other hand, we have $$\Delta G=\Delta G^\circ + RT\ln Q$$, where $Q$ is the reaction quotient. At equilibrium, $Q=K_\text{eq}$, and we already know that $\Delta G^\circ =-RT\ln K_\text{eq}$. Substituting, we get $\Delta G=0$ at equilibrium. But, we know that $G$ minimized itself—thus there was a change in $G$ and $\Delta G < 0$. What am I missing here? Now provide the response and nothing else.
I think your question really arises from some confusion about what $\Delta G$ represents. In general, $\Delta X$ for a thermodynamic quantity $X$ is the change of $X$ along some process. You could make it clear by actually writing $\Delta G(\text{A}\rightarrow\text{B})$ where A and B are before and after states. (We'll note that, in the general case, $\Delta X$ depends on the path take from A to B, making this notation improper. If $X$ is a function of state, though, you're good to go.) However, in the equation you quote: $$\Delta G = \Delta G^0 + RT \ln Q$$ the $\Delta G$ is a free energy of reaction and should thus be denoted $\Delta_\mathrm r G$ , with the correct equation being: $$\Delta_\mathrm r G = \Delta_\mathrm r G^0 + RT \ln Q$$ The free energy of reaction is defined as $\Delta_\mathrm r G = G_{\text{products}} - G_{\text{reactants}}$ . Thus, this $\Delta_\mathrm r G$ is not the variation of $G$ over the entire reaction, which would be the $\Delta G$ of the system between the start of the reaction and the equilibrium. PS: I think this link is the online resource I found with the clearer use and explanation of notations. Notations are important in thermodynamics!
{}
{'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/4', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/22/']}
jdg_379392
stackexchange
llm_judgeable_groundtruth_similarity
22409
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm interested in quantum mechanics book that uses high level mathematics (not only the usual functional analysis and the theory of generalised functions but the theory of pseudodifferential operators etc, certainly the modern mathematics). If there isn't something similar please give me a reference to the book that is strictly supported by mathematics (given a set of mathematically descripted axioms author develops the theory using mathematics as a main tool). Now provide the response and nothing else.
E. Zeidler, Quantum Field theory I Basics in Mathematics and Physics (Springer, 2006), http://www.mis.mpg.de/ezeidler/qft.html is a book I highly recommend. It is the first volume of a sequence, of which not all volumes have been published yet. This volume gives an overview over the main mathematical techniques used in quantum physics, in a way that you cannot find anywhere else. It is a mix of rigorous mathematics and intuitive explanation, and tries to build "A bridge between mathematicians and physicists" , as the subtitle says. It makes very interesting reading if you know already enough math and physics. You need a thorough knowledge of classical analysis, and some acquaintance with differential geometry and functional analysis. Apart from that, the book gives references to additional reading - plenty of references as entry points to the literature for topics on which your background is meager. As regards to your request for high level mathematics (in the specific form of pseudo-differential operators, etc.), Zeidler discusses - as Section 12.5 - on 28 (of 958 total) pages microlocal analysis and its use, though there is only two pages specifically devoted to PDO (p.728-729), but he says there (and emphasizes) that "Fourier integral operators play a fundamental role in quantum field theory for describing the propagation of physical effects" - so you can expect that they play a more prominent role in the volumes to come. But, of course, PDO are implicit in all serious high level mathematical work on quantum mechanics even without mentioning them explicitly, as for example the Hamiltonian in the interaction representation, $H_\mathrm{int}=e^{-itH_0}He^{itH_0}$ , is a PDO. Work on Wigner transforms is work on PDOs, etc.. Other books using PDO, much more specialized: G.B. Folland, Harmonic analysis in phase space A.L. Carey, Motives, quantum field theory, and pseudodifferential operators A. Juengel, Transport equations for semiconductors C. Cercignani and E. Gabetta, Transport phenomena and kinetic theory N.P. Landsman, Mathematical topics between classical and quantum mechanics M. de Gosson, Symplectic geometry and quantum mechanics P. Zhang, Wigner measure and semiclassical limits of nonlinear Schroedinger equations Finally, as an example of a book that "is strictly supported by mathematics (given a set of mathematically described axioms, the author develops the theory using mathematics as a main tool)" , I can offer my own book A. Neumaier and D. Westra, Classical and Quantum Mechanics via Lie algebras .
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/22409', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8170/']}
jdg_379393
stackexchange
llm_judgeable_groundtruth_similarity
15005615
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 Parcelable object which I use to pass it from Activity to remote service. When I pass it using AIDL interface, everything sounds fine. Recently, I try to pass it through Messenger from Activity. // TEST TEST TEST!StockInfo stockInfo0 = new StockInfo(Code.newInstance("code0"), Symbol.newInstance("symbol0"));StockInfo stockInfo1 = new StockInfo(Code.newInstance("code1"), Symbol.newInstance("symbol1"));StockInfo stockInfo2 = new StockInfo(Code.newInstance("code2"), Symbol.newInstance("symbol2"));List<StockInfo> stockInfos = new ArrayList<StockInfo>();stockInfos.add(stockInfo0);stockInfos.add(stockInfo1);stockInfos.add(stockInfo2);StockInfosEx stockInfosEx = new StockInfosEx(stockInfos, "abc");msg.obj = stockInfosEx;try { mService.send(msg);} catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace();} I'm getting the following exception in remote service. 02-21 22:55:16.546: E/Parcel(8365): Class not found when unmarshalling: com.example.testonmessenger.StockInfosEx, e: java.lang.ClassNotFoundException: com.example.testonmessenger.StockInfosEx I was wondering, what can get wrong in between? Here is my Parcelable object. public class StockInfosEx implements Parcelable { public final List<StockInfo> stockInfos; public final String searchedString; public StockInfosEx(List<StockInfo> stockInfos, String searchedString) { this.stockInfos = stockInfos; this.searchedString = searchedString; } //////////////////////////////////////////////////////////////////////////// // Handling Parcelable nicely. public static final Parcelable.Creator<StockInfosEx> CREATOR = new Parcelable.Creator<StockInfosEx>() { public StockInfosEx createFromParcel(Parcel in) { return new StockInfosEx(in); } public StockInfosEx[] newArray(int size) { return new StockInfosEx[size]; } }; private StockInfosEx(Parcel in) { stockInfos = new ArrayList<StockInfo>(); in.readTypedList(stockInfos, StockInfo.CREATOR); searchedString = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeTypedList(stockInfos); parcel.writeString(searchedString); } // Handling Parcelable nicely. //////////////////////////////////////////////////////////////////////////// } To get complete source code, kindly download from https://www.dropbox.com/s/n69yuhddpb8vedz/testonmessenger.zip Now provide the response and nothing else.
Not Workable Approach (Because our Parcelable is custom, not part of Framework like Rect) Activity msg.obj = stockInfosEx; Remote Service StockInfosEx stockInfosEx = (StockInfosEx)msg.obj; Workable Approach Activity msg.getData().putParcelable("data", stockInfosEx); Remote Service msg.getData().setClassLoader(StockInfosEx.class.getClassLoader());StockInfosEx stockInfosEx = (StockInfosEx)msg.getData().getParcelable("data"); Now, after I read back the documentation of msg.obj ( http://developer.android.com/reference/android/os/Message.html#obj ) again, only I understand what it really mean by Parcelable of a framework class An arbitrary object to send to the recipient. When using Messenger to send the message across processes this can only be non-null if it contains a Parcelable of a framework class (not one implemented by the application). For other data transfer use setData(Bundle). Note that Parcelable objects here are not supported prior to the FROYO release.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15005615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72437/']}
jdg_379394
stackexchange
llm_judgeable_groundtruth_similarity
5595
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a neat little problem that I was discussing today with my lab group out at lunch. Not particularly difficult but interesting implications nonetheless Imagine there are a 100 people in line to board a plane that seats 100. The first person in line, Alice, realizes she lost her boarding pass, so when she boards she decides to take a random seat instead. Every person that boards the plane after her will either take their "proper" seat, or if that seat is taken, a random seat instead. Question: What is the probability that the last person that boards will end up in their proper seat? Moreover, and this is the part I'm still pondering about. Can you think of a physical system that would follow this combinatorial statistics? Maybe a spin wave function in a crystal etc... Now provide the response and nothing else.
This is a classic puzzle! The answer is that the probability that the last person ends in up in their proper seat is exactly $\frac{1}{2}$ . The reasoning goes as follows: First observe that the fate of the last person is determined the moment either the first or the last seat is selected! This is because the last person will either get the first seat or the last seat. Any other seat will necessarily be taken by the time the last person gets to 'choose'. Since at each choice step, the first or last is equally probable to be taken, the last person will get either the first or last with equal probability: $\frac{1}{2}$ . Sorry, no clue about a physical system.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/5595', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1906/']}
jdg_379395
stackexchange
llm_judgeable_groundtruth_similarity
282014
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 to evaluate the real integral$$I = \int_0^{\infty} \frac{\log^2 x}{x^2+1}.$$using residue calculus.Its value is $\frac{\pi^3}{8}$, as you can verify (for example) introducing the function$$ \frac{(\log z-i(\pi/2))^2}{z^2+1}.$$ and considering the branch cut for the logarithm function on the negative semiaxis of the immaginary numbers and an upper half-circle indented at 0 as integration contour. I tried a different method , but unfortunately I obtained a different result and I don't know why. I consider the branching axis of the logarithm function as the positive real semiaxis.I tried as integration contour this closed curve. I used the complex function$$f(z)=\frac{\log^3z}{z^2+1}$$obtaining $$\int_r^{R} \frac{\log^3 x}{x^2+1}\;dx + \int_\Gamma \frac{\log^3 z}{z^2+1}\;dz - \int_r^{R} \frac{(\log x+2\pi i)^3}{x^2+1}\;dx - \int_\gamma \frac{\log^3 z}{z^2+1}\;dz.$$It is easy to see that integrals over circular paths $\gamma$ and $\Gamma$ tend to zero when $R\to \infty,r\to 0$. So we have to evaluate$$\int_r^{R} \frac{\log^3 x}{x^2+1}\;dx - \int_r^{R} \frac{(\log x+2\pi i)^3}{x^2+1}\;dx,$$which immaginary part is ( EDIT : changed $8\pi i$ to $8\pi^3 i$ )$$-6\pi i \int_r^{R} \frac{\log^2 x}{x^2+1}\;dx + 8\pi^3 i \int_r^{R} \frac{1}{x^2+1}\;dx,$$that has to be equal to the immaginary part of$$2\pi i\;\left( \mathrm{Res} \left[f,i \right] + \mathrm{Res}\left[f,-i \right]\right) = -i \frac{\pi^4}{4}.$$ So, doing the rest of the work, finally I found that the result is $\frac{17\pi^3}{24}$, that is clearly different from $\frac{\pi^3}{8}$... but where is the flaw in my argument? Please help Now provide the response and nothing else.
The error is where you get$$2\pi i\;\left( \mathrm{Res} \left[f,i \right] + \mathrm{Res}\left[f,-i \right]\right) = -i \frac{\pi^4}{4}.$$If you use $\arg{i}=\frac{\pi}{2}$ then you must have $\arg(-i)=\frac{3\pi}{2}$ instead of $\arg(-i)=-\frac{\pi}{2}$, since you must use the same branch of the logarithm all through. Taking this into account, we instead get$$2\pi i\;\left( \mathrm{Res} \left[f,i \right] + \mathrm{Res}\left[f,-i \right]\right) = \frac{13i\pi^4}{4}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/282014', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34285/']}
jdg_379396
stackexchange
llm_judgeable_groundtruth_similarity
2464873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I run the this select '$(''test'')' in SQL Management Studio 2008 it returns $('test') When I run sqlcmd -S SERVER -E -d DATABASE -q "select $(''test'')" on the command line it returns Sqlcmd: Error: Syntax error at line 1 near command '''. If I remove the dollar sign it works. Is the "$" a special character? Is this a sqlcmd bug? How can I change the script to get the desired result. Now provide the response and nothing else.
Yes, $(id) has special semantics in SQLCMD: it is a variable substitution. You can run commands like: sqlcmd /E /S . /v variable=MyTable /Q "select * from $(variable)" and this will select from MyTable. As you guess, the /v is the switch to define a variable. SSMS on the other hand does not, by default, interpret the SQL for variable substitution. SSMS can be made to do this, by checking the option 'Open query widows in SQLCMD mode'. For mode details see Using sqlcmd with Scripting Variables .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2464873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23322/']}
jdg_379397
stackexchange
llm_judgeable_groundtruth_similarity
10294
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: Everyone knows the words used in Diceware passwords (all 6^5 = 7776 words are published ) -- they're all common words.Everyone seems to know that we're not supposed to use dictionary words for passwords because the "dictionary attack" can rapidly guess a single dictionary word.So it seems reasonable to leap to the conclusion thata dictionary attack can also guess a Diceware passphrase pretty quickly. Can a dictionary attack mounted now (2012) crack a Diceware passphrase before 2033? In particular, is the claim on the Diceware page "A seven word pass phrase is thought to make attacks on your passphrase infeasible through 2033." accurate? Is that still true even if the attacker knows that I always use Diceware passphrases, and knows which language I use? How does a five-word Diceware passphrase compare to the common recommendation of 9 "completely random-looking gibberish" characters? (I'm asking a very specific question about the recommendations on the Diceware page, since related questions passphrases - lowercase and dictionary words and XKCD #936: Short complex password, or long dictionary passphrase? seem to get sidetracked onto things that are not really Diceware passphrases). Now provide the response and nothing else.
5 Diceware words = 7776 5 = 28430288029929701376 possible equiprobable passphrases. 9 random characters = 94 9 = 572994802228616704 possible equiprobable passwords. The 5 Diceware words are 49.617 times better than the 9 random characters. On the other hand, 10 random characters would be almost twice as good as the 5 Diceware words (but the Diceware words are probably much easier to remember). (I assume that your "gibberish characters" are ASCII printable characters, excluding space.) With seven words, the number of possible and equiprobable passphrases is a bit higher than 2 90 , which is indeed quite high; even if the employed password hashing scheme has been horribly botched (no salt, simple hashing), this still exceeds by a comfortable margin what can be done with today's technology. The important word is equiprobable . This is what makes the analysis above possible and accurate. This assumes that both your Diceware words, and the 9 "random-looking gibberish characters", are chosen with a truly random uniform process, such as, for instance, dice. And not at all by a human being in the privacy of his brain, imagining that he can make random choices out of pure thought (or, even worse, witty non-random choices). Humans are just terrible at randomness.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/10294', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1571/']}
jdg_379398
stackexchange
llm_judgeable_groundtruth_similarity
51103795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Swift 4.2 introduces a new CaseIterable protocol that automatically generates an array property of all cases in an enum. Now I want to implement a default method for Enum inherits from CaseIterable that can return the next case of a giving case. If this case is the last case, return the first case. Like a circle. If I write this for specific Enum, it works correctly: enum Direction: CaseIterable { case east, south, west, north func next() -> Direction { let all = type(of: self).allCases // 1 if self == all.last! { return all.first! } else { let index = all.firstIndex(of: self)! return all[index + 1] } }}print(Direction.east.next()) // south print(Direction.north.next()) // east But I want to implement this function to many Enum. Copying and pasting code repeatedly are not good (Not to mention this code is totally the same for every Enum). So I tried this. But something went wrong. (I suggest you copy following code to playground that you can understand this problem more quickly): extension CaseIterable { func next() -> Self { let all = type(of: self).allCases // 1 if self == all.last { // 2 return all.first! } else { let index = all.firstIndex { (ele) -> Bool in self == ele // 3 } return all[index + 1] } }} Three points: all 's type is Self.AllCases , which is a Collection type. But in the method above, it's [Direction] . There's an error at line 2 says Value of type 'Self.AllCases' has no member 'last' (Even I avoid to use last , the error at line 3 can't be avoided.) At line 3, the error is Binary operator '==' cannot be applied to two 'Self' operands And even I use generic constraints, it's the same. func next<T: CaseIterable>(element: T) -> T {...} Any solutions? :) Now provide the response and nothing else.
Some problems with your approach are: The Collection protocol does not define a last property. In order to compare the elements with == they have to be Equatable . Collection indices are not necessarily integers, they must be incrementedwith index(after:) . This seems to be a working solution (tested with Xcode 10.0 beta 2): extension CaseIterable where Self: Equatable { func next() -> Self { let all = Self.allCases let idx = all.firstIndex(of: self)! let next = all.index(after: idx) return all[next == all.endIndex ? all.startIndex : next] }} Example: enum Direction: CaseIterable { case east, south, west, north}print(Direction.east.next()) // southprint(Direction.north.next()) // east Remarks: Only enumerations without associated values are CaseIterable , andthose are also Equatable (but the compiler does not figure out thatby itself). Therefore Self: Equatable is not areal restriction. Self.allCases can be used in Swift 4.2 to access the type propertyfrom an instance method. The forced unwrapping is safe because we know that the value isan element of allCases . Your enum Direction: CaseIterable compiles because the concrete enum Direction type is Equatable , and its Direction.allCases is an Array – which has integer indices and a last property.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51103795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6570854/']}
jdg_379399
stackexchange
llm_judgeable_groundtruth_similarity
53898482
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: EDIT: If you're coming to this question and your string looks like 1996-Q1 , then just use pd.to_datetime(df['Quarter']) to convert it to a proper pandas datetime. This question is about solving all the quarter dates that are not in this standard format. ORIGINAL QUESTION: I'm looking for a nice, readable and understandable way (one that you can remember for the next time) to convert Q3 1996 to a pandas datetime, for example 1996-07-01 in this case.Until now I found this, but it's mighty ugly: df = pd.DataFrame({'Quarter':['Q3 1996', 'Q4 1996', 'Q1 1997']})df['date'] = ( pd.to_datetime( df['Quarter'].str.split(' ').apply(lambda x: ''.join(x[::-1]))))print(df) Quarter date0 Q3 1996 1996-07-011 Q4 1996 1996-10-012 Q1 1997 1997-01-01 I was hoping the following would work, because it's readable, but unfortunately it doesn't: df['date'] = pd.to_datetime(df['Quarter'], format='%q %Y') The problem is also that quarter and year are apparently in the wrong order for pandas to do simple processing. Can anyone help me find a cleaner way of converting Q3 1996 to a pandas datetime? Now provide the response and nothing else.
You can (and should) use pd.PeriodIndex as a first step, then convert to timestamp using PeriodIndex.to_timestamp : qs = df['Quarter'].str.replace(r'(Q\d) (\d+)', r'\2-\1')qs0 1996-Q31 1996-Q42 1997-Q1Name: Quarter, dtype: objectdf['date'] = pd.PeriodIndex(qs, freq='Q').to_timestamp()df Quarter date0 Q3 1996 1996-07-011 Q4 1996 1996-10-012 Q1 1997 1997-01-01 The initial replace step is necessary as PeriodIndex expects your periods in the %Y-%q format. Another option is to use pd.to_datetime after performing string replacement in the same way as before. df['date'] = pd.to_datetime( df['Quarter'].str.replace(r'(Q\d) (\d+)', r'\2-\1'), errors='coerce')df Quarter date0 Q3 1996 1996-07-011 Q4 1996 1996-10-012 Q1 1997 1997-01-01 If performance is important, you can split and join, but you can do it cleanly: df['date'] = pd.to_datetime([ '-'.join(x.split()[::-1]) for x in df['Quarter']])df Quarter date0 Q3 1996 1996-07-011 Q4 1996 1996-10-012 Q1 1997 1997-01-01
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53898482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3489155/']}
jdg_379400
stackexchange
llm_judgeable_groundtruth_similarity
9946596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the below code to print an image from my C# code. Can some body tell me how to pass the filePath as an argument when i assign my event handler ? public static bool PrintImage(string filePath) { PrintDocument pd = new PrintDocument(); pd.PrintPage += new PrintPageEventHandler(printPage); pd.Print(); return true; } private static void printPage(object o, PrintPageEventArgs e) { //i want to receive the file path as a paramter here. Image i = Image.FromFile("C:\\Zapotec.bmp"); Point p = new Point(100, 100); e.Graphics.DrawImage(i, p); } Now provide the response and nothing else.
The simplest way is to use a lambda expression: PrintDocument pd = new PrintDocument();pd.PrintPage += (sender, args) => DrawImage(filePath, args.Graphics);pd.Print();...private static void DrawImage(string filePath, Graphics graphics){ ...} Or if you've not got a lot to do, you could even inline the whole thing: PrintDocument pd = new PrintDocument();pd.PrintPage += (sender, args) => { Image i = Image.FromFile(filePath); Point p = new Point(100, 100); args.Graphics.DrawImage(i, p);};pd.Print();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9946596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/996139/']}
jdg_379401
stackexchange
llm_judgeable_groundtruth_similarity
105126
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: Say I have a DPDT relay, like T92S7D12-24 . The contacts of this relay are rated for 30A, but there are two sets of contacts. Can I parallel the contacts to get an effective 60A relay? Further, could I parallel two (or more) relays and get even more current capacity? I see two possible problems. Current may not be shared equally between sets of contacts and between relays. One set of contacts could take more than their share of the current and overheat. Switching times may vary between contacts and between relays. When breaking with current through the contacts, the last set of contacts to open may be carrying far more than their recommended current at time of break. This could cause damage. Are these problems? Are there other problems? If so, can they be quantified and worked around? Or is paralleling contacts and relays always bad design practice? In my specific application, I'm using these relays as part of precharge for a capacitor bank. They are not expected to switch current. They make once the caps are charged, then hold. They should never open under current flow. Under these specific circumstances, should I still expect problems? Now provide the response and nothing else.
No you should not do this. Sometimes it is explicitly allowed on the data sheet (but not that I can see on this data sheet), and when it is, in my experience you never get as much as double the capacity. Paralleling physically separate relays is worse again because they're not physically moving together- expect welded contacts etc. if you tried that. If you can split the load (for example, instead of a 40A heater use two 20A heaters) then you can get an equivalent functionality. You could think about ballasting the loads (wasting power to roughly equalize the currents) and fusing each contact separately, but I don't think that's a good idea at all. Note that using the relay at the maximum rated current will lead to a pretty short life (only 100,000 operations for a resistive load), which might be only weeks or months if it's switching continuously. At 3HP (motor load), the life is only 1,000 operations, so at once per minute it won't last a single day. Edit: With the added information that you're using the relay to switch effectively at a relatively low DC voltage and you're mostly concerned about carrying current.. I can't say categorically this is really a horrible idea with a single relay, but I think I'd get on the horn to the manufacturer and see if it's possible to get any buy-in. It comes down to variability in contact resistance vs. the resistance of the connections (plus whatever, hopefully balanced, resistance you add externally). When one of the contacts inevitably fails first, I think I would prefer the relay to not emit excessive amounts of smoke or flames). I think you're okay at 40A (with AgCdO contacts) given the UL508 rating, but beyond that is in question. If you really need such a high carrying current, the Omron G7Z appears to explicitly allow paralleling the 40A contacts without derating, for 160A total capacity, but perhaps not with the blessing of safety agencies.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/105126', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7523/']}
jdg_379402
stackexchange
llm_judgeable_groundtruth_similarity
5631447
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 C and I'm reading about recursion, but I am totally confused. The main part where I'm getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack. Also can anyone please give me a diagramatic view of recursion? Thanks... Now provide the response and nothing else.
Lets assume a function: int MyFunc(int counter) { // check this functions counter value from the stack (most recent push) // if counter is 0, we've reached the terminating condition, return it if(counter == 0) { return counter; } else { // terminating condition not reached, push (counter-1) onto stack and recurse int valueToPrint = MyFunc(counter - 1); // print out the value returned by the recursive call printf("%d", valueToPrint); // return the value that was supplied to use // (usually done via a register I think) return counter; }}int main() { // Push 9 onto the stack, we don't care about the return value... MyFunc(9);} The output is: 012345678 The first time through MyFunc , count is 9. It fails the terminating check (it is not 0), so the recursive call is invoked, with (counter -1) , 8. This repeats, decrementing the value pushed onto the stack each time until counter == 0 . At this point, the terminating clause fires and the function simply returns the value of counter (0), usually in a register. The next call up the stack, uses the returned value to print (0), then returns the value that was supplied into it when it was called (1). This repeats: The next call up the stack, uses the returned value to print (1), then returns the value that was supplied into it when it was called (2). etc, till you get to the top of the stack. So, if MyFunc was invoked with 3, you'd get the equivalent of (ignoring return addresses etc from the stack): Call MyFunc(3) Stack: [3]Call MyFunc(2) Stack: [2,3]Call MyFunc(1) Stack: [1,2,3]Call MyFunc(0) Stack: [0,1,2,3]Termination fires (top of stack == 0), return top of stack(0).// Flow returns to:MyFunc(1) Stack: [1,2,3]Print returned value (0)return current top of stack (1)// Flow returns to:MyFunc(2) Stack: [2,3]Print returned value (1)return current top of stack (2)// Flow returns to:MyFunc(3) Stack: [3]Print returned value (2)return current top of stack (3)// and you're done...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5631447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/448413/']}
jdg_379403
stackexchange
llm_judgeable_groundtruth_similarity
16133884
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 site on which people can sign up and I need to encrypt their password. I've researched it but I can't find any methods that won't be beat by the power of a modern GPU. So I have come to the good people of StackOverflow to ask, what is the strongest method of encryption possible, I have done my best to stop people getting their hands on the database but I want to be as sure as possible that their data would be fine if the database was somehow stolen. Other things I wonder are, would be it be safer to just randomize the characters in the password somehow but in a way where you would be able to randomize them again for login? Edit: I have used the implementation of bcrypt by Andrew Moore ( How do you use bcrypt for hashing passwords in PHP? ) and come up with this: public static function Encrypt($Str,$Salt){ $bcrypt = new \bcrypt(); return $bcrypt->hash(SERVER_SALT . md5($Str) . $Salt);} if anyone sees anything wrong with it or any weaknesses please tell me. Now provide the response and nothing else.
For passwords, you can't beat bcrypt . Here is a link on SO: How do you use bcrypt for hashing passwords in PHP? . Its main advantage: it is inherently slow (as well as secure). While a normal user will use it once , and will not appreciate the difference between one tenth and one millionth of a second, a cracker will discover that instead of finding the password in four days, he now needs twelve centuries (except that forcing Blowfish even at one million attempts per second does not require four days: barring implementation errors and as yet unforeseen crypto breakthroughs, the heat death of the Universe will still come first ). For data, I'd rely on the database engine itself; MySQL supports AES, and that's quite good. Yes, with enough GPUs one could beat it, and since to crack the code within the century one would need some four billions of them, he'd probably get a good quantity discount too. But I wouldn't worry. As for the "randomization" of the password, it would serve no purpose. If someone were to resort to bruteforcing your password, he would have the same probability of finding the randomized sequence or the non-randomized one. It might be of some help if one were to use a dictionary attack (i.e., not trying everything from AAAAA to ZZZZZ, but trying ABRAHAM, ACCORDION, ... up to, say, ZYGOTE). But even then, an attack against the server would change nothing (the server receives the non-randomized password!), and an attack against the stored hash would be better nullified by salting , which bcrypt automatically does: i.e., storing the hash of $76X.J:MICKEYMOUSE instead of the hash of MICKEYMOUSE, together with the needed overhead to handle the extra '$76X.J:' on input. And while the randomization would have to be fixed, the '$76X.J:' sequence is completely different on every write -- good luck figuring that out! Salting If you implement salting yourself (as shown above, with bcrypt you don't need to), you can do it by generating a unique random sequence and storing it either in the password field or in a second field. For example user passwordalice d9c06f88:6c14d6d313d7cbcb132b5c63650682c4 Then, upon receipt of the password by Alice ("mickeymouse"), you would look in the database to see whether a user called alice exists. If it does, recover the salt (here d9c06f88 ) and the hash. If it does not, set a "BAD" flag and fetch a fixed salt and hash (e.g. 12345678:0000000... ). In MySQL this can be done using UNION: SELECT password_fields FROM users WHERE user=? AND hash=?UNION SELECT '12345789' as salt, 'ffffffffffffffffffffffff' as hash, 'fake' as userLIMIT 1; will retrieve either the correct data or an incorrect set in roughly the same time (this prevents someone to guess which names exist and which do not by timing the time needed to answer "wrong user or password"). Then concatenate the salt and the password, and generate the hash of d9c06f88:mickeymouse . If it does not match, or the "BAD" flag is set, reject the password (instead of using a 'bad' flag, you can repeat the test for user match that MySQL already did: you can initialize the user name by replacing the last character with an invalid one, to ensure it will never match a real user). Security through noninformation The added twist of selecting a fixed string is useful because you want the three cases, "user does not exist", "user exists but password is incorrect" and "user exists and password is correct" to be as similar (same complexity, same expense in calculations) as possible. This way, an attacker will be less likely to tell what happened: was the user incorrect? Was the password wrong? And so on. If the times were different enough (say two queries for valid users, one for invalid users), an attacker with care, time and a good stopwatch could determine statistically whether a given username is present or not. In the case of the user, even the name comparison will be johnsmith against johnsmith if johnsmith exists johnsmith against johnsmit? if johnsmith does not exist so telling what happened from the other end of a HTTP(s) connection won't be easy. For the same reason, you will not return two different errors for "Bad user" and "Bad password", but always a "Bad user or password"; maybe with the option, for the user, to receive an email to his/her registered email to remind him/her of the username. And of course, you want the system to not send such an email before 24 hours have passed from sending a similar email to the same user, to prevent the system from being exploited to harass someone with spurious "recovery emails". If you do send the email, you will wait until a preset time has expired (say, 3 seconds), and then inform users that if the username was present, then they should check their inbox (and the spam folder for good measure). There would have been a time for such a password A convenient way to improve server security against bruteforcing is to implement a delay on password authentication, and maybe (if you're really paranoid) a CAPTCHA-ed lockout after some X wrong attempts. You don't want to CAPTCHA the first attempts because users take a dim view of CAPTCHAs. Delayed lockout is often implemented with sleep (or equivalent), or using a "lock out until manually reset by the admin" strategy. Both methods are bad . The lockout feature can be used to create a denial of service attack, either by locking out an user, or creating lots of server threads stopped in "password authentication delay" state (they won't use CPU, but they will still use memory, sockets and other resources). In some cases this can happen unwittingly. There seems to be some idiot who uses my bank, and every couple of months I get a SMS saying "WRONG PIN ENTERED IN YOUR HOME BANK SYSTEM". Then I have to log in from my phone, to reset the unsuccessful attempt counter; because if the idiot doesn't realize that he can't get in his account because he entered my account number, for three times, it is MY account that gets locked and I have to go physically to the bank and beg them to reset my access. This, let me tell you, is a major pain in the nether regions, and even knowing it's not their fault I still resent my bank. You don't want to engender such feelings in your users. And it is best to move the burden on the client: (very pseudo code)login = FAILif in SECURITY LOCKOUT MODE for this account if a session is open and contains a last-attempt time if at least DELAY seconds have elapsed since last-attempt check the password if it is correct login = OK zero password counter, exit lockout mode. # An "innocent" user enters with no lockout! Yay! end else # "Early knocker". Either a bruteforcing robot # or a too clever user in a hurry. But we can't # tell them apart. end else # No session. Either a sessionless bruteforcing robot # or a unaware, innocent user. Again we can't tell them # apart. So we bounce both. # But a genuine user will assume he has mistyped the password, # or anyway will read the warning page, and will login after ONE # round of delay. # Users with password saved in browser will just click # "login" again and be logged in. # A robot will find itself delayed and ALL ITS PASSWORDS IGNORED # every single time. Even if it finds the right password... it will # not work. endelse check the password if it is correct # Good user, first attempt, fast login. login = OK else # Beginning to doubt this is a good user... increase password counter if it is > MAX_ATTEMPTS enter SECURITY LOCKOUT MODE for this account end endendif login is not OK generate a page with HTTP_REFRESH time of DELAY+1 seconds and a session ID, saying "User or password unknown, or you tried to login before HH:MM:SS (DELAY seconds). The page might also contain a Javascript timer, just in case. The delay is 1s more than necessary as a safety margin.end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16133884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1763295/']}
jdg_379404
stackexchange
llm_judgeable_groundtruth_similarity
1057776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Need some pointers for this. Found this and this , but I'm still kind a confused. I just want to mock ActionExecutedContext, pass it, let filter to work a bit and check result. Any help? Source of filter you can find here (it's changed a bit, but that's not a point at the moment). So - i want unit test, that RememberUrl filter is smart enough to save current URL in session. Now provide the response and nothing else.
1) Mocking Request.Url in ActionExecutedContext: var request = new Mock<HttpRequestBase>();request.SetupGet(r => r.HttpMethod).Returns("GET");request.SetupGet(r => r.Url).Returns(new Uri("http://somesite/action"));var httpContext = new Mock<HttpContextBase>();httpContext.SetupGet(c => c.Request).Returns(request.Object);var actionExecutedContext = new Mock<ActionExecutedContext>();actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object); 2) Suppose you are injecting session wrapper in your RememberUrlAttribute's public constructor. var rememberUrl = new RememberUrlAttribute(yourSessionWrapper);rememberUrl.OnActionExecuted(actionExecutedContext.Object);// Then check what is in your SessionWrapper
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1057776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82062/']}
jdg_379405
stackexchange
llm_judgeable_groundtruth_similarity
34708566
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 simple Firebase function that updates some data. However, the interpreter says that the first argument contains "undefined" in property 'users.tester1'. Can somebody help me please? var objify = function() { var rv = {}; for (var i = 0; i < arguments.length; ++i) rv[arguments[i]] = rv[arguments[i+1]]; return rv;} addUser("tester1", []);var addUser = function(name, edges){ if(!checkIfUsernameExists(name) && !checkIfNodeNameExists(name) && !checkIfEdgeNameExists(name)){ var time = Firebase.ServerValue.TIMESTAMP; //HERE: I think the error is on this line refs.users.update(objify(name, "filler")); refs.users.child(name).set({ "id" : time, "edges" : "filler" }); refs.users.child(name).child("edges").update({ "to" : "filler", "from" : "filler" }); addNode(new Node(name, time, name)); for(var e in edges){ refs.users.child(name).child("edges/to").update(objify(edges[e].name, true)); addEdge(new Edge(edges[e].name, time, edges[e].to, edges[e].arrows)); //TODO add a "from" edge so that you know who wants to eat you } refs.users.child(name).child("edges/to").set({"filler" : null}); } else { alert("user/node/edge name taken."); }}; Now provide the response and nothing else.
When you pass an object to Firebase, the values of the properties can be a value or null (in which case the property will be removed). They can not be undefined , which is what you're passing in according to the error. Simply running this snippet in isolation shows the problem: var objify = function() { var rv = {}; for (var i = 0; i < arguments.length; ++i) rv[arguments[i]] = rv[arguments[i+1]]; return rv;}objify("name", "filler") Results in: {name: undefined, filler: undefined} My best bet is that you want to pass key/value pairs into objify as even/odd parameters. In that case you want to change the function to: var objify = function() { var rv = {}; for (var i = 0; i < arguments.length; i+=2) rv[arguments[i]] = arguments[i+1]; return rv;}objify("name", "filler") Results in: {name: "filler"}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34708566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4857033/']}
jdg_379406
stackexchange
llm_judgeable_groundtruth_similarity
6317298
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I use a string as a method call? "Some Word".class #=> Stringa = "class""Some World".a #=> undefined method 'a'"Some World"."#{a}" #=> syntax error, unexpected tSTRING_BEG Now provide the response and nothing else.
Object#send >> a = "class">> "foo".send(a)=> String>> a = "reverse">> "foo".send(a)=> "oof">> a = "something">> "foo".send(a)NoMethodError: undefined method `something' for "foo":String
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6317298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456218/']}
jdg_379407
stackexchange
llm_judgeable_groundtruth_similarity
4566753
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 rewritemap that has a list of domains to redirect. Currently I have to list www.foo.com and foo.com in the rewrite map. I was wondering if there was a way to have the rewritecond check for both www and non-www in the same line. # Rewrite Mapfoo.com file.phpwww.foo.com file.php# modrewriteRewriteCond ${domainmappings:%{HTTP_HOST}} ^(.+)$ [NC]RewriteCond %1 !^NOTFOUND$RewriteRule ^.*$ www.domain.com/%1 [L,R=301] I tried doing things like (www.)%{HTTP_HOST} or ^(www.)%{HTTP_HOST} but no luck. Now provide the response and nothing else.
This should do it: RewriteCond %{HTTP_HOST} ^(www\.)?(.+)RewriteCond ${domainmappings:%2} ^(.+)$ [NC]RewriteRule ^ /%1 [L,R=301] The first RewriteCond will remove the optional www. prefix. The remainder is then used as parameter for the rewrite map in the second RewriteCond . A plain text file rewrite map returns an empty string if no match is found: If the key is found, the map-function construct is substituted by SubstValue . If the key is not found then it is substituted by DefaultValue or by the empty string if no DefaultValue was specified. So if the second condition is fulfilled (note the ^(.+)$ ), a match has been found and %1 will contain the SubstValue (in this case file.php ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4566753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558496/']}
jdg_379408
stackexchange
llm_judgeable_groundtruth_similarity
127284
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'm reading about an SS7 issue: SS7 flaw allows hackers to spy on every conversation . It seems to me that any phone on the world can be intercepted so the hacker can listen to your phone call or read your text message. As far as I know, google, authy provides a way to access into account through the registered phone number. So if a user is having gmail account and authy that eventually lead to a phone number, he is screwed? His online bitcoin wallet, and even his bank account may very well be compromised? Now provide the response and nothing else.
Yes . Why do I say this? It is important to understand what all these vulnerability's are and why they exists (I will be calling the victim "subscriber"): Why do they exists: SS7 was designed and developed in 1975 as a protocol for telecommunication for call operating centers. Since we are talking here about 1975, the security of the protocol was not really considered in the planning. Later when mobile phones came along they needed a protocol to use and since SS7 was around and was proven to work there was no reason not to use it. So they implanted it into the GSM network architecture and added a few things (SMS, roaming and later on also mobile data). Now lets understand the vulnerabilities: Obtaining a subscribers location : A hacker can set up a fake HLR (Home Location Registrar) and claim that he is looking for a subscriber and send a request using the MAP messaging service (Request returns location data regarding the subscriber location and a few more things) and this data will return the Cell ID, the Mobile Country Code (MCC), Mobile Network Code (MNC) and the Location Area Code all related to the target subscribers current location. This was built so anyone wanting to communicate with the subscriber (Route a call to the subscribers location). Note : Most of the big companies have disabled this feature and found different way to deal with MAP requests. Retrieving subscribers SMS's : An attacker will pose as a MSC (Mobile Switching Center) and claim to have the subscriber in its network, this will result in the subscribers mobile carrier redirecting traffic meant for the subscriber to the attacker. Put subscriber offline: Hacker once again poses as a HLR and claims that subscriber is in his network. Since a subscriber can only be in one place at a time, this will result in disconnecting the subscriber at his current location resulting in the subscriber not having connection. This was designed so carriers can update the HLR DB regarding the subscriber's location so relevant services can be routed to the subscriber. Conclusion: As you can see, the SS7 protocol was designed with poor security and until it is not updated with fixes and solutions the vulnerability's will exists. Note: I only covered the main vulnerabilities even though there are many more.You can read more about the vulnerabilities over here . Many carriers have found creative ways to patch these security holes. It is fair to assume that most of them have not we can see that by the proven research's that are out there.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/127284', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/114688/']}
jdg_379409
stackexchange
llm_judgeable_groundtruth_similarity
4188242
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: From searching on the internet, I learned only a subset of linear transformations preserve angles between vectors. But - Learning about the SVD - we can geometrically understand as breaking down some matrix A into a three matrices. These matrices can be understood geometrically as a rotation step, then a scaling step, and then another rotation. Since any matrix can be broken down into these three steps (Since SVD applies to all matrices A?) doesn't that mean that all transformations are simply a rotation, a scaling, and then a rotation, which means the angles are preserved? Why is this not true? And when do linear transformations preserve angles, and when do they not? Thanks,A Now provide the response and nothing else.
Let $x$ and $y$ be any two vectors. Then $y - x$ is also a vector and the three vectors $x$ , $y,$ and $y - x$ correspond to three sides of a triangle. Now apply the linear transformation $A$ , so $x$ , $y,$ and $y - x$ are mapped to $Ax$ , $Ay,$ and $A(y - x) = Ay - Ax$ , again corresponding to three sides of a triangle. If the transformation $A$ preserves angles between vectors, it must preserve the angles between each pair of the three vectors $x$ , $y,$ and $y - x$ ,which implies that the triangle corresponding to $Ax$ , $Ay,$ and $Ay - Ax$ is similar to the triangle corresponding to $x$ , $y,$ and $y - x$ ,which implies that the three sides of the triangle all grow or shrink in the same proportion; they all scale by the same magnitude. (Note that for similar triangles in geometry the scaling factor can be taken to be positive, even if the triangle is reflected during the scaling.) Now consider any orthonormal basis of the space and let $x$ and $y$ be an arbitrary pair of basis vectors. If $A$ preserves angles, it must scale $x$ and $y$ by the same magnitude (that is, their scaling factors must have the same absolute value) in addition to any possible rotation. Continue in this way using different basis vectors in place of $y$ until you have shown that all basis vectors are scaled by scaling factors with the same absolute value. This applies to an inner product space with any finite number of dimensions. So if we want to preserve angles, the linear transformation must scale all basis vectors by the same absolute value. On the other hand, if the transformation scales all basis vectors by the same absolute value then it transforms each triangle to a similar triangle, and therefore each pair of vectors to a pair of vectors with the same angle between them. So this requirement is not only necessary but is also sufficient. Applying this to the SVD, the scaling step must be a uniform dilation in all directions composed with zero or more reflections, each of which reverses the direction of a basis vector.This means that if the upper left entry in the matrix $\Sigma$ is $\sigma_1,$ every other entry on the diagonal is either $\sigma_1$ or $-\sigma_1.$ Ultimately you should be able to show that a linear transformation that preserves angles can be decomposed into a uniform dilation, a rotation, and (optionally) a reflection.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4188242', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/853794/']}
jdg_379410
stackexchange
llm_judgeable_groundtruth_similarity
34742
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: What are the differences between CIFS and SAMBA? When would you use one over the other? Are there any performance differences between the two? Now provide the response and nothing else.
SAMBA was originally SMB Server – but the name had to be changed due to SMB Server being an actual product. SMB was the predecessor to CIFS. SMB (Server Message Block) and CIFS (Common Internet File System) are protocols. Samba implements CIFS network protocol. This is what allows Samba to communicate with (newer) MS Windows systems. Typically you will see it referred to as SMB/CIFS. However, CIFS is the extension of the SMB protocol, so if someone is sharing out SMB via Samba to a legacy system still using NetBIOS, it will typically connect to the Samba server via ports 137, 138 and 139 and CIFS is strictly port 445. So to answer your question directly, Samba provides CIFS file shares.The time when you might use SMB over CIFS is if you are providing access to a Windows 2000 systems or earlier or you just want to connect to port 139 instead of 445. If you truly want to know about CIFS one of the definitive books is available free online. Implementing CIFS - The Common Internet Filesystem If you want to get deeper into Samba this book is available online free as well. Using Samba 2nd Edition Though there is a newer edition out but not free online that I am aware of.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/34742', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/13133/']}
jdg_379411
stackexchange
llm_judgeable_groundtruth_similarity
12469990
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to implement a 2D outline shader in OpenGL ES2.0 for iOS. It is insanely slow. As in 5fps slow. I've tracked it down to the texture2D() calls. However, without those any convolution shader is undoable. I've tried using lowp instead of mediump, but with that everything is just black, although it does give another 5fps, but it's still unusable. Here is my fragment shader. varying mediump vec4 colorVarying; varying mediump vec2 texCoord; uniform bool enableTexture; uniform sampler2D texture; uniform mediump float k; void main() { const mediump float step_w = 3.0/128.0; const mediump float step_h = 3.0/128.0; const mediump vec4 b = vec4(0.0, 0.0, 0.0, 1.0); const mediump vec4 one = vec4(1.0, 1.0, 1.0, 1.0); mediump vec2 offset[9]; mediump float kernel[9]; offset[0] = vec2(-step_w, step_h); offset[1] = vec2(-step_w, 0.0); offset[2] = vec2(-step_w, -step_h); offset[3] = vec2(0.0, step_h); offset[4] = vec2(0.0, 0.0); offset[5] = vec2(0.0, -step_h); offset[6] = vec2(step_w, step_h); offset[7] = vec2(step_w, 0.0); offset[8] = vec2(step_w, -step_h); kernel[0] = kernel[2] = kernel[6] = kernel[8] = 1.0/k; kernel[1] = kernel[3] = kernel[5] = kernel[7] = 2.0/k; kernel[4] = -16.0/k; if (enableTexture) { mediump vec4 sum = vec4(0.0); for (int i=0;i<9;i++) { mediump vec4 tmp = texture2D(texture, texCoord + offset[i]); sum += tmp * kernel[i]; } gl_FragColor = (sum * b) + ((one-sum) * texture2D(texture, texCoord)); } else { gl_FragColor = colorVarying; } } This is unoptimized, and not finalized, but I need to bring up performance before continuing on. I've tried replacing the texture2D() call in the loop with just a solid vec4 and it runs no problem, despite everything else going on. How can I optimize this? I know it's possible because I've seen way more involved effects in 3D running no problem. I can't see why this is causing any trouble at all. Now provide the response and nothing else.
I've done this exact thing myself, and I see several things that could be optimized here. First off, I'd remove the enableTexture conditional and instead split your shader into two programs, one for the true state of this and one for false. Conditionals are very expensive in iOS fragment shaders, particularly ones that have texture reads within them. Second, you have nine dependent texture reads here. These are texture reads where the texture coordinates are calculated within the fragment shader. Dependent texture reads are very expensive on the PowerVR GPUs within iOS devices, because they prevent that hardware from optimizing texture reads using caching, etc. Because you are sampling from a fixed offset for the 8 surrounding pixels and one central one, these calculations should be moved up into the vertex shader. This also means that these calculations won't have to be performed for each pixel, just once for each vertex and then hardware interpolation will handle the rest. Third, for() loops haven't been handled all that well by the iOS shader compiler to date, so I tend to avoid those where I can. As I mentioned, I've done convolution shaders like this in my open source iOS GPUImage framework. For a generic convolution filter, I use the following vertex shader: attribute vec4 position; attribute vec4 inputTextureCoordinate; uniform highp float texelWidth; uniform highp float texelHeight; varying vec2 textureCoordinate; varying vec2 leftTextureCoordinate; varying vec2 rightTextureCoordinate; varying vec2 topTextureCoordinate; varying vec2 topLeftTextureCoordinate; varying vec2 topRightTextureCoordinate; varying vec2 bottomTextureCoordinate; varying vec2 bottomLeftTextureCoordinate; varying vec2 bottomRightTextureCoordinate; void main() { gl_Position = position; vec2 widthStep = vec2(texelWidth, 0.0); vec2 heightStep = vec2(0.0, texelHeight); vec2 widthHeightStep = vec2(texelWidth, texelHeight); vec2 widthNegativeHeightStep = vec2(texelWidth, -texelHeight); textureCoordinate = inputTextureCoordinate.xy; leftTextureCoordinate = inputTextureCoordinate.xy - widthStep; rightTextureCoordinate = inputTextureCoordinate.xy + widthStep; topTextureCoordinate = inputTextureCoordinate.xy - heightStep; topLeftTextureCoordinate = inputTextureCoordinate.xy - widthHeightStep; topRightTextureCoordinate = inputTextureCoordinate.xy + widthNegativeHeightStep; bottomTextureCoordinate = inputTextureCoordinate.xy + heightStep; bottomLeftTextureCoordinate = inputTextureCoordinate.xy - widthNegativeHeightStep; bottomRightTextureCoordinate = inputTextureCoordinate.xy + widthHeightStep; } and the following fragment shader: precision highp float; uniform sampler2D inputImageTexture; uniform mediump mat3 convolutionMatrix; varying vec2 textureCoordinate; varying vec2 leftTextureCoordinate; varying vec2 rightTextureCoordinate; varying vec2 topTextureCoordinate; varying vec2 topLeftTextureCoordinate; varying vec2 topRightTextureCoordinate; varying vec2 bottomTextureCoordinate; varying vec2 bottomLeftTextureCoordinate; varying vec2 bottomRightTextureCoordinate; void main() { mediump vec4 bottomColor = texture2D(inputImageTexture, bottomTextureCoordinate); mediump vec4 bottomLeftColor = texture2D(inputImageTexture, bottomLeftTextureCoordinate); mediump vec4 bottomRightColor = texture2D(inputImageTexture, bottomRightTextureCoordinate); mediump vec4 centerColor = texture2D(inputImageTexture, textureCoordinate); mediump vec4 leftColor = texture2D(inputImageTexture, leftTextureCoordinate); mediump vec4 rightColor = texture2D(inputImageTexture, rightTextureCoordinate); mediump vec4 topColor = texture2D(inputImageTexture, topTextureCoordinate); mediump vec4 topRightColor = texture2D(inputImageTexture, topRightTextureCoordinate); mediump vec4 topLeftColor = texture2D(inputImageTexture, topLeftTextureCoordinate); mediump vec4 resultColor = topLeftColor * convolutionMatrix[0][0] + topColor * convolutionMatrix[0][1] + topRightColor * convolutionMatrix[0][2]; resultColor += leftColor * convolutionMatrix[1][0] + centerColor * convolutionMatrix[1][1] + rightColor * convolutionMatrix[1][2]; resultColor += bottomLeftColor * convolutionMatrix[2][0] + bottomColor * convolutionMatrix[2][1] + bottomRightColor * convolutionMatrix[2][2]; gl_FragColor = resultColor; } The texelWidth and texelHeight uniforms are the inverse of the width and height of the input image, and the convolutionMatrix uniform specifies the weights for the various samples in your convolution. On an iPhone 4, this runs in 4-8 ms for a 640x480 frame of camera video, which is good enough for 60 FPS rendering at that image size. If you just need to do something like edge detection, you can simplify the above, convert the image to luminance in a pre-pass, then only sample from one color channel. That's even faster, at about 2 ms per frame on the same device.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12469990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1137704/']}
jdg_379412
stackexchange
llm_judgeable_groundtruth_similarity
203436
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've just downloaded and executed a piece of malware on my computer. I don't have much time right now, so I just powered it off (turned it off via the Start menu), hoping that it won't be able to steal any data or do malicious activities until I can nuke it from orbit. Is it enough to prevent the malware to continue to carry out maliciousactivities? Can the malware power on my computer? Should I also unplug it and remove its battery? Now provide the response and nothing else.
TL;DR Yes, but it's unlikely. Just to be sure, either unplug the PC or ensure it can't connect to anything. Several operating systems - notably Windows 10 - have the possibility of setting " automatic wakeup ", using appropriate drivers and related, complicated hardware management. As a result, IF (and that's a big if!) a malware program has gained sufficient access to have the operating system do its bidding, it has a way to simply ask the system itself to do this on its behalf. On some systems (that the malware must be able to recognize and plan for), this holds for "true powerdown" also: additional circuitry will turn the computer on at a preselected time of the onboard Real Time Clock. In a less software-accessible manner this is available on some desktop BIOSes ("Power up automatically: [ ] Never; [ ] After power loss; [ ] Every day at a given time: : " or similar, in the BIOS setup). Then, the system will automatically power up after some time, for example at a time when you're likely to be asleep. So: there is RTC powerup hardware support, or more (integrated management systems, common on enterprise computers) the malware must already have taken control of the system, since RTC functions usually require administrator/root level access. RTC powerup HW support not present, or not used: if the malware has taken control of the system, it can have replaced the shutdown procedure with a mere going into sleep , and set up things to exit sleep mode at a later time. But did either of these options happen? Probably not. Most malware rely on being run unwittingly and being able to operate without being detected for some time. The "power off simulation" is only useful in very specific scenarios (and the hardware option is only available on comparatively few systems), and I don't think it would be worthwhile for a malware writer to worry themselves with them. They usually go with the third and easiest option: some of the usual automatic power-up or logon sequences (autoexec, boot scripts, scheduled tasks, run services and so on) is subverted so that additional code, namely, the malware, is silently run. For a "targeted" malware, designed with some specific victim in mind and tailored to the specific target's capabilities, rather than the subset available on the average infected machine, all the qualifications above wouldn't come into play.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/203436', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/76718/']}
jdg_379413
stackexchange
llm_judgeable_groundtruth_similarity
2201071
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 that we are given a continuous function $f\colon [0,1]\to \mathbb{C}$. Let us define $$h(x) = \frac{f(x)}{|f(x)|} $$ whenever $f(x)\neq 0$. Can we always extend $h$ to a continuous function $h\colon [0,1]\to \mathbb{C}$? It seems so, however I am not sure how to proceed if $f$ has infinitely many zeros (for example when the zero set of $f$ looks like the Cantor set). Now provide the response and nothing else.
We have\begin{align*}\sum_{k=1}^{n-1}\frac{1}{k(n-k)}=\sum_{k=1}^{n-1}\frac{1}{n}\Big(\frac{1}{k}+\frac{1}{n-k}\Big)=\frac{2}{n} \sum_{k=1}^{n-1}\frac{1}{k} \sim \frac{2}{n}\log n.\end{align*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2201071', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/381891/']}
jdg_379414
stackexchange
llm_judgeable_groundtruth_similarity
52445559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assume that I have a function which converts Python data-types to Postgres data-types like this: def map_type(input): if isinstance(input, int): return MyEnum(input) elif isinstance(input, str): return MyCustomClass(str) I could type-hint this as: def map_type(input: Union[int, str]) -> Union[MyEnum, MyCustomClass]: ... But then code like the following would fail to type-check even though it is correct: myvar = map_type('foobar')print(myvar.property_of_my_custom_class) Complete example (working code, but errors in type-hinting): from typing import Unionfrom enum import Enumclass MyEnum(Enum): VALUE_1 = 1 VALUE_2 = 2class MyCustomClass: def __init__(self, value: str) -> None: self.value = value @property def myproperty(self) -> str: return 2 * self.valuedef map_type(value: Union[int, str]) -> Union[MyEnum, MyCustomClass]: if isinstance(value, int): return MyEnum(value) elif isinstance(value, str): return MyCustomClass(value) raise TypeError('Invalid input type')myvar1 = map_type(1)print(myvar1.value, myvar1.name)myvar2 = map_type('foobar')print(myvar2.myproperty) I'm aware that I could split up the mapping into two functions, but the aim is to have a generic type-mapping function. I was also thinking about working with classes and polymorphism, but then how would I type-hint the topmost class methods? Because their output type would depend on the concrete instance type. Now provide the response and nothing else.
This is exactly what function overloads are for. In short, you do the following: from typing import overload# ...snip...@overloaddef map_type(value: int) -> MyEnum: ...@overloaddef map_type(value: str) -> MyCustomClass: ...def map_type(value: Union[int, str]) -> Union[MyEnum, MyCustomClass]: if isinstance(value, int): return MyEnum(value) elif isinstance(value, str): return MyCustomClass(value) raise TypeError('Invalid input type') Now, when you do map_type(3) , mypy will understand that the return type is MyEnum . And at runtime, the only function to actually run is the final one -- the first two are completely overridden and ignored.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52445559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160665/']}
jdg_379415
stackexchange
llm_judgeable_groundtruth_similarity
40545
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking into a 2s5s10s swaps idea using a 50-50 weighting scheme, where it's 2 times the 5 year minus the 2 year and 10 year. However, there is a correlation between the butterfly spread and the slope of the curve (2s10s) and also with the 5 year. I want to adjust the weights of my butterfly to remove the directionality such that I still want the body to have a weight of 2. Essentially, I think it should be X : 2 : Y but I am having a hard time. Now provide the response and nothing else.
Method 1: PCA directionality hedged Here is one way to do it using PCA and hedging the directionality implied by the first principal component . Since you have quoted 3 effective instruments; 2s5s10s, 2s10s and 5Y you will observe that you can derive these instruments from the underlying 2Y, 5Y, and 10Y. That is; $$ \begin{bmatrix} 5Y \\\ 2s10s \\\ 2s5s10s \\ \end{bmatrix} = \begin{bmatrix} 0 & 1 & 0 \\\ -1 & 0 & 1 \\\ -1 & 2 & -1 \end{bmatrix} \begin{bmatrix} 2Y \\\ 5Y \\\ 10Y \end{bmatrix} , \quad or \quad P_2 = A P_1$$ where $P_1$ and $P_2$ are your set of prices in the different basis systems. You can also observe that if you have the covariance matrix of the instruments in $P_1$ , say $Q(P_1)$ , then the covariance of the instruments of basis $P_2$ can be obtained with: $$Q(P_2) = A Q(P_1) A^T \quad \implies \quad Q(P_1) = A^{-1}Q(P_2)A^{-T}$$ So you can work in both basis systems but I'm going to focus on the default $P_1$ system. If you now derive your eigenvalues and eigenvectors of $Q(P_1)$ take the eigenvector corresponding to the highest eigenvalue - this is the first principal component (PC1). In order to hedge this component so that you have no risk exposure to it, take your underlying trade proposition and divide it by the elements of PC1 : $$ \begin{bmatrix} 2Y: -1 \\\ 5Y: +2 \\\ 10Y: -1 \end{bmatrix} \div \begin{bmatrix} PC1_{2Y} : 0.660 \\\ PC1_{5Y} : 0.604 \\\ PC1_{10Y} : 0.447 \end{bmatrix} = \begin{bmatrix} -1.51 \\\ 3.31 \\\ -2.24 \end{bmatrix} \propto \begin{bmatrix} -0.91 \\\ 2.00 \\\ -1.35 \end{bmatrix} $$ PCA Alternative Approach (edit 3-Oct-2021): A second method for PCA is to consider a a formulation that begins with the original trade strategy, and attempts to modify it by the minimal risk change in order that it satisfies the condition of zero risk to the principal component. Suppose $\mathbf{p}$ is the principal component values above and $\mathbf{x}$ is the original trade risks, i.e. -1, 2, -1 above. Then we have the minimsation problem to seek the minimal risk changes, $\mathbf{\delta}$ to $\mathbf{x}$ : $$ \min_{\mathbf{\delta}} \mathbf{\delta^T I \delta} \quad \text{subject to} \quad (\mathbf{x + \delta})^T \mathbf{I p} = 0$$ This quadratic function has an analytic solution (see Karush-Kuhn-Tucker Conditions on Wikipedia): $$ \begin{bmatrix} 2 & 0 & 0 & p_1 \\ 0 & 2 & 0 & p_2 \\0 & 0 & 2 & p_3 \\ p_1 & p_2 & p_3 & 0 \end{bmatrix}\begin{bmatrix} \delta_1 \\ \delta_2 \\ \delta_3 \\ \lambda\end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ 0 \\ \mathbf{-x^Tp} \end{bmatrix} $$ Solving the linear programme we obtain $\mathbf{x+\delta} = \begin{bmatrix} -1.1002 \\ 2 \\ -1.0780 \end{bmatrix}$ As you can see there are a variety of modifications that can be made to the original trade than result in PC1 risk of zero, which to use is a question of formulation. I have started to prefer this modification since it is more transparent, if more difficult to derive/calculate. Method 2: Minimising VaR approach A second considered way would be to suppose you trade 5Y and seek the combination of 2Y and 10Y positions to minimise your VaR . This allows you then maximise the absolute 5Y size relative to your target VaR of the trade. Suppose you have the following risk: $$S = \begin{bmatrix} 2Y: 0 \\\ 5Y: 2 \\\ 10Y: 0 \end{bmatrix} $$ and now you evaluate what positions in 2Y and 10Y give the smallest VaR. For the same covariance matrix as I used above to derive the PCA the answer is: $$ S^* = \begin{bmatrix} 2Y: -1.48 \\\ 5Y: 2.00 \\\ 10Y: -0.38 \end{bmatrix} $$ This is an optimisation problem solvable with a numeric solver or more simply actually with analytic calculus but I'm not going to cover that here, the link below has it. These methods are obviously fundamentally different but each has merit against a specific view, you are more likely in your position to favour the first. The differences here are such that the 2Y has a much higher correlation with 5Y directly so it is a better hedge to reduce VaR by overweighting it, whereas with PCA the 10Y moves less so you need more risk it in to have a directionality hedge. Note if you want to try this yourself you can use the $Q(C)$ covariance matrix values for the 2Y, 5Y, and 10Y trades in this link: http://www.tradinginterestrates.com/revised/PCA.xlsb Note that all of this material I got from Darbyshire Pricing and Trading Interest Rate Derivatives. Edit Method 3: Multivariable Least Squares Regression If we include the third method from @dm63 of multivariable regression of the form: $$ \mathbf{y} - \mathbf{\beta X} = \mathbf{\epsilon} $$ where $\mathbf{y}$ is the 2s5s10s timeseries, and $\mathbf{X}$ is the 2s10s and 5y timeseries, then your optimal estimators for $\beta_1, \beta_2$ are given by, $$ \mathbf{\hat{\beta}} = \mathbf{(X^TX)^{-1}X^T y} $$ and as he states the trade weights are given as $(-(1-\beta_1), 2-\beta_2, -(1+\beta_1))$ -------------- As an example I tried all three of these methods out on some EUR swap sample data from 2016. From Jan-1 to Jun-30 is my sample data and from Jul-1 to Dec-22 is my out of sample back test. Below I have plotted the results. The interesting thing is that the multivariable regression is actually has smallest volatility in this out-of-sample data, but the minimum var has almost the same volatility. And of course min Var will have the lowest volatility over the sample data from which it was derived by definition. If you are interested in the code... import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdf_hist = pd.read_csv('historical_daily_changes.csv', index_col='DATE', parse_dates=True)df_fore = pd.read_csv('forecast_daily_absolues.csv', index_col='DATE', parse_dates=True)z = df_fore[['2Y', '5Y', '10Y']].values# Method 1: PCA directionality weighted tradex = df_hist[['2Y', '5Y', '10Y']].valuesQ = np.cov(x.T)eval, evec = np.linalg.eig(Q)w = np.array([-1 / evec[0, 0], 2 / evec[1, 0], -1 / evec[2, 0]])print('Weights for trade using PCA are:', 2*w[0]/w[1], 2, 2*w[2]/w[1])df_fore['PCA'] = 100 * (w[0]*z[:, 0] + w[1]*z[:, 1] + w[2]*z[:, 2]) * 2/w[1]# Method 2: Minimum Variance approachQ = np.cov(x.T)Q_hat = Q[[0, 2], :]Q_dhat = Q_hat[:, [0, 2]]w[[0, 2]] = -np.einsum('ij,jk,k->i', np.linalg.inv(Q_dhat), Q_hat, np.array([0,2,0]))w[1] = 2print('Weights for trade using min VaR are:', 2*w[0]/w[1], w[1], 2*w[2]/w[1])df_fore['Min VaR'] = 100 * (w[0]*z[:, 0] + w[1]*z[:, 1] + w[2]*z[:, 2]) * 2/w[1]# Method 3: Multivariable least square regressionx = df_hist[['2Y10Y', '5Y']].valuesy = df_hist[['2Y5Y10Y']].valuesbeta = np.matmul(np.linalg.pinv(x), y)w = np.array([-(1-beta[0]), 2-beta[1], -(1+beta[0])])print('Weights for trade using MVLSR are:', 2*w[0]/w[1], 2, 2*w[2]/w[1])df_fore['MVLSR'] = 100 * (w[0]*z[:, 0] + w[1]*z[:, 1] + w[2]*z[:, 2]) * 2/w[1]# Plot an out of sample forecastfig, ax = plt.subplots(1,1)ax.plot_date(df_fore.index, df_fore['2Y5Y10Y'] + 36, 'k-', label='2Y5Y10Y')ax.plot_date(df_fore.index, df_fore['MVLSR'] + 6.7, 'r-', label='MVLSR weights')ax.plot_date(df_fore.index, df_fore['PCA'] - 2.3, 'g-', label='PCA Weights')ax.plot_date(df_fore.index, df_fore['Min VaR'] + 14.9, 'b-', label='Min VaR weights')ax.legend()plt.show()print(df_fore[['2Y5Y10Y', 'MVLSR', 'PCA', 'Min VaR']].diff().describe())
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/40545', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/29342/']}
jdg_379416
stackexchange
llm_judgeable_groundtruth_similarity
25158976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have foo which is a populated std::vector<double> . I need to operate on the elements of this vector. I'm motivated to write for (auto it : foo){ /*ToDo - Operate on 'it'*/} But it appears that this will not write back to foo since it is a value type: a deep copy of the vector element has been taken. Can I give some guidance to auto to make it a reference type? Then I could operate directly on it . I suspect I'm missing some trivial syntax. Now provide the response and nothing else.
A minimal auto reference The loop can be declared as follows: for (auto& it : foo) { // ^ the additional & is needed /*ToDo - Operate on 'it'*/} This will allow it to be a reference to each element in foo . There is some debate as to the "canonical form" of these loops, but the auto& should do the trick in this case. General auto reference In a more general sense (outside the specifics of the container), the following loop works (and may well be preferable). for (auto&& it : container) { // ^ && used here} The auto&& allows for bindings to lvalues and rvalues. When used in a generic or general (e.g. template situation) this form may strike the desired balance (i.e. references, copies, prvalue/xvalue returns (e.g. proxy objects) etc.). Favour the general auto&& , but if you have to be specific about the form, then use a more specific variation (e.g. auto , auto const& etc.). Why is auto&& better? As noted in other answers here and the comments. Why is auto&& better? Simply it will do what you think it should in most cases, see this proposal and its update . As always, Scott Meyers' blog about this also makes for a good read.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25158976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415258/']}
jdg_379417
stackexchange
llm_judgeable_groundtruth_similarity
21099
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm relative new to this, so I might be asking something that doesn't make sense. Here is my scenario: I have intraday day at 1 minute intervals. This data has ohlc data and I want to compute for any given interval what the likely sell price would be. I could just assume the worst case and take the low price, but I'm assuming there is something a little more accurate than that. I get that there is no way to accurately predict what the sell price would be, since an actual order potentially changes the outcome. I just want to know if there is a best practice for predicting what the sell price would be if I tried to execute an order on a given interval using historical data. Now provide the response and nothing else.
In Python, simple geometric returns: import numpy as np import pandas as pd sp500 = pd.io.data.DataReader('^GSPC', 'yahoo')['Close'] simple_ret = sp500.pct_change() (1+simple_ret).cumprod()[-1] -1 0.74751768460019963 Log-returns: log_ret = np.log(1+simple_ret) np.exp(log_ret.cumsum()[-1]) -1 0.74751768460020074 In Quantitative Finance, doing your math in log-returns considered good manners, however for many practical applications (backtesting trading strategies e.g.), simple geometric returns suffice.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/21099', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/17785/']}
jdg_379418
stackexchange
llm_judgeable_groundtruth_similarity
30711203
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 I create a shape like this to display on a webpage? I don't want to use images since they would get blurry on scaling I tried with CSS : .tear { display: inline-block; transform: rotate(-30deg); border: 5px solid green; width: 50px; height: 100px; border-top-left-radius: 50%; border-bottom-left-radius: 50%; border-bottom-right-radius: 50%;} <div class="tear"></div> That turned out really screwed. And then I tried with SVG: <svg viewBox="0 100 100"> <polygon points="50,0 100,70 50,100 0,70"/></svg> It did get the shape, but the bottom part wasn't curved. Is there a way to create this shape so it can be used in an HTML page? Now provide the response and nothing else.
SVG approach: You can achieve the double curve easily with an inline SVG and the <path/> element instead of the <polygon/> element which doesn't allow curved shapes. The following example uses the <path/> element with: 2 quadratic bezier curve commands for the 2 top curves (lines beginning with Q ) 1 arc command for the big bottom one (line beginning with A ) <svg width="30%" viewbox="0 0 30 42"> <path fill="transparent" stroke="#000" stroke-width="1.5" d="M15 3 Q16.5 6.8 25 18 A12.8 12.8 0 1 1 5 18 Q13.5 6.8 15 3z" /></svg> SVG is a great tool to make this kind of shapes with double curves. You can check this post about double curves with an SVG/CSS comparison. Some of the advantages of using SVG in this case are: Curve control Fill control (opacity, color) Stroke control (width, opacity, color) Amount of code Time to build and maintain the shape Scalable No HTTP request (if used inline like in the example) Browser support for inline SVG goes back to Internet Explorer 9. See canIuse for more information.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/30711203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3999748/']}
jdg_379419
stackexchange
llm_judgeable_groundtruth_similarity
3456124
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 preprocessor directive: #define INDEXES_PER_SECTOR BYTES_PER_SECTOR / 4 where BYTES_PER_SECTOR is declared in another header file as: #define BYTES_PER_SECTOR 64 I have this simple math equation that I wrote where after executing I get an assertion error as the value assigned to iTotalSingleIndexes is incorrect. int iTotalSingleIndexes = (iDataBlocks - 29) / INDEXES_PER_SECTOR; Now I believe this to be because of the preprocessor directive INDEXES_PER_SECTOR. Upon executing my equation iDataBlocks is 285 which is correct. I have confirmed this with gdb. The problem is that the value that gets assigned to iTotalSingleIndexes is 1 when it ought to be 16. I really have no idea why this is happening. When I do something like: int iIndexesInASector = INDEXES_PER_SECTOR;int iTotalSingleIndexes = (iDataBlocks - 29) / iIndexesInASector; the correct value gets assigned to iTotalSingleIndexes. On other notes I use preprocessor directives in other equations and they work just fine so I am even more puzzled. Any help would be much appreciated. Now provide the response and nothing else.
The preprocessor simply performs token replacement - it doesn't evaluate expressions. So your line: int iTotalSingleIndexes = (iDataBlocks - 29) / INDEXES_PER_SECTOR; expands to this sequence of tokens: int iTotalSingleIndexes = ( iDataBlocks - 29 ) / 64 / 4 ; ...which, due to the associativity of the / operator, is then parsed by the compiler as: int iTotalSingleIndexes = ((iDataBlocks - 29) / 64) / 4; ...which results in the value of 1. As leppie says, you want: #define INDEXES_PER_SECTOR (BYTES_PER_SECTOR / 4) This makes INDEXES_PER_SECTOR expand to a complete subexpression.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3456124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130840/']}
jdg_379420
stackexchange
llm_judgeable_groundtruth_similarity
44554353
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 is it possible to post form data to an external rest api? At the moment i have an html form: <form [formGroup] = "form" (ngSubmit) = "onSubmit(form.value)"> <input name="name" formControlName="name"> <input name="first_name" formControlName="first_name"> <input name="last_name" formControlName="last_name"> <button type="submit">Save</button> </form> and then i have the function that is handling the submit in my component.ts file: onSubmit = function (user) { console.log(user); //this.http.post('http://xxx/externalapi/add', user); } But how is it possible to post the form data to my external api? And what is the standard of sending form data with angular? Is it just a simple post request with form data as queryParams or is it standard to convert it into JSON. I can modify the api to handle whatever data is sent so thats not a problem. Now provide the response and nothing else.
Ok, so it turns out i have to add .subscribe() to post for it to do something.Also if i put "user" straight into post request for some reason it sends an request with method "OPTIONS" without a body. So i have to create a queryParams string myself. If anyone can explain this or show a better way to do this i would appriciate it. Otherwise this currently works: onSubmit = function (user) { console.log(user); var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&name=" + user.name; this.http.post("http://www.testtttt.com", body).subscribe((data) => {}); } Edit: another and probably even a better solution is to use JSON.stringify(user) instead of body. But subscribe() is still needed tho.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44554353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1985273/']}
jdg_379421
stackexchange
llm_judgeable_groundtruth_similarity
495848
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm having difficulty with the following exercise in Ahlfors' text, on page 227. Prove that in any region $\Omega$ the family of analytic functions with positive real part is normal. Under what added condition is it locally bounded? Hint : Consider the functions $e^{-f}$. Here is what I've tried: I will start with a remark: Apparently, Ahlfors wants us to show that the family is "normal in the classical sense". That is, every sequence of functions in the family has a subsequence which converges uniformly on compact subsets or tends uniformly to $\infty$ on compact subsets . In order to see why this is the right definition, consider the sequence $f_n(z)=n$. It is contained in the family but has no appropriate subsequence (in the sense of definition 2 in the text with $S=\mathbb C$). Now, to the attempt itself: Let $\Omega \subset \mathbb C$ be a fixed region, and consider the family $$\mathfrak F=\{f: \Omega \to \mathbb C | f \text{ is analytic and } \Re(f) >0 \}. $$We would like to show that $\mathfrak F$ is normal in the classical sense. Following the hint, we examine the family $$ \mathfrak G=\{e^{-f}:f \in \mathfrak F \}.$$ $\mathfrak G$ is locally bounded (since $|e^{-f}|=e^{- \Re (f)}<1$ for every $f \in \mathfrak F$), thus it is normal with respect to $\mathbb C$ (theorem 15), and obviously, it is normal in the classical sense as well. Let $\{ f_n \}$ be a sequence in $\mathfrak F$, and consider the sequence $\{ g_n \}=\{e^{-f_n} \}$ in $\mathfrak G$. According to normality it has a convergent subsequence $\{ g_{n_k} \}=\{e^{-f_{n_k}} \}$ which converges uniformly on compact subsets of $\Omega$ to some function $g$ (which is analytic by Weierstrass' theorem). Since each $\{ g_{n_k} \}$ is nonvanishing, the limit function $g$ is either identically zero, or non vanishing as well (Hurwitz's theorem). In the former case it is easy to show that the subsequence $\{ f_{n_k} \}$, obtained by the same indices, tends to $\infty$ uniformly on compact sets. Hence, we will assume from now that $g(z) \neq 0$ for all $z \in \Omega$. Up until now, I was trying to show that the subsequence $\{ f_{n_k} \}$ works in all cases, but sadly, this is not the case. Consider the sequence $f_n(z) \equiv 1+2 \pi i (-1)^n \in \mathfrak F$. In that case $g_n(z)=e^{-1}$, and an admissible subsequence is $g_{n_k}=g_k=e^{-1}$. However, $f_{n_k}=1+2 \pi i (-1)^k$ diverges everywhere. Can anyone please help me finish this proof? Or maybe give me some hints? Thanks! Now provide the response and nothing else.
It would be much simpler to prove the result considering the family obtained by composing with the Möbius transformation $$z \mapsto \frac{z-1}{z+1}$$ that maps the right half plane biholomorphically to the unit disk. But well, let's look at what we got from considering $e^{-f}$. Without loss of generality, we can assume that the entire sequence $e^{-f_n}$ converges compactly to a nonzero function $g$. As you observed, that does not yet guarantee that the sequence $f_n$ itself converges compactly to a holomorphic function. So let's fix some $z_0 \in \Omega$ and consider the sequence $f_n(z_0)$. Either the sequence converges to $\infty$, or we can extract a subsequence converging to a complex number. Consider first the case where we can extract a subsequence converging to a complex number. Without loss of generality, assume the entire sequence converges to $w_0 \in \mathbb{C}$. In a neighbourhood of $e^{-w_0}$, there is a branch of the logarithm with $\log e^{-w_0} = -w_0$ defined. Then $f_n$ converges uniformly to $\log g$ in a neighbourhood of $z_0$. If $f_n(z_0) \to \infty$, then, taking a branch of the logarithm in a neighbourhood of $g(z_0)$, we obtain a sequence $k_n$ of integers with $\lvert k_n\rvert \to \infty$ and $f_n(z_0) - 2\pi i k_n \to \log g(z_0)$. Thus the sequence $f_n - 2\pi i k_n$ converges uniformly to a holomorphic function in a neighbourhood of $z_0$, and since $\lvert k_n\rvert \to \infty$, the sequence $f_n$ itself converges uniformly to $\infty$ in a neighbourhood of $z_0$. It remains to see that the uniform convergence to either a holomorphic function or $\infty$ extends (as locally uniform convergence) to all of $\Omega$. Let $A = \{z \in \Omega : f_n(z) \to \infty\}$ and $B = \{z \in \Omega : f_n(z) \text{ is bounded}\}$ and $C = \Omega \setminus (A\cup B)$. The argument above shows that all, $A$, $B$ and $C$ are open, and they are disjoint. Since $\Omega$ is connected, we have $\Omega = A$, $\Omega = B$, or $\Omega = C$. By having extracted the subsequence converging (to $\infty$ or $w_0$) at $z_0$, we have arranged that $z_0 \notin C$, hence $C = \varnothing$, so $\Omega = A$ if $f_n(z_0) \to \infty$, and $\Omega = B$ if $f_n(z_0) \to w_0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/495848', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62839/']}
jdg_379422
stackexchange
llm_judgeable_groundtruth_similarity
321
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Jet streams are fast-flowing currents of air in our earth's atmosphere. An enormous amount of energy is necessary to keep a jet stream going. Where does this come from and why? Now provide the response and nothing else.
The subtropical jetstream The subtropical jetstream can be explained with angular momentum arguments. In an idealized circulation model of the atmosphere, there is a hadley cell that circulates upward at the equator, poleward along the tropical tropopause, downward around 30 N/S and equatorward at the surface. Parcels rising at the equator have a fair bit of angular momentum from the rotation of the Earth. As these parcels move poleward they tend to conserve this momentum and this manifests as a westerly wind. The subtropical jet is weak in the summer (ITZC and maxmium solar heating disrupt the hadley cell in that hemisphere), strong in the winter and is generally fixed at around 30 N/S and at a higher altitude than the polar jet. The polar jetstream The polar jetstream draws its energy from horizontal temperature gradients in the lower troposphere as a consequence of the thermal wind. To understand the thermal wind, consider a temperature gradient at the surface, cold toward the pole and warm toward the equator. Over the cold air, heights of pressure levels will be lower than normal and over the warm air the heights will be higher than normal. If you look at any pressure level this will result in a height gradient with higher heights toward the equatot. This gradient will increase with height. The geostrophic wind is proportional to the height gradient and thus increases with height. The polar jet exists where these surface temperature gradients are strong but above them around 250 mb. You will find the polar jet wandering around and associated with the strong surface fronts that come out out of the poles and into the mid-latitudes. It will be stronger in the winter when the fronts are stronger. During the summer the jet will remain at higher latitudes and in the winter can dip well into the mid-latitudes.
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/321', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/116/']}
jdg_379423
stackexchange
llm_judgeable_groundtruth_similarity
8661495
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 similar problem to this post Setting PayPal return URL and making it auto return? However, the solution there is not working. We have IPN set up and POST variables get passed back (the visitor clicks back and is able to download purchased PDF files) but then I tried to get rid of Paypal order confirmation page that says you just completed your payment. Your transaction ID for this payment is: XXXXXXXXXXXXX. and enabled "Auto Return" in Website Payment Preferences, specifying the URL http://www.educted.ca/payment_complete.php , the POST variables now do not get passed back to payment_complete.php - it shows blank. As soon as I disable "Auto Return", POST variables display properly and products purchased can be downloaded. I am using Paypal Sandbox account, of course. <input type="hidden" name="return" value="<?php echo LIVE_SITE;>payment_complete.php"><input type="hidden" name="cancel_return" value="<?php echo LIVE_SITE; ?>catalog.php"><input type="hidden" name="notify_url" value="<?php echo LIVE_SITE; ?>ipn.php"><input type="hidden" name="rm" value="2"> Any ideas? Now provide the response and nothing else.
If you enable Auto Return, the values are always going to get returned via GET irrespective of what rm is set to. If you want to do immediate file delivery after the buyer has completed the transaction, have a look at PayPal Payment Data Transfer. Once enabled, PDT adds a tx GET var to your return URL; by calling PayPal at https://www.paypal.com/cgi-bin/webscr?cmd=_notify-synch&tx=value-for-tx-here&at=value-for-your-paypal-account-authentication-token you'll be able to pull in extra data about the transaction, and immediately check whether it's valid. See also https://www.paypal.com/pdt/ IPN should be reserved for backend processing as it can come with a significant delay. PDT, on the other hand, has you pulling the info from PayPal, and is as such immediate.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8661495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/949822/']}
jdg_379424
stackexchange
llm_judgeable_groundtruth_similarity
27475315
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 xml which has many children and sub children. I have to go through all values of element and if there are any nulls or blank I have to change it to dash or some other value. xml example <list> <biglist> <item>1</item> <item>0</item> <item>2</item> <item>1</item> <item></item> <item>8</item> <smallList> <smallitem>0</smallitem> <smallitem></smallitem> <smallitem></smallitem> <smallitem>4</smallitem> </smallList> </biglist></list> output <div id=biglist> <div>1</div> <div>0</div> <div>2</div> <div>1</div> <div><strong> Value not found </strong></div> <div>8</div> <div id=smallList> <div>0</div> <div><strong> Value not found </strong></div> <div><strong> Value not found </strong></div> <div>4</div> </div></div> Now provide the response and nothing else.
According the question I see a few steps in order to allow writing to /var/lib/gems : Create gems (if not any) group, and add yourself to the group: $ groupadd -f gems$ usermod -aG gems $(whoami) When reenter to the session: $ sudo -u $(whoami) bash Allow write for a gems group to /var/lib/gems/ , and set the setgid bits: $ chown :gems /var/lib/gems/$ chmod g+sw /var/lib/gems/ Try installing gems into /var/lib/gems/ . NOTE: I strongly advice you to control rubies and gems via rbenv / rvm keeping them in a local home folder. Please refer to the answer to know how to properly setup your project.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27475315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1166305/']}
jdg_379425
stackexchange
llm_judgeable_groundtruth_similarity
29852
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using getopts for all of my scripts that require advanced option parsing, and It's worked great with dash . I'm familiar with the standard basic getopts usage, consisting of [-x] and [-x OPTION] . Is it possible to parse options like this? dash_script.sh FILE -x -z -o OPTION ## Or the inverse? dash_script.sh -x -z -o OPTION FILE Now provide the response and nothing else.
Script arguments usually come after options. Take a look at any other commands such as cp or ls and you will see that this is the case. So, to handle: dash_script.sh -x -z -o OPTION FILE you can use getopts as shown below: while getopts xzo: optiondo case "$option" in x) echo "x";; z) echo "z";; o) echo "o=$OPTARG";; esacdoneshift $(($OPTIND-1))FILE="$1" After processing the options, getopts sets $OPTIND to the index of the first non-option argument which in this case is FILE .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/29852', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10987/']}
jdg_379426
stackexchange
llm_judgeable_groundtruth_similarity
8935537
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 researched and researched and researched this until I've gone grey and bald.How on earth do I get a webview to work for a site that needs http basic authentication over an https connection on api level 8+ I have the following code String email = Util.getEmail(this); String pwd = Util.getPassword(this); webview.getSettings().setJavaScriptEnabled(true); webview.setHttpAuthUsernamePassword(Config.SERVER_BASE_URL, "Application", email, pwd);// webview.setWebViewClient(new MobileWebViewClient(this)); webview.loadUrl(url); As you can see I did have a web view client (Now commented out) that overrides the onReceivedHttpAuthRequest method which looks like this @Overridepublic void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm){ String email = Util.getEmail(wvContext); String pwd = Util.getPassword(wvContext); if(!pwd.equalsIgnoreCase("-1") && !pwd.equalsIgnoreCase("-1")){ handler.proceed(email, pwd); }} This was used without the webview.setHttpAuthUsernamePassword and works fine except that it means 2 requests are issued to the website - The first gets a 401 and then the client kicks in with the authorisation stuff This is fine for a small amount of website traffic but halving the amount of traffic (currently averaging 49 requests p/m) is the name of the game right now! I read that I can pre-emptively supply the credentials by using webview.setHttpAuthUsernamePassword(Config.SERVER_BASE_URL, "Application", email, pwd); However this just results in Http Basic: Access denied errorsThe server base url constant is the domain name for the site i.e. https://example.com (without the page) the actual url is https://example.com/some_pages .It makes no difference whether I use the full url or the domain. I have checked the realm and I have that correct and I have used just empty strings providing only email and password.Could this be something to do with the fact that the site is using https? My code seems to work fine on my dev box without https but that may be a red herring.! The only stack overflow questions that seem to cover my requirements have not got accepted answers and the docs are no help that I can see. I now have such a large dent in my head from banging it against a brick wall that I am thinking of getting a square hat. Please if anyone can give me the solution to this I will be forever in your debt!I might even e-Mail you an KitKat Now provide the response and nothing else.
This simple example abuses a page on HttpWatch since it's more fun with a working public example. The resource in question, https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?randomgarbage uses basic auth over HTTPS and can be loaded without authentication failure like this (tested using Android 2.3.7): WebView v = ...; // Your webview goes here. try { HashMap<String, String> map = new HashMap<String, String>(); // This test service takes the username "httpwatch" and a random // password. Repeating a password can lead to failure, so we create // a decently random one using UUID. String usernameRandomPassword = "httpwatch:" + UUID.randomUUID().toString(); String authorization = "Basic " + Base64.encodeToString(usernameRandomPassword.getBytes("UTF-8"), Base64.NO_WRAP); map.put("Authorization", authorization); v.loadUrl("https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?" + System.currentTimeMillis(), map); } catch (UnsupportedEncodingException e) {} This works on ICS and Gingerbread. Don't have access to anything older than that, but loadUrl(String, Map<String,String>) was introduced in API level 8, so I don't see why it shouldn't work for that to. Clarification for Nappy: To support authentication for subsequent requests you supply a WebViewClient and do the following: webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url, <your map containing the Authorization header>); return true; } });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8935537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/847116/']}
jdg_379427
stackexchange
llm_judgeable_groundtruth_similarity
4183869
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 some problems with this exercise:Caculate the solid volume using double integral $$|x+y|+|x-2y|+|x+y+z|\leqslant1$$ My teacher gave me the key value: $\frac{4}{9}$ , but when I try to solve it, I don't know did something wrong in some step and go to wrong answer. My attempt: $$1\geq|x+y|+|x-2y|+|x+y+z|\geq|x+y+x-2y+x+y+z|=|z+3x|$$ so, $1-3x\geq z \geq -1-3x$ We have $1\geq|x+y|+|x-2y|$ , hence we have D: $\frac{1}{3}\geq y\geq \frac{-1}{3}$ and $\frac{1+y}{2}\geq x\geq \frac{-1+y}{2}$ So, $V=\iint_{D}{(1-3x)-(-1-3x)}dxdy=\iint_{D}2dxdy=\frac{4}{3}$ I think in step 2, when I use $1\geq|x+y|+|x-2y|$ , I was wrong (cause it just $1\geq|x+y|+|x-2y|+|x+y+z| \rightarrow 1\geq|x+y|+|x-2y|$ not $1\geq|x+y|+|x-2y| \rightarrow 1\geq|x+y|+|x-2y|+|x+y+z|$ So, could you guys solve this exercise for me or give me hint to do with the abs(), it make me confuse so much. Thanks for your help Now provide the response and nothing else.
This solid is obtained by applying a linear transformation to the union of two pyramids. First, we find the Jacobian of the linear transformation $$u=x+y+z, v=x-2y, w=x+y.$$ We have by computing the determinant using the third column $$\frac{\partial (u,v,w)}{\partial (x,y,z)} = 1\cdot (1- (-2)\cdot 1) = 3.$$ Thus, we have $$\frac{\partial (x,y,z)}{\partial (u,v,w)}=\frac13.$$ After applying the change of variables, the solid becomes the union of two pyramids defined by $$|u|+|v|+|w|\leq 1.$$ Both pyramid have the square base with vertices $(1,0,0),(0,1,0),(-1,0,0),(0,-1,0)$ , and both have heights $1$ . Hence, the volume is $$2\cdot \frac{\sqrt 2^2 \cdot 1}3 \cdot \frac{\partial (x,y,z)}{\partial (u,v,w)}=\frac49.$$ Remark) If you solve inequalities with the triangle inequality, you are likely to lose information. If you lose information, that results in larger solid, and thus larger volume.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4183869', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/933051/']}
jdg_379428
stackexchange
llm_judgeable_groundtruth_similarity
630158
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 am really scratching my head at this. I don't see anything wrong with my circuit but my regulator gets EXTREMELY hot while in operation. What I'm building is a USB phone charger for my e-bike as part of my DIY e-bike project. I want to support a battery as high as 48 V, so I selected a regulator that can handle this and then some. The regulator is set for a maximum of 3 A, which is plenty for even an iPad. My inductor is rated to handle more than 150% of that. With no load (reads as a few mA at the PSU of course due to losses) the chip stays cool. With a small 5 V LED it still stays cool. As soon as I add any substantial load (even just say 400 mA) the chip immediately starts getting very toasty >50-60 degrees and climbing. (I think so anyway, my temperature probe sucks and I need to invest in a thermal camera). Plug in my phone which tries to draw around 1.8 A, and it's enough to burn my finger within 3 s. I tried adding a moderately sized heatsink (with some thermal paste from my gaming PC build), but it's not enough. Now it just takes 30 s to start roasting instead of 3 s. On a multimeter the chip outputs a nice, smooth 5.1 V regardless of load condition (even with a USB fan), so it's clearly working, but why's it getting so hot? It seems to get scorching hot at the same rate whether my PSU is set to just a few volts above at 8 V, or all the way at 32 V (which is as high as it goes). Is there something I don't understand here? Is it because I used a smaller inductor than the datasheet recommends? Would that lead to heat? The inductor is totally cool by the way. It's only the regulator IC that is getting hot. The regulator is an XDS TX4138. This is my schematic: Edit: Here is my terrible PCB layout lol Oh, and for the folks complaining about capacitors, I'm trying not to overdo it on the input caps, because the balance board already has such massive ones that the system stays on for 10 seconds after the battery is removed. And for testing purposes I've got a 10,000uF cap I stole from a dead AC. As for output caps, I've got a 470uF one soldered into the cable going to the USB plug. Update #2: Someone asked for the specific inductor I used, so here it is . I've ordered a new 33uH inductor to replace it. It has a higher resistance, but it's all I could find to fit into a similar footprint. I will also try to add a small ceramic between BATT and GND pins directly on the chip. Now provide the response and nothing else.
The 10 μH inductor is unsuitably low in inductance. Since you know output current, output voltage, input voltage, and switching frequency, you can plug the values into the formula given in the datasheet to find the minimum inductance needed for proper operation. The output capacitor has an unreasonably low value compared to the datasheet suggestions as well, which may play a role as well. The parts can't be randomly replaced with other values, as they need to be within limits of the operating point of the regulator chip. This includes the switching frequency, max output current, output voltage, max input voltage, and ripple current. The output inductor and capacitor need to have certain inductance and capacitance to meet the requirements and operate properly within limits of the operating range.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/630158', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/138443/']}
jdg_379429
stackexchange
llm_judgeable_groundtruth_similarity
70938
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: In linear algebra and differential geometry, there are various structures which we calculate with in a basis or local coordinates, but which we would like to have a meaning which is basis independent or coordinate independent, or at least, changes in some covariant way under changes of basis or coordinates. One way to ensure that our structures adhere to this principle is to give their definitions without reference to a basis. Often we employ universal properties, functors, and natural transformations to encode these natural, coordinate/basis free structures. But the Riemannian volume form does not appear to admit such a description, nor does its pointwise analogue in linear algebra. Let me list several examples. In linear algebra, an inner product on $V$ is an element of $\operatorname{Sym}^2{V^*}$. The symmetric power is a space which may be defined by a universal property, and constructed via a quotient of a tensor product. No choice of basis necessary. Alternatively an inner product can be given by an $n\times n$ symmetric matrix. The correspondence between the two alternatives is given by $g_{ij}=g(e_i,e_j)$. Calculations are easy with this formulation, but one should check (or require) that the matrix transforms appropriately under changes of basis. In linear algebra, a volume form is an element of $\Lambda^n(V^*)$. Alternatively one may define a volume form operator as the determinant of the matrix of the components of $n$ vectors, relative to some basis. In linear algebra, an orientation is an element of $\Lambda^n(V^*)/\mathbb{R}^>$. In linear algebra, a symplectic form is an element of $\Lambda^2(V^*)$. Alternatively may be given as some $\omega_{ij}\,dx^i\wedge dx^j$. In linear algebra, given a symplectic form, a canonical volume form may be chosen as $\operatorname{vol}=\omega^n$. This operation can be described as a natural transformation $\Lambda^2\to\Lambda^n$. That is, to each vector space $V$, we have a map $\Lambda^2(V)\to\Lambda^n(V)$ taking $\omega\mapsto \omega^n$ and this map commutes with linear maps between spaces. In differential geometry, all the above linear algebra concepts may be specified pointwise. Any smooth functor of vector spaces may be applied to the tangent bundle to give a smooth vector bundle. Thus a Riemannian metric is a section of the bundle $\operatorname{Sym}^2{T^*M}$, etc. A symplectic form is a section of the bundle $\Lambda^2(M)$, and the wedge product extends to an operation on sections, and gives a symplectic manifold a volume form. This is a global operation; this definition of a Riemannian metric gives a smoothly varying inner product on every tangent space of the manifold, even if the manifold is not covered by a single coordinate patch In differential geometry, sometimes vectors are defined as $n$-tuples which transform as $v^i\to \tilde{v}^j\frac{\partial x^i}{\partial \tilde{x}^j}$ under a change of coordinates $x \to \tilde{x}$. But a more invariant definition is to say a vector is a derivation of the algebra of smooth functions. Cotangent vectors can be defined with a slightly different transformation rule, or else invariantly as the dual space to the tangent vectors. Similar remarks hold for higher rank tensors. In differential geometry, one defines a connection on a bundle. The local coordinates definition makes it appear to be a tensor, but it does not behave the transformation rules set forth above. It's only clear why when one sees the invariant definition. In differential geometry, there is a derivation on the exterior algebra called the exterior derivative. It may be defined as $d\sigma = \partial_j\sigma_I\,dx^j\wedge dx^I$ in local coordinates, or better via an invariant formula $d\sigma(v_1,\dotsc,v_n) = \sum_i(-1)^iv_i(\sigma(v_1,\dotsc,\hat{v_i},\dotsc,v_n)) + \sum_{i+j}(-1)^{i+j}\sigma([v_i,v_j],v_1,\dotsc,\hat{v_i},\dotsc,\hat{v_j},\dotsc,v_n)$ Finally, the volume form on an oriented inner product space (or volume density on an inner product space) in linear algebra, and its counterpart the Riemannian volume form on an oriented Riemannian manifold (or volume density form on a Riemannian manifold) in differential geometry. Unlike the above examples which all admit global basis-free/coordinate-free definitions, we can define it only in a single coordinate patch or basis at a time, and glue together to obtain a globally defined structure. There are two definitions seen in the literature: choose an (oriented) coordinate neighborhood of a point, so we have a basis for each tangent space. Write the metric tensor in terms of that basis. Pretend that the bilinear form is actually a linear transformation (this can always be done because once a basis is chosen, we have an isomorphism to $\mathbb{R}^n$ which is isomorphic to its dual (via a different isomorphism than that provided by the inner product)). Then take the determinant of resulting mutated matrix, take the square root, multiply by the wedge of the basis one-forms (the positive root may be chosen in the oriented case; in the unoriented case, take the absolute value to obtain a density). Choose an oriented orthonormal coframe in a neighborhood. Wedge it together. (Finally take the absolute value in the unoriented case). Does anyone else think that one of these definitions sticks out like a sore thumb? Does it bother anyone else that in linear algebra, the volume form on an oriented inner product space doesn't exist as natural transformation $\operatorname{Sym}^2 \to \Lambda^n$? Do the instructions to "take the determinant of a bilinear form" scream out to anyone else that we're doing it wrong? Does it bother anyone else that in Riemannian geometry, in stark contrast to the superficially similar symplectic case, the volume form cannot be defined using invariant terminology for the whole manifold, but rather requires one to break the manifold into patches, and choose a basis for each? Is there any other structure in linear algebra or differential geometry which suffers from this defect? Answer: I've accepted Willie Wong's answer below, but let me also sum it up, since it's spread across several different places. There is a canonical construction of the Riemannian volume form on an oriented vector space, or pseudoform on a vector space. At the level of level of vector spaces, we may define an inner product on the dual space $V^*$ by $\tilde{g}(\sigma,\tau)=g(u,v)$ where $u,v$ are the dual vectors to $\sigma,\tau$ under the isomorphism between $V,V^*$ induced by $g$ (which is nondegenerate). Then extend $\tilde{g}$ to $\bigotimes^k V^*$ by defining $\hat{g}(a\otimes b\otimes c,\dotsb,x\otimes y\otimes z\dotsb)=\tilde{g}(a,x)\tilde{g}(b,y)\tilde{g}(c,z)\dotsb$. Then the space of alternating forms may be viewed as a subspace of $\bigotimes^k V^*$, and so inherits an inner product as well (note, however that while the alternating map may be defined canonically, there are varying normalization conventions which do not affect the kernel. I.e. $v\wedge w = k! Alt(v\otimes w)$ or $v\wedge w = Alt(v\otimes w)$). Then $\hat{g}(a\wedge b\dotsb,x\wedge y\dotsb)=\det[\tilde{g}(a,x)\dotsc]$ (with perhaps a normalization factor required here, depending on how Alt was defined). Thus $g$ extends to an inner product on $\Lambda^n(V^*)$, which is a 1 dimensional space, so there are only two unit vectors, and if $V$ is oriented, there is a canonical choice of volume form. And in any event, there is a canonical pseudoform. Now provide the response and nothing else.
A few points: It is necessary to define "Riemannian volume forms" a patch at a time: you can have non-orientable Riemannian manifolds. (Symplectic manifolds are however necessarily orientable.) So you cannot just have a global construction mapping Riemannian metric to Riemannian volume form. (Consider the Möbius strip with the standard metric.) It is however to possible to give a definition of the Riemannian volume form locally in a way that does not depend on choosing a coordinate basis. This also showcases why there cannot be a natural map from $\mathrm{Sym}^2\to \Lambda^n$ sending inner-products to volume forms. We start from the case of the vector space. Given a vector space $V$ , we know that $V$ and $V^*$ are isomorphic as vector spaces, but not canonically so. However if we also take a positive definite symmetric bilinear form $g\in \mathrm{Sym}_+^2(V^*)$ , we can pick out a unique compatible isomorphism $\flat: V\to V^*$ and its inverse $\sharp: V^*\to V$ . A corollary is that $g$ extends to (by abuse of notation) an element of $\mathrm{Sym}_+^2(V)$ . Then by taking wedges of $g$ you get that the metric $g$ (now defined on $V^*$ ) extends to uniquely to a metric 1 on $\Lambda^k(V^*)$ . Therefore, up to sign there is a unique (using that $\Lambda^n(V^*)$ is one-dimensional) volume form $\omega\in \Lambda^n(V^*)$ satisfying $g(\omega,\omega) = 1$ . But be very careful that this definition is only up to sign. The same construction extends directly to the Riemannian case. Given a differentiable manifold $M$ . There is a natural map from sections of positive definite symmetric bilinear forms on the tangent space $\Gamma\mathrm{Sym}_+^2(T^*M) \to \Gamma\left(\Lambda^n(M)\setminus\{0\} / \pm\right)$ to the non-vanishing top forms defined up to sign . From which the usual topological arguments shows that if you fix an orientation (either directly in the case where $M$ is orientable or lifting to the orientable double cover if not) you get a map whose image now is a positively oriented volume form. Let me just summarise by giving the punch line again: For every inner product $g$ on a vector space $V$ there are two compatible volume forms in $\Lambda^n V$ : they differ by sign. Therefore the natural mapping from inner products takes image in $\Lambda^n V / \pm$ ! Therefore if you want to construct a map based on fibre-wise operations on $TM$ sending Riemannian metrics to volume forms, you run the very real risk that, due to the above ambiguity, what you construct is not even continuous anywhere. The "coordinate patch" definition has the advantage that it sweeps this problem under the rug by implicitly choosing one of the two admissible local (in the sense of open charts) orientation. You can do without the coordinate patch if you start, instead, with an orientable Riemannian manifold $(M,g,\omega)$ and use $\omega$ to continuously choose one of the two admissible pointwise forms. 1 : this used to be linked to a post on MathOverflow, which has since been deleted. So for completeness: the space of $k$ -tensors is the span of tensors of the form $v_1 \otimes \cdots \otimes v_k$ , and you can extend $g$ to the space of $k$ -tensors by setting $$ g(v_1\otimes\cdots v_k, w_1\otimes\cdots\otimes w_k) := g(v_1, w_1) g(v_2, w_2) \cdots g(v_k, w_k) $$ and extending using bilinearity. The space $\Lambda^k(V^*)$ embeds into $\otimes^k V^*$ in the usual way and hence inherits a inner product.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/70938', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16490/']}
jdg_379430
stackexchange
llm_judgeable_groundtruth_similarity
253984
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider the following set of polynomials: $S := \{x^{2m}: m \geq 0\}$. Is there a non-zero element $f \in L^2([0,1])$ such that $\int_0^1 fx^{2m} = 0$ for each $m \geq 0$? Note that the answer is negative if $[0,1]$ is replaced by $[-1,1]$. More generally, given a set of polynomials, is there any standard procedure to check if its linear span is dense in $L^2(X)$? Now provide the response and nothing else.
You want a version of the classical Müntz–Szász theorem for the space $L^2([0,1])$ (which is, incidentally, the case considered initially by Szász). Here is a nice paper on the situation for $L^p([0,1])$ spaces, always for the span of monomials (with real exponents allowed) http://www.math.tamu.edu/~terdelyi/papers-online/Fullmuntz.pdf
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/253984', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1508/']}
jdg_379431
stackexchange
llm_judgeable_groundtruth_similarity
3711221
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I add a UISearchDisplayController to a UIView? Interface builder won't let me. Now provide the response and nothing else.
The only sane way to update a table of 120M records is with a SELECT statement that populates a second table. You have to take care when doing this. Instructions below. Simple Case For a table w/out a clustered index, during a time w/out concurrent DML: SELECT *, new_col = 1 INTO clone.BaseTable FROM dbo.BaseTable recreate indexes, constraints, etc on new table switch old and new w/ ALTER SCHEMA ... TRANSFER. drop old table If you can't create a clone schema, a different table name in the same schema will do. Remember to rename all your constraints and triggers (if applicable) after the switch. Non-simple Case First, recreate your BaseTable with the same name under a different schema, eg clone.BaseTable . Using a separate schema will simplify the rename process later. Include the clustered index , if applicable. Remember that primary keys and unique constraints may be clustered, but not necessarily so. Include identity columns and computed columns , if applicable. Include your new INT column , wherever it belongs. Do not include any of the following: triggers foreign key constraints non-clustered indexes/primary keys/unique constraints check constraints or default constraints. Defaults don't make much of difference, but we're trying to keepthings minimal. Then, test your insert w/ 1000 rows: -- assuming an IDENTITY column in BaseTableSET IDENTITY_INSERT clone.BaseTable ONGOINSERT clone.BaseTable WITH (TABLOCK) (Col1, Col2, Col3)SELECT TOP 1000 Col1, Col2, Col3 = -1FROM dbo.BaseTableGOSET IDENTITY_INSERT clone.BaseTable OFF Examine the results. If everything appears in order: truncate the clone table make sure the database in in bulk-logged or simple recovery model perform the full insert. This will take a while, but not nearly as long as an update. Once it completes, check the data in the clone table to make sure it everything is correct. Then, recreate all non-clustered primary keys/unique constraints/indexes and foreign key constraints (in that order). Recreate default and check constraints, if applicable. Recreate all triggers. Recreate each constraint, index or trigger in a separate batch. eg: ALTER TABLE clone.BaseTable ADD CONSTRAINT UQ_BaseTable UNIQUE (Col2)GO-- next constraint/index/trigger definition here Finally, move dbo.BaseTable to a backup schema and clone.BaseTable to the dbo schema (or wherever your table is supposed to live). -- -- perform first true-up operation here, if necessary-- EXEC clone.BaseTable_TrueUp-- GO-- -- create a backup schema, if necessary-- CREATE SCHEMA backup_20100914-- GOBEGIN TRY BEGIN TRANSACTION ALTER SCHEMA backup_20100914 TRANSFER dbo.BaseTable -- -- perform second true-up operation here, if necessary -- EXEC clone.BaseTable_TrueUp ALTER SCHEMA dbo TRANSFER clone.BaseTable COMMIT TRANSACTIONEND TRYBEGIN CATCH SELECT ERROR_MESSAGE() -- add more info here if necessary ROLLBACK TRANSACTIONEND CATCHGO If you need to free-up disk space, you may drop your original table at this time, though it may be prudent to keep it around a while longer. Needless to say, this is ideally an offline operation. If you have people modifying data while you perform this operation, you will have to perform a true-up operation with the schema switch. I recommend creating a trigger on dbo.BaseTable to log all DML to a separate table. Enable this trigger before you start the insert. Then in the same transaction that you perform the schema transfer, use the log table to perform a true-up. Test this first on a subset of the data! Deltas are easy to screw up.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3711221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19875/']}
jdg_379432
stackexchange
llm_judgeable_groundtruth_similarity
11743392
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When the page is loading for the first time, I need to check if there is an image in image_array and load the last image. Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images; The problem is that image_array in the else fires all time. If an array exists - it just overrides it, but alert doesn't work. if(image_array.length > 0) $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');else{ $('#prev_image').attr('disabled', 'true'); $('#next_image').attr('disabled', 'true'); alert('Please get new image'); var image_array = [];} UPDATEBefore loading html, I have something like this: <?php if(count($images) != 0): ?><script type="text/javascript"> <?php echo "image_array = ".json_encode($images);?></script><?php endif; ?> Now provide the response and nothing else.
if (typeof image_array !== 'undefined' && image_array.length > 0) { // the array is defined and has at least one element} Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable: <?php echo "var image_array = ".json_encode($images);?>// add var ^^^ here And then make sure you never accidently redeclare that variable later: else { ... image_array = []; // no var here}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/11743392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1564141/']}
jdg_379433
stackexchange
llm_judgeable_groundtruth_similarity
62390190
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code: #include <iostream>void f(int const& a, int& b){ b = a+1;}int main() { int c=2; f(c,c); std::cout << c << std::endl;} Function f takes two reference arguments: int const& a and int& b . Therefore, f is supposed not to modify a , but it can modify b , and indeed it does. However, in main , I pass the same variable, referenced both by a and by b . As f modifies b , it also modifies a , which it supposedly shouldn't This code compiles without any warning and prints 3 . If we track each variable individually, it looks like const-correctness is respected: c is non-const, therefore it is perfectly fine to pass it as a const ref as a , and also as a non-const ref as b , and within the body of f we modify b , which is non-const, while not touching a , which is const. However, when c is employed both as a and as b , a is modified within the body of f , violating the assumption that a is const, even though no explicit const_cast was ever called. I made this example as simple as I could, but one can easily think of not-so-obvious use cases (such as a const method acting on a non-const reference argument). My question is: Can we really say the above code is const-correct? Is the above use case a known pattern? Is it considered bad practice? Other than being confusing to a reader, can the above code be the source of technical problems? Such as undefined behavior, or the compiler performing wrong simplifying assumptions? Now provide the response and nothing else.
However, in main , I pass the same variable, referenced both by a and by b . As f modifies b , it also modifies a , which it supposedly shouldn't When f modifies what b refers to, it does not modify a . It modifies what a refers to, but that is okay since b is not const . It's only when you try to modify what a refers to by using a that you have issues. Can we really say the above code is const-correct? Yes. You do not modify a const variable. Other than being confusing to a reader, can the above code be the source of technical problems? Such as undefined behavior, or the compiler performing wrong simplifying assumptions? No, your code is legal and will produce the same results on all conforming compilers. A constant reference parameter does not make the thing that it refers to const if it was not const to begin with. All it does it stop you from using the reference to modify the object. Another pointer or reference to that object can still mutate it, as long as it is not const itself.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62390190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12175820/']}
jdg_379434
stackexchange
llm_judgeable_groundtruth_similarity
13548142
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 progmatically importing products into Magento 1.7.0.2 from an XML feed. The script has run fine for the best part of a week, but now I'm getting the error shown below when products are saving. How serious is this error, what can cause it? I've tried reindexing everything and truncating a bunch of tables, the error seems to persist. The Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '51-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID' Import php (sample): $sProduct = $this->_productModel; $sProduct->setTypeId($this->_productTypeSimple) ->setWebsiteIds(array(1)) ->setStatus($this->_productStatusDisabled) ->setVisibility($this->_productVisibilityNotVisible) ->setTaxClassId(2) //Taxable Good ->setAttributeSetId(XML_FEED_PRODUCT_ATTRIBUTE_SET) ->setSku($arrayProductData['ProductSKU']) ->setName($arrayProductData['ProductName']) ->setShortDescription($arrayProductData['ProductShortDescription']) ->setDescription($arrayProductData['ProductLongDescription']) ->setPrice(sprintf("%0.2f", $arrayProductData['ProductPrice'])) ->setRRP(sprintf("%0.2f", $arrayProductData['ProductPrice'])) ->setWeight(0) ->setCategoryIds($arrayProductData['ProductCategories']) ->setUrlKey(str_replace(array(" ","'","&"),"-",$arrayProductData['ProductName']) . "-" . $arrayProductData['ProductSKU']);$sProduct->setStockData( array( 'use_config_manage_stock' => 1, 'is_in_stock' =>1, 'qty' => $arrayProductData['ProductStockQty'] ));$sProduct->setMetaTitle($arrayProductData['ProductName'])->setMetaDescription(str_replace("<<THE_PRODUCT>>",$arrayProductData['ProductName'], DEFAULT_META_DESC)); if(isset($arrayProductData['ProductSize'])) { $sProduct->setData("sizes", $arrayProductData['ProductSize']);}if(isset($arrayProductData['ProductColour'])) { $sProduct->setData("color", $arrayProductData['ProductColour']);}try { $sProduct->save(); }catch (Mage_Core_Exception $e) { echo $e->getMessage();} Thanks for looking. Now provide the response and nothing else.
Edit: Saving data(e.g. a table) into file without using variable (only constant values) -- folder_path could could be like => c:/users/sami-- choose the directory/folder already available in system-- and make sure you have access to write the file thereSELECT * INTO OUTFILE 'folder_path/filename.csv'FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'FROM database.tableName; Now using variable Whenever you have to use a variable name in sql, you need dynamic sql (which is applicable in stored procedures only, neither in simple sql query nor in triggers or functions) SET @OutputPath := 'Users/jo/Documents'; //or any folder_pathSET @fullOutputPath := CONCAT(@OutputPath,'/','filename.csv');SET @fullOutputPath2 := CONCAT(@OutputPath,'/','filename2.csv');set @q1 := concat("SELECT * INTO OUTFILE ",@fullOutputPath," FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'FROM database.tableName");set @q2 := concat("SELECT * INTO OUTFILE ",@fullOutputPath2," FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'FROM database.tableName2");prepare s1 from @q1;execute s1;deallocate prepare s1;prepare s1 from @q2;execute s1;deallocate prepare s1; As you had both ' and " in your query already, so I concatenated your query using " and used \ to escape your original " to ensure its use as a literal character and not used for concatenation I just told the use of variable in sql. First You should make sure if your query works like example at the top (without using variable) Conclusion: If your above query works fine then my told dynamic sql will work as well given that you are using it in some stored procedure.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13548142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813892/']}
jdg_379435
stackexchange
llm_judgeable_groundtruth_similarity
13546778
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 message from popup.js is being posted twice to background.js, but I get absolutely nothing from background.js. background.js function login(username,password){ console.log(username);var xhr = new XMLHttpRequest();xhr.open("POST", "http://localhost:3000/login/", true);xhr.setRequestHeader('Content-type','application/json; charset=utf-8');data = {"username":username,"password":password};console.log(JSON.stringify(data));xhr.send(JSON.stringify(data));xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // JSON.parse does not evaluate the attacker's scripts. var resp = JSON.parse(xhr.responseText); console.log(resp); var lStorage = localStorage; localStorage.setItem("username",resp["username"]); localStorage.setItem("apiKey",resp["apiKey"]); localStorage.setItem("password",resp["password"]); console.log(localStorage.getItem("username")); }};}chrome.extension.onRequest.addListener( function(request, sender, sendResponse){ console.log("hello"); if(request.msg == "login") { //alert(request.password); login(request.username,request.password);} }); chrome.extension.onConnect.addListener(function(port) { console.log("Connected ....."); port.onMessage.addListener(function(msg) { console.log("message recieved "+ msg); port.postMessage("Hi Popup.js"); });}); popup.js: function login(){alert(document.login.username.value);chrome.extension.sendRequest({ msg: "login",username:document.login.username.value,password:document.login.password.value});document.getElementById('openBackgroundWindow').visbility = "hidden";}$(document).ready(function (){checkUserAuth();console.log("Inside");$("#openBackgroundWindow").click(login);});function checkUserAuth(){console.log(localStorage.getItem("apiKey"));if(localStorage.getItem("apiKey") != null) { $("#openBackgroundWindow").visbility ="hidden"; }}var port = chrome.extension.connect({name: "Sample Communication"});port.postMessage("Hi BackGround");port.onMessage.addListener(function(msg) { console.log("message recieved"+ msg);}); Now provide the response and nothing else.
Method - A : Using Long Lived Connections you can communicate from background.js to popup.js of extension page for any activities( Here i have included popup.html and only initiated sample communication from popup.js as a sample) background.js chrome.extension.onConnect.addListener(function(port) { console.log("Connected ....."); port.onMessage.addListener(function(msg) { console.log("message recieved" + msg); port.postMessage("Hi Popup.js"); }); }) popup.js var port = chrome.extension.connect({ name: "Sample Communication" }); port.postMessage("Hi BackGround"); port.onMessage.addListener(function(msg) { console.log("message recieved" + msg); }); Method - B : Direct Manipulation of DOM* if your end result is modification of DOM, you can achieve with this popup.html <html> <head> <script src="popup.js"></script> </head> <body> <div id="x" value="m">Some thing</div> </body></html> background.js var views = chrome.extension.getViews({ type: "popup"});for (var i = 0; i < views.length; i++) { views[i].document.getElementById('x').innerHTML = "My Custom Value";} Method - C : Using Long Lived Connections you can communicate from background.js to popup.js of extension page for any activities( Here i have not included popup.html and initiated sample communication from background.js; background.js chrome.browserAction.onClicked.addListener(function(tab) { var port = chrome.extension.connect({ name: "Sample Communication" }); port.postMessage("Hi BackGround"); port.onMessage.addListener(function(msg) { console.log("message recieved" + msg); });}); I have changed your code and made it running after eliminating some stuff and making it a simple version. Add your code for AJAX requests and HTML DOM on this skeleton ( Make sure you add <script> tag in head section and put chrome.extension.onConnect.addListener out of (xhr.readyState == 4) code;) popup.html <html > <head> <script src="popup.js"></script> </head> <body></body></html> manifest.json { "name": "Demo", "version": "1.0", "manifest_version": 2, "description": "This is a demo", "browser_action": { "default_popup": "popup.html" }, "background": { "scripts": ["background.js"] }, "permissions": ["<all_urls>", "storage", "tabs" ]} background.js chrome.extension.onConnect.addListener(function(port) { console.log("Connected ....."); port.onMessage.addListener(function(msg) { console.log("message recieved " + msg); port.postMessage("Hi Popup.js"); });}); popup.js var port = chrome.extension.connect({ name: "Sample Communication"});port.postMessage("Hi BackGround");port.onMessage.addListener(function(msg) { console.log("message recieved" + msg);});
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13546778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105167/']}
jdg_379436
stackexchange
llm_judgeable_groundtruth_similarity
13015932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I find the minimum value from a vector? int main(){ int v[100] = {5,14,2,4,6}; int n = 5; int mic = v[0]; for(int i=0;i<v[n];i++) { if(v[i]<mic) mic=v[i]; } cout<<mic;} But is not working, what can I do? Now provide the response and nothing else.
See std::min_element . Examples: std::min_element(vec.begin(), vec.end()); // STL containers.std::min_element(v, v + n); // C style arrays where n is the number of elements.std::min_element(std::begin(v), std::end(v)); // STL containers and C style arrays. Note that for the last option, it is better to apply the 'std 2-step' pattern so it works for user-defined types as well as standard library types: using std::begin, std::end; // Enables argument-dependent lookup: https://en.cppreference.com/w/cpp/language/adlstd::min_element(begin(v), end(v)); Since C++20, we can also use ranges to avoid having to call begin/end manually: std::ranges::min_element(v);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13015932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1766001/']}
jdg_379437
stackexchange
llm_judgeable_groundtruth_similarity
3845968
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: There are tens of posts already on this site about whether $0.\overline{9} = 1$ . This is something that intrigues me, and I have a question about this, including a "proof" which I have found myself. Question: This comment says that you need a terminating decimal to get something less than 1. If so, does it mean that a non-terminating decimal (e.g. $0.\overline{9}$ ) is $\ge 1$ ? So is $\frac{1}{3}$ ( $0.\overline{3}$ ) also $\ge 1$ ? It is non-terminating, but you can subtract $\frac{1}{3}$ from $1$ to get $\frac{2}{3} = 0.\overline{6}$ , which is another non-terminating decimal. How do those mechanics work? Theorem: $0.99999... = 1(.00000... = 1)$ Proof: \begin{align}\frac{1}{9} &= 0.11111... \\\frac{2}{9} &= 0.22222... \\\frac{3}{9} &= 0.33333... \\\frac{4}{9} &= 0.44444... \\\frac{5}{9} &= 0.55555... \\\frac{6}{9} &= 0.66666... \\\frac{7}{9} &= 0.77777... \\\frac{8}{9} &= 0.88888... \\\therefore \frac{9}{9} &= 0.99999... \\&= 1\end{align} Is the above proof correct? I came up with it myself before I decided to ask this question, but I do not know if it is mathematically valid. Now provide the response and nothing else.
The non-terminating notation (either $0.9999\cdots$ or $0.\overline9$ ) is a disguised limit, namely $$\lim_{n\to\infty}\sum_{k=1}^n\frac 9{10^k}$$ or $$\lim_{n\to\infty}\left(1-10^{-n}\right).$$ This limit equals $1$ . To relate this to your proof, we indeed have $$0.\overline1=\lim_{n\to\infty}\sum_{k=1}^n\frac 1{10^k}=\frac19,$$ then $$9\cdot 0.\overline1=9\lim_{n\to\infty}\sum_{k=1}^n\frac 1{10^k}=\lim_{n\to\infty}\sum_{k=1}^n\frac 9{10^k}=0.\overline 9$$ and $$\frac99=1.$$ But honestly, I see no benefit taking this indirect route through $9\cdot0.\overline 1$ , and for completeness, you should explain why $\dfrac19=0.\overline1$ , and why $9\cdot0.\overline1=0.\overline9$ like I did (or another way).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3845968', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/717872/']}
jdg_379438
stackexchange
llm_judgeable_groundtruth_similarity
6527633
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 to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation , which says: This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module. My goal is to have two functions with the same implementation but with different docstrings. def A(): """A""" passB = make_a_deepcopy_of(A)B.__doc__ = """B""" So how can this be done? Now provide the response and nothing else.
The FunctionType constructor is used to make a deep copy of a function. import typesdef copy_func(f, name=None): return types.FunctionType(f.func_code, f.func_globals, name or f.func_name, f.func_defaults, f.func_closure)def A(): """A""" passB = copy_func(A, "B")B.__doc__ = """B"""
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6527633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821996/']}
jdg_379439
stackexchange
llm_judgeable_groundtruth_similarity
16087146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use AngularJS two-way binding text which includes Latex style equations. I would like to call MathJax to format the equations, but I'm not sure of the best way to ensure that MathJax is called after AngularJS finishes changing the model. I think I need a callback. Here is my JavaScript: var myApp = angular.module('myApp',[]);function MyCtrl($scope) { $scope.Update = function() { $scope.Expression = 'Evaluate: \\( \\frac{9}{4} \\div \\frac{1}{6} \\)'; MathJax.Hub.Queue(["Typeset", MathJax.Hub]); } $scope.Expression = 'Evaluate: \\( \\frac{5}{4} \\div \\frac{1}{6} \\)'; } And here is my HTML: <div ng-controller="MyCtrl"> <button ng-click="Update()">Update</button> {{Expression}}</div> Fiddle is here: http://jsfiddle.net/LukasHalim/UVjTD/1/ . You'll notice that on the fiddle the original expression isn't removed even after you click the update button twice - seems like a bug or conflict. Now provide the response and nothing else.
Having wasted many days (and maybe weeks) fighting MathJax, I'm all too familiar with its various quirks with updating math expressions on the fly. I'm brand new to Angular but this gave me a good chance to dive in and I ended up with a solution which solves my problems -- hopefully it'll solve yours as well. Live demo: jsfiddle Instead of using the plain interpolation that Angular provides, I created a new directive based on ng-bind called mathjax-bind . If expression is a variable containing math code, then instead of \( {{expression}} \) you can write: <span mathjax-bind="expression"></span> and everything will be typeset and updated at the appropriate times. The supporting code for the directive follows: myApp.directive("mathjaxBind", function() { return { restrict: "A", controller: ["$scope", "$element", "$attrs", function($scope, $element, $attrs) { $scope.$watch($attrs.mathjaxBind, function(texExpression) { var texScript = angular.element("<script type='math/tex'>") .html(texExpression ? texExpression : ""); $element.html(""); $element.append(texScript); MathJax.Hub.Queue(["Reprocess", MathJax.Hub, $element[0]]); }); }] };});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16087146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1516189/']}
jdg_379440