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
|
6272644
|
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'd like to setup my ComboBox values as a named array constant, where you go into the Name Manager and define a name and give it a value like: ={"A", "B", "C"} I've found that ListFillRange will only take a Range so I can't assign to that. Though it would work for a normal named range, like so: myComboBox.ListFillRange = "MyList" So how do you assign a Named Array Constant to fill a ComboBox?
Now provide the response and nothing else.
|
Your problem is you are using ISet in System.Collections.Generic namespace but nHibernate expects ISet to be Iesi.Collections.Generic.ISet<> . So change your property definition to public virtual Iesi.Collections.Generic.ISet<People> People { get; set; } If you want to use .net 4 ISet<> interface, go through this article
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6272644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13295/']}
|
jdg_377041
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25849042
|
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 div with id and class names as tab . The css are defined for the div . The original background-color is blue and color is white. I need to flash some text on this div , where the message should flash 3 times with black background and white text and vice versa. I tried toggleClass . Using this the effect is generated but the previous class css is not restored. I have tried fade also $("#tab").fadeOut(200).fadeIn(200); , it helps the blinking part but doesnt give the desired results. Please suggest... Thanks in advance. This is what i have tried so far: <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script><link type="text/css" rel="stylesheet" href="css/styles.css"><style type="text/css">.backgroundRed{ background-color: #cccccc; color: red;}.blink{ background-color: black; color: white;}</style><script type="text/javascript">$(document).ready(function(){var flg = 0;$.fn.blink = function(){ var i = 0; for(var i = 0; i <= 3; i++) { // attempt#1 // //blinking works well with this //// //$("#test").fadeOut(200).fadeIn(200); // attempt#2 // //changes looks good but doesnt revert back to original class //// //$(".backgroundRed").toggleClass("blink"); //$("#test").removeClass("blink"); //$("#test").addClass("backgroundRed"); // attempt #3 // // doesnt work correctly if(i >= 3) { $("#test").fadeOut(200).fadeIn(200); $("#test").removeClass("blink"); $("#test").addClass("backgroundRed"); } else { $("#test").fadeOut(200).fadeIn(200); $("#test").removeClass("backgroundRed"); $("#test").addClass("blink"); } }}$("#tab").click(function(){ $.fn.blink();});});</script><html><body><div id="test" class="backgroundRed" style="height: 200px; width: 400px; "><h1>test value</h1></div><button id="tab">click</button></html>
Now provide the response and nothing else.
|
Have you ever been to a book club where members do not all use the same edition of the "book of the week"? It's a nightmare, right? Moving a tag would essentially put you in the same situation. If you think of your repository as a book that chronicles progress in your project, you can think of a tag as a chapter heading . Moving a tag to a different commit after sharing it is like telling all your book-club buddies You know what, guys? The edition of the book we've all been using so far is now obsolete, because I have solely decreed that chapter 8 shall now start, not on page 126, but on page 128. Not good. Moving a tag is a form of history rewriting, and you shouldn't rewrite history that has been shared. It's the surest way to piss your collaborators off. Besides, you write I'm the only contributor to my repo [...] That may be true for now, but if other people than you have access to your GitHub repository (e.g. if it's public), some of them may already have forked or cloned it (although there is a way to find out), and you run the risk of pissing them off if you rewrite history. If you're 100% sure that you want to move that tag anyway, Git does allow you to do it. Here, you could use git tag --force v1.0 <ID-of-commit-127> and then you would have to force push that tag, using git push --force --tags But again, think twice before going ahead... Addendum (2018/09/26) I feel the need to revisit my answer... Over the years, some people have objected in the comments to my injunction not to move an already published tag. Of course, this piece of advice is contextual rather than universal; I don't doubt that good cases for moving a published tag exist. However, I stand firm in the belief that, as a general rule, the decision to move a published tag should be made deliberately and with extreme care. One recent example comes to mind. Go 1.11 added experimental support for a module system that relies heavily on Git tags for versioning. Moving a tag in a Go module that has been published (on GitHub, say) would have disastrous consequences. By doing so, you would break the contract established between you (the module author) and your users (those who depend on your module), because you would negate the guarantees that Go's module system intends to provide: Modules record precise dependency requirements and create reproducible builds. That's one sure way to piss people off. This example may be enough to convince you that, at least in some cases, you shouldn't mindlessly move published tags. I rest my case.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25849042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3446683/']}
|
jdg_377042
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34145
|
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 $$f\in C^\infty (\mathbb{R})$$ and $f$ is an odd function. ($f(x)=-f(-x)$) What can we say about the zero at zero? Does $f$ have to be of the form $x g(x)$ for some $g\in C^\infty (\mathbb{R})$? I know this is true for complex analytic functions, and I think it is true here, but I don't know how to prove/disprove it.
Now provide the response and nothing else.
|
Set $g(x) = \begin{cases} f(x)/x \; (x \ne 0) \\ f'(0) \; (x = 0) \end{cases}$. Then check that $g$ has all derivatives at 0, using Taylor polynomials. Analyticity of $f$ is not needed. If $f$ is real analytic, then so is $g$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/34145', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9834/']}
|
jdg_377043
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10539129
|
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 know how replication works in a distributed database. It would be nice if this could be explained in a thorough, yet easy to understand way. It would also be nice if you could make a comparison between distributed transactions and distributed replication.
Now provide the response and nothing else.
|
Single point of failure The database server is a central part of an enterprise system, and, if it goes down, service availability might get compromised. If the database server is running on a single server, then we have a single point of failure. Any hardware issue (e.g., disk drive failure) or software malfunction (e.g., driver problems, malfunctioning updates) will render the system unavailable. Limited resources If there is a single database server node, then vertical scaling is the only option when it comes to accommodating a higher traffic load. Vertical scaling, or scaling up, means buying more powerful hardware, which provides more resources (e.g., CPU, Memory, I/O) to serve the incoming client transactions. Up to a certain hardware configuration, vertical scaling can be a viable and simple solution to scale a database system. The problem is that the price-performance ratio is not linear, so after a certain threshold, you get diminishing returns from vertical scaling. Another problem with vertical scaling is that, in order to upgrade the server, the database service needs to be stopped. So, during the hardware upgrade, the application will not be available, which can impact underlying business operations. Database Replication To overcome the aforementioned issues associated with having a single database server node, we can set up multiple database server nodes. The more nodes, the more resources we will have to process incoming traffic. Also, if a database server node is down, the system can still process requests as long as there are spare database nodes to connect to. For this reason, upgrading the hardware or software of a given database server node can be done without affecting the overall system availability. The challenge of having multiple nodes is data consistency. If all nodes are in-sync at any given time, the system is Linearizable , which is the strongest guarantee when it comes to data consistency across multiple registers. The process of synchronizing data across all database nodes is called replication, and there are multiple strategies that we can use. Single-Primary Database Replication The Single-Primary Replication scheme looks as follows: The primary node, also known as the Master node, is the one accepting writes while the replica nodes can only process read-only transactions. Having a single source of truth allows us to avoid data conflicts. To keep the replicas in-sync, the primary nodes must provide the list of changes that were done by all committed transactions. Relational database systems have a Redo Log, which contains all data changes that were successfully committed. PostgreSQL uses the WAL (Write-Ahead Log) records to ensure transaction Durability and for Streaming Replication. Because the storage engine is separated from the MySQL server, MySQL uses a separate Binary Log for replication. The Redo Log is generated by the InnoDB storage engine, and its goal is to provide transaction Durability while the Binary Log is created by the MySQL Server, and it stores the logical logging records, as opposed to physical logging created by the Redo Log. By applying the same changes recorded in the WAL or Binary Log entries, the replica node can stay in-sync with the primary node. Horizontal scaling The Single-Primary Replication provides horizontal scalability for read-only transactions. If the number of read-only transactions increases, we can create more replica nodes to accommodate the incoming traffic. This is what horizontal scaling, or scaling out, is all about. Unlike vertical scaling, which requires buying more powerful hardware, horizontal scaling can be achieved using commodity hardware. On the other hand, read-write transactions can only be scaled up (vertical scaling) as there is a single primary node.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10539129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1387762/']}
|
jdg_377044
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7421808
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
NSData has always had a very convenient method called +dataWithContentsOfURL:options:error: . While convenient, it also blocks execution of the current thread, which meant it was basically useless for production code (Ignoring NSOperation ). I used this method so infrequently, I completely forgot that it existed. Until recently. The way I've been grabbing data from the tubes is the standard NSURLConnectionDelegate approach: Write a download class that handles the various NSURLConnectionDelegate methods, gradually build up some data, handle errors, etc. I'll usually make this generic enough to be reused for as many requests as possible. Say my typical downloader class runs somewhere in the ballpark of 100 lines. That's 100 lines to do asynchronously what NSData can do synchronously in one line. For more complexity, that downloader class needs a delegate protocol of its own to communicate completion and errors to its owner, and the owner needs to implement that protocol in some fashion. Now, enter Grand Central Dispatch, and I can do something as fantastically simple as: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { NSData* data = [NSData dataWithContentsOfURL:someURL]; // Process data, also async... dispatch_async(dispatch_get_main_queue(), ^(void) { // Back to the main thread for UI updates, etc. });}); And I can throw that sucker in anywhere I want, right in-line. No need for a download class, no need to handle connection delegate methods: Easy async data in just a few lines. The disparity between this approach and my pre-GCD approach is of a magnitude great enough to trigger the Too Good to be True Alarm. Thus, my question: Are there any caveats to using NSData + GCD for simple data download tasks instead of NSURLConnection (Assuming I don't care about things like download progress)?
Now provide the response and nothing else.
|
You are losing a lot of functionality here: Can't follow the download progression Can't cancel the download Can't manage the possible authentication process You can't handle errors easily, which is really important especially in mobile development like on iPhone of course (because you often lose your network in real conditions, so it is very important to track such network error cases when developing for iOS) and there's probably more I guess. The right approach for that is to create a class than manages the download. See my own OHURLLoader class for example, which is simple and I made the API to be easy to use with blocks: NSURL* url = ...NSURLRequest* req = [NSURLRequest requestWithURL:url];OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req];[loader startRequestWithCompletion:^(NSData* receivedData, NSInteger httpStatusCode) { NSLog(@"Download of %@ done (statusCode:%d)",url,httpStatusCode); if (httpStatusCode == 200) { NSLog(%@"Received string: %@", loader.receivedString); // receivedString is a commodity getter that interpret receivedData using the TextEncoding specified in the HTTP response } else { NSLog(@"HTTP Status code: %d",httpStatusCode); // Log unexpected status code }} errorHandler:^(NSError *error) { NSLog(@"Error while downloading %@: %@",url,error);}]; See the README file and sample project on github for more info. This way: you still rely on the asynchronous methods provided by NSURLConnection (and as the Apple's documentation says about Concurrency Programming if an API already exists to make asynchronous tasks, use it instead of relying on another threading technology if possible) you keep advantages of NSURLConnection (error handlings, etc) but you also have the advantages of the blocks syntax that makes your code more readable than when using delegate methods
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7421808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538308/']}
|
jdg_377045
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
540997
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm diagnosing an error in a water heater. The error code indicates that the error is related to the connectors X2. Between both connectors X2 there is this Symbol "/" with the number 5. I have marked it with slight yellow. What does this symbol indicate?
Now provide the response and nothing else.
|
The slash indicates that the schematic line indicates a bus of five wires, rather than just a single wire. For the /5 example you call out, it means that all five pins on the X2 connector of item 1 are connected to the corresponding five pins of the X2 connector (item 13). If connector X2 is implicated in a troubleshooting guide, you may want to use a multimeter to ensure that all five pins of the cable still have continuity from one end to the other, and there are no short circuits between adjacent pins. This is in addition to any further measurements (e.g. of voltages on those pins) that the manual recommends. Likewise, item 2 presumably has a single three-pin cable going to the three-pin connector X10 (item 12). The /1 going to item 3 is a bit of an oddball - there's a single wire, and it's specifically called out as a single wire. The return for that signal might be chassis ground (given the dotted lines between that wire and ground on/near the X7 connector).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/540997', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/273070/']}
|
jdg_377046
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12838230
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is the scenario: AndroidManifest.xml defines a single Activity with android:launchMode="singleTask" . (This means there should be a single activity in the stack throughout the entire application lifecycle, right ?) During Activity.onCreate() , a broadcast receiver is programmatically created and listens for incomming SMS. The receiver remains active even after Activity.onPause() by design . When the user is done with the application, he presses the device Home button which calls Activity.onPause() and the application disappears. The device shows then the Android home screen. Upon receiving SMS, the broadcast receivers receives SMS and tries to show up the Activity via: Intent it = new Intent(context, Akami.class);it.setAction(Intent.ACTION_MAIN);it.addCategory(Intent.CATEGORY_LAUNCHER);it.setComponent(new ComponentName(context.getPackageName(), "MyActivity"));it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(it); However, the activity is NOT showed up to the user. a) Why ? b) What are the possible ways to bring an Activty to foreground ?
Now provide the response and nothing else.
|
In MyMainActivity definition (AndroidManifest.xml): <intent-filter> <action android:name="intent.my.action" /> <category android:name="android.intent.category.DEFAULT" /></intent-filter> Programmatically bringing application to foreground: Intent it = new Intent("intent.my.action");it.setComponent(new ComponentName(context.getPackageName(), MyMainActivity.class.getName()));it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.getApplicationContext().startActivity(it); Note: context.startActivity(it) would NOT work when the context object is same as the activity one wants to bring up.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12838230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219728/']}
|
jdg_377047
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29591245
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I want to give an example: int *pi; // pi is a pointer that points to an integerconst int *cpi; // cpi is a pointer that points to a constant integerchar *pc; // pc is a pointer to a char How can I read these: char **x; //x is a pointer to a char pointer?char *y[];char **z[]; Thanks.
Now provide the response and nothing else.
|
cdecl.org is often linked to such questions. No doubt that it make easier to decipher any complex declaration, but at the same time it just provide an abstracted information. Being a C or C++ programmer one should know how to decipher complex declaration manually. Spiral Rule help to some extent but fails in some cases . This answer will help programmers to decipher any complex declaration manually. Remember these two simple rules: Always read declaration from the inside out . When there is a choice, always favor [] and () over * . The first rule simply states that, locate the variable that is being declared and start deciphering the declaration from it. For second rule, if * precedes the identifier and [] or () follows it, then the identifier represents an array or function (respectively), not a pointer. Example 1: char *y[5]; Variable/identifier is y . * precedes y and follows [] . y must be an array. Combining above deciphering will result in: y is an array of 5 pointers to char . Also note that you can always use parentheses to override the normal priority of [] or () . Example 2: void (*pf) (int); Variable/identifier is pf . *pf is enclosed in parenthesis, it must be a pointer. () follows *pf , means pf must points to a function. Since () encloses int , function must expects an argument of type int . So, pf is a pointer to function that expects an int argument and returns nothing . Now, what would you get after deciphering the following declaration int *(*a[5])(void); ? Answer: a is an array of pointers to functions that expects no argument and returning pointer to int . Note: Note that both of char *y[];char **z[]; will cause compilation error if they are not declared as arguments of a function. If they are function's argument then char *y[] is equivalent to char **y and char **z[] is equivalent to char ***z . If that's not the case, then you need to specify the dimension as I did in my first example.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29591245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1173112/']}
|
jdg_377048
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60541105
|
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 updated a GKE cluster from 1.13 to 1.15.9-gke.12. In the process I switched from legacy logging to Stackdriver Kubernetes Engine Monitoring. Now I have the problem that the stackdriver-metadata-agent-cluster-level pod keeps restarting because it gets OOMKilled . The memory seems to be just fine though. The logs also look just fine (same as the logs of a newly created cluster): I0305 08:32:33.436613 1 log_spam.go:42] Command line arguments:I0305 08:32:33.436726 1 log_spam.go:44] argv[0]: '/k8s_metadata'I0305 08:32:33.436753 1 log_spam.go:44] argv[1]: '-logtostderr'I0305 08:32:33.436779 1 log_spam.go:44] argv[2]: '-v=1'I0305 08:32:33.436818 1 log_spam.go:46] Process id 1I0305 08:32:33.436859 1 log_spam.go:50] Current working directory /I0305 08:32:33.436901 1 log_spam.go:52] Built on Jun 27 20:15:21 (1561666521) at gcm-agent-dev-releaser@ikle14.prod.google.com:/google/src/files/255462966/depot/branches/gcm_k8s_metadata_release_branch/255450506.1/OVERLAY_READONLY/google3 as //cloud/monitoring/agents/k8s_metadata:k8s_metadata with gc go1.12.5 for linux/amd64 from changelist 255462966 with baseline 255450506 in a mint client based on //depot/branches/gcm_k8s_metadata_release_branch/255450506.1/google3Build label: gcm_k8s_metadata_20190627a_RC00Build tool: Blaze, release blaze-2019.06.17-2 (mainline @253503028)Build target: //cloud/monitoring/agents/k8s_metadata:k8s_metadataI0305 08:32:33.437188 1 trace.go:784] Starting tracingd dapper tracingI0305 08:32:33.437315 1 trace.go:898] Failed loading config; disabling tracing: open /export/hda3/trace_data/trace_config.proto: no such file or directoryW0305 08:32:33.536093 1 client_config.go:549] Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.I0305 08:32:33.936066 1 main.go:134] Initiating watch for { v1 nodes} resourcesI0305 08:32:33.936169 1 main.go:134] Initiating watch for { v1 pods} resourcesI0305 08:32:33.936231 1 main.go:134] Initiating watch for {batch v1beta1 cronjobs} resourcesI0305 08:32:33.936297 1 main.go:134] Initiating watch for {apps v1 daemonsets} resourcesI0305 08:32:33.936361 1 main.go:134] Initiating watch for {extensions v1beta1 daemonsets} resourcesI0305 08:32:33.936420 1 main.go:134] Initiating watch for {apps v1 deployments} resourcesI0305 08:32:33.936489 1 main.go:134] Initiating watch for {extensions v1beta1 deployments} resourcesI0305 08:32:33.936552 1 main.go:134] Initiating watch for { v1 endpoints} resourcesI0305 08:32:33.936627 1 main.go:134] Initiating watch for {extensions v1beta1 ingresses} resourcesI0305 08:32:33.936698 1 main.go:134] Initiating watch for {batch v1 jobs} resourcesI0305 08:32:33.936777 1 main.go:134] Initiating watch for { v1 namespaces} resourcesI0305 08:32:33.936841 1 main.go:134] Initiating watch for {apps v1 replicasets} resourcesI0305 08:32:33.936897 1 main.go:134] Initiating watch for {extensions v1beta1 replicasets} resourcesI0305 08:32:33.936986 1 main.go:134] Initiating watch for { v1 replicationcontrollers} resourcesI0305 08:32:33.937067 1 main.go:134] Initiating watch for { v1 services} resourcesI0305 08:32:33.937135 1 main.go:134] Initiating watch for {apps v1 statefulsets} resourcesI0305 08:32:33.937157 1 main.go:142] All resources are being watched, agent has started successfullyI0305 08:32:33.937168 1 main.go:145] No statusz port provided; not starting a serverI0305 08:32:37.134913 1 binarylog.go:95] Starting disk-based binary loggingI0305 08:32:37.134965 1 binarylog.go:265] rpc: flushed binary log to "" I already tried to disable the logging and reenable it without success. It keeps restarting all the time (more or less every minute). Does anybody have the same experience?
Now provide the response and nothing else.
|
The issue is being caused because the LIMIT set on the metadata-agent deployment is too low on resources so the POD is being killed (OOM killed) since the POD requires more memory to properly work. There is a workaround for this issue until it is fixed. You can overwrite the base resources in the configmap of the metadata-agent with: kubectl edit cm -n kube-system metadata-agent-config Setting baseMemory: 50Mi should be enough, if it doesn't work use higher value 100Mi or 200Mi . So metadata-agent-config configmap should look something like this: apiVersion: v1data: NannyConfiguration: |- apiVersion: nannyconfig/v1alpha1 kind: NannyConfiguration baseMemory: 50Mikind: ConfigMap Note also that You need to restart the deployment, as the config map doesn't get picked up automatically: kubectl delete deployment -n kube-system stackdriver-metadata-agent-cluster-level For more details look into addon-resizer Documentation .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60541105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6213728/']}
|
jdg_377049
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38610307
|
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 function where the statement foo should be executed under lock_guard but only when a pointer to a mutex object has been provided to the function as a parameter. Otherwise foo does not have to be protected by lock_guard . I cannot use the lock_guard within an if because the lock will be released immediately when the if block ends. so, this code is nonsense: bar( std::mutex * optionalMutex = nullptr ){ ... if ( nullptr != optionalMutex ) { std::lock_guard<std::mutex> lockScope( *optionalMutex ); } <- Here the lock ends foo... <- foo is not protected when optionalMutex was provided} I tried something like this: bar( std::mutex * optionalMutex = nullptr ){ ... nullptr == optionalMutex ? 0 : std::lock_guard<std::mutex> lockScope( *optionalMutex ); // this scope should be protected by lock_guard when optionalMutex was provided foo...} More or less, the only one possible solution for me is to repeat foo : bar( std::mutex * optionalMutex = nullptr ){ ... if ( nullptr != optionalMutex ) { std::lock_guard<std::mutex> lockScope( *optionalMutex ); foo... } else { foo... }} The compiler gcc 4.9.3 does not compile the 2nd example and complains: error: expected primary-expression before 'lockScope' . Update: Superlokkus explained in his answer why. But I do want to avoid any code duplicates and therefore also the duplicate foo . My question: Is there an elegant way how to implement this problem and not to use duplicate foo . I know, I could use a lambda function to group foo but I am curious if there is an another solution.
Now provide the response and nothing else.
|
How about this one? void bar(std::mutex * optionalMutex = nullptr){ auto lockScope = (optionalMutex == nullptr) ? std::unique_lock<std::mutex>() : std::unique_lock<std::mutex>(*optionalMutex);} Explanation: Your compiler had trouble with your prior statement because, you can not suddenly change the type of the ternary ? expression; i.e. the literal 0 is not a std::lock_guard and vice versa. So I changed the two branches to the same type, here std::unique_lock<std::mutex> because lock_guard isn't designed be used without a valid mutex. But still prefer std::lock_guard over std::unique_lock in the simpler cases, because it will make your code more readable. Also your statement wasn't viable for the compiler, i.e. even syntactical correct, because the variable lockScope would only have existed in one branch.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38610307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3179492/']}
|
jdg_377050
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19094099
|
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 Java background, and I love to use signal QUIT to inspect Java thread dump. How to let Golang print out all goroutines stack trace?
Now provide the response and nothing else.
|
To print the stack trace for the current goroutine, use PrintStack() from runtime/debug . PrintStack prints to standard error the stack trace returned by Stack. For example: import( "runtime/debug")... debug.PrintStack() To print the stack trace for all goroutines use Lookup and WriteTo from runtime/pprof . func Lookup(name string) *Profile// Lookup returns the profile with the given name,// or nil if no such profile exists.func (p *Profile) WriteTo(w io.Writer, debug int) error// WriteTo writes a pprof-formatted snapshot of the profile to w.// If a write to w returns an error, WriteTo returns that error.// Otherwise, WriteTo returns nil. Each Profile has a unique name. A few profiles are predefined: goroutine - stack traces of all current goroutines heap - a sampling of all heap allocations threadcreate - stack traces that led to the creation of new OS threads block - stack traces that led to blocking on synchronization primitives For example: pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19094099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377051
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6736
|
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The primal problem is $$\min_{w,b}\frac{1}{2}w^Tw$$$$s.t. f_i(w)=1-y_i(w\cdot x_i+b)\leq0$$ Where $y_i=\pm1$. Instead of using Gradient Descent directly, the dual is usually solved: $$\max_{\lambda}\min_{w,b}\frac{1}{2}w^Tw+\sum_{i=1}^M{\lambda_i(1-y_i(w\cdot x_i+b))}$$$$s.t. \lambda_i\geq0$$ Why not solve the primal directly? What I was thinking is that it's hard to use gradient descent when $b$ which is part of the constraints is unknown (it can actually be calculated as a function of $w$). But maybe I'm missing something.
Now provide the response and nothing else.
|
You've identiifed the key problem. Certainly the primal can be solved directly by, say, a quadratic programming solver. But typical QP solvers often don't scale well to large problem sizes. A projected gradient method can often scale to significantly larger problems---but only if the derivatives and projections are simple to compute. As I will show, the dual problem can be solved with inexpensive projected gradient iterations, while the primal cannot be. First, let's simplify notation a bit: collect the vectors $y_ix_i$ into the rows of a matrix $Z$, and the values $y_i$ into the elements of a vector $y$. Then we can write the problem as$$\begin{array}{ll} \text{minimize}_{w,b} & f(w,b) \triangleq \tfrac{1}{2}w^T w \\ \text{subject to} & Z w + y b \succeq \vec{1} \end{array}$$ A projected gradient algorithm will alternate between gradient steps and projections. The gradient is simply $\nabla f(w,b)=(w,0)$, so this is a pretty trivial operation. Let's denote by $(w_+,b_+)$ the result of a single gradient step. We must then project $(w_+,b_+)$ back onto the feasible set: find the nearest point $(w',b')$ that satisfies $Xw+y \succeq \vec{1}$. This means we must solve$$\begin{array}{ll}\text{minimize}_{w,b} & \|w-w_+\|_2^2+(b_+-b)^2 \\ \text{subject to} & Zw+by\succeq \vec{1} \\\end{array}$$ This is virtually the same problem as the original. In other words, each step of projected gradients for the primal problem is as expensive as the original problem itself. Now examine the dual problem. To get a handle on this we need to simplify the dual function$$g(\lambda) = \min_{w,b} \tfrac{1}{2} w^T w - \lambda^T ( Z w + b y - \vec{1} )$$With a little calculus you can determine that the optimal value of $w=Z^T\lambda$. As for $b$, we observe that if $y^T\lambda\neq 0$, the right-hand expression can be driven to $-\infty$ by growing $b\cdot(y^T\lambda)\rightarrow +\infty$. So$$g(\lambda) = \begin{cases} - \vec{1}^T \lambda - \tfrac{1}{2} \lambda^T ZZ^T \lambda & y^T \lambda = 0 \\ -\infty & y^T \lambda \neq 0 \end{cases}$$So the effect of $b$ is to introduce an implicit constraint $y^T\lambda =0$, and the dual problem is equivalent to $$\begin{array}{ll} \text{maximize} & \bar{g}(\lambda) \triangleq \vec{1}^T \lambda - \tfrac{1}{2} \lambda^T ZZ^T \lambda \\ \text{subject to} & y^T \lambda = 0 \\ & \lambda \succeq 0 \end{array}$$We would not have been able to apply projected gradients to the original dual function, because it wasn't differentiable; but removing the implicit constraint $y^T\lambda=0$ changes that. Now the gradient is $\nabla\bar{g}(\lambda) = \vec{1} - ZZ^T\lambda$---a bit more complex than the primal gradient, but entirely manageable. (Note that we're maximizing now, so gradient steps are taken in the positive direction). So what's left is to perform the projection. Given the point $\lambda_+$ that comes out of the gradient step, we need to solve$$\begin{array}{ll} \text{minimize} & \tfrac{1}{2} \|\lambda-\lambda_+\|_2^2 \\ \text{subject to} & y^T \lambda = 0 \\ & \lambda \geq 0 \end{array}$$This looks much easier than the primal projection, doesn't it? I haven't looked at the literature to see how people solve it now, but this is what I came up with: the value of $\lambda$ is$$\lambda_i = \max\{\lambda_{+,i}+sy,0\}, ~i=1,2,\dots, n$$where the parameter $s$ is chosen so that $y^T\lambda = 0$. I suspect there is a simple iterative method: start with $s=0$, compute $\lambda$ and $y^T\lambda$, adjust $s$, and repeat. A few $O(n)$ computations get the result. Don't trust me on this, I suspect the extant SVM literature has something solid here. An important final step is to recover $(w,b)$ from the optimal solution $\lambda^*$. Our derivations for $g(\lambda)$ showed that $w=Z^T\lambda^*$. Once this has been recovered, $b$ is any value in the following interval:$$b \in \left[ 1 - \max_{i:y_i=1} w\cdot x_i, \max_{i:y_i=-1} w \cdot x_i - 1 \right] $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/6736', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/4019/']}
|
jdg_377052
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2554116
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read in some references (some of them important, like page $328$ from Heights in Diophantine Geometry , by Bombieri and Gubler) that André Weil proved in his PhD thesis that the rank of an abelian variety (over a number field) is finite. I've read Weil's thesis and what I found was this (I'm paraphrasing): If $C$ is a plane algebraic curve over a number field $K$, with arbitrary genus, then its jacobian variety $J(C)$ has a structure of a finitelly generated abelian group. I don't know much about abelian varieties, but I have the feeling that what Weil proved was not in that level of generality mentioned in the book (i.e., for any abelian variety). Is it true that the case of abelian varieties can be reduced to that of the Jacobian of a plane curve? If it is, how so?
Now provide the response and nothing else.
|
Hint: $$\left(1 + \frac{1}{\lfloor a_n \rfloor+1} \right)^{\lfloor a_n \rfloor} \leqslant \left(1 + \frac{1}{a_n} \right)^{a_n} \leqslant \left(1 + \frac{1}{\lfloor a_n \rfloor} \right)^{\lfloor a_n \rfloor+1}, $$ and $$\left(1 + \frac{1}{n+1} \right)^n, \left( 1 + \frac{1}{n} \right)^{n+1} \to e$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2554116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/200513/']}
|
jdg_377053
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22710627
|
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 save my canvas to a img . I have this function: function save() { document.getElementById("canvasimg").style.border = "2px solid"; var dataURL = canvas.toDataURL(); document.getElementById("canvasimg").src = dataURL; document.getElementById("canvasimg").style.display = "inline";} It gives me error: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. What should I do?
Now provide the response and nothing else.
|
For security reasons, your local drive is declared to be "other-domain" and will taint the canvas. (That's because your most sensitive info is likely on your local drive!). While testing try these workarounds: Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders). Post your images to a site that supports cross-domain sharing (like dropbox.com or GitHub). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image ( var img=new Image(); img.crossOrigin="anonymous" ...) Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22710627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3465096/']}
|
jdg_377054
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2764953
|
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 $|z| < 1$ , prove that $\Re \left(\frac{1}{1 - z} \right) > \frac{1}{2}$ . My attempt: Consider $\frac{1}{1 - z}$ . Let $z = x + iy$ , we know that $|z| < 1 \implies x, y < 1$ . $$\frac{1}{1 - z} = \frac{1}{1 - x - iy} = \frac{1 - x + iy}{(1 - x)^2 + y^2}.$$ $$\Re \left(\frac{1}{1 - z} \right) = \frac{1 - x}{(1 - x)^2 + y^2}.$$ I got $$\frac{1}{(x-1)^2 + y^2} > \frac{1}{2}.$$ How do I manage the numerator? Can you help me? I welcome the alternative approaches.
Now provide the response and nothing else.
|
You need to use more than just $x,y<1$ for example with $x=y=\frac{3}{4}$ you obtain $\Re\left(\frac{1}{1-(x+iy)} \right)=\frac{2}{5} <\frac{1}{2}$. Hint : Using your computations:$$ \Re\left(\frac{1}{1-z}\right)=\frac{1-x}{(1-x)^2+y^2}=\frac{1-x}{x^2+y^2-2x+1}$$but $x^2+y^2<1$ so:$$\frac{1-x}{x^2+y^2-2x+1}>\frac{1-x}{1-2x+1}=\frac{1}{2}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2764953', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_377055
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26934506
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got a whole heap of files on a server, and I want to upload these onto S3. The files are stored with a .data extension, but really they're just a bunch of jpegs,pngs,zips or pdfs. I've already written a short script which finds the mime type and uploads them onto S3 and that works but it's slow. Is there any way to make the below run using gnu parallel? #!/bin/bashfor n in $(find -name "*.data") do data=".data" extension=`file $n | cut -d ' ' -f2 | awk '{print tolower($0)}'` mimetype=`file --mime-type $n | cut -d ' ' -f2` fullpath=`readlink -f $n` changed="${fullpath/.data/.$extension}" filePathWithExtensionChanged=${changed#*internal_data} s3upload="s3cmd put -m $mimetype --acl-public $fullpath s3://tff-xenforo-data"$filePathWithExtensionChanged response=`$s3upload` echo $response done Also I'm sure this code could be greatly improved in general :) Feedback tips would be greatly appreciated.
Now provide the response and nothing else.
|
You are clearly skilled in writing shell, and extremely close to a solution: s3upload_single() { n=$1 data=".data" extension=`file $n | cut -d ' ' -f2 | awk '{print tolower($0)}'` mimetype=`file --mime-type $n | cut -d ' ' -f2` fullpath=`readlink -f $n` changed="${fullpath/.data/.$extension}" filePathWithExtensionChanged=${changed#*internal_data} s3upload="s3cmd put -m $mimetype --acl-public $fullpath s3://tff-xenforo-data"$filePathWithExtensionChanged response=`$s3upload` echo $response }export -f s3upload_singlefind -name "*.data" | parallel s3upload_single
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26934506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346271/']}
|
jdg_377056
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24227816
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following (working) code in an existing code base, used in include file that is shared between C and C++, compiling on MSVC (2010) and Windows DDK: struct X { USHORT x;} typedef X, *PX; And: enum MY_ENUM { enum_item_1, enum_item_2 } typedef MY_ENUM; As far as I know, correct definition should look like this: typedef struct { USHORT x;} X, *PX; Is there any purpose for having the form below? Am I missing something?
Now provide the response and nothing else.
|
The fact that both typedef <type> <alias> and <type> typedef <alias> are valid simply comes from the language grammar definition. typedef is classified as a storage-class specfifier (just like static , auto ), and the type itself is known as the type-specifier . From the syntax definitions in section 6.7 of the standard, you'll see that these are free to be interchanged: declaration: declaration-specifiers init-declarator-list ;declaration-specifiers: storage-class-specifier declaration-specifiers type-specifier declaration-specifiers type-qualifier declaration-specifiers function-specifier declaration-specifiersinit-declarator-list: init-declarator init-declarator-list , init-declaratorinit-declarator: declarator declarator = initializer (Note, of course, that this is equally true for structs and for non-structs, meaning that double typedef trouble; is also valid.)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24227816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397604/']}
|
jdg_377057
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4204
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Computational complexity includes the study of time or space complexity of computational problems. From the the perspective of mobile computing, energy is very valuable computational resource. So, Is there a well studied adaptation of Turing machines that account for the energy consumed during the execution of algorithms. Also, Are there established energy-complexity classes for computational problems? References are appreciated.
Now provide the response and nothing else.
|
Is there a well studied adaptation of Turing machines that account for the energy consumed during the execution of algorithms? No! But maybe you could come up with one. It's possible you could divide the Turing machine steps into reversible and non-reversible (the non-reversible ones are where information is lost). Theoretically, it is only the non-reversible steps that cost energy. A cost of one unit of energy for each bit that is erased would theoretically be the right measure. There is a theorem of Charles Bennett that the time complexity increases by at most a constant when a computation is made reversible (C.H. Bennett, Logical Reversibility of Computation ), but if there are also limits on space, then making the computational reversible might incur a substantial increase in time (Reference here) . Landauer's principle says that erasing a bit costs $kT\, \ln 2$ of energy, where $T$ is temperature and $k$ is Boltzmann's constant. In real life, you cannot come anywhere close to achieving this minimum. However, you can build chips which perform reversible steps using substantially less energy than they use for irreversible steps. If you give reversible steps a cost of $\alpha$ and irreversible steps a cost of $\beta$, this seems like it may give a reasonable theoretical model. I don't know how Turing machines with some reversible steps relate to chips with some reversible circuitry, but I think both models are worth investigating.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/4204', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/495/']}
|
jdg_377058
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31788195
|
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 dataframe with panel structure: 2 observations for each unit from two years: library(tidyr)mydf <- data.frame( id = rep(1:3, rep(2,3)), year = rep(c(2012, 2013), 3), value = runif(6))mydf# id year value#1 1 2012 0.09668064#2 1 2013 0.62739399#3 2 2012 0.45618433#4 2 2013 0.60347152#5 3 2012 0.84537624#6 3 2013 0.33466030 I would like to reshape this data to wide format which can be done easily with tidyr::spread . However, as the values of the year variable are numbers, the names of my new variables become numbers as well which makes its further use harder. spread(mydf, year, value)# id 2012 2013#1 1 0.09668064 0.6273940#2 2 0.45618433 0.6034715#3 3 0.84537624 0.3346603 I know I can easily rename the columns. However, if I would like to reshape within a chain with other operations, it becomes inconvenient. E.g. the following line obviously does not make sense. library(dplyr)mydf %>% spread(year, value) %>% filter(2012 > 0.5) The following works but is not that concise: tmp <- spread(mydf, year, value)names(tmp) <- c("id", "y2012", "y2013")filter(tmp, y2012 > 0.5) Any idea how I can change the new variable names within spread ?
Now provide the response and nothing else.
|
I know some years has passed since this question was originally asked, but for posterity I want to also highlight the sep argument of spread . When not NULL , it will be used as separator between the key name and values: mydf %>% spread(key = year, value = value, sep = "")# id year2012 year2013#1 1 0.15608322 0.6886531#2 2 0.04598124 0.0792947#3 3 0.16835445 0.1744542 This is not exactly as wanted in the question, but sufficient for my purposes. See ?spread . Update with tidyr 1.0.0 : tidyr 1.0.0 have now introduced pivot_wider (and pivot_longer ) which allows for more control in this respect with the arguments names_sep and names_prefix . So now the call would be: mydf %>% pivot_wider(names_from = year, values_from = value, names_prefix = "year")# # A tibble: 3 x 3# id year2012 year2013# <int> <dbl> <dbl># 1 1 0.347 0.388# 2 2 0.565 0.924# 3 3 0.406 0.296 To get exactly what was originally wanted (prefixing "y" only) you can of course now get that directly by simply having names_prefix = "y" . The names_sep is used in case you gather over multiple columns as demonstrated below where I have added quarters to the data: # Add quarters to datamydf2 <- data.frame( id = rep(1:3, each = 8), year = rep(rep(c(2012, 2013), each = 4), 3), quarter = rep(c("Q1","Q2","Q3","Q4"), 3), value = runif(24))head(mydf2)# id year quarter value# 1 1 2012 Q1 0.8651470# 2 1 2012 Q2 0.3944423# 3 1 2012 Q3 0.4580580# 4 1 2012 Q4 0.2902604# 5 1 2013 Q1 0.4751588# 6 1 2013 Q2 0.6851755mydf2 %>% pivot_wider(names_from = c(year, quarter), values_from = value, names_sep = "_", names_prefix = "y")# # A tibble: 3 x 9# id y2012_Q1 y2012_Q2 y2012_Q3 y2012_Q4 y2013_Q1 y2013_Q2 y2013_Q3 y2013_Q4 # <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl># 1 1 0.865 0.394 0.458 0.290 0.475 0.685 0.213 0.920# 2 2 0.566 0.614 0.509 0.0515 0.974 0.916 0.681 0.509# 3 3 0.968 0.615 0.670 0.748 0.723 0.996 0.247 0.449
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31788195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3409615/']}
|
jdg_377059
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3067596
|
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:
A sizeable chunk of my first calculus course at university comprised of learning techniques to evaluate limits, such as this simple example, evaluating the limit: $$\lim_{x \to 7} \frac{x^2 -8x + 7}{x-7}.$$ A typical solution would be to identify that for $x \neq 7$ , $$\frac{x^2 -8x + 7}{x-7} = x-1,$$ so $$\lim_{x \to 7} \frac{x^2 -8x + 7}{x-7} = \lim_{x \to 7} x-1 = 6.$$ In my eyes, we have shown that if the limit exists, its value must be $6$ . We have not shown that the limit exists in the first place and is equal to $6$ , since we have presupposed the existence of the limit when writing $$\lim_{x \to 7} \frac{x^2 -8x + 7}{x-7} = \lim_{x \to 7} x-1,$$ since the existence of both objects on either side of an equality is a necessary condition for the equality to be true (right?). My main questions are: do such methods of evaluation serve as evidence that these limits in fact exist in the first place, or do they only tell us what the limit ought to be, and the only way we can be sure is to formally prove it using the $\epsilon$ - $\delta$ definition? Is this case similar to "finding" the derivatives of functions?
Now provide the response and nothing else.
|
There's no logical problem with this argument. The expressions $$ \frac{x^2 -8x + 7}{x-7} \text{ and } x-1$$ are equal when $x \ne 7$ , so the first expression has a limit at $7$ if and only if the second does. There is no need to assume the existence of the limit in advance. Whether or not you need the $\epsilon - \delta$ argument to find the the limit of $x-1$ depends on the level of rigor your instructor requires. (There are other situations where a correct argument does have the form the limit is such and such provided the limit exists usually followed by a separate proof that there is a limit.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3067596', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_377060
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40442568
|
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 figure out what I'm doing wrong here, but I keep getting lost... In python 2.7, I'm running following code: >>> import requests>>> req = requests.request('GET', 'https://www.zomato.com/praha/caf%C3%A9-a-restaurant-z%C3%A1ti%C5%A1%C3%AD-kunratice-praha-4/daily-menu')>>> req.content'<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n' If I open this one in browser, it responds properly. I was digging around and found similar one with urllib library ( 500 error with urllib.request.urlopen ), however I am not able to adapt it, even more I would like to use requests here. I might be hitting here some missing proxy setting, as suggested for example here ( Perl File::Fetch Failed HTTP response: 500 Internal Server Error ), but can someone explain me, what is the proper workaround with this one?
Now provide the response and nothing else.
|
One thing that is different with the browser request is the User-Agent; however you can alter it using requests like this: url = 'https://www.zomato.com/praha/caf%C3%A9-a-restaurant-z%C3%A1ti%C5%A1%C3%AD-kunratice-praha-4/daily-menu'headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}response = requests.get(url, headers=headers)print(response.status_code) #should be 200 Edit Some web applications will also check the Origin and/or the Referer headers (for example for AJAX requests); you can set these in a similar fashion to User-Agent . headers = { 'Origin': 'http://example.com', 'Referer': 'http://example.com/some_page'} Remember, you are setting these headers to basically bypass checks so please be a good netizen and don't abuse people's resources.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40442568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6905166/']}
|
jdg_377061
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
424746
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a linear map over the finite-field vector space $(\mathbb F_2)^n$ , i.e., an $\mathbb F_2$ -valued $n\times n$ matrix, not necessarily symmetric. I'm interested in the sum $$Z(A) = \sum_{X\in \mathbb F_2^n} (-1)^{X^T A X}\;,$$ where $$x\rightarrow (-1)^x$$ should be thought of as a function from $\mathbb F_2$ to $\mathbb Z$ (or $\mathbb R$ or $\mathbb C$ ). Is there a way to efficiently compute $Z(A)$ for large matrices $A$ ? Can one say anything interesting about for which $A$ we have $Z(A)=0$ ? For example, one can easily see that $Z(A)=0$ if $A=1\oplus B$ where $1$ is a $1\times 1$ matrix. The motivation behind this question comes from physics. $Z(A)$ is the partition function of a discrete path integral, $X$ is are the different configurations of degrees of freedom which are summed over, and $X^T A X$ is a quadratic action. Reposting this mathematics stackexchange question here since I didn't get any answers there.
Now provide the response and nothing else.
|
This is a multidimensional Gauss sum, and can be handled by the same methods used to handle Gauss sums. $Z(A)=0$ if and only if $X^T A X$ is nonzero for some $X \in \ker (A + A^T)$ , and, if $Z(A) \neq 0$ , then $$Z(A) = \pm 2^{ \frac{n + \dim ( ker (A + A^T))}{2}}$$ which implies your divisibility claim. To prove this, just note that $$Z(A)^2 = \sum_{X_1, X_2 \in \mathbb F_2^n} (-1)^{X_1^T A X_1 + X_2^T A X_2} = \sum_{X,Y\in \mathbb F_2^n} (-1)^{ (X+Y)^T A (X+Y) + X^T A X } $$ and the exponent satisfies $$(X+Y)^T A (X+Y) + X^T A X = X^T A X + X^T A Y + Y^T A X + Y^T A Y + X^T A X$$ $$ = X^T A Y + Y^T A X + Y^T A Y = X^T A Y + X^T A^T Y + Y^T A^T Y $$ so $$Z(A)^2 = \sum_{Y \in \mathbb F_2^n} (-1)^{Y^T A Y} \sum_{X\in \mathbb F_2^n} (-1)^{ X^T (A + A^T ) Y } $$ Now the inner sum $\sum_{X\in \mathbb F_2^n} (-1)^{ X^T (A + A^T ) Y } $ vanishes unless $(A+A^T) Y =0$ , i.e. $Y \in \ker (A+A^T)$ , and equals $2^n$ in that case. Restricted to $\ker (A +A^T)$ , $Y^T A Y$ is actually a linear form, so the outer sum vanishes unless it is identically zero on $\ker (A + A^T)$ and is $2^{ \dim (A+A^T)}$ otherwise, giving $$Z(A)^2 =2^{ n + \dim (\ker(A+A^T))}$$ unless $Y^T A Y$ is nonzero for some $Y \in \ker (A +A^T)$ and $$Z(A)^2= 0$$ if $Y^T A Y$ is nonzero for some $Y \in \ker (A +A^T)$ , and thus the claim above.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/424746', 'https://mathoverflow.net', 'https://mathoverflow.net/users/115363/']}
|
jdg_377062
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7245702
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've done a few searches and I'm unable to find a suitable answer. Basically I have an unordered list which can be of a varying length. I want to iterate through the list, do some other things and then come back and select the next item on the list. I can do this fine when I define the amount of times my loop should iterate as I know the amount of items in the list. However I don't want to define this for each test, I want to grab the number of items in the list and then pop that into a variable that I can use to exit the loop and do the next thing I want. The HTML is like so: <ul id="PageContent_cat"> <li class="sel"> <a target="_self" href="/searchlocation.aspx?c=S1">S1</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S2">S2</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S3">S3</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S4">S4</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S5">S5</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S6">S6</a> </li> <li> <a target="_self" href="/searchlocation.aspx?c=S7">S7</a> </li></ul> So I can see there are 7 items in the list. Apparently in watir I could have used something the following: arr= ie.select_list(:name,'lr').getAllContents.to_a But not with webdriver. I thought I could maybe use 'lis' but I just get a Hex result: $bob = browser.ul(:id => "PageContent_cat").lisputs $bob Thanks, Paul
Now provide the response and nothing else.
|
Depending on the information you're wanting to gather and what purpose you're going to put it to, here is the way that is typically done. Rather than getting a number to define your iterations and THEN iterating that number of times, you can have it stop naturally when it reaches the last element: MyList = browser.ul(:id => "PageContent_cat")#Scrape links from the UL for visitingMyList.links.each do |link| puts link puts link.text b.goto(link) #etcend#Save li items to an array for later processingMyArray = []MyList.lis.each do |li| puts li.text MyArray << li.text #etcend#Iterate through your array in the same method, to report/visit/etcMyArray.each do |item| puts "I collected something: #{item}" b.goto(item)end #
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7245702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919951/']}
|
jdg_377063
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58096084
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an image as an ndarray with a shape of (2000, 2000, 3) . In a next step a split the channels to do some work on them: image_r = (image_color[:,:,0])image_g = (image_color[:,:,1])image_b = (image_color[:,:,2]) When the work is done I need to merge the channels to one image. How do I do that? I tried to generate an empty image full_image = np.zeros((image.shape[0], image.shape[1]), 3) And to append the channels to it. But this didn't work out. I also tried to stack the values using the hstack. full_image = np.zeros((image.shape[0], image.shape[1]))full_image = np.hstack(full_image, image_r)full_image = np.hstack(full_image, image_g)full_image = np.hstack(full_image, image_b) But this didn't work out either. With the following error: full_image = np.hstack(full_image, image_r) File "<__array_function__ internals>", line 4, in hstackTypeError: _vhstack_dispatcher() takes 1 positional argument but 2 were given Do you have any ideas?
Now provide the response and nothing else.
|
The current helm version does not work with kubernetes version 1.16.0 You can downgrade kubernetes to version 1.15.3 minikube start --kubernetes-version 1.15.3helm init or use my solution to fix it at version 1.16.0 You have to create tiller Service Account and ClusterRoleBinding . You can simply do that by using those commands: kubectl --namespace kube-system create sa tillerkubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller And simply create tiller helm init --override spec.selector.matchLabels.'name'='tiller',spec.selector.matchLabels.'app'='helm' --output yaml | sed 's@apiVersion: extensions/v1beta1@apiVersion: apps/v1@' | kubectl apply -f -
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58096084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5152497/']}
|
jdg_377064
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
176983
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The common definition of Reedy category seems to be this one that a Reedy category is a small category $R$ with two wide subcategories $R_+$ and $R_-$ and an ordinal-valued degree function on its objects such that Every nonidentity morphism in $R_+$ raises degree, Every nonidentity morphism in $R_-$ lowers degree, and Every morphism $f$ in $R$ factors uniquely as a map in $R_-$ followed by a map in $R_+$. However, in a few places, such as the DHKS book Homotopy Limit Functors on Model Categories and Homotopical Categories or Barwick's note On Reedy Model Categories , there is a slightly different definition in which the factorizations are only required to be functorial , rather than unique. Unique factorizations are functorial, but the converse is not generally true. I think I can prove that a "Reedy category" with functorial factorizations is also a Reedy category with unique factorizations, but my proof is quite roundabout and involves (at least apparently) shrinking the subcategories $R_-$ and $R_+$. Are the definitions actually equivalent? Edit: Now I think this claim is wrong; see my answer below.
Now provide the response and nothing else.
|
Is this a counterexample? $R$ is the poset category $1\to 0\to 2$. Nonidentity maps in $R^+$: $0\to2$, $1\to 2$. Nonidentity maps in $R^-$: $1\to 0$. There are no other maps in $R$. The map $1\to 2$ admits two distinct "Reedy factorizations": $1\to1\to 2$ and $1\to 0\to 2$. (This is the only map with more than one possible choice.) It appears that $R$ has a functorial Reedy factorization $Fun([1],R)\to Fun([2],R)$, where the functorial factorization of $1\to 2$ is set to be $1\to 0\to 2$ (the other choice isn't functorial). Checking that this is well-defined involved looking at each of the $20$ possible commutative squares in $R$. I would not swear that I got it right.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/176983', 'https://mathoverflow.net', 'https://mathoverflow.net/users/49/']}
|
jdg_377065
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9820401
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TimeSpan time24 = new TimeSpan(24, 0, 0);TimeSpan time18 = new TimeSpan(18, 0, 0); // first get today's sleeping hoursList<Model.Sleep> sleeps = context.Sleeps.Where( o => (clientDateTime - o.ClientDateTimeStamp < time24) && o.ClientDateTimeStamp.TimeOfDay > time18 && clientDateTime.TimeOfDay < time18 && o.UserID == userid).ToList(); This Linq expression throws this exception: DbArithmeticExpression arguments must have a numeric common type. Please Help!
Now provide the response and nothing else.
|
Arithmetic with DateTime is not supported in Entity Framework 6 and earlier. You have to use DbFunctions *. So, for the first part of your statement, something like: var sleeps = context.Sleeps(o => DbFunctions.DiffHours(o.ClientDateTimeStamp, clientDateTime) < 24); Note that the DiffHours method accepts Nullable<DateTime> . Entity Framwork core (when used with Sql Server, maybe other db providers) supports the DateTime AddXxx functions (like AddHours ). They're translated into DATEADD in SQL. * EntityFunctions prior to Entity Framework version 6.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9820401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435158/']}
|
jdg_377066
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28458058
|
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 maven-shade-plugin , is there a way to exclude a dependency (which is not provided ) and all its transitive dependencies ? For example : <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>some-artifact</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency> ... other dependencies</dependencies> and 1) <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <artifactSet> <includes> <include>*:*</include> </includes> <excludes> <exclude>com.example:some-artifact</exclude> </excludes> </artifactSet> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins></build> or 2) <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <artifactSet> <includes> <include>*:*</include> </includes> </artifactSet> <filters> <filter> <artifact>com.example:some-artifact</artifact> <excludes> <exclude>**</exclude> </excludes> </filter> </filters> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins></build> Those don't work. All the transitive dependencies of com.example:some-artifact are added to the final jar. Note that I don't want to set the scope of com.example:some-artifact to provided .
Now provide the response and nothing else.
|
Run "shade" from within a profile, and mark your dependency as provided only in that profile. For example: <profiles> <profile> <id>shadeProfile</id> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>some-artifact</artifactId> <version>1.23</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <shadedClassifierName>shaded</shadedClassifierName> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile></profiles> When you run mvn -PshadeProfile package it will treat your dependency as provided (and thus omit its dependencies), and it will use the classifier "shaded" so you can use this as a dependency in other modules.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28458058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/843699/']}
|
jdg_377067
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12546
|
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:
In org-mode , I am trying to define a function, a variable, and then assigning to another variable the result of the function call on the first variable. However, then it seems that I cannot use this new variable in subsequent functions calls. Inlining the function calls does work, but affecting the value to a variable first would allow for faster debug in case something goes wrong in the first function call, and to avoid duplicating potentially expensive computations. MWE: (use (require 'ob-emacs-lisp) if needed) #+name: square#+begin_src emacs-lisp :var x=3 (message (format "%s" (* x x)))#+end_src#+RESULTS: square: 9#+name: value: 45#+name: squaredvalue#+call: square(x=value)#+RESULTS: squaredvalue: 2025Now I try to reuse this value: #+begin_src emacs-lisp :var res=squaredvalue (message res)#+end_src#+RESULTS:: nilInlined calls do work: #+begin_src emacs-lisp :var res=square(value) (message res)#+end_src#+RESULTS:: 2025 Expanding the second code block shows: (let ((res (quote "nil"))) (message res)) What am I missing? (This has been tested on emacs 24.3.1, 24.4 and 24.5, using org 8.2.10)
Now provide the response and nothing else.
|
Explicitly add new #+name: above the #+results: block. Note: Updated your code from (message res) to (message (format "%s" res)) to prevent a Wrong type argument: stringp, 2025 from causing additional confusion. #+name: square#+begin_src emacs-lisp :var x=3 (message (format "%s" (* x x)))#+end_src#+RESULTS: square: 9#+name: value: 45#+name: squaredvalue#+call: square(x=value)#+name: squaredvalue-results#+RESULTS: squaredvalue: 2025#+begin_src emacs-lisp :var res=squaredvalue (message (format "%s" res))#+end_src#+RESULTS:: nil#+begin_src emacs-lisp :var res=squaredvalue-results (message (format "%s" res)) #+end_src#+RESULTS:: 2025 Tested using GNU Emacs 24.4.1 (x86_64-unknown-cygwin, GTK+ Version 3.10.9) Org-Mode Version: 8.2.10
|
{}
|
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/12546', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/184/']}
|
jdg_377068
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
421547
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Imagine that I will make an async call in .NET, i.e. HttpWebRequest.BeginGetResponse, and the HttpWebRequest object isn't referenced at a broader scope. Will the Garbage Collector destroy it and cause problems? Example code: using System;using System.Net;public class AsyncHttpWebRequest{ void Main() { var Request = HttpWebRequest.Create("http://www.contoso.com"); var result = Request.BeginGetResponse(GetResponseCallback, null); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. }} Alternate version (with the request being passed as an AsyncState): using System;using System.Net;public class AsyncHttpWebRequest{ void Main() { var Request = HttpWebRequest.Create("http://www.contoso.com"); var result = Request.BeginGetResponse(GetResponseCallback, Request); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. }}
Now provide the response and nothing else.
|
An object is considered alive and non-eligible for garbage collection if any live thread contains a reference to it, or if it's referenced statically (directly or indirectly in both cases). In both examples the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won't be garbage collected until it completes.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/421547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48465/']}
|
jdg_377069
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
515668
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When a man is doing ice skating and rotating on his toe, with his arms widespread, his angular velocity is less, in comparison to the angular velocity when he is rotating with his arms closed inside. Now suppose man is turning his hands slowly inwards, so his angular velocity will start to increase, now there is no external torque on the man but his angular velocity is increasing and increasing angular velocity will have an associated angular acceleration, so we can conclude that the man has angular acceleration without any external torque, which is an apparent contradiction of the terms, so how do we reconcile the case with the concept? Can we explain this case without using the concept of "Angular Momentum Conservation"? because that encapsulates a lot of details, without giving the complete clarity.
Now provide the response and nothing else.
|
The definition of torque is not $\tau=Id\omega/dt$ . We can't even define things like $I$ and $\omega$ for rotation that isn't rigid. The definition of torque is $\tau=dL/dt$ . So yes, it is possible to have an angular acceleration without an external torque. Your example shows correctly that this can happen.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/515668', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/185612/']}
|
jdg_377070
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13011204
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've searched for a half-hour, and still cannot figure it out. In SIP: Modularizing Language Features there are a number of features which will require explicit "enabling" in Scala 2.10 ( import language.feature ).Amongst them there is postfixOps , to which I just cannot find a reference anywhere. What exactly does this feature allow?
Now provide the response and nothing else.
|
It allows you to use operator syntax in postfix position. For example List(1,2,3) tail rather than List(1,2,3).tail In this harmless example it is not a problem, but it can lead to ambiguities. This will not compile: val appender:List[Int] => List[Int] = List(1,2,3) ::: //add ; hereList(3,4,5).foreach {println} And the error message is not very helpful: value ::: is not a member of Unit It tries to call the ::: method on the result of the foreach call, which is of type Unit . This is likely not what the programmer intended. To get the correct result, you need to insert a semicolon after the first line.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13011204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/978664/']}
|
jdg_377071
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8467141
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I know how to have the emboss effect as the text " Reminders " as shown on the picture? It looks like the text are embedded? Thanks
Now provide the response and nothing else.
|
UPDATE FOR iOS 7.0 In iOS 7.0, Apple added a new attribute, NSTextEffectAttributeName , for attributed strings. If your deployment target is iOS 7.0 or later, you can set this attribute to NSTextEffectLetterpressStyle to draw an attributed string in an embossed style. ORIGINAL I can't say for certain how Apple draws the embossed text. It looks to me like they fill the string glyphs with a reddish color, then apply a shadow around the interior edges of the glyphs, and also apply a very faint shadow along the top outside edges of the glyphs. I tried it out and here's what it looks like: On top is my rendering. Below that is a simple UILabel with shadow as Chris suggested in his answer. I put a screen shot of the Reminders app in the background. Here's my code. First, you need a function that creates an image mask of your string. You'll use the mask to draw the string itself, and then to draw a shadow that only appears around the inside edges of the string. This image just has an alpha channel and no RGB channels. - (UIImage *)maskWithString:(NSString *)string font:(UIFont *)font size:(CGSize)size{ CGRect rect = { CGPointZero, size }; CGFloat scale = [UIScreen mainScreen].scale; CGColorSpaceRef grayscale = CGColorSpaceCreateDeviceGray(); CGContextRef gc = CGBitmapContextCreate(NULL, size.width * scale, size.height * scale, 8, size.width * scale, grayscale, kCGImageAlphaOnly); CGContextScaleCTM(gc, scale, scale); CGColorSpaceRelease(grayscale); UIGraphicsPushContext(gc); { [[UIColor whiteColor] setFill]; [string drawInRect:rect withFont:font]; } UIGraphicsPopContext(); CGImageRef cgImage = CGBitmapContextCreateImage(gc); CGContextRelease(gc); UIImage *image = [UIImage imageWithCGImage:cgImage scale:scale orientation:UIImageOrientationDownMirrored]; CGImageRelease(cgImage); return image;} Second, you need a function that inverts that mask. You'll use this to make CoreGraphics draw a shadow around the inside edges of the string. This needs to be a full RGBA image. (iOS doesn't seem to support grayscale+alpha images.) - (UIImage *)invertedMaskWithMask:(UIImage *)mask{ CGRect rect = { CGPointZero, mask.size }; UIGraphicsBeginImageContextWithOptions(rect.size, NO, mask.scale); { [[UIColor blackColor] setFill]; UIRectFill(rect); CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage); CGContextClearRect(UIGraphicsGetCurrentContext(), rect); } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image;} You can use those in a function that draws the string in red and applies a shadow to its interior edges. -(UIImage *)imageWithInteriorShadowAndString:(NSString *)string font:(UIFont *)font textColor:(UIColor *)textColor size:(CGSize)size{ CGRect rect = { CGPointZero, size }; UIImage *mask = [self maskWithString:string font:font size:rect.size]; UIImage *invertedMask = [self invertedMaskWithMask:mask]; UIImage *image; UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale); { CGContextRef gc = UIGraphicsGetCurrentContext(); // Clip to the mask that only allows drawing inside the string's image. CGContextClipToMask(gc, rect, mask.CGImage); // We apply the mask twice because we're going to draw through it twice. // Only applying it once would make the edges too sharp. CGContextClipToMask(gc, rect, mask.CGImage); mask = nil; // done with mask; let ARC free it // Draw the red text. [textColor setFill]; CGContextFillRect(gc, rect); // Draw the interior shadow. CGContextSetShadowWithColor(gc, CGSizeZero, 1.6, [UIColor colorWithWhite:.3 alpha:1].CGColor); [invertedMask drawAtPoint:CGPointZero]; invertedMask = nil; // done with invertedMask; let ARC free it image = UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext(); return image;} Next you need a function that takes an image and returns a copy with a faint upward shadow. - (UIImage *)imageWithUpwardShadowAndImage:(UIImage *)image{ UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); { CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(), CGSizeMake(0, -1), 1, [UIColor colorWithWhite:0 alpha:.15].CGColor); [image drawAtPoint:CGPointZero]; } UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultImage;} Finally, you can combine those functions to create an embossed image of your string. I put my final image into a UIImageView for easy testing. - (void)viewDidLoad{ [super viewDidLoad]; CGRect rect = self.imageView.bounds; NSString *string = @"Reminders"; UIFont *font = [UIFont systemFontOfSize:33]; UIImage *interiorShadowImage = [self imageWithInteriorShadowAndString:string font:font textColor:[UIColor colorWithHue:0 saturation:.9 brightness:.7 alpha:1] size:rect.size]; UIImage *finalImage = [self imageWithUpwardShadowAndImage:interiorShadowImage]; self.imageView.image = finalImage;}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8467141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/759076/']}
|
jdg_377072
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14322408
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have two NSManagedObjectContext objects. A parent context and a child context. I have a few NSManagedObjectModels and I'm able to create/edit/destroy 4 out of 5 of them. No problem. I can insert objects on the child context then save it and voila it pops up on the root context. However it's the 1 out of 5 that's giving me trouble. I can insert it with no problem, it'll show up on root context. When I attempt to change the attributes of the object though it does not get updated on the root context. Here's the printout from the console (notice the value attribute does not get updated). ====root_context:("<Token: 0x1006f6a30> ( entity: Token; id: 0x107115130 <x-coredata:///Token/t2AC116F0-E89B-485D-B0A9-C3D2A58B84847> ; data: { association = 0; equation = \"0x107114b10 <x-coredata:///Equation/t2AC116F0-E89B-485D-B0A9-C3D2A58B84846>\"; isValid = 0; precedence = 0; type = 0; value = nil;})") ====child_context:("<Token: 0x1071150a0> ( entity: Token; id: 0x107115130 <x-coredata:///Token/t2AC116F0-E89B-485D-B0A9-C3D2A58B84847> ; data: { association = 0; equation = \"0x107114b10 <x-coredata:///Equation/t2AC116F0-E89B-485D-B0A9-C3D2A58B84846>\"; isValid = 0; precedence = 0; type = 0; value = 4;})" ) From my newbie eyes these seem to be the same object. Even when I print out the objectID for both of these objects (even though they're in different contexts) their objectID matches. Some more background To merge I'm calling [_childContext save:&error] which pushes the changes to the parent context. This code is being called every time it detects a change in the child context. And then once I observe a NSManagedObjectContextDidSaveNotification in the child context I call [_rootContext mergeChangesFromContextDidSaveNotification:notification] Additional Note I don't know if this is another clue, but when I save the data to an XML file it omits the value attribute. Here's the output: <object type="TOKEN" id="z104"> <attribute name="type" type="int16">0</attribute> <attribute name="precedence" type="int16">0</attribute> <attribute name="isvalid" type="bool">0</attribute> <attribute name="association" type="int16">0</attribute> <relationship name="equation" type="1/1" destination="EQUATION" idrefs="z106"></relationship></object> Thanks everyone! p.s. I checked my .xcdatamodeld file and everything seems to be in order. I'm storing value as a String and the rest of them as Integer 16 and Booleans.
Now provide the response and nothing else.
|
I have finally managed to perform automatically the copy from Project B without having to modify it. IIya was not so far from the solution, but the fact is that I cannot generate statically as the list of files to generate from Project A with MyCustomTask is dynamic. After digging more into Microsoft.Common.targets , I have found that ProjectB will get the list of output from Project A by calling the target GetCopyToOutputDirectoryItems . This target is dependent from AssignTargetPaths which itself is dependent on the target list property AssignTargetPathsDependsOn . So in order to generate dynamically content and to get this content being copied automatically through standard project dependency, we need to hook Project A at two different places: In AssignTargetPathsDependsOn as it is called indirectly by Project B on Project A through GetCopyToOutputDirectoryItems. And also it is indirectly called by Project A when PrepareResource is called. Here, we are just outputing the list of files that will be generated (by Project A ) or consumed by Project B . AssignTargetPathsDependsOn will call a custom task MyCustomTaskList which is only responsible to output the list of files (but not to generate them), this list of files will create dynamic "Content" with CopyOutputDirectory . In BuildDependsOn in order to actually generate the content in Project A . This will call MyCustomTask that will generate the content. All of this was setup like this in ProjectA: <!-- In Project A --><!-- Task to generate the files --><UsingTask TaskName="MyCustomTask" AssemblyFile="$(PathToMyCustomTaskAssembly)"/><!-- Task to output the list of generated of files - It doesn't generate the file --><UsingTask TaskName="MyCustomTaskList" AssemblyFile="$(PathToMyCustomTaskAssembly)"/><!-- 1st PART : When Project A is built, It will generate effectively the files --><PropertyGroup> <BuildDependsOn> MyCustomTaskTarget; $(BuildDependsOn); </BuildDependsOn></PropertyGroup><Target Name="MyCustomTaskTarget"> <!-- Call MyCustomTask generate the files files that will be generated by MyCustomTask --> <MyCustomTask ProjectDirectory="$(ProjectDir)" IntermediateDirectory="$(IntermediateOutputPath)" Files="@(MyCustomFiles)" RootNamespace="$(RootNamespace)" > </MyCustomTask></Target><!-- 2nd PART : When Project B is built, It will call GetCopyToOutputDirectoryItems on ProjectA so we need to generate this list when it is called --><!-- For this we need to override AssignTargetPathsDependsOn in order to generate the list of files --><!-- as GetCopyToOutputDirectoryItems ultimately depends on AssignTargetPathsDependsOn --><!-- Content need to be generated before AssignTargets, because AssignTargets will prepare all files to be copied later by GetCopyToOutputDirectoryItems --><!-- This part is also called from ProjectA when target 'PrepareResources' is called --><PropertyGroup> <AssignTargetPathsDependsOn> $(AssignTargetPathsDependsOn); MyCustomTaskListTarget; </AssignTargetPathsDependsOn></PropertyGroup><Target Name="MyCustomTaskListTarget"> <!-- Call MyCustomTaskList generating the list of files that will be generated by MyCustomTask --> <MyCustomTaskList ProjectDirectory="$(ProjectDir)" IntermediateDirectory="$(IntermediateOutputPath)" Files="@(MyCustomFiles)" RootNamespace="$(RootNamespace)" > <Output TaskParameter="ContentFiles" ItemName="MyCustomContent"/> </MyCustomTaskList> <ItemGroup> <!--Generate the lsit of content generated by MyCustomTask --> <Content Include="@(MyCustomContent)" KeepMetadata="Link;CopyToOutputDirectory"/> </ItemGroup></Target> This method is working with anykind of C# projects that is using Common.Targets (so It is working with pure Desktop, WinRT XAML App or Windows Phone 8 projects).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14322408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021018/']}
|
jdg_377073
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
90009
|
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:
Can someone explain how torrent poisoning attacks work? I am looking for some tutorials on how to do it. What are the countermeasures that someone can use to defend themselves against it?
Now provide the response and nothing else.
|
Torrent poisoning means that peers join the swarm which don't contribute to it and only use up resources. One method is an evil peer which claims to be seeding the whole file. However, instead of returning valid data, it returns garbage. The clients won't notice this until they received the whole chunk and verified the checksum, which means that they wasted time and bandwidth. Another variant is to accept all requests, but then not send any data at all until the connection times out. At the same time, the bogus peers request chunks from legitimate seeds even though they don't need them. This takes up bandwidth and connection slots which would otherwise be available to legitimate peers. By flooding the swarm with a large number of such peers it can become impossible for the leachers to find any real seeds to obtain legit chunks of the file. This can not be prevented tracker-sided, because each of these interactions is directly between peers. A mechanism for reporting such abusive peers to the tracker or a 3rd party would be counter-productive because it could be abused by the malicious peers to accuse legit peers and knock them off the network. The only possible countermeasure is to have the bit torrent client identify the IP addresses of malicious peers and block any connections with them.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/90009', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/69876/']}
|
jdg_377074
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
465882
|
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 some applications (some native, some .NET) which use manifest files so that they can be deployed in complete isolation , without requiring any global COM registration. For example, the dependency on the dbgrid32.ocx com server is declared as follows in the myapp.exe.manifest file which sits in the same folder as myapp.exe: <?xml version="1.0" encoding="utf-8" standalone="yes"?><assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity type="win32" name="myapp.exe" version="1.2.3.4" /> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" /> </dependentAssembly> </dependency></assembly> The dbgrid32.ocx is deployed to the same folder, along with it's own dbgrid32.ocx.manifest file: <?xml version="1.0" encoding="utf-8" standalone="yes"?><assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity type="win32" name="dbgrid32.ocx" version="5.1.81.4" /> <file name="dbgrid32.ocx"> <typelib tlbid="{00028C01-0000-0000-0000-000000000046}" version="1.0" helpdir=""/> <comClass progid="MSDBGrid.DBGrid" clsid="{00028C00-0000-0000-0000-000000000046}" description="DBGrid Control" /> </file></assembly> This all works fine but maintaining these manifest files manually is a bit of a pain. Is there a way to generate these files automatically? Ideally I would just like to declare the application's dependency on a list of COM servers (both native and .NET) and then let the rest be generated automatically. Is it possible?
Now provide the response and nothing else.
|
It looks like the perfect solution does not yet exist. To summarize some research: Make My Manifest ( link ) This tool scans a VB6 project to look for COM dependencies, but it also supports manual declaration of late-bound COM dependencies (i.e. those used via CreateObject). Interestingly enough, this tool puts all information about the dependencies inside the application manifest. The application exe and its dependencies are described as a single assembly consisting of multiple files. I hadn't realized before that this was possible. Looks like a very good tool but as of version 0.6.6 it has the following limitations: only for VB6 applications, startsfrom VB6 project file. Shame, becausea lot of what it does really has nothing to dowith VB6. wizard style application, notsuitable to integrate in a buildprocess. This is not a huge problem if yourdependencies don't change a lot. freeware without source, risky to rely on it because it could become abandonware at any moment. I did not test whether it supports .NET com libraries. regsvr42 ( codeproject link ) This command line tool generates manifest files for native COM libraries. It invokes DllRegisterServer and then spies on the self-registration as it adds information into the registry. It can also generate a client manifest for applications. This utility does not support .NET COM libraries, since these don't expose a DllRegisterServer routine. The utility is written in C++. The source code is available. mt.exe Part of the windows SDK (can be downloaded from MSDN ), which you already have if you have visual studio installed. It is documented here .You can generate manifest files for native COM libraries with it like this: mt.exe -tlb:mycomlib.ocx -dll:mycomlib.ocx -out:mycomlib.ocx.manifest You can generate manifest files for .NET COM libraries with it like this: mt.exe -managedassemblyname:netlib.dll -nodependency -out:netlib.dll.manifest However, there are some problems with this tool: The first snippet will not generateprogid attributes, breaking clientswhich use CreateObject with progids. The second snippet will generate <runtime> and <mvid> elementswhich need to be stripped out beforethe manifests actually work. Generation of client manifests forapplications is not supported. Maybe future SDK releases will improve this tool, I tested the one in the Windows SDK 6.0a (vista).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/465882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52626/']}
|
jdg_377075
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41263896
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using C89 on an embedded platform. I attempted to print out a size_t , but it did not work: #include <stdio.h>int main(void) { size_t n = 123; printf("%zu\n",n); return 0;} Instead of 123 , I got zu . Other specifiers work correctly. If size_t exists shouldn't zu also be available in printf ? Is this something I should contact my library vendor about, or is a library implementation allowed to exclude it?
Now provide the response and nothing else.
|
If size_t exists shouldn't zu also be available in printf? size_t existed at least since C89 but the respective format specifier %zu (specifically the length modifier z ) was added to the standard only since C99. So, if you can't use C99 (or C11) and had to print size_t in C89, you just have to fallback to other existing types, such as: printf("%lu\n", (unsigned long)n);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41263896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908939/']}
|
jdg_377076
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
195384
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am a physicist with some background in differential geometry and I apologize for any possible unprecise terminology. Consider the Lie group $SU(2)$ and its tangent space $su(2)$ forming a tangent bundle. It is well known that SU(2) is noncommutative, thus $ a \circ b \circa^{-1} \circ b^{-1} \neq 0$ in general ($a,b \in SU(2)$). This operation may be associated with surrounding a surface in the tangent space, resulting in a nonzero curvature. In particluar, there should be a curvature 2-form that reflects the above nonlinearity. How is this expressed precisely? Can anyone point me to such a specific treatment of SU(2) in differential forms language? Hints to the literature are appreciated, but please no general textbooks about lie groups or DG. I try to specify. There should be a common metric in SU(2), such as the angle in the Euler axis- angle representation when projecting to SO(3). Then, a metric is not even necessary, one just needs a connection. There should be a canonical connection.
Now provide the response and nothing else.
|
$SU(2)$ is a compact Lie group, so it has a bi-invariant Riemannian metric, whose Levi-Civita connection and Riemann curvature can be expressed using the Lie bracket on its Lie algebra $su(2)$. See, for example, Lie groups with bi-invariant Riemannian metric The book Comparison Theorems in Riemannian Geometry by Cheeger and Ebin also explains all of this. The whole story is particularly elegant using the dual description with differential forms and the Maurer-Cartan equations, but I don't know a reference for this. As it happens, $SU(2)$ is the 3-dimensional sphere and its bi-invariant metric is, up to a constant scale factor, the standard one. All of this can be worked out nicely using quaternions, as explained in Naive Lie Theory by Stillwell. Actually, the differential form version is not so hard to explain. First, the Riemannian geometry part: If you have an orthonormal frame of tangent vector fields and let $\omega^1, \dots, \omega^n$ be the dual $1$-forms, then there is a unique set of $1$-forms, $\omega^i_j = -\omega^j_i$, satisfying$$d\omega^i + \omega^i_j\wedge\omega^j = 0.$$These $1$-forms represent the Levi-Civita connection. The Riemannian curvature tensor $R$ is then given by $2$-forms $\Omega^i_j = -\Omega^j_i$, where$$\frac{1}{2}R^i_{jkl}\omega^k\wedge\omega^l = \Omega^i_j = d\omega^i_j + \omega^i_k\wedge\omega^k_j.$$ As for $SU(2)$, note that if $A$ denotes the map from an element in the group to the the element written as matrix, then the differential form $\Theta = A^{-1}\,dA$ is a trace-free skew-hermitian matrix of $1$-forms. In other words,$$\Theta = \begin{bmatrix} i\omega^1 & \omega^2 - i\omega^3\\\omega^2 + i\omega^2 & -i\omega^1 \end{bmatrix}$$ It is easy to verify that $\Theta$ is invariant under left translations, and the Riemannian metric where $\omega^1, \omega^2, \omega^3$ are orthonormal is bi-invariant. $\Theta$ is called the Maurer-Cartan form and satisfies the Maurer-Cartan equation:$$d\Theta = d(A^{-1}\,dA) = -A^{-1}\,dA\wedge A^{-1}\,dA = -\Theta \wedge\Theta.$$Using this and the formula for $\Theta$ above, you can figure out what the connection $1$-forms $\omega^i_j$ associated with $\omega^1, \omega^2, \omega^3$ are and compute the curvature. You can use the definition of the exterior derivative of a $1$-form $\theta$$$\langle d\theta, X\otimes Y\rangle = X\langle\theta,Y\rangle - Y\langle\theta,X\rangle - \langle\theta,[X,Y]\rangle$$with $\theta = \omega^1, \omega^2, \omega^3$ and vector fields $X$ and $Y$ equal to two of the left invariant vector fields $e_1, e_2, e_3$, which are dual to $\omega^1, \omega^2, \omega^3$, to figure out how to express the Riemann curvature in terms of the Lie bracket. Or you could represent each element of $SU(2)$ by a unit imaginary quaternion $u$. Then you would write $\Theta = \bar{u}\,du$, which is an imaginary quaternion-valued $1$-form and therefore of the form $\Theta = i\omega^1 + j\omega^2 + k\omega^3$. The rest is similar to the calculations described above.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/195384', 'https://mathoverflow.net', 'https://mathoverflow.net/users/31722/']}
|
jdg_377077
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5002555
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've tagged a commit with a lightweight tag, and pushed that tag to a remote repo, shared with other developers. I have now realised I should have annotated it so that it appears in git describe . Is there a way to convert it/re-tag the commit without breaking things?
Now provide the response and nothing else.
|
A lightweight tag is just a 'ref' that points at that commit. You can force-create a new annotated tag on top of the old tag: git tag -a -f <tagname> <tagname> As of Git v1.8.2, you need to use --force to replace any tags on a remote with git push , even if you are replacing a lightweight tag with something that is effectively a fast-forward or a true tag object pointing at the same commit as the existing tag reference. git push --force origin <tagname>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5002555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100172/']}
|
jdg_377078
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45485
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I observe a source that is actually two sources (source A and source B) where each cannot be individually resolved. Source A is a variable source and source B is a constant source. I want to measure the magnitude of source A by "subtracting" the known constant magnitude of source B from the total measured magnitude. Can this be done through simple subtraction? I know with flux the subtraction is straightforward, but magnitude is logarithmic so I am unsure how to do this.
Now provide the response and nothing else.
|
The magnitudes don't sum and subtract that way: consider two 0.00 magnitude stars closely together. Is their combined magnitude 0.00? Actually, it is -0.75. This paper might help you with the derivation of the formula for addition of magnitudes, but you are interested in subtraction. You just need to rearrange the formula in the paper to $$m_a=-2.5\log(10^{-0.4m_{TOT}}-10^{-0.4m_b})$$ If you want to discover other calculations regarding magnitude, search for Pogson's law.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/45485', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/42637/']}
|
jdg_377079
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19161872
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
At the moment I'm playing with the LSM303DLHC accelerometer/magnetometer/thermometer. This is its datasheet: http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/DM00027543.pdf Everything is working quite well, but I don't know how to interpret the output values. The datasheet (page 9) says something like "1 mg/LSB" (no, it's not milligramm :D) about the linear acceleration sensitivity in my configuration. What the hell should that mean? Same with temperature sensor output change (8 LSB/°C) and magnetic gain setting (1100 LSB/gauss), only the other way around. For example, what to do with this accelerometer output: 16384? That is my measured gravitational acceleration.
Now provide the response and nothing else.
|
Now I got the trick. There are several things on this MEMS you have to know, but which are not mentioned in the datasheet: The accelerometer's output register is just 12 bits and not 16 bits, so you need to right-shift the value by 4 and multiply it with 0,001 G. Furthermore it's little-endian. The magnetometer's output register is 16 bits, but big-endian. Furthermore the vector order is (X|Z|Y) not (X|Y|Z). To calculate the correct value you need to devide X and Y by 980 gauss⁻¹, while it's 1100 gauss⁻¹ for Z. The temperature sensor works, but it's not calibrated. So you can use it to measure temperature change, but no absolute temperatures. It's also just 12 bits, but big-endian and you have to devide the output by 8 C⁻¹. With that Information it's possible to use the LSM303DLHC. But who the hell invented this? "Let's build a new accelerometer, magnetometer and thermometer in one package and screw the user up by mixing word length and endianness up without mentioning it in the datasheet."
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19161872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1628596/']}
|
jdg_377080
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7807588
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please note : I'm not trying to restart the argument whether Mercurial or Git is better, I just have a technical question that I, as a Mercurial user, don't understand. I'm also not sure whether SO is the right place to ask such a question, but it is programming related. There have been many discussions about how the two version control systems Git and Mercurial differ from each other from a user's point of view (e.g. What is the Difference Between Mercurial and Git? and http://felipec.wordpress.com/2011/01/16/mercurial-vs-git-its-all-in-the-branches/ ), and the major difference is the handling of branches. I have read through many of these discussions, but I keep asking myself this question: Why does Git not store the branch name as part of the commit? I don't really see a good reason for not doing that; it means that data can't just simply vanish because there is no reference (tag, branch, whatever) poiting to it. I see storing the branch in the commit as a big plus for Mercurial, because that makes it more difficult to lose data. The main point of the Git crowd in favor of Git's branching model, that you can simply delete branches, does not prevent Git from storing the name of the branch as part of each commit: If the commits of a branch are deleted, so are the references to that branch. It will also not interfere with the "cheap branching" argument: branches will not be more expensive to manage. And I don't think that the additional storage needed should be of concern: it's just a couple of bytes per commit.
Now provide the response and nothing else.
|
One of the definitive source about branches for Git and Mercurial is the SO question: " Git and Mercurial - Compare and Contrast " In Git references (branches, remote-tracking branches and tags) reside outside DAG of commits. (That allows to manage different namespaces regarding branches, for local and remote branches) You have a similar notion with Mercurial with bookmark branches (which can be pushed/pulled). Note that in Git, the data won't "vanish" because there is no reference: you still have the reflog to retrieve those unreferenced commits. Why does Git not store the branch name as part of the commit? I don't really see a good reason for not doing that The idea is to separate what has changed (the commits) from why m ie from the context of the change (the name of the branch). Since you can fast-forward merge a branch, commits from one branch can be part of another at any time. That is why Jakub Narębski questioned the design of Mercurial "named branches" (with branch names embedded in changeset metadata), especially with a global namespace, not very suited for a distributed version control system. You create a branch to isolate a development effort (see " When should you branch? "), but with a DVCS, that development effort (the set of commits) should be published under any branch name. What local context (branch name) you have defined might not be valid once published to another Git repo.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7807588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85615/']}
|
jdg_377081
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50982505
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running the following code (C#7.1 Console App), and I can't really understand why the difference in behavior. If I await a regular async method call, or a Task.Run - it works as expected (i.e. the app doesn't return immediately). But if I use Task.Factory.StartNew - it will return immediately without the code actually running. Strangely enough - if I use StartNew but inside the method remove the await, it will not return immediately... Problem: This returns immediately: static async Task Main(string[] args){ await Task.Factory.StartNew(DisplayCurrentInfo);}static async Task DisplayCurrentInfo(){ await WaitAndApologize(); Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}"); Thread.Sleep(3000);} i.e. - I won't get to see anything printed out to the console, and the console will already be shut down. No problem: this doesn’t return immediately : static async Task Main(string[] args){ await DisplayCurrentInfo(); // or await Task.Run(DisplayCurrentInfo);}static async Task DisplayCurrentInfo(){ await WaitAndApologize(); Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}"); Thread.Sleep(3000);} Strange: this also doesn't return immediately: static async Task Main(string[] args){ await Task.Factory.StartNew(DisplayCurrentInfo); }static async Task DisplayCurrentInfo(){ WaitAndApologize(); Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}"); Thread.Sleep(3000);} WaitAndApologize: static async Task WaitAndApologize(){ // Task.Delay is a placeholder for actual work. await Task.Delay(2000); // Task.Delay delays the following line by two seconds. Console.WriteLine("\nSorry for the delay. . . .\n");}
Now provide the response and nothing else.
|
If you use Task.Factory.StartNew(MethodThatReturnsTask) you get back a Task<Task<T>> or Task<Task> depending on whether the method is returning a generic task or not. The end result is that you have 2 tasks: Task.Factory.StartNew spawns a task that calls MethodThatReturnsTask , let's call this task "Task A" MethodThatReturnsTask in your case returns a Task , let's call this "Task B", this means that an overload of StartNew that handles this is used and the end result is that you get back a Task A that wraps Task B. To "correctly" await these tasks needs 2 awaits, not 1. Your single await simply awaits Task A, which means that when it returns, Task B is still executing pending completion. To naively answer your question, use 2 awaits: await await Task.Factory.StartNew(DisplayCurrentInfo); However, it is questionable why you need to spawn a task just to kick off another async method. Instead you're much better off using the second syntax, where you simply await the method: await DisplayCurrentInfo(); Opinion follows : In general, once you've started writing async code, using Task.Factory.StartNew or any of its sibling methods should be reserved for when you need to spawn a thread (or something similar) to call something that isn't async in parallel with something else. If you're not requiring this particular pattern, it's best to not use it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50982505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6296435/']}
|
jdg_377082
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31917988
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying for days to get this working. I'm trying to connect to my server over https with a self signed certificate. I don't think there is any pages or examples that I haven't read by now. What I have done: Created bks keystore by following this tutorial: http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html It uses openssl s_client -connect domain.com:443 to get the certificate from the server. Then creates a bks keystore using bouncy castle. Reading created keystore from raw folder adding it to sslfactory and and then to OkHttpClient. Like this: public ApiService() { mClient = new OkHttpClient(); mClient.setConnectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS); mClient.setReadTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS); mClient.setCache(getCache()); mClient.setCertificatePinner(getPinnedCerts()); mClient.setSslSocketFactory(getSSL());}protected SSLSocketFactory getSSL() { try { KeyStore trusted = KeyStore.getInstance("BKS"); InputStream in = Beadict.getAppContext().getResources().openRawResource(R.raw.mytruststore); trusted.load(in, "pwd".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trusted); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch(Exception e) { e.printStackTrace(); } return null;}public CertificatePinner getPinnedCerts() { return new CertificatePinner.Builder() .add("domain.com", "sha1/theSha=") .build();} This for some reason this always generates a SSLPeerUnverifiedException with or without the keystore. And with or without the CertificatePinner . javax.net.ssl.SSLPeerUnverifiedException: Hostname domain.com not verified: 0 W/System.err﹕ certificate: sha1/theSha= W/System.err﹕ DN: 1.2.840.113549.1.9.1=#1610696e666f40626561646963742e636f6d,CN=http://domain.com,OU=development,O=domain,L=Valencia,ST=Valencia,C=ES W/System.err﹕ subjectAltNames: [] W/System.err﹕ at com.squareup.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:124) W/System.err﹕ at com.squareup.okhttp.Connection.connect(Connection.java:143) W/System.err﹕ at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:185) W/System.err﹕ at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128) W/System.err﹕ at com.squareup.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341) W/System.err﹕ at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330) W/System.err﹕ at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248) W/System.err﹕ at com.squareup.okhttp.Call.getResponse(Call.java:273) W/System.err﹕ at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:230) W/System.err﹕ at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:201) W/System.err﹕ at com.squareup.okhttp.Call.execute(Call.java:81) ... What am I doing wrong?
Now provide the response and nothing else.
|
I finally got this working with a mix of multiple answers. First, the certificates was made wrongly, not sure how. But by creating them using the script in this answer made them work. What was needed was a server certificate and a key. Then the client needed another certificate. To use the certificate in android I converted the .pem file to a .crt file like this: openssl x509 -outform der -in client.pem -out client.crt In android I added the certificate to my OkHttp client like the following: public ApiService() { mClient = new OkHttpClient(); mClient.setConnectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS); mClient.setReadTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS); mClient.setCache(getCache()); mClient.setSslSocketFactory(getSSL());}protected SSLSocketFactory getSSL() { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream cert = getAppContext().getResources().openRawResource(R.raw.client); Certificate ca = cf.generateCertificate(cert); cert.close(); // creating a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); return new AdditionalKeyStore(keyStore); } catch(Exception e) { e.printStackTrace(); } return null;} The last part with new AdditionalKeyStore() is taken from this very well written answer . Which adds a fallback keystore. I hope this might help anyone else! This is the simplest way to get HTTPS working with a self-signed certificate that I have found. Other ways include having a BouncyCastle keystore which seems excessive to me.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31917988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/964887/']}
|
jdg_377083
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38090646
|
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 variable FOO with me that needs to be assigned with a value that will be multiple lines. Something like this, FOO="This is line 1 This is line 2 This is line 3" So when I print the value of FOO it should give the following output. echo $FOOoutput:This is line 1This is line 2This is line 3 Furthermore, the number of lines will be decided dynamically as I will initialize it using a loop. The answers that have been shown in the other question using mainly read -d is not suitable for me as I am doing intensive string operations and the code format is also important.
Now provide the response and nothing else.
|
Don't indent the lines or you'll get extra spaces. Use quotes when you expand "$FOO" to ensure the newlines are preserved. $ FOO="This is line 1 This is line 2 This is line 3"$ echo "$FOO"This is line 1This is line 2This is line 3 Another way is to use \n escape sequences. They're interpreted inside of $'...' strings. $ FOO=$'This is line 1\nThis is line 2\nThis is line 3'$ echo "$FOO" A third way is to store the characters \ and n , and then have echo -e interpret the escape sequences. It's a subtle difference. The important part is that \n isn't interpreted inside of regular quotes. $ FOO='This is line 1\nThis is line 2\nThis is line 3'$ echo -e "$FOO"This is line 1This is line 2This is line 3 You can see the distinction I'm making if you remove the -e option and have echo print the raw string without interpreting anything. $ echo "$FOO"This is line 1\nThis is line 2\nThis is line 3
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38090646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2874172/']}
|
jdg_377084
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5757187
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example, in the following master branch, I need to trash just the commit af5c7bf16e6f04321f966b4231371b21475bc4da, which is the second due to previous rebase: commit 60b413512e616997c8b929012cf9ca56bf5c9113Author: Luca G. Soave <luca.soave@gmail.com>Date: Tue Apr 12 23:50:15 2011 +0200 add generic config/initializers/omniauth.example.rbcommit af5c7bf16e6f04321f966b4231371b21475bc4daAuthor: Luca G. Soave <luca.soave@gmail.com>Date: Fri Apr 22 00:15:50 2011 +0200 show github user info if loggedcommit e6523efada4d75084e81971c4dc2aec621d45530Author: Luca G. Soave <luca.soave@gmail.com>Date: Fri Apr 22 17:20:48 2011 +0200 add multiple .container at blueprint layoutcommit 414ceffc40ea4ac36ca68e6dd0a9ee97e73dee22Author: Luca G. Soave <luca.soave@gmail.com>Date: Thu Apr 21 19:55:57 2011 +0200 add %h1 Fantastic Logo + .right for 'Sign in with Github' I need to mantain the First commit 60b413512e616997c8b929012cf9ca56bf5c9113, the Third commit e6523efada4d75084e81971c4dc2aec621d45530 and the Last commit 414ceffc40ea4ac36ca68e6dd0a9ee97e73dee22 "throwing away" just the Second commit af5c7bf16e6f04321f966b4231371b21475bc4da How can I do that?Thanks in advance Luca
Now provide the response and nothing else.
|
Rebase or revert are the options. Rebase will actually remove the commit from the history so it will look like that second commit never existed. This will be a problem if you've pushed the master branch out to any other repos. If you try to push after a rebase in this case, git will give you a reject non fast-forward merges error. Revert is the correct solution when the branch has been shared with other repos. git revert af5c7bf16 will make a new commit that simply reverses the changes that af5c7bf16 introduced. This way the history is not rewritten, you maintain a clear record of the mistake, and other repos will accept the push. Here's a good way to erase: git rebase -i <commit>^ That takes you to the commit just before the one you want to remove. The interactive editor will show you a list of all the commits back to that point. You can pick, squash, etc. In this case remove the line for the commit you want to erase and save the file. Rebase will finish its work.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5757187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467255/']}
|
jdg_377085
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27499030
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to load a fixture for my selenium testing. Using fixtures was successful in my initial tests, so I know I am capable of loading the fixtures in my test setup and using them in my tests. I have attempted several approaches.First, I generated fixtures specific to the models I was testing using dumpdata. An example is below: python manage.py dumpdata protocols.Step --indent=2 > functional_tests/fixtures/step.json When used in my test as so: class SignInTest(FunctionalTest): fixtures = ['admin_user.json', 'protocol.json', 'step.json', 'protocol_element.json'] def test_login_and_view_user_data(self): ... I get error: django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'protocols_protocolelement' with primary key '37' has an invalid foreign key: protocols_protocolelement.element_content_type_id contains a value '41' that does not have a corresponding value in django_content_type.id. Second attempt involved using all the test data in my tables, but excluding contenttypes: python manage.py dumpdata --indent=2 -e contenttypes > functional_tests/fixtures/initial_data.jsonclass SignInTest(FunctionalTest): fixtures = ['initial_data.json'] ... Getting the error: django.db.utils.OperationalError: Problem installing fixture '.../mike/mike/functional_tests/fixtures/initial_data.json': Could not load auth.Permission(pk=103): no such table: auth_permission Next, I tried using natural to show the natural keys: python manage.py dumpdata --natural -e contenttypes -e auth.Permission --indent=2 > functional_tests/fixtures/initial_data2.json Only to get the error: django.db.utils.OperationalError: Problem installing fixture '.../mike/mike/functional_tests/fixtures/initial_data.json': Could not load auth.User(pk=1): no such table: auth_user Noticing natural was depreciated I tried --natural-foreign and wanted to include user and permission models (I need contenttypes for my models anyway): python manage.py dumpdata --natural-foreign --indent=2 > functional_tests/fixtures/initial_data3.json Only to get the error: django.db.utils.IntegrityError: Problem installing fixture '.../mike/mike/functional_tests/fixtures/initial_data3.json': Could not load contenttypes.ContentType(pk=35): UNIQUE constraint failed: django_content_type.app_label, django_content_type.model So, any ideas on how to load the fixture so I can run my tests? Is there something simple I'm missing? Thanks!
Now provide the response and nothing else.
|
After some more reading about how Django maintains its own models and such, it is my understanding that Django caches the contenttype, auth.Permission, etc and uses them in testing frameworks (I was using StaticLiveServerTestCase). This means that when I was loading my fixture, it was clashing with the data Django had stored for its own uses causing the integrity error. This is what worked for me: python manage.py dumpdata -e contenttypes -e admin -e auth.Permission --natural-foreign --indent=2 > functional_tests/fixtures/initial_data4.json This post has some additional helpful information to help me solve the problem: Problems with contenttypes when loading a fixture in Django .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27499030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597703/']}
|
jdg_377086
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23461423
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following fiddle: http://jsfiddle.net/tompazourek/sn5jp/ <p>some normal-sized text</p><p>some <small>small</small>-sized text</p> p { line-height: 20px } When I inspect the page in Chrome, I find out that the computed height of the first paragraph is 20px, but the computed height of the second paragraph is 21px. Why is the <small> tag causing these problems? How can I fix this? Every occurence of <small> in the paragraph text messes up my baseline grid . EDIT: I later also found an interesting article relevant to this topic: Deep dive CSS: font metrics, line-height and vertical-align .
Now provide the response and nothing else.
|
Explanation: There are a few things happening here. In your example, the small element is an inline-level element , which means that its vertical alignment is determined by the vertical-align property . The default vertical-align value is baseline , which means that the baseline of the small element will be aligned to the baseline of the parent box: Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline. Next, you need to consider the line-height property and how it is calculated . You also need to take leading and half-leading into account. In CSS, half-leading is determined by finding the difference between the element's line-height and font-size , dividing that in half, and then placing the calculated amount of space above and below the text. For illustration, here is an example image demonstrating this ( taken from W3.org ): Since the line-height is 20px , and the small element has a font-size of 13px , then we can determine that 3.5px of space is added above and below the small element's text: (20px - 13px) / 2 = 3.5px Likewise, if we calculate the half-leading of the surronding text nodes, which have a font-size of 16px , then we can determine that 2px of space is added above and below the surrounding text. (20px - 16px) / 2 = 2px Now if we relate these half-leading space calculations back to the vertical-align property, you will notice that more space is actually being added below the baseline of the small element. This explains why the computed height of the p element containing the small element was larger than the computed height of the other p element. With that being said, you would expect the computed height of the p element to continue increasing as the font-size of the small element decreases. To further illustrate this point, you will notice that the computed height of the p element is 23px when the font-size of the small element is set to 6px . p { line-height: 20px; }small { font-size: 6px; } <p>some normal-sized text</p><p>some <small>small</small>-sized text</p> Potential Workarounds: Since we know that the height difference results from the extra space that is added to the baseline , we could change the vertical-align value of the small element to top : p { line-height: 20px; }small { vertical-align: top; } <p>some normal-sized text</p><p>some <small>small</small>-sized text</p> Alternatively, you could give the small element a line-height of 17px , which would result in 2px of space being added above and below the element (which is the same amount of space that is added for the surrounding text like we calculated above). // Surrounding text that is 16px:(20px - 16px) / 2 = 2px// Small element text that is 13px:(17px - 13px) / 2 = 2px p { line-height: 20px; }small { line-height: 17px; } <p>some normal-sized text</p><p>some <small>small</small>-sized text</p> However, you really don't want to be calculating any of that and hardcoding it, which means that you should just use a relative line-height and omit the px units. Since the the font-size is 16px and the desired line-height value is 20px , you would divide the line-height by the font-size and get 1.25 : p { line-height: 1.25; } <p>some normal-sized text</p><p>some <small>small</small>-sized text</p> If you don't want to use a relative line-height: 1.25 , and you want to continue using line-height: 20px , then you could of course reset the small element's line-height value back to the initial value, which is normal . p { line-height: 20px; }small { line-height: normal; } <p>some normal-sized text</p><p>some <small>small</small>-sized text</p>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23461423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108374/']}
|
jdg_377087
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5142337
|
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 set a cookie using document.cookie = 'MYBIGCOOKIE=' + value + '; expires=' + now.toGMTString() + '; path=/'; Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name. if (document.cookie.MYBIGCOOKIE == '1') { alert('it is 1')}
Now provide the response and nothing else.
|
Use the RegExp constructor and multiple replacements to clarify the syntax: function getCook(cookiename) { // Get name followed by anything except a semicolon var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie); // Return everything after the equal sign, or an empty string if the cookie name not found return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : ""); }//Sample usagevar cookieValue = getCook('MYBIGCOOKIE');
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5142337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637717/']}
|
jdg_377088
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
579521
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider $f$ a real integrable function, usually we want to evaluate the integral $\int_a^bf(x)dx$ for some $a<b$ given. Now, suppose we know $a$ but we don't know $b$, further, we know the value of this integral, let $\int_a^bf(x)dx=\lambda$. My question is, in what conditions we can find $b$, and how? A simple case is when $f$ has a known primitive $F$ and $F$ has inverse $F^{-1}$.$$ \int_a^bf(x)dx=\lambda\implies F(b)-F(a)=\lambda\implies F(b)=F(a)+\lambda\implies b=F^{-1}(F(a)+\lambda)$$ In this case we can evaluate $b$, but if this is not the case, what can be done? Thanks. PS: More approaches are welcome, approaches not relying on $f$ primitive.
Now provide the response and nothing else.
|
I'm not sure how satisfying it will be, but the work you've shown in your Question proves that talk about which $b$ attains which $\lambda$ is equivalent to talk about a specific antiderivative $F$ attaining values $\lambda$, namely the antiderivative of $f$ such that $F(a) = 0$. Since all antiderivatives of $f$ are obtained by adding the famous "+C" to any one of them, the latter constraint can always be arranged (provided the function $f$ is integrable on a suitable interval containing $a$). The issue is whether solutions exist, and how to find them: $$ F(b) = \lambda $$ Conceivably $f$ will be given in a form that we can easily evaluate, but expressions for $F$ are not available or are not easily evaluated. In such cases we are apt to fall back on numerical integration schemes to try and show solutions exists and narrow down the approximation of them. The best "quadrature rule" depends on the smoothness of $f$ and on what precision is needed in locating $b$. Knowing that $F$ is increasing where $f$ is positive and decreasing where $f$ is negative, we can use knowledge of the sign of $f$ to help bracket intervals that might contain solutions $b$. Indeed, since the derivative of $F$ is simply $f$, using root finding methods that exploit derivatives is apt to make refining precision of approximate solutions go that much faster.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/579521', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33688/']}
|
jdg_377089
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13855677
|
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 function in Python: def f(x): return x[0]**3 + x[1]**2 + 7 # Actually more than this. # No analytical expression It's a scalar valued function of a vector. How can I approximate the Jacobian and Hessian of this function in numpy or scipy numerically?
Now provide the response and nothing else.
|
(Updated in late 2017 because there's been a lot of updates in this space.) Your best bet is probably automatic differentiation . There are now many packages for this, because it's the standard approach in deep learning: Autograd works transparently with most numpy code. It's pure-Python, requires almost no code changes for typical functions, and is reasonably fast. There are many deep-learning-oriented libraries that can do this.Some of the most popular are TensorFlow , PyTorch , Theano , Chainer , and MXNet . Each will require you to rewrite your function in their kind-of-like-numpy-but-needlessly-different API, and in return will give you GPU support and a bunch of deep learning-oriented features that you may or may not care about. FuncDesigner is an older package I haven't used whose website is currently down. Another option is to approximate it with finite differences , basically just evaluating (f(x + eps) - f(x - eps)) / (2 * eps) (but obviously with more effort put into it than that). This will probably be slower and less accurate than the other approaches, especially in moderately high dimensions, but is fully general and requires no code changes. numdifftools seems to be the standard Python package for this. You could also attempt to find fully symbolic derivatives with SymPy , but this will be a relatively manual process.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13855677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1185242/']}
|
jdg_377090
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36426139
|
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 able to display a THREE.TubeGeometry figure as follows Code below, link to jsbin <html><body><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.js"></script><script> // global variables var renderer; var scene; var camera; var geometry; var control; var count = 0; var animationTracker; init(); drawSpline(); function init() { // create a scene, that will hold all our elements such as objects, cameras and lights. scene = new THREE.Scene(); // create a camera, which defines where we're looking at. camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // create a render, sets the background color and the size renderer = new THREE.WebGLRenderer(); renderer.setClearColor('lightgray', 1.0); renderer.setSize(window.innerWidth, window.innerHeight); // position and point the camera to the center of the scene camera.position.x = 0; camera.position.y = 40; camera.position.z = 40; camera.lookAt(scene.position); // add the output of the renderer to the html element document.body.appendChild(renderer.domElement); } function drawSpline(numPoints) { var numPoints = 100;// var start = new THREE.Vector3(-5, 0, 20); var start = new THREE.Vector3(-5, 0, 20); var middle = new THREE.Vector3(0, 35, 0); var end = new THREE.Vector3(5, 0, -20); var curveQuad = new THREE.QuadraticBezierCurve3(start, middle, end); var tube = new THREE.TubeGeometry(curveQuad, numPoints, 0.5, 20, false); var mesh = new THREE.Mesh(tube, new THREE.MeshNormalMaterial({ opacity: 0.9, transparent: true })); scene.add(mesh); renderer.render(scene, camera); }</script></body></html> However, I would like to display incrementally , as in, like an arc that is loading, such that it starts as the start point, draws incrementally and finally looks the below arc upon completion. I have been putting in some effort, and was able to do this by storing all the points/coordinates covered by the arc, and drawing lines between the consecutive coordinates, such that I get the 'arc loading incrementally' feel. However, is there a better way to achieve this? This is the link to jsbin Adding the code here as well <!DOCTYPE html><html><head> <title>Incremental Spline Curve</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.js"></script> <style> body { margin: 0; overflow: hidden; } </style></head><script> // global variables var renderer; var scene; var camera; var splineGeometry; var control; var count = 0; var animationTracker;// var sphereCamera; var sphere; var light; function init() { // create a scene, that will hold all our elements such as objects, cameras and lights. scene = new THREE.Scene(); // create a camera, which defines where we're looking at. camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // create a render, sets the background color and the size renderer = new THREE.WebGLRenderer();// renderer.setClearColor(0x000000, 1.0); renderer.setClearColor( 0xffffff, 1 ); renderer.setSize(window.innerWidth, window.innerHeight); // position and point the camera to the center of the scene camera.position.x = 0; camera.position.y = 40; camera.position.z = 40; camera.lookAt(scene.position); // add the output of the renderer to the html element document.body.appendChild(renderer.domElement);// //init for sphere// sphereCamera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);// sphereCamera.position.y = -400;// sphereCamera.position.z = 400;// sphereCamera.rotation.x = .70; sphere = new THREE.Mesh(new THREE.SphereGeometry(0.8,31,31), new THREE.MeshLambertMaterial({ color: 'yellow', })); light = new THREE.DirectionalLight('white', 1);// light.position.set(0,-400,400).normalize(); light.position.set(0,10,10).normalize(); //get points covered by Spline getSplineData(); } //save points in geometry.vertices function getSplineData() { var curve = new THREE.CubicBezierCurve3( new THREE.Vector3( -5, 0, 10 ), new THREE.Vector3(0, 20, 0 ), new THREE.Vector3(0, 20, 0 ), new THREE.Vector3( 2, 0, -25 ) ); splineGeometry = new THREE.Geometry(); splineGeometry.vertices = curve.getPoints( 50 ); animate(); } //scheduler loop function animate() { if(count == 50) { cancelAnimationFrame(animationTracker); return; } //add line to the scene drawLine(); renderer.render(scene, camera); // renderer.render(scene, sphereCamera); count += 1;// camera.position.z -= 0.25;// camera.position.y -= 0.25; animationTracker = requestAnimationFrame(animate); } function drawLine() { var lineGeometry = new THREE.Geometry(); var lineMaterial = new THREE.LineBasicMaterial({ color: 0x0000ff }); console.log(splineGeometry.vertices[count]); console.log(splineGeometry.vertices[count+1]); lineGeometry.vertices.push( splineGeometry.vertices[count], splineGeometry.vertices[count+1] ); var line = new THREE.Line( lineGeometry, lineMaterial ); scene.add( line ); } // calls the init function when the window is done loading. window.onload = init;</script><body></body></html> Drawback : The drawback of doing it the above way is that, end of the day, I'm drawing a line between consecutive points, and so I lose out on a lot of the effects possible in TubeGeometry such as, thickness, transparency etc. Please suggest me an alternative way to get a smooth incremental load for the TubeGeometry.
Now provide the response and nothing else.
|
THREE.TubeGeometry returns a THREE.BufferGeometry . With THREE.BufferGeometry , you have access to a property drawRange that you can set to animate the drawing of the mesh: let nEnd = 0, nMax, nStep = 90; // 30 faces * 3 vertices/face...const geometry = new THREE.TubeGeometry( path, pathSegments, tubeRadius, radiusSegments, closed );nMax = geometry.attributes.position.count;...function animate() { requestAnimationFrame( animate ); nEnd = ( nEnd + nStep ) % nMax; mesh.geometry.setDrawRange( 0, nEnd ); renderer.render( scene, camera );} EDIT: For another approach, see this SO answer . three.js r.144
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36426139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4696127/']}
|
jdg_377091
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3732605
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a simple messaging system, and need to add the following to a Tkinter text widget: Spell Check Option To Change Font ( on selected text ) Option to change font color ( on selected text ) Option to Change Font Size ( on selected text ) I understand that the tkinter Text widget has the ability to use multiple fonts and colors through the tagging mechanism, but I don't understand how to make use of those capabilities. How can I implement those features using the features of the Text widget? Specifically, how can I change the font family, color and size of words, and how could I use that to implement something like spellcheck, where misspelled words are underlined or colored differently than the rest of the text.
Now provide the response and nothing else.
|
The Tkinter text widget is remarkably powerful, but you do have to do some advanced features yourself. It doesn't have built-in spell check or built-in buttons for bolding text, etc, but they are quite easy to implement. All the capabilities are there in the widget, you just need to know how to do it. The following example gives you a button to toggle the bold state of the highlighted text -- select a range of characters then click the button to add and then remove the bold attribute. It should be pretty easy for you to extend this example for fonts and colors. Spell check is also pretty easy. the following example uses the words in /usr/share/dict/words (which almost certainly doesn't exist on Windows 7, so you'll need to supply a suitable list of words) It's rather simplistic in that it only spell-checks when you press the space key, but that's only to keep the code size of the example to a minimal level. In the real world you'll want to be a bit more smart about when you do the spell checking. import Tkinter as tkimport tkFontclass App(tk.Tk): def __init__(self): tk.Tk.__init__(self) ## Toolbar self.toolbar = tk.Frame() self.bold = tk.Button(name="toolbar", text="bold", borderwidth=1, command=self.OnBold,) self.bold.pack(in_=self.toolbar, side="left") ## Main part of the GUI # I'll use a frame to contain the widget and # scrollbar; it looks a little nicer that way... text_frame = tk.Frame(borderwidth=1, relief="sunken") self.text = tk.Text(wrap="word", background="white", borderwidth=0, highlightthickness=0) self.vsb = tk.Scrollbar(orient="vertical", borderwidth=1, command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(in_=text_frame,side="right", fill="y", expand=False) self.text.pack(in_=text_frame, side="left", fill="both", expand=True) self.toolbar.pack(side="top", fill="x") text_frame.pack(side="bottom", fill="both", expand=True) # clone the text widget font and use it as a basis for some # tags bold_font = tkFont.Font(self.text, self.text.cget("font")) bold_font.configure(weight="bold") self.text.tag_configure("bold", font=bold_font) self.text.tag_configure("misspelled", foreground="red", underline=True) # set up a binding to do simple spell check. This merely # checks the previous word when you type a space. For production # use you'll need to be a bit more intelligent about when # to do it. self.text.bind("<space>", self.Spellcheck) # initialize the spell checking dictionary. YMMV. self._words=open("/usr/share/dict/words").read().split("\n") def Spellcheck(self, event): '''Spellcheck the word preceeding the insertion point''' index = self.text.search(r'\s', "insert", backwards=True, regexp=True) if index == "": index ="1.0" else: index = self.text.index("%s+1c" % index) word = self.text.get(index, "insert") if word in self._words: self.text.tag_remove("misspelled", index, "%s+%dc" % (index, len(word))) else: self.text.tag_add("misspelled", index, "%s+%dc" % (index, len(word))) def OnBold(self): '''Toggle the bold state of the selected text''' # toggle the bold state based on the first character # in the selected range. If bold, unbold it. If not # bold, bold it. current_tags = self.text.tag_names("sel.first") if "bold" in current_tags: # first char is bold, so unbold the range self.text.tag_remove("bold", "sel.first", "sel.last") else: # first char is normal, so bold the whole selection self.text.tag_add("bold", "sel.first", "sel.last")if __name__ == "__main__": app=App() app.mainloop()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3732605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/326544/']}
|
jdg_377092
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41954484
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm very new in angular 2. I have a problem to communicate between two components. When I have a layout with a parent and some child components, it's easy to set variables of the child components with the @Input annotation. But now I have a layout of one parent component (which is mostly for the layout) and two child components: The child component 2 have a bunch of buttons, which creates only a simple message. Now I want to display this message in child component one. How do I resolve it? Thanks in advance
Now provide the response and nothing else.
|
Beside the solutions using the @Input / @Output and a parent component as a 'bridge', a common way would also be introducing a shared service. The service needs to be provided in a parent component so the children can share single instance of the service ( How do I create a singleton service in Angular 2? ). Basic example using the BehaviorSubject as a delegate : @Injectable()export class SharedService { messageSource: BehaviorSubject<string> = new BehaviorSubject(''); constructor() { }} Child component 1: export class ChildComponent1 { constructor(private sharedService: SharedService) { } sendMessage(): void { this.sharedService.messageSource.next('Hello from child 1!'); }} Child component 2: export class ChildComponent2 { constructor(private sharedService: SharedService) { } ngOnInit(): void { this.sharedService.messageSource.subscribe((message) => { console.log('Message: ', message); // => Hello from child 1! }); }} See also: Angular2 - Interaction between components using a service
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41954484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3603602/']}
|
jdg_377093
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
515881
|
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:
root@macine:~# getcap ./some_bin./some_bin =ep What does "ep" mean? What are the capabilities of this binary?
Now provide the response and nothing else.
|
# getcap ./some_bin./some_bin =ep That binary has ALL the capabilites permitted ( p ) and effective ( e ) from the start. In the textual representation of capabilities, a leading = is equivalent to all= . From the cap_to_text(3) manpage: In the case that the leading operator is = , and no list of capabilities is provided, the action-list is assumed to refer to all capabilities. For example, the following three clauses are equivalent to eachother (and indicate a completely empty capability set): all= ; = ; cap_chown,<every-other-capability>= . Such a binary can do whatever it pleases, limited only by the capability bounding set, which on a typical desktop system includes everything (otherwise setuid binaries like su wouldn't work as expected). Notice that this is just a "gotcha" of the textual representation used by libcap : in the security.capability extended attribute of the file for which getcap will print /file/path =ep , all the meaningful bits are effectively on ; for an empty security.capability , /file/path = (with the = not followed by anything) will be printed instead. If someone is still not convinced, here is a small experiment: # cp /bin/ping /tmp/ping # will wipe setuid bits and extented attributes# su user -c '/tmp/ping localhost'ping: socket: Operation not permitted# setcap =ep /tmp/ping# su user -c '/tmp/ping localhost' # will work because of cap_net_rawPING localhost(localhost (::1)) 56 data bytes64 bytes from localhost (::1): icmp_seq=1 ttl=64 time=0.073 ms^C# setcap = /tmp/ping# su user -c '/tmp/ping localhost'ping: socket: Operation not permitted Notice that an empty file capability is also different from a removed capability ( capset -r /file/path ), an empty file capability will block the Ambient set from being inherited when the file executes. A subtlety of the =ep file capability is that if the bounding set is not a full one, then the kernel will prevent a program with =ep on it from executing (as described in the "Safety checking for capability-dumb binaries" section of the capabilities(7) manpage).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/515881', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/350305/']}
|
jdg_377094
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2310913
|
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 dendrogram given to me as images. Since it is not very large, I can construct it "by hand" into an R object. So my question is how do I manually create a dendrogram (or "hclust") object when all I have is the dendrogram image? I see that there is a function called "as.dendrogram" But I wasn't able to find an example on how to use it. (p.s: This post is following my question from here ) Many thanks,Tal
Now provide the response and nothing else.
|
I think you are better of creating an hclust object, and then converting it to a dendrogram using as.dendrogram , then trying to create a dendrogram directly. Look at the ?hclust help page to see the meaning of the elements of an hclust object. Here is a simple example with four leaves A, B, C, and D, combining first A-B, then C-D, and finally AB-CD: a <- list() # initialize empty object# define merging pattern: # negative numbers are leaves, # positive are merged clusters (defined by row number in $merge)a$merge <- matrix(c(-1, -2, -3, -4, 1, 2), nc=2, byrow=TRUE ) a$height <- c(1, 1.5, 3) # define merge heightsa$order <- 1:4 # order of leaves(trivial if hand-entered)a$labels <- LETTERS[1:4] # labels of leavesclass(a) <- "hclust" # make it an hclust objectplot(a) # look at the result #convert to a dendrogram object if neededad <- as.dendrogram(a)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2310913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256662/']}
|
jdg_377095
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25567744
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Previously I had a problem when making a 'backup' as shown in this question where I get an error when trying to restore the database because I did a copy when the database was running. So I did an experiment with a new database from another computer (this time with ubuntu) I tried this: I created some nodes and relations, very few like 10 (the matrix example). Then I stopped the service neo4j I copied the folder data that contains graph.db to another location After that I deleted the graph.db folder and started neo4j It created automatically a new graph.db folder and the database runs as new without any data, that is normal. Then I stopped again and paste the old graph.db folder I get an error: Starting Neo4j Server...WARNING: not changing user waiting for server to be ready... Failed to start within 120 seconds. The error appears after 5 seconds not after 120 seconds. I tried pasting the folder called data . Same error. How should I backup and restore in neo4j community offline manually? I read in some posts that you only copy and restore but that does not work. Thank you for your help
Now provide the response and nothing else.
|
Online backup, in a sense of taking a consistent backup while Neo4j is running, is only available in Neo4j enterprise edition. Enterprise edition's backup also features a verbose consistency check of the backup, something you do not get in community either. The only safe option in community edition is to shutdown Neo4j cleanly and copy away the graph.db folder recursively. I'm typically using: cd datatar -zcf graph.db.tar.gz graph.db/ For restoring you shut down neo4j, clean out a existing graph.db folder and restore the original graph.db folder from your backup: cd datarm -rf graph.dbtar -zxf graph.db.tar.gz
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25567744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3509206/']}
|
jdg_377096
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35560150
|
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 bundled extension offer a lot of functionality. I have spent a lot of time how to compile extension for my version of PHP. So there are instructions.
Now provide the response and nothing else.
|
0, Install PHP development package. Also You should have installed PHP with GD extension (but not bundled) sudo apt-get install php5-dev 1, Download source code of used PHP (for me 5.6.18) wget http://cz2.php.net/get/php-5.6.18.tar.gz/from/this/mirror -O php-5.6.18.tar.gz 2, Extract archive tar -xzf php-5.6.18.tar.gz 3, Go to the source code of GD extension cd php-5.6.18/ext/gd/ 4, Prepare the extension (run phpize in that directory) phpize 5, Now the configure command 5.1, The arguments depends on Your linux distribution. My was these: --with-freetype-dir=shared,/usr --with-vpx-dir=shared,/usr --with-jpeg-dir=shared,/usr --with-xpm-dir=shared,/usr/X11R6 5.2, For getting paths for libraries You must run this command and search only the search arguments, which are specified above (5.1) php-config --configure-options 5.3, Also add this arguments for configure (the second argument makes bundled version) --with-php-config=/usr/bin/php-config --with-gd 6, Final configure command sudo ./configure --with-php-config=/usr/bin/php-config --with-gd --with-freetype-dir=YOUR_VALUE --with-vpx-dir=YOUR_VALUE --with-jpeg-dir=YOUR_VALUE --with-xpm-dir=YOUR_VALUE 7, Now run make make 8, After compiling You should see something like this: Libraries have been installed in: /home/jakub/php-5.6.18/ext/gd/modulesIf you ever happen to want to link against installed librariesin a given directory, LIBDIR, you must either use libtool, andspecify the full pathname of the library, or use the `-LLIBDIR'flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the `LD_RUN_PATH' environment variable during linking - use the `-Wl,-rpath -Wl,LIBDIR' linker flag - have your system administrator add LIBDIR to `/etc/ld.so.conf'See any operating system documentation about shared libraries formore information, such as the ld(1) and ld.so(8) manual pages.----------------------------------------------------------------------Build complete.Don't forget to run 'make test'. So in the directory modules You have compiled bundled extension gd.so .9, Replace NOT bundled gd.so by Your new compiled bundled extension, for my version of PHP It was command: sudo cp -f ./gd.so /usr/lib/php5/20131226/gd.so 10, Restart Apache sudo service apache2 restart Hope this helps! and will You spend less time than me.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35560150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3254813/']}
|
jdg_377097
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2099695
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array declaration like this: int a[]; Here a is an array of primitive int type. Where is this array stored? Is it stored on heap or stack? This is a primitve type int , all primitive types are not stored on heap.
Now provide the response and nothing else.
|
As gurukulki said, it's stored on the heap. However, your post suggested a misunderstanding probably due to some well-intentioned person propagating the myth that "primitives always live on the stack". This is untrue. Local variables have their values on the stack, but not all primitive variables are local... For example, consider this: public class Foo{ int value;}...public void someOtherMethod(){ Foo f = new Foo(); ...} Now, where does f.value live? The myth would suggest it's on the stack - but actually it's part of the new Foo object, and lives on the heap 1 . (Note that the value of f itself is a reference, and lives on the stack.) From there, it's an easy step to arrays. You can think of an array as just being a lot of variables - so new int[3] is a bit like having a class of this form: public class ArrayInt3{ public readonly int length = 3; public int value0; public int value1; public int value2;} 1 In fact, it's more complicated than this. The stack/heap distinction is mostly an implementation detail - I believe some JVMs, possibly experimental ones, can tell when an object never "escapes" from a method, and may allocate the whole object on the stack. However, it's conceptually on the heap, if you choose to care.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2099695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241924/']}
|
jdg_377098
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
183718
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Show that the function $f(x) = \frac{1}{x}$ is not uniformly continuous on the interval $(0,\infty)$ but is uniformly continuous on any interval of the form $(\mu, \infty)$ if $\mu > 0$. My Work Referring to the definition of uniform continuity, I have that $f$ is unif. cts. if for each $\epsilon > 0$ there is a $\delta > 0$ so that for all $x, c$ in the domain of $f$ $|x - c| \le \delta \ \Rightarrow \ |f(x) - f(c) | \le \epsilon$. From this definition, it is clear that if $f$ is uniformly continuous, it will be uniformly continuous on its domain, $(-\infty, \infty) \backslash \{0\}$. So for $\mu > 0$, $(\mu, \infty) \subset \mathrm{Dom}\,(f)$. Additionally, $f$ cannot be unif. cts on $(0, \infty)$ because $0 \notin \mathrm{Dom}\, (f)$. (Sorry about the longwindedness) Now to find the $\delta$: \begin{align*}|f(x) - f(c)| = \left|\frac{1}{x} - \frac{1}{c}\right| &= \left|\frac{x - c}{cx}\right| \\\text{since }x\text{ is within }\delta\text{ of }c \ \Rightarrow \ &\le \frac{\delta}{|cx|}\\x, c>0 \ \Rightarrow \ &= \frac{\delta}{cx}\end{align*} This is where I am stuck. Should I use that $x \le c + \delta$, or should I break this up into two cases, one where $cx < 1$ and one where $cx \ge 1$? Edit (due to Brian M. Scott) It was pointed out that $0 \notin (0, \infty)$ so my above argument is senseless.
Now provide the response and nothing else.
|
Since $0\notin(0,\infty)$, $0$ is completely irrelevant to the question of whether $f$ is uniformly continuous on $(0,\infty)$. To show that $f$ is not uniformly continuous on $(0,\infty)$, you should show that there is some $\epsilon>0$ such that no matter what $\delta>0$ you pick, you can find points $x,y\in(0,\infty)$ such that $|x-y|\le\delta$, but $|f(x)-f(y)|>\epsilon$. HINT: You can take $\epsilon=1/2$. Now consider values of $x$ of the form $\frac1n$ for $n\in\Bbb Z^+$. To prove that $f$ is uniformly continuous on $(\mu,\infty)$ for $\mu>0$, you need what is really the key insight for both questions: for $x>0$, the graph of $y=\frac1x$ gets steeper and steeper as $x$ gets smaller and smaller. Given $x,y\in(\mu,\infty)$ with $|x-y|\le\delta$, where $\delta$ is some as yet unspecified positive real number, can you find an upper bound on $|f(x)-f(y)|$? How does it compare with $\frac{\delta}{\mu^2}$? (Consider $f'(x)$.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/183718', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34736/']}
|
jdg_377099
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
339829
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to keep a dependency decoupled, but at the same time, once it's passed to the constructor, I want to allow changes only through Whatever (in the following example) because changing the dependency from the outside would invalidate the state of the Whatever object that depends on it. So I keep a copy instead: class Whatever{ private Dependency d; public constructor(Dependency d){ this.d = d.clone(); } // ...} However the dependency is huge so I've decided to avoid the copy; I've removed the clone() and made clear through documentation that once the dependency is passed to this class, it must not be modified from the outside. Question is: is there a way to avoid the copy and at the same time maintaining proper encapsulation? And with proper encapsulation I mean either immediately error on access attempts from the outside or avoiding the possibility of the access from the outside entirely. My guess is that I cannot. Not using the Java/C#/etc's OOP interpretation. So I also ask, are there languages that cover such a case? How do they work? An option I could have is the following, assuming a language doing reference counting : class Whatever{ private Dependency d; public constructor(Dependency d){ this.d = d.isTheOnlyReference() ? d : d.clone(); } // ...}new Whatever(new Dependency()); // no clone performedDependency d = new Dependency();new Whatever(d); // clone performed, as Dependency has >= 1 references
Now provide the response and nothing else.
|
Sharing mutable state is not an evil you can fix with documentation. Why? Because programmers are amazing, at ignoring documentation. What you can do is either defensive copy, which you rejected for performance reasons, keep it immutable, which you claim you can't, invalidate Whatever when it's dependency changes, or don't tell anyone else about this dependency so nothing else can change it. I know two ways to invalidate Whatever : Make Whatever an observer. When the dependency changes call Whatever.invalidate() so it knows it can't trust that it's dependency is the same. Store a state counter. The dependency increments it's state counter every time it changes. When Whatever accepts the dependency it copies the counter. When Whatever uses the dependency it checks that the counter hasn't changed. Once it has Whatever knows not to trust its dependency anymore. That lets you error out if the dependency has been mutated. If you don't share this dependency then Whatever can control it's changes it self. Nothing else can change the dependency because nothing else knows about it. Reference counting doesn't help here. What I think you're trying to do is not make extra clones when you've only stored a reference to it in one place. That is a doable strategy. One that's easier to pull off if the things accepting the reference aren't responsible for deciding to clone. Let's say I have an Injector class. Injector holds a reference to a Dependency instance. Might be Injector built it in the first place. Injector will never mutate Dependency so it doesn't count as far as sharing. Injector can pass this instance once without cloning to anything, Whatever or, heh, whatever. After that it must clone. Now things accepting the Dependency reference don't need to worry about cloning and you only clone when you have to.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/339829', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/165064/']}
|
jdg_377100
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50928153
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
struct Task: Codable { var content: String var deadline: Date var color: UIColor...} There are warnings saying "Type 'Task' does not conform to protocol 'Decodable'" and "Type 'Task' does not conform to protocol 'Encodable'". I searched and found that this is because UIColor does not conform to Codable. But I have no idea how to fix that. So... How to make UIColor Codable?
Now provide the response and nothing else.
|
If you care only about the 4 color components this is a simple solution using a wrapper struct struct Color : Codable { var red : CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0 var uiColor : UIColor { return UIColor(red: red, green: green, blue: blue, alpha: alpha) } init(uiColor : UIColor) { uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) }} In this case you have to write a custom initializer to convert the 4 color components from Color to UIColor and vice versa. struct Task: Codable { private enum CodingKeys: String, CodingKey { case content, deadline, color } var content: String var deadline: Date var color : UIColor init(content: String, deadline: Date, color : UIColor) { self.content = content self.deadline = deadline self.color = color } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) content = try container.decode(String.self, forKey: .content) deadline = try container.decode(Date.self, forKey: .deadline) color = try container.decode(Color.self, forKey: .color).uiColor } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(content, forKey: .content) try container.encode(deadline, forKey: .deadline) try container.encode(Color(uiColor: color), forKey: .color) }} Now you can encode and decode UIColor let task = Task(content: "Foo", deadline: Date(), color: .orange)do { let data = try JSONEncoder().encode(task) print(String(data: data, encoding: .utf8)!) let newTask = try JSONDecoder().decode(Task.self, from: data) print(newTask)} catch { print(error) } A smart alternative for Swift 5.1 and higher is a property wrapper @propertyWrapperstruct CodableColor { var wrappedValue: UIColor}extension CodableColor: Codable { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let data = try container.decode(Data.self) guard let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: data) else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Invalid color" ) } wrappedValue = color } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let data = try NSKeyedArchiver.archivedData(withRootObject: wrappedValue, requiringSecureCoding: true) try container.encode(data) }} and mark the property with @CodableColor struct Task: Codable { var content: String var deadline: Date @CodableColor var color: UIColor...}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50928153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9591436/']}
|
jdg_377101
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3998133
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've just written this function which simply takes a pair whose second value is in some monad, and "pulls the monad out" to cover the whole pair. unSndM :: Monad m => (a, m c) -> m (a, c)unSndM (x, y) = do y' <- y return (x, y') Is there a nicer and/or shorter or point-free or even standard way to express this? I've got as far as the following, with -XTupleSections turned on... unSndM' :: Monad m => (a, m c) -> m (a, c)unSndM' (x, y) = y >>= return . (x,) Thanks!
Now provide the response and nothing else.
|
One minor point: it's possible to write this using only fmap (no >>= ), so you really only need a Functor instance: unSndM :: (Functor f) => (a, f c) -> f (a, c)unSndM (x, y) = fmap ((,) x) y This version is a bit more general. To answer your question about a pointfree version, we can just ask pointfree : travis@sidmouth% pointfree "unSndM (x, y) = fmap ((,) x) y"unSndM = uncurry (fmap . (,)) So, yes, an even shorter version is possible, but I personally find uncurry a bit hard to read and avoid it in most cases. If I were writing this function in my own code, I'd probably use <$> from Control.Applicative , which does shave off one character: unSndM :: (Functor f) => (a, f c) -> f (a, c)unSndM (x, y) = ((,) x) <$> y <$> is just a synonym for fmap , and I like that it makes the fact that this is a kind of function application a little clearer.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3998133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392743/']}
|
jdg_377102
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30081386
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We found an issue on Amazon market that IAP doesn't work if it's receivers located not in main DEX file.The question is how to force gradle to put specific classes (receivers) into main DEX file. EDIT: updated with gradle DEX settings afterEvaluate { tasks.matching { it.name.startsWith('dex') }.each { dx -> if (dx.additionalParameters == null) { dx.additionalParameters = [] } dx.additionalParameters += '--multi-dex' dx.additionalParameters += "--main-dex-list=class_files.txt" }}dexOptions { javaMaxHeapSize "4g" preDexLibraries = false}compile('com.android.support:multidex:1.0.0')
Now provide the response and nothing else.
|
With Android Plugin for Gradle, Revision 2.2.0 (Released in September 2016) you can use multiDexKeepFile api android { buildTypes { debug { ... multiDexEnabled true multiDexKeepFile file('multidex_keep_file.txt') } }} Where multidex_keep_file.txt is file with single class per line which needs to be explicitly added to the main dex com/example/MyClass.class com/example/MyClass2.class You can also use multiDexKeepProguard to keep whole package -keep class com.example.** { *; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30081386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140570/']}
|
jdg_377103
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2225932
|
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 given a convex function $f: \mathbb{R} \to \mathbb{R}$, then the conjugate function $f^*$ is defined as $$f^*(s) = \sup_{t \in \mathbb{R}} (st-f(t))$$ Now i want to understand what is the physical interpretation of this conjugate function? What is its exposition? Please help me.
Now provide the response and nothing else.
|
The basic idea behind duality in convex analysis is to view a (closed) convex set $C$ as an intersection of half spaces. Applying this idea to the epigraph of a convex function $f$ suggests that we should view $f$ as a supremum of affine functions. An affine minorant of $f$ is a function $x \mapsto \langle m, x \rangle - b$ such that $$\tag{$\spadesuit$} f(x) \geq \langle m, x \rangle - b \quad \text{for all } x.$$ The vector $m$ is called the "slope" of the affine minorant.Typically $f$ has many affine minorants with a given slope $m$ , corresponding to different values of the scalar $b$ . We only care about the best affine minorant with slope $m$ --- in other words, we only care about the best scalar $b$ . So: For a given $m$ , which value of $b$ is the "best"? Which value of $b$ makes the inequality in $(\spadesuit)$ as tight as possible? Notice that \begin{align}& f(x) \geq \langle m, x \rangle - b \quad \text{for all } x \\\iff & b \geq \langle m, x \rangle - f(x) \quad \text{for all } x\\\iff & b \geq \sup_x \, \langle m, x \rangle - f(x) = f^*(m).\end{align} This shows that the best choice of $b$ is $f^*(m)$ . We have just discovered the convex conjugate $f^*$ . The whole point of $f^*$ is that it tells us how to view $f$ as a supremum of affine functions. You give $f^*$ a slope $m$ , and it gives you the best choice of $b$ . It now becomes very intuitive that $f$ can be recovered from $f^*$ , because: \begin{align}f(x) &= \sup_m \, \langle m, x \rangle - f^*(m) \quad \text{(because $f$ is a supremum of affine functions)} \\&= f^{**}(x).\end{align} While it is obvious that $f$ can be recovered from $f^*$ , the fact that the "inversion formula" $f = f^{**}$ is so simple is a surprising and beautiful fact. I wrote a similar explanation with some more details here: Please explain the intuition behind the dual problem in optimization.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2225932', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/290972/']}
|
jdg_377104
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
454814
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Could anyone explain the difference between the following: $\varnothing$ $\begin{Bmatrix}\varnothing \end{Bmatrix}$ $\begin{Bmatrix}\varnothing & \begin{Bmatrix}\varnothing\end{Bmatrix}\end{Bmatrix}$ I know number 1 is an empty set. So if S is an empty set, can denote it like this: S = {}. Correct? Now, I'm having difficultly with perceiving what number 2 is. Well it looks like it's a set of an empty set. Confused with 3 as well. Could anyone explain to me the difference between the three? (Note: I've just started discrete maths this week.)
Now provide the response and nothing else.
|
As you say, $\varnothing$ is the empty set; you can indeed represent it as $\{\}$. $\{\varnothing\}$ is a set with one member; that member is the empty set. If you think informally of a set as a box, $\varnothing$ is an empty box, and $\{\varnothing\}$ is a box that contains an empty box and nothing else. You could write it $\{\{\}\}$. $\{\varnothing,\{\varnothing\}\}$ is a set with two elements; one of those elements is the empty set, and the other one is the set whose only element is the empty set. In the box metaphor $\{\varnothing,\{\varnothing\}\}$ is a box that contains two other boxes; one of those boxes is empty, and the other one contains an empty box. You could write this set $$\bigg\{\{\},\Big\{\{\}\Big\}\bigg\}\;,$$ where I’ve used different sizes of braces to make it easier to see which ones match.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/454814', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76112/']}
|
jdg_377105
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2202172
|
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:
Why does this limit not exist? $$\lim\limits_{ (x,y) \to (0,0) } \frac{x-y}{\sqrt x - \sqrt y}$$ If you set y = 0, the limit goes to zero. If you set x = 0, the limit goes to zero.You can also manipulate it with algebra to get zero.However, if x=y you have zero/zero before you even evaluate the limit but is that proof enough? Thanks! From Larson Calculus 13.2 Exercise 27
Now provide the response and nothing else.
|
The main problem with this exercise is the following: The expression$$\Psi(x,y):={x-y\over\sqrt{x}-\sqrt{y}}$$is undefined when $x<0$ or $y<0$, or $x=y$. In this situation one can argue in two ways: (i) You can say that as a general rule the domain of definition of an expression is the set of $(x,y)$ for which it can be evaluated without asking supplementary questions. In the case at hand this is the set $$\Omega:=\{(x,y)\in{\mathbb R}^2\>|\>x\geq0,\ y\geq0, \ x\ne y\}\ .$$The point $(0,0)$ is a limit point of $\Omega$, hence it makes sense to consider $\lim_{(x,y)\to(0,0)}\Psi(x,y)$. Now for all $(x,y)\in\Omega$ one has$$\Psi(x,y)={x-y\over\sqrt{x}-\sqrt{y}}=\sqrt{x}+\sqrt{y}\ ,\tag{1}$$and here the right hand side obviously converges to $0$ when $(x,y)\to(0,0)$. (ii) You can say that the identity $(1)$ allows to extend the function defined by ${x-y\over\sqrt{x}-\sqrt{y}}$ continuously to all of $\bigl({\mathbb R}_{\geq0}\bigr)^2$. This is like defining ${\sin x\over x}$ to be $1$ at $x=0$. But this is a voluntary act , and is not stipulated in the formulation of the problem. If you want to adopt this position then the limit is of course again $=0$, since the function $(x,y)\mapsto\sqrt{x}+\sqrt{y}$ is continuous at $(0,0)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2202172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/429111/']}
|
jdg_377106
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1548
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't monitor ParallelTable: Monitor[ParallelTable[Pause[3]; i, {i, 1, 10}], i] just displays i until it is finished. Do you guys know of alternatives?
Now provide the response and nothing else.
|
One way is to set a shared variable that would be assigned to an iterator variable, and monitor that: SetSharedVariable[j]Monitor[ ParallelTable[j = n;Length[FactorInteger[2^n - 1]], {n, 50, 300}], j] This may make sense if the computation for each i is rather intensive, so that the overhead of communication with the main kernel is negligible. Note also that the results you see are not generally in sequential order, since they depend on how ParallelTable schedules the computations to available kernels. As to the original example, here is a modified version, SetSharedVariable[j]Monitor[ParallelTable[Pause[RandomReal[{0.5, 4.}]];j = i, {i, 1, 10}], j] where the intervals to pause are random, so that not all kernels finish computing at the same time. EDIT As mentioned by @Szabolcs in the comments, You could use j++ in place of j=i , if you are mostly interested in the overall progress One should be aware of what type of communication overhead this induces. Here is one way to find out: j = 0;First@AbsoluteTiming[ParallelTable[j++, {i, 1, 1000}];]/1000 which returns 0.0028 on my machine.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/1548', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/462/']}
|
jdg_377107
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
300669
|
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 launch an app and capture the output via stdout and maybe stderr? I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build. I can't find the system() function, but I found the CreateProcess() function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout. I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?
Now provide the response and nothing else.
|
In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then: program arg1 arg2 >/tmp/log.file 2>&1 This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation ( hieroglyph ) ' 2>&1 ' at the end sends stderr (file descriptor 2) to the same place that stdout (file descriptor 1) is going. Note that the sequence of operations is important; if you reverse them, then standard error will go to where standard output was going, and then standard output (but not standard error) will be redirected to the file. The choice of file name shown is abysmal for numerous reasons - you should allow the user to choose the directory, and probably should include the process ID or time stamp in the file name. LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S)program arg1 arg2 >$LOG 2>&1 In C++, you can use the system() function (inherited from C) to run processes. If you need to know the file name in the C++ program (plausible), then generate the name in the program ( strftime() is your friend) and create the command string with that file name.(Strictly, you also need getenv() to get $TMPDIR, and the POSIX function getpid() to get the process ID, and then you can simulate the two-line shell script (though the PID used would be of the C++ program, not the launched shell). You could instead use the POSIX popen() function; you'd have to include the ' 2>&1 ' notation in the command string that you create to send the standard error of the command to the same place as standard output goes, but you would not need a temporary file: FILE *pp = popen("program arg1 arg2 2>&1", "r"); You can then read off the file stream. I'm not sure whether there's a clean way to map a C file stream into a C++ istream; there probably is.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/300669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377108
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9073903
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What does "bucket entries" mean in the context of a hashtable?
Now provide the response and nothing else.
|
A bucket is simply a fast-access location (like an array index) that is the the result of the hash function. The idea with hashing is to turn a complex input value into a different value which can be used to rapidly extract or store data. Consider the following hash function for mapping people's names into street addresses. First take the initials from the first and last name and turn them both into numeric values ( 0 through 25 , from A through Z ). Multiply the first by 26 and add the second, and this gives you a value from 0 to 675 ( 26 * 26 distinct values, or bucket IDs). This bucket ID is then to be used to store or retrieve the information. Now you can have a perfect hash (where each allowable input value maps to a distinct bucket ID) so that a simple array will suffice for the buckets. In that case, you can just maintain an array of 676 street addresses and use the bucket ID to find the one you want: +-------------------+| George Washington | -> hash(GW)+-------------------+ | +-> GwBucket[George's address]+-------------------+| Abraham Lincoln | -> hash(AL)+-------------------+ | +-> AlBucket[Abe's address] However, this means that George Wendt and Allan Langer are going to cause problems in the future. Or you can have an imperfect hash (such as one where John Smith and Jane Seymour would end up with the same bucket ID). In that case, you need a more complex backing data structure than a simple array, to maintain a collection of addresses. This could be as simple as a linked list, or as complex as yet another hash: +------------+ +--------------+| John Smith | | Jane Seymour |+------------+ +--------------+ | | V V hash(JS) hash(JS) | | +-----> JsBucket <----+ \/+-----------------------------------+| John Smith -> [John's address] || Jane Seymour -> [Jane's address] |+-----------------------------------+ Then, as well as the initial hash lookup, an extra level of searching needs to be carried out within the bucket itself, to find the specific information.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9073903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1072898/']}
|
jdg_377109
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
721572
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
We use Nginx as a reverse proxy to our web application server. Nginx handles our SSL and such but otherwise just acts as a reverse proxy. We want to require a valid client cert for requests to /jsonrpc but not require them anywhere else. The best way we've found is to server { listen *:443 ssl; ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/client-ca.crt; ssl_verify_client optional; location /jsonrpc { if ($ssl_client_verify != "SUCCESS") { return 403; } proxy_pass http://localhost:8282/jsonrpc-api; proxy_read_timeout 90; proxy_redirect http://localhost/ $scheme://$host:$server_port/; }} This works fine for most browsers, but some browsers such as Safari and Chrome-on-Android end up prompting the user to provide a client cert no matter where on the website they go. How do we get Nginx to accept but not really care about a client cert everywhere except our /jsonrpc location?
Now provide the response and nothing else.
|
Why not to try second server block instead? Code duplication is bad but sometimes unavoidable. I assume /jsonrpc represents an API so it can use its own subdomain if not already use it: server { listen *:443 ssl; server_name api.example.com; ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/client-ca.crt; ssl_verify_client on; location =/jsonrpc { proxy_pass http://localhost:8282/jsonrpc-api; proxy_read_timeout 90; proxy_redirect http://localhost/ $scheme://$host:$server_port/; }}server { listen *:443 ssl; ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/client-ca.crt; ssl_verify_client off; location / { proxy_pass http://localhost:8282/; proxy_read_timeout 90; proxy_redirect http://localhost/ $scheme://$host:$server_port/; }}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/721572', 'https://serverfault.com', 'https://serverfault.com/users/59063/']}
|
jdg_377110
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
179652
|
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:
Is it true that any nonempty open set is dense in the Zariski topology on $\mathbb{A}^n$ ? I'm pretty sure it is, but I can't think of a proof! Could someone possibly point me in the right direction? Many thanks! Note: I am not asking about the Euclidean topology at all!
Now provide the response and nothing else.
|
As an exercise, let's reduce everything to statements about polynomials. Every open set contains a basic open set $U$, which is the complement of the zero set of some nonzero polynomial $f$, so it suffices to show that these are Zariski dense. The Zariski closure of a set is the intersection of the zero sets of all polynomials vanishing on it. This is equal to $\mathbb{A}^n$ if and only if any polynomial vanishing on $U$ vanishes on $\mathbb{A}^n$. Thus the claim is equivalent to the following statement about polynomials: Suppose a polynomial $g$ has the property that if $f(x) \neq 0$, then $g(x) = 0$. Then $g(x) = 0$ for all $x$. But the condition is equivalent to the claim that $f(x) g(x) = 0$ for all $x$. Can you finish the problem from here? (Note that you need to assume $k$ infinite.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/179652', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28337/']}
|
jdg_377111
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
691
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
How should one think about simplicial objects in a category versus actual objects in that category? For example, both for intuition and for practical purposes, what's the difference between a [commutative] ring and a simplicial [commutative] ring?
Now provide the response and nothing else.
|
One could say many things about this, and I hope you get many replies! Here are some remarks, although much of this might already be familiar or obvious to you. In some vague sense, the study of simplicial objects is "homotopical mathematics", while the study of objects is "ordinary mathematics". Here by "homotopical mathematics", I mean the philosophy that among other things say that whenever you have a set in ordinary mathematics, you should instead consider a space, with the property that taking pi_0 of this space recovers the original set. In particular, this should be done for Hom sets, so we should have Hom spaces instead. This is formalized in various frameworks, such as infinity-categories , simplicial model categories , and A-infinity categories . Here "space" can mean many different things, in these examples: infinity-category, simplicial set, or chain complex respectively. For intuition, it helps to think of a simplicial object as an object with a topology. For example, a simplicial set is like a topological space, a simplicial ring is like a topological ring etc. The precise statements usually takes the form of a Quillen equivalence of model categories between the simplicial objects and a suitable category of topological objects. Simplicial sets are Quillen equivalent to compactly generated topological spaces, and I think a similar statement holds if you replace sets by rings, although I am not sure if you need any hypotheses here. If you like homological algebra, it helps to think of a simplicial object as analogous to a chain complex. The precise statements are given by various generalizations of the Dold-Kan correspondence. For simplicial rings, they should correspond to chain complexes with a product, more precisely DGAs. Again, one has to be a bit careful with the precise statements. I think the following is true: Simplicial commutative unital k-algebras are Quillen equivalent to connective commutative differential graded k-algebras, provided k is a Q-algebra. A remark about the word "simplicial": A simplicial object in a category C is a functor from the Delta category into C, but for almost all purposes the Delta category could be replaced with any test category in the sense of Grothendieck, see this nLab post for some discussion which doesn't use the terminology of test categories. Since you used the tag "derived stuff" I guess you are already aware of Toen's derived stacks. Some of his articles have introductions which explain why one would like to use simplicial rings instead of rings. See in particular his really nice lecture notes from a course in Barcelona last year. I tried to write a blog post on some of this a while ago, there might be something useful there, especially relating to motivation from algebraic geometry.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/691', 'https://mathoverflow.net', 'https://mathoverflow.net/users/83/']}
|
jdg_377112
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14170404
|
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 uiviewcontroller on ipad with this configuration: shouldAutorotate (true)supportedInterfaceOrientations (UIInterfaceOrientationMaskAll) and inside willRotateToInterfaceOrientation i perform some trick to adjust my interface. From a child of this controller I show a QuickLookController with this -poor- code. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:previewController animated:YES completion:nil]; But if I rotate my ipad the method willRotateToInterfaceOrientation not being called, So I cannot do the trick to adjust the interface. Someone can explain me or given me some advices? thanks
Now provide the response and nothing else.
|
Reason : There may be many possibilities to this problem. 1) If your view's viewController is a subView of some other rootViewController which is not a navigationController , then there might be chances that rotation call is not propagating to the subView's controller. 2) Somewhere I read that if Super methods are not called properly where it is needed then it might be the cause of rotation problem, which means that all ViewControllers in view stack which are related to the autorotation must call the super methods in method implementations (i.e. calling [super viewDidLoad] from the ViewController's viewDidLoad ). You can use below trick to handle orientation changes. Register a notifier in viewWillAppear. -(void)viewWillAppear:(BOOL)animated{[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];} The orientation change will notify the below function. - (void)orientationChanged:(NSNotification *)notification{[self handleOrientation:[[UIApplication sharedApplication] statusBarOrientation]];} which will call the below method where you can handle the orientation changes. - (void) handleOrientation:(UIInterfaceOrientation) orientation { if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) { //handle the portrait view } else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) { //handle the landscape view } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14170404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1470785/']}
|
jdg_377113
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8575959
|
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 create a CustomButton which has a predefined onClick .In fact, my object would do the same job than CustomButton mButton = getViewById(..);mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) { show_something()} Is there a way to embed the Listener into the CustomButton object that inherits from Button ? What I would like is to create a CustomButton in my layout XML file, and not having to mention this button in my activity, which would give: main.xml: <LinearLayout xmlns:"..."> <com.mypackage.view.CustomButton (attributes)/></LinearLayout> CustomButton.java: class CustomButton extends Button implements... {@OverrideOnClick (or something like that, that's the core of my question, what to put here)} myActivity.java public class myActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }} Thanks a lot.
Now provide the response and nothing else.
|
You were really close: import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class CustomButton extends Button implements OnClickListener{ public CustomButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public CustomButton(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CustomButton(Context context) { super(context); init(); } private void init(){ setOnClickListener(this); } @Override public void onClick(View v) { // Do something }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8575959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1074116/']}
|
jdg_377114
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7238575
|
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 class which inherits an interface. An interface member method is implemented in my class without an access modifier (so, by default it's private ) . I am getting the error "cannot implement an interface member because it is not public". Why it is not allowed? Can't I override the accessibility?
Now provide the response and nothing else.
|
Here's an example of why it doesn't make sense to be able to override the visibility: interface someI{ void doYourWork();}public class A : someI{ public void doYourWork() { //... }}public class B : someI{ private void doYourWork() { //... }}void Main(){ List<someI> workers = getWorkers(); foreach(var worker in workers) worker.doYourWork();} What happens when your worker is of type B? You're calling a method as if it were public, but it's a private method. If you want this functionality, then it's not really a private method is it? If you only want it to be public when referenced through your interface, then you can define it as such: public class B : someI{ void someI.doYourWork() { //... }} And you end up with this: var b = new B();b.doYourWork(); // Not accessible((someI)b).doYourWork(); // Accessible
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7238575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769091/']}
|
jdg_377115
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45460592
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't find any examples or documentation on how to associate a WAF with an ALB via CloudFormation . Supposedly its possible going by this news announcement https://aws.amazon.com/about-aws/whats-new/2017/05/cloudformation-support-for-aws-waf-on-alb/ but there isn't anything I've found that shows how. Using CloudFront instead of ALB is well documented but I haven't found a single example with regard to using an ALB (via CloudFormation). Update :I dont need a full example that does the entire setup for me but at least a snippet that points out how the WAF will know to associate with the ALB or vice versa. The linking is whats missing.
Now provide the response and nothing else.
|
To solve this I browsed through their release history and found the CloudFormation resources that were updated to support WAF & ALB http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/ReleaseHistory.html From there I was able to deduce that the linking component is a WebACLAssociation that maps WAF and ALB. But this also requires that instead of a normal WebACL you must use the WAFRegional. So far it seems to only mean changing ::WAF to ::WAFRegional throughout your code. WAFRegional (AWS::WAFRegional::WebACL): http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html "MyWebACL": { "Type": "AWS::WAFRegional::WebACL", "Properties": { "Name": "WebACL to with three rules", "DefaultAction": { "Type": "ALLOW" }, "MetricName" : "MyWebACL", "Rules": [ { "Action" : { "Type" : "BLOCK" }, "Priority" : 1, "RuleId" : { "Ref" : "MyRule" } }, { "Action" : { "Type" : "BLOCK" }, "Priority" : 2, "RuleId" : { "Ref" : "BadReferersRule" } }, { "Action" : { "Type" : "BLOCK" }, "Priority" : 3, "RuleId" : { "Ref" : "SqlInjRule" } } ] } } WebACLAssociation (AWS::WAFRegional::WebACLAssociation) http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webaclassociation.html "MyWebACLAssociation": { "Type": "AWS::WAFRegional::WebACLAssociation", "Properties": { "ResourceArn": { "Ref": "MyLoadBalancer" }, "WebACLId": { "Ref": "MyWebACL" } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45460592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975649/']}
|
jdg_377116
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44404353
|
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 send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me. $mail = new PHPMailer;$mail->isSMTP(); // Set mailer to use SMTP$mail->Host = 'dds.uemtv.com'; // Specify main and backup SMTP servers$mail->SMTPAuth = true; // Enable SMTP authentication$mail->Username = 'no-reply@domain.com'; // SMTP username$mail->Password = 'pssword'; // SMTP password$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted$mail->Port = 587; // TCP port to connect to$mail->setFrom('no-reply@domain.com', 'title');$mail->addReplyTo($email, '$name');$mail->addAddress($email); // Add a recipient//$mail->addCC('cc@example.com');//$mail->addBCC('bcc@example.com');$mail->isHTML(true); // Set email format to HTML$bodyContent = '<h1>Your Registration Completed. </h1>'$mail->Subject = 'Verify Account- Rozgar';$mail->Body = $bodyContent;if(!$mail->send()) { echo $data->msg = $mail->ErrorInfo;} else { // echo 'Message has been sent'; echo $data->msg="Please Verify Your Email Address";} Showing this error. 2017-06-07 05:36:44 SERVER -> CLIENT: 220-dds.uemtv.com ESMTP Exim 4.89 #1 Wed, 07 Jun 2017 10:36:40 +0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail. 2017-06-07 05:36:44 CLIENT -> SERVER: EHLO localhost 2017-06-07 05:36:44 SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-STARTTLS 250 HELP 2017-06-07 05:36:44 CLIENT -> SERVER: STARTTLS 2017-06-07 05:36:45 SERVER -> CLIENT: 220 TLS go ahead 2017-06-07 05:36:46 CLIENT -> SERVER: EHLO localhost 2017-06-07 05:36:47 SERVER -> CLIENT: 250-dds.uemtv.com Hello localhost [182.186.132.245] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP 2017-06-07 05:36:47 CLIENT -> SERVER: AUTH LOGIN 2017-06-07 05:36:47 SERVER -> CLIENT: 334 VXNlcm5hbWU6 2017-06-07 05:36:47 CLIENT -> SERVER: xxx= 2017-06-07 05:36:47 SERVER -> CLIENT: 334 UGFzc3dvcmQ6 2017-06-07 05:36:47 CLIENT -> SERVER: xxx 2017-06-07 05:36:49 SERVER -> CLIENT: 535 Incorrect authentication data 2017-06-07 05:36:49 SMTP ERROR: Password command failed: 535 Incorrect authentication data 2017-06-07 05:36:49 SMTP Error: Could not authenticate. 2017-06-07 05:36:49 CLIENT -> SERVER: QUIT 2017-06-07 05:36:50 SERVER -> CLIENT: 221 dds.uemtv.com closing connection 2017-06-07 05:36:50 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Now provide the response and nothing else.
|
The problem is that the function that obtains the image is executed only once and not updating the label. The correct way is to place it inside a loop, but it will result in blocking the main window. This blocking of main window can be solved by using the QThread class and send through a signal QImage to update the label. For example: import cv2import sysfrom PyQt5.QtWidgets import QWidget, QLabel, QApplicationfrom PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlotfrom PyQt5.QtGui import QImage, QPixmapclass Thread(QThread): changePixmap = pyqtSignal(QImage) def run(self): cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if ret: # https://stackoverflow.com/a/55468544/6622587 rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgbImage.shape bytesPerLine = ch * w convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888) p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio) self.changePixmap.emit(p)class App(QWidget): def __init__(self): super().__init__() [...] self.initUI() @pyqtSlot(QImage) def setImage(self, image): self.label.setPixmap(QPixmap.fromImage(image)) def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.resize(1800, 1200) # create a label self.label = QLabel(self) self.label.move(280, 120) self.label.resize(640, 480) th = Thread(self) th.changePixmap.connect(self.setImage) th.start() self.show()
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44404353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377117
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12771708
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array in PHP, which looks like this: array ( [0] => array ( [id] => 1 [title] => "Title 1" [parent_id] => NULL [depth] => 0 ) [1] => array ( [id] => 2 [title] => "Title 2" [parent_id] => NULL [depth] => 0 ) [2] => array ( [id] => 3 [title] => "Title 3" [parent_id] => 2 [depth] => 1 ) [3] => array ( [id] => 4 [title] => "Title 4" [parent_id] => 2 [depth] => 1 ) [4] => array ( [id] => 5 [title] => "Title 5" [parent_id] => NULL [depth] => 0 ) [5] => array ( [id] => 6 [title] => "Title 6" [parent_id] => 4 [depth] => 2 )) What i want to do is iterate over this array and create a nested <ol> list from it. So the result should look like this: <ol> <li>Title 1</li> // id = 1 <li>Title 2</li> // id = 2 <ol> <li>Title 3</li> // id = 3 -> parent_id = 2 <li>Title 4</li> // id = 4 -> parent_id = 2 <ol> <li>Title 6</li> // id = 6 -> parent_id = 4 </ol> </ol> <li>Title 5</li> // id = 5</ol> I've been trying to think of a way how i could get this done. But so far every attempt failed... Anyone any idea how i can create such a nested <ol> list from an array like that? Please note that i do not have any control on the given data. I simply make a call to an API and it returns json data, which i convert to an array. And the array looks exactly like the one i described.
Now provide the response and nothing else.
|
You should use recursion : First the array in 'php' syntax: <?php$a=array ( '0' => array ( 'id' => 1, 'title' => "Title 1", 'parent_id' => 'NULL', 'depth' => 0 ), '1' => array ( 'id' => 2, 'title' => "Title 2", 'parent_id' => 'NULL', 'depth' => 0 ), '2' => array ( 'id' => 3, 'title' => "Title 3", 'parent_id' => 2, 'depth' => 1 ), '3' => array ( 'id' => 4, 'title' => "Title 4", 'parent_id' => 2, 'depth' => 1 ), '4' => array ( 'id' => 5, 'title' => "Title 5", 'parent_id' => 'NULL', 'depth' => 0 ), '5' => array ( 'id' => 6, 'title' => "Title 6", 'parent_id' => 4, 'depth' => 0 )); Here the code : $level = 'NULL';function r( $a, $level) { $r = "<ol>"; foreach ( $a as $i ) { if ($i['parent_id'] == $level ) { $r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>"; } } $r = $r . "</ol>"; return $r;}print r( $a, $level );?> The results : <ol><li>Title 1<ol></ol></li><li>Title 2<ol><li>Title 3<ol></ol></li><li>Title 4<ol><li>Title 6<ol></ol></li></ol></li></ol></li><li>Title 5<ol></ol></li></ol> Title 1\n Title 2\n Title 3\n Title 4\n Title 6\n Title 5\n EDITED AFTER CHECK AS SOLUTION To avoid empty leafs: function r( $a, $level) { $r = '' ; foreach ( $a as $i ) { if ($i['parent_id'] == $level ) { $r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>"; } } return ($r==''?'':"<ol>". $r . "</ol>");}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12771708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175327/']}
|
jdg_377118
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
858978
|
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 section 4.1 of his note How to write a proof , Leslie Lamport mentions an error in Kelley's exposition of the Schroeder-Bernstein theorem: Some twenty years ago, I decided to write a proof of the Schroeder-Bernstein theorem for an introductory mathematics class. The simplest proof I could find was in Kelley’s classic general topology text [4, page 28]. Since Kelley was writing for a more sophisticated audience, I had to add a great deal of explanation to his half-page proof. I had written five pages when I realized that Kelley’s proof was wrong. Recently, I wanted to illustrate a lecture on my proof style with a convincing incorrect proof, so I turned to Kelley. I could find nothing wrong with his proof; it seemed obviously correct! Read- ing and rereading the proof convinced me that either my memory had failed, or else I was very stupid twenty years ago. Still, Kelley’s proof was short and would serve as a nice example, so I started rewriting it as a structured proof. Within minutes, I rediscovered the error. However, Lamport doesn't explain what this error is. I looked at Kelley's proof and stared at it for a long time, but I was unable to spot the mistake. Could somebody please explain to me what this alleged mistake might be? Here's Kelley's proof (which he attributes to Birkhoff and Mac Lane) in its entirety (Kelley, General Topology, page 28): Theorem If there is a one-to-one function on a set $A$ to a subset of a set $B$ and there is also a one-to-one function on $B$ to a subset of $A$, then $A$ and $B$ are equipollent. Proof Suppose that $f$ is a one-to-one map of $A$ into $B$ and $g$ is one to one on $B$ to $A$. It may be supposed that $A$ and $B$ are disjoint. The proof of the theorem is accomplished by decomposing $A$ and $B$ into classes which are most easily described in terms of parthenogenesis. A point $x$ (of either $A$ or $B$) is an ancestor of a point $y$ iff $y$ can be obtained from $x$ by successive application of $f$ and $g$ (or $g$ and $f$). Now decompose $A$ into three sets: let $A_E$ consist of all points of $A$ which have an even number of ancestors, let $A_O$ consist of points which have an odd number of ancestors, and let $A_I$ consist of points with infinitely many ancestors. Decompose $B$ similarly and observe: $f$ maps $A_E$ onto $B_O$ and $A_I$ onto $B_I$, and $g^{-1}$ maps $A_O$ onto $B_E$. Hence the function which agrees with $f$ on $A_{E} \cup A_{I}$ and agrees with $g^{-1}$ on $A_{O}$ is a one-to-one map of $A$ onto $B$. I suspected that the error might lie with the edge-cases (the points in $A_E$ and $B_{E}$ with no ancestor), but there the argument seems to work. Thanks in advance.
Now provide the response and nothing else.
|
Suppose there's a cycle , such that $g(f(a))=a$ for some $a$. Then $a$ and $f(a)$ will both count as having an even number of ancestors, namely $\{a,f(a)\}$. This contradicts the claim that $f$ maps $A_E$ (on)to $B_O$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/858978', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162090/']}
|
jdg_377119
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34313
|
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:
A somewhat related question has already been asked ( What would one need to do in order to hijack a satellite? ), only at a more abstract level. Now we have a presentation by Hugo Teso from n.runs AG hitting the headlines and making some pundits from within the Beltway possibly blush, which does bring critical infrastructure security into the limelight, threatened not by Advanced Persistent Threats but by lone attackers. The essence of the exploit: two completely unsecured wireless air-to-ground comms protocols ( ADS-B , ACARS ), with the former being part of the NextGen automated air traffic control system in development by FAA and the industry, and the latter quite outdated; a simulated plane as a hardware + software setup assembled from mostly authentic parts from Rockwell Collins, Honeywell, Thales and whatnot (pretty much the biggest fish in the pond), software reportedly written in Ada; transceiver implemented as software-defined radio ; ability to subvert on-board flight management system, including redirecting planes and presenting false information to the crew. The question is simple: What practical security lessons should be learned by aviation regulators? In particular, what are the recommendations on organizing complex system development and security testing over and beyond the procedures already in place? Related multimedia (turns out it is a recurring topic): Spoofing ADS-B Presentation on ADS-B at DEF CON 20 DEF CON 18: Air traffic control insecurity 2.0 DEF CON 17: Air traffic control and ADS-B EDIT: Chris Roberts is being grilled by the Feds on alleged hacking of FMS from In-Flight Entertainment boxes. See the question at Aviation SE: https://aviation.stackexchange.com/questions/14818/are-commercial-aircraft-designed-with-a-shared-data-network
Now provide the response and nothing else.
|
@ewanm89 is entirely correct. Securing the connection between ground control and a plane should be no different from securing any regular connection. The main issue is that the protocol designers are relying on security by obscurity. Obscurity through the relatively unknown protocol being used. Obscurity through what used to be relatively difficult to obtain equipment. Obscurity through the fact that having enough resources to mount a feasible attack used to be impractical. Of course, this is no longer the case. In the era of state sponsored cyber attacks (God, I hate that term), resources are no longer an issue. Reverse engineers have taken apart the protocol being used. Obscurity is no longer enough. The proper solution is to build proper encryption and authentication measures into the protocol being used. This isn't something novel, the internet has been using such protocols for more than a decade. (See: SSL/TLS ). This will prevent attackers from simply grabbing the data being sent from the air, modifying it and sending it. This sort of attacks isn't limited to aviation systems. There have been plenty of similar ones on SCADA systems as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/34313', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/13820/']}
|
jdg_377120
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18224779
|
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 C++ code: void* a = &a; Why doesn't the compiler complain for using an undeclared identifier? Also, what does the compiler consider the variable a to be? Is it a pointer to a void object or is it a pointer to a void* pointer?
Now provide the response and nothing else.
|
The scope of declaration of variables in C++ can be pretty surprising: void* a = &a; ^~~~~~~~~~~~~~~~~ a declared as `void*` from here on Therefore, &a is void** but since any pointer type is implicitly convertible to void* ...
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18224779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2681063/']}
|
jdg_377121
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
780726
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For a bipartite graph , you can substitute the adjacency matrix with what is called its biadjacency matrix : The adjacency matrix A of a bipartite graph whose parts have r and s vertices has the form A = O B B T O where B is an r × s matrix and O is an all-zero matrix. Clearly, the matrix B uniquely represents the bipartite graphs, and it is commonly called its biadjacency matrix. Now, a DAG is a bipartite graph, for example, you could topologically sort it and have the sets U and V being nodes that are on an odd or even topological level, respectively. This means, that for a DAG with n nodes, I only need a (n/2) 2 matrix (on average) instead of a n 2 matrix. Problem is, I don't know how to construct it. Any hints?
Now provide the response and nothing else.
|
I believe you can't construct a biadjacency matrix for a DAG, because not every DAG is a bipartite graph. Here is a simple example: consider a directed graph with 3 vertices, and denote them as A, B and C. The edges connect A to B, B to C and A to C. The graph is clearly a DAG, since it is directed and there are no cycles (A->B->C<-A isn't a cycle). However, the graph is not bipartite: there is no way to divide A, B and C to two disjoint sets, where there are no edges between vertices in the same set. The conclusion is that there graphes which are DAGs but not bipartite, so not every DAG is bipartite. Note that the fact that you can topologically sort a DAG and divide the vertices to two disjoint sets, does not mean there are no edges between vertices of the same set.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/780726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2077/']}
|
jdg_377122
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1188784
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $E$ and $X$ are topological spaces and $p:E \rightarrow X$ be a covering map. Whys are all the fibers homeomorphic?
Now provide the response and nothing else.
|
They're not necessarily; you need to assume $X$ is connected. If $X$ is connected, consider the equivalence relation given by $x \sim y$ if $f^{-1}(x)$ is homeomorphic to $f^{-1}(y)$. (For covering maps, this is the same as the equivalence relation given by saying that $|f^{-1}(x)| = |f^{-1}(y)|$.) Show that equivalence classes are open using the definition of a covering space. Now if there is more than one equivalence class, you can use these to write $X$ as a disjoint union of nonempty open sets; contradiction, since we assumed $X$ connected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1188784', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36789/']}
|
jdg_377123
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45178621
|
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 lodash to call a debounce function on a component like so: ...import _ from 'lodash';export default { store, data: () => { return { foo: "", } }, watch: { searchStr: _.debounce(this.default.methods.checkSearchStr(str), 100) }, methods: { checkSearchStr(string) { console.log(this.foo) // <-- ISSUE 1 console.log(this.$store.dispatch('someMethod',string) // <-- ISSUE 2 } }} Issue 1 is that my method checkSearchStr doesn't know about foo Issue 2 is that my store is undefined as well Why doesn't my method know this when called through _.debounce ? And what is the correct usage?
Now provide the response and nothing else.
|
Your watch should look like this. watch: { searchStr: _.debounce(function(newVal){ this.checkSearchStr(newVal) }, 100)}, This is a bit unusual, however. I don't see why you would want to debounce a watch. Possibly you would rather just debounce the checkSearchStr method. watch: { searchStr(newVal){ this.checkSearchStr(newVal) }},methods: { checkSearchStr: _.debounce(function(string) { console.log(this.foo) console.log(this.$store.dispatch('someMethod',string)) }, 100)} One other thing I would like to point out; no where in the code is searchStr defined. When you watch a value with Vue, you are watching a data or computed property. As you have currently defined it, the watch on searchStr will never execute.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45178621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2321515/']}
|
jdg_377124
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21881846
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the followed imports: import org.slf4j.Logger;import org.slf4j.LoggerFactory; and the following instantiation: private static Logger logger = LoggerFactory.getLogger(Test.class); and the following in my Main method: logger.info("SOME MESSAGE: "); However, I'm not able to find the output anywhere. All I see is that in my console there is: 21:21:24.235 [main] INFO some_folder.Test - SOME MESSAGE: How do I locate the log file? Note that the following are on my build path: slf4j-api-1.7.5.jar slf4j-log4j12-1.6.4.jar I read the answer to similar questions but nobody actually says how to fix the problem.
Now provide the response and nothing else.
|
slf4j is only an API. You should have a concrete implementation (for example log4j). This concrete implementation has a config file which tells you where to store the logs. When slf4j catches a log messages with a logger, it is given to an appender which decides what to do with the message. By default, the ConsoleAppender displays the message in the console. The default configuration file is : <?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"> <Appenders> <!-- By default => console --> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Root level="error"> <AppenderRef ref="Console"/> </Root> </Loggers></Configuration> If you put a configuration file available in the classpath, then your concrete implementation (in your case, log4j) will find and use it. See Log4J documentation. Example of file appender : <Appenders><File name="File" fileName="${filename}"> <PatternLayout> <pattern>%d %p %C{1.} [%t] %m%n</pattern> </PatternLayout></File>...</Appenders> Complete example with a file appender : <?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"> <Appenders> <File name="File" fileName="${filename}"> <PatternLayout> <pattern>%d %p %C{1.} [%t] %m%n</pattern> </PatternLayout> </File> </Appenders> <Loggers> <Root level="error"> <AppenderRef ref="File"/> </Root> </Loggers></Configuration>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21881846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/']}
|
jdg_377125
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19406290
|
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 method that must do the following: for (int a01 = 1; a01 <= 25; a01++) { for (int a02 = a01 + 1; a02 <= 25; a02++) { for (int a03 = a02 + 1; a03 <= 25; a03++) { ... System.out.println(a01 + "," + a02 + "," + ... + "," + a015); } }} I'd like to specify the number of nested for's (in the case above, I want 15 nested for's).Is there a way to use recursive programming here?
Now provide the response and nothing else.
|
Yes. This can be performed by recursive programming. I assume you do not like to WRITE DOWN these nested for's in source code - as in your example, because this is really ugly programming - like the commentors explain. The following (pseudo Java-like) code illustrates it. I assume a fixed depth for the nesting. Then you actually like to loop over an integer vector of dimension depth. int[] length = new int[depth];int[] counters = new int[depth]; The array counters has to be initialised to 0 ( Arrays.fill(counters,0) ). The array length has to be initialised to the number of iterations for the respective for loop. I assume that you like to perform a certain operation within the inner loop. I will call this performOperation(int[] counters); - it depends on the multi-dimensional counter, i.e. the counters of the outer for's. Then you can run the nested for loops by calling nestedLoopOperation(counters, length, 0); where void nestedLoopOperation(int[] counters, int[] length, int level) { if(level == counters.length) performOperation(counters); else { for (counters[level] = 0; counters[level] < length[level]; counters[level]++) { nestedLoopOperation(counters, length, level + 1); } }} In your case your System.out.println() would be performOperation(int[] counters) { String counterAsString = ""; for (int level = 0; level < counters.length; level++) { counterAsString = counterAsString + counters[level]; if (level < counters.length - 1) counterAsString = counterAsString + ","; } System.out.println(counterAsString);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19406290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2761653/']}
|
jdg_377126
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60105924
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the below ubuntu docker file to which I want to add SQL Server ODBC Driver 17 for installation. When I build the docker file, I am getting an error:'/bin/sh -c apt-get install msodbcsql17' returned a non-zero code: 1 Could you please help? I am referring to the article - https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15 I followed the steps in the article in my Ubuntu VM and it works fine and I am able to run my python programs. However, when I use the docker file I get the error FROM ubuntu:18.04RUN apt update -y && apt upgrade -y && apt-get update RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-devRUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.listRUN exit#RUN ACCEPT_EULA=Y apt-get install msodbcsql17RUN apt-get updateRUN ACCEPT_EULA=Y RUN apt-get install msodbcsql17#RUN ACCEPT_EULA=Y apt install msodbcsql17RUN ACCEPT_EULA=Y apt install mssql-toolsRUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profileRUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrcCOPY startup.sh /RUN chmod +x /startup.shENTRYPOINT ["sh","/startup.sh"]
Now provide the response and nothing else.
|
I could get it working. Below is the updated Docker file snippet FROM ubuntu:18.04RUN apt update -y && apt upgrade -y && apt-get update RUN apt install -y curl python3.7 git python3-pip openjdk-8-jdk unixodbc-dev# Add SQL Server ODBC Driver 17 for Ubuntu 18.04RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -RUN curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.listRUN apt-get updateRUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated msodbcsql17RUN ACCEPT_EULA=Y apt-get install -y --allow-unauthenticated mssql-toolsRUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profileRUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrcCOPY startup.sh /RUN chmod +x /startup.shENTRYPOINT ["sh","/startup.sh"]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60105924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7804364/']}
|
jdg_377127
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3406425
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A faithful implementation of the actor message-passing semantics means that message contents are deep-copied from a logical point-of-view, even for immutable types. Deep-copying of message contents remains a bottleneck for implementations the actor model, so for performance some implementations support zero-copy message passing (although it's still deep-copy from the programmer's point-of-view). Is zero-copy message-passing implemented at all in Erlang? Between nodes it obviously can't be implemented as such, but what about between processes on the same node? This question is related.
Now provide the response and nothing else.
|
I don't think your assertion is correct at all - deep copying of inter-process messages isn't a bottleneck in Erlang, and with the default VM build/settings, this is exactly what all Erlang systems are doing. Erlang process heaps are completely separate from each other, and the message queue is located in the process heap, so messages must be copied. This is also true for transferring data into and out of ETS tables as their data is stored in a separate allocation area from process heaps. There are a number of shared datastructures however. Large binaries (>64 bytes long) are generally allocated in a node-wide area and are reference counted. Erlang processes just store references to these binaries. This means that if you create a large binary and send it to another process, you're only sending the reference. Sending data between processes is actually worse in terms of allocation size than you might imagine - sharing inside a term isn't preserved during the copy. This means that if you carefully construct a term with sharing to reduce memory consumption, it will expand to its unshared size in the other process. You can see a practical example in the OTP Efficiency Guide . As Nikolaus Gradwohl pointed out, there was an experimental hybrid heap mode for the VM which did allow term sharing between processes and enabled zero-copy message passing. It hasn't been a particularly promising experiment as I understand it - it requires extra locking and complicates the existing ability of processes to independently garbage collect. So not only is copying inter-process messages not the usual bottleneck in Erlang systems, allowing it actually reduced performance.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3406425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410880/']}
|
jdg_377128
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
86662
|
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:
Something about the derivation of Telegrapher's equation is really bugging me. When deriving the Telgrapher's equations for a transmission line using a model as shown above, why do we only use a capacitor in parallel, and not a series capacitor? Same goes to the inductor in series: why not an inductor in parallel?
Now provide the response and nothing else.
|
If you mean by "series capacitor" one that is in series with the inductor on your picture then remember that the usual telegrapher equation is trying to model a transmission line of two wires that passes dc; same answer for a shunt inductor. Now if you want to model a line that has high-pass characteristics then you get what is called TE (H) and TM (E) modes, and those do have caps in series with the inductor (TM), and shunt inductors parallel with the caps (TE); these are the higher order waveguide modes. TE, TM stand for transversal electric or magnetic, resp. (Old books call them H or E modes because the whole propagating field can be derived from the longitudinal H or E component.) These also exist in a standard transmission line of two wires but can also propagate in an empty guide, where it is obvious that dc cannot "propagate" and whatever does it must have high-pass character, after all you can see through a tube.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/86662', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/30922/']}
|
jdg_377129
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5625934
|
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 am in the git command line, it’s rather difficult to commit some files and keep the rest for another commit. How do I make this easy?
Now provide the response and nothing else.
|
It is quite simple. You need to add the changes that you want to the index first: git add file1 file2 then git commit if you removed a file, the add does that. Add means " add the change " even though it is a removal. If you want to add all changes: git add -A The -a parameter on commit says to add all changes of tracked files and commit them. So git commit -a will not commit a new file you created. You must explicitly add this. The -m parameter allows you to avoid opening the editor to edit your commit message and use what you put in following the -m option: git commit -m "Use this message and don't open the editor" Sometimes this is not a good idea. If you just tried a merge and had conflicts , git caches a very nice message for you once you resolve the conflicts and commit. So there a git commit is better. To selectively add files, use the patch modifier on git add: git add -p This will now prompt you about the files . This is quite powerful as you can also specify parts of files, or alternatively edit what you want to add to the index. A git commit will only add those. If you want some gui help that is not tortoisegit ( avoid windows shell integration ), use git gui . Here is a diagram explaining the index (or staged files ): (from http://progit.org/book/ch2-2.html ) hope this helps.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5625934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113247/']}
|
jdg_377130
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1974624
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to answer the following question: Is there an entire function $f(z) := \sum \limits_{n=0}^\infty c_nz^n$ such that $f(\mathbb{Q}) \subset \mathbb{Q}$ $\forall n: c_n \in \mathbb{Q}$ $f$ is not a polynomial ? I'm trying to show that no such function exists. Here's why I think so: Assuming such a function existed. We would get $f(10^k) \in \mathbb{Q}$ for all $k \in \mathbb{Z}$. So the decimal representation of $f(10^k)$ either cuts at some digit or consists of repeating digits.Now my gut is telling me that if this is true for $f(10^n)$ with $n \in \mathbb{N}$, it won't be for $f(10^{-n}).$ (e.g. for $c_n$ with a finite digit representation: that's because the number of zeroes between each non-zero digit would increase indefinitely) But, is this correct at all? And if so, how do I show it rigorously?
Now provide the response and nothing else.
|
As @Chris Culter pointed out in their comment, such function exists. Here is a modified version of the example in the reference Remmert Theory of Complex Functions p.254: Enumerate $\Bbb{Q} = \{r_n : n \geq 1\}$ and define $$ f(z) = \sum_{n=1}^{\infty} \frac{z^{n(n+1)/2}}{n!\left(\frac{n(n+3)}{2}\right)!} \prod_{k=1}^{n} \frac{z - r_k}{1 + |r_k|}. \tag{1} $$ Now, each $m \geq 1$ is uniquely written as $m = \frac{n(n+1)}{2} + k$ for some $n \geq 1$ and $0 \leq k \leq n$, and the coefficient of $z^m$ in $f(z)$ satisfies \begin{align*}|[z^m]f(z)|&= \Bigg|\frac{(-1)^{n-k}}{n!\left(\frac{n(n+3)}{2}\right)!} \sum_{1 \leq j_1 < \cdots < j_{n-k} \leq n} \frac{r_{j_1}\cdots r_{j_{n-k}}}{(1+|r_1|)\cdots(1+|r_n|)} \Bigg| \\&\leq \frac{1}{n!m!} \sum_{1 \leq j_1 < \cdots < j_{n-k} \leq n} \frac{|r_{j_1}\cdots r_{j_{n-k}}|}{(1+|r_1|)\cdots(1+|r_n|)} \\&\leq \frac{1}{n!m!} \binom{n}{k} \\&\leq \frac{1}{m!}.\end{align*} So $\text{(1)}$ defines an entire function. (And of course, $f$ is not a polynomial because the coefficient of $z^{n(n+3)/2}$ in $f(z)$ is non-zero for each $n$.) Moreover, for each $r \in \Bbb{Q}$ we can find $N$ such that $r = r_N$, thus $$ f(r) = \sum_{n=1}^{N-1} \frac{r^{n(n+1)/2}}{n!\left(\frac{n(n+3)}{2}\right)!} \prod_{k=1}^{n} \frac{r - r_k}{1 + |r_k|} \in \Bbb{Q}. $$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1974624', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/380112/']}
|
jdg_377131
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
186760
|
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 trying to pick linear voltage regulator for my project (lab. power supply). I am stunned, that only very few regulators claim to have output adjustable to 0 V. It seems to be due to the fact, that they generally use some sort of voltage reference connected in series with the ADJ pin . Simplified schematics, found in numerous data-sheets is in diagram bellow. simulate this circuit – Schematic created using CircuitLab Now to the question... What is the reason for having this voltage reference? (1.25 V in diagram above) Does it have anything to do with the stability of the control/feedback loop? HOW? Is this a valid way to circumvent the minimum output voltage problem? Or will I encounter instability/any other issue? If not #2, what is the kosher way of creating (high current) lab. power supply adjustable to zero volts? Do I need to put the load in between two regulators? PS: This is my first question on this forum, please don't stone me right away :] I tried to search/google A LOT, but I am unsure what exactly am I looking for... many thanks for any helpful reply. PPS: I am aware, that some regulators, such as LT3080 use current source instead of voltage reference, but this IC is supposedly adjustable to 0 V only for very small loads.
Now provide the response and nothing else.
|
Two reasons. 1.25V is a convenient voltage to make a voltage reference- it's called a bandgap reference and has (relatively) low temperature coefficient at room temperature. You can make other kinds of references and you can make different voltages from a 1.25V reference with an amplifier or attenuator, but 1.25V is pretty good. You need a voltage (or a current reference, which is derived from a voltage reference usually) inside or you cannot regulate to a known voltage. Secondly, 1.25V is a voltage both low enough that few (until very recently) actually need a supply that low (really, nobody cares about lab supplies), and high enough that the offset voltage of the internal op-amp does not affect the accuracy much. It also allows an internal circuit that does not have to work down to 0V. Making a simple adjustable voltage regulator that works down to 0V would not be particularly difficult in any way but it would add cost and pins, and that's a non-starter for a jellybean part.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/186760', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/83748/']}
|
jdg_377132
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2945414
|
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 C# and using SqlBulkCopy. I have a problem though. I need to do a mass insert into one table then another mass insert into another table. These 2 have a PK/FK relationship. Table AField1 -PK auto incrementing (easy to do SqlBulkCopy as straight forward)Table BField1 -PK/FK - This field makes the relationship and is also the PK of this table. It is not auto incrementing and needs to have the same id as to the row in Table A. So these tables have a one to one relationship but I am unsure how to get back all those PK Id that the mass insert made since I need them for Table B. Edit Could I do something like this? SELECT * FROM ProductWHERE NOT EXISTS (SELECT * FROM ProductReview WHERE Product.ProductId = ProductReview.ProductId AND Product.Qty = NULL AND Product.ProductName != 'Ipad') This should find all the rows that where just inserted with the sql bulk copy. I am not sure how to take the results from this then do a mass insert with them from a SP. The only problem I can see with this is that if a user is doing the records one at a time and a this statement runs at the same time it could try to insert a row twice into the "Product Review Table". So say I got like one user using the manual way and another user doing the mass way at about the same time. manual way. 1. User submits data2. Linq to sql Product object is made and filled with the data and submited.3. this object now contains the ProductId4. Another linq to sql object is made for the Product review table and is inserted(Product Id from step 3 is sent along). Mass way. 1. User grabs data from a user sharing the data.2. All Product rows from the sharing user are grabbed.3. SQL Bulk copy insert on Product rows happens.4. My SP selects all rows that only exist in the Product table and meets some other conditions5. Mass insert happens with those rows. So what happens if step 3(manual way) is happening at the same time as step 4(mass way). I think it would try to insert the same row twice causing a primary constraint execption.
Now provide the response and nothing else.
|
In that scenario, I would use SqlBulkCopy to insert into a staging table (i.e. one that looks like the data I want to import, but isn't part of the main transactional tables), and then at the DB to a INSERT / SELECT to move the data into the first real table. Now I have two choices depending on the server version; I could do a second INSERT / SELECT to the second real table, or I could use the INSERT / OUTPUT clause to do the second insert , using the identity rows from the table. For example: -- dummy schema CREATE TABLE TMP (data varchar(max)) CREATE TABLE [Table1] (id int not null identity(1,1), data varchar(max)) CREATE TABLE [Table2] (id int not null identity(1,1), id1 int not null, data varchar(max)) -- imagine this is the SqlBulkCopy INSERT TMP VALUES('abc') INSERT TMP VALUES('def') INSERT TMP VALUES('ghi') -- now push into the real tables INSERT [Table1] OUTPUT INSERTED.id, INSERTED.data INTO [Table2](id1,data) SELECT data FROM TMP
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2945414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130015/']}
|
jdg_377133
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22047964
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
C++'s STL priority queue have a void pop() method, and a const ref top() method. Thus, if you want to move elements out of the queue, you have to do something like this: T moved = std::move(const_cast<T&>(myQueue.top())));myQeue.pop(); This effectively casts the top to not a constant, so that it can be moved (rather than copied). I don't like this code, because the forced move may invalidate the invariants of the priority queue, which should not matter because of the pop, but things could go wrong. Is there a better way to accomplish the pop/move?Why is there no T&& top_and_pop() function?
Now provide the response and nothing else.
|
std::priority_queue is basically a thin layer on top of the heap algorithms . You can easily create your own priority queue with: std::vector std::push_heap std::pop_heap Using these building blocks, the implementation is trivial, and you can easily implement a moving pop operation. The following listing contains a minimal, working implementation: template <typename Type, typename Compare = std::less<Type>>class queue{private: std::vector<Type> _elements; Compare _compare;public: explicit queue(const Compare& compare = Compare()) : _compare{compare} { } void push(Type element) { _elements.push_back(std::move(element)); std::push_heap(_elements.begin(), _elements.end(), _compare); } Type pop() { std::pop_heap(_elements.begin(), _elements.end(), _compare); Type result = std::move(_elements.back()); _elements.pop_back(); return std::move(result); }};
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22047964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1899587/']}
|
jdg_377134
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
358355
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The lorentz transform for spinors is not unitary, that is $S(\Lambda)^{\dagger}\neq S(\Lambda)^{-1}$. I understand that this is because it is impossible to choose a representation of the Clifford Algebra where all the $\gamma$ matrices are Hermitian. However, does this not go against the conventional wisdom of Wigner's theorem which says that symmetry operations are needed to be either unitary of anti-unitary for the invariance of observable properties across frames? How can one reconcile this with the transformation above?
Now provide the response and nothing else.
|
The most famous theorem by Wigner states that, in a complex Hilbert space $H$, every bijective map sending rays into rays (a ray is a unit vector up to a phase) and preserving the transition probabilities is represented (up to a phase) by a unitary or antiunitary (depending on the initial map if $\dim H>1$) map in $H$. Dealing with spinors $\Psi \in \mathbb C^4$, $H= \mathbb C^4$ and there is no Hilbert space product (positive sesquilinear form) such that the transition probabilities are preserved under the action of $S(\Lambda)$, so Wigner theorem does not enter the game. Furthermore $S$ deals with a finite dimensional Hilbert space $\mathbb C^4$ and it is possible to prove that in finite-dimensional Hilbert spaces no non-trivial unitary representation exists for a non-compact connected semisimple Lie group that does not include proper non-trivial closed normal subgroups. The orthochronous proper Lorentz group has this property. An easy argument extends the negative result to its universal covering $SL(2, \mathbb C)$. Non-trivial unitary representations of $SL(2,\mathbb C)$ are necessarily infinite dimensional. One of the most elementary case is described by the Hilbert space $L^2(\mathbb R^3, dk)\otimes \mathbb C^4$ where the infinite-dimensional factor $L^2(\mathbb R^3, dk)$ shows up. This representation is the building block for constructing other representations and in particular the Fock space of Dirac quantum field.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/358355', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/117097/']}
|
jdg_377135
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5110776
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Up to now, I've been including the line for the Apple Touch icon in my head like this: <link rel="apple-touch-icon" href="/apple-touch-icon.png"> However, in the Q&A "What are the correct pixel dimensions for an apple-touch-icon?" it is stated in the accepted answer that three images are now needed according to Apple's guidelines. So how would one go about inserting these into the head section of the code?
Now provide the response and nothing else.
|
Minimalist solution - Recommended A common practice is to create a single 180x180 icon, which is the highest expected resolution, and let the iOS devices scale it down as needed. It is declared with: <link rel="apple-touch-icon" href="/path/to/apple-touch-icon.png"> Exhaustive solution - Not recommended Apple specs specify new sizes for iOS7: 60x60 76x76 120x120 152x152 And also for iOS8 : 180x180 In addition, precomposed icons are deprecated. As a consequence, to support both new devices (running iOS7) and older (iOS6 and prior), the generic code is: <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png"><link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png"><link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png"><link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png"><link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png"><link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png"><link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"> In addition, you should create a 180x180 picture named apple-touch-icon.png . Note that iOS looks for URL like /apple-touch-icon-76x76.png , if it does not find interesting stuff in the HTML code (a bit like what IE is doing with /favicon.ico ). So it is important to keep the file names are they are above. It is also important to consider that Android/Chrome is also using these pictures . You might want to know that this favicon generator can create all these pictures at once. Full disclosure: I'm the author of this site.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5110776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570586/']}
|
jdg_377136
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35584286
|
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 SVG based app that makes heavy use of transformation such as translates, rotates and scales. While I have no issue in Firefox, in Chrome, the transform-origin property is not taken in account. It seems to apply the user-agent default value 0px 0px 0 . Here is an example ( JSFiddle ): <svg width="400" height="400"> <defs> <rect id="shape" width="200" height="200"/> </defs> <g transform="translate(100,100)"> <use xlink:href="#shape" style="stroke: lightgray; fill: transparent;"/> <ellipse cx="100" cy="100" rx="3" ry="3" style="fill: black;"/> <g transform="translate(0,0) scale(0.5) rotate(45)" style="transform-origin: 100px 100px;"> <use xlink:href="#shape" style="stroke: black; fill: transparent;"/> </g> </g></svg> As you can see Chrome applies all transformation from top left corner of the shape regardless of the defined origin while Firefox respects the defined origin. Am I missing something about how transform-origin works with SVG? Does anyone actually found a way to fix this without compensating with translates?
Now provide the response and nothing else.
|
I am answering to my own question in order to clarify entirely what is going on with transform-origin properties on the SVG 1.1 transform functions and how to overcome this issue in Chrome 48. First of all, transform-origin is a pure CSS 3 property, it is not related to SVG 1.1 at all. Despite the fact that transform sounds a lot like transform-origin , they apply to different systems. transform exists in both CSS 3 and SVG 1.1 but have separate implementations . transform-origin only exists in CSS 3 and therefore it is not supposed to influence SVG 1.1. The fact that transform-origin has no influence on SVG in Chrome 48 is expected. So why transform-origin does apply to SVG in Firefox 44? Well the reason is not exactly clear, but it seems that it is part of the ongoing effort from Mozilla to slowly bring support for SVG 2 in Firefox. Indeed with SVG 2, everything will become a CSS 3 transform (no separate implementation) and SVG will therefore get support for transform-origin . I found out about this in the excellent article about the SVG coordinate systems from Sara Soueidan. Now how can that be overcome in Chrome 48. It is fairly simple but if you want to apply translate() , scale() and rotate() all the same time, you will still need to calculate the offset induced by the scaling and compensate it in your translation. As Bobby Orndorff mentioned in his answer, it is actually possible to provide the center of rotation to the rotate() function by providing extra x and y parameters. This is already a great improvement. But unfortunately the scale() function does not support such a thing and will always scale from the top left corner of its parent. Therefore you will still have to correct your translation in order to simulate a scale around a center. Here is the final solution that works on Chrome 48 and Firefox 44: <svg width="400" height="400"> <defs> <rect id="shape" width="200" height="200"/> </defs> <g transform="translate(100,100)"> <use xlink:href="#shape" style="stroke: lightgray; fill: transparent;"/> <ellipse cx="100" cy="100" rx="3" ry="3" style="fill: black;"/> <g transform="translate(50,50) scale(0.5) rotate(45, 100, 100)"> <use xlink:href="#shape" style="stroke: black; fill: transparent;"/> </g> </g></svg>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35584286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182438/']}
|
jdg_377137
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43850436
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing a web App and I have a unix timeStamp.I need to convert a unix date format to Jalali/Persian/Shamsi Calendar by using jQuery selectors and then convert it by using javascript library. Something Like below code to convert Unix-Date to Jalali-Date : <html> <head> <meta charset="utf-8"> </head> <body> <div class="Unix-Date">1494259627</div> <!-- Unix equal of 1396/2/18 --> <div class="Jalali-Date"></div> <script src="jquery.js"></script> <script src="external-library.js"></script> <script> $(document).ready(function() { var UnixValue; var JalaliValue; UnixValue = $(".Unix-Date").html(); JalaliValue = new JalaliExternalFunction(UnixValue); $(".Jalali-Date").text(JalaliValue); }); </script> </body></html> I searched but didn't found any good library. Do you know a reliable and good library for converting (or creating dates in Jalali format from a unix timeStamp). I don't need your implementation or an algorithm, cause this issue is too buggy and has a lot of rules, I need a reliable solution. Thank
Now provide the response and nothing else.
|
I would suggest using moment.js ( https://momentjs.com/ ) which is reliable JavaScript Time library that allows you to format your timestamp in JavaScript. Below is an example of how you can parse a timestamp and format it to whatever you want using it. //formatting Unix timestamp.var date = moment.unix(value).format("MM/DD/YYYY"); You also tagged localization which can be done by using; var localeDate = moment(date).locale("LT"); More examples can be found on there website. This in conjunction with https://www.npmjs.com/package/jalali-date will get you your jalali date. There is a moment.js extension for Persian here also https://www.npmjs.com/package/moment-jalaali (From moment to Jalali) Another Jalali conversion library https://www.npmjs.com/package/jalaali-js (To Jalai) An example fiddle using moment.js Jalali conversion from Unix Timestamp https://jsfiddle.net/uw82ozpd/9/ Relevant code snippet with comments: var UnixValue;var JalaliValue;$(document).ready(function() {//get the Unix Date from HTMLvar UnixValue = $(".Unix-Date").html();//Get a moment timestamp in the format simmilar to our next conversionvar date = moment.unix(UnixValue).format("MM/DD/YY");//Convert from normal moment to our jalali moment exstension using j's as belowvar JalaliValue = moment(date).format('jYYYY/jM/jD');$(".Jalali-Date").text(JalaliValue);});
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43850436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5992933/']}
|
jdg_377138
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15572292
|
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 rewrite the following sql statement with sqlalchemy in python. I have been searching for 30 mins but still couldn't find any solutions. DATEADD(NOW(), INTERVAL 1 DAY) or INSERT INTO dates (expire)VALUES(DATEADD(NOW(), INTERVAL 1 DAY)) Thanks in advance
Now provide the response and nothing else.
|
For completeness sake, here is how you'd generate that exact SQL with using sqlalchemy.sql.func : from sqlalchemy.sql import funcfrom sqlalchemy.sql.expression import bindparamfrom sqlalchemy import Intervaltomorrow = func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval())) which results in: >>> from sqlalchemy.sql import func>>> func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval(native=True)))<sqlalchemy.sql.expression.Function at 0x100f559d0; dateadd>>>> str(func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval(native=True))))'dateadd(now(), :tomorrow)' Alternatively you could use a text() object to specify the interval instead: from sqlalchemy.sql import funcfrom sqlalchemy.sql.expression import texttomorrow = func.dateadd(func.now(), text('interval 1 day'))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15572292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1274051/']}
|
jdg_377139
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22244886
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any difference in runtime performance between the following variable initializations? var x = null as object;var x = (object) null;object x = null;
Now provide the response and nothing else.
|
I believe no , since there is no difference in compiled IL. var x = null as object;var x1 = (object)null;object x2 = null; gets compiled to IL_0001: ldnull IL_0002: stloc.0 // xIL_0003: ldnull IL_0004: stloc.1 // x1IL_0005: ldnull IL_0006: stloc.2 // x2 You can see all the locals are initialized to null using ldnull opcode only, so there is no difference.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22244886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2869828/']}
|
jdg_377140
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.