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
34539507
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 needed to change the data_scale of a decimal field implemented by the module "computed field".I changed the field_data_MYFIELD directly in database (from 10,2 to 10,4). I also modified the field_revision_MYFIELD the same way.As third step, I modified the data of the field_config by changing: FROM s:14:"data_precision";s:2:"10";s:10:"data_scale";s:1:"2"; TO s:14:"data_precision";s:2:"10";s:10:"data_scale";s:1:"4"; As I'm trying to clear caches with drush cc all, I get the following error: PHP Fatal error: Unsupported operand types in DRUPAL_SITE/modules/field/field.info.class.inc on line 495 The line 495 is: // Make sure all expected field settings are present.$field['settings'] += field_info_field_settings($field['type']); I enabled the error log in index.php and have the following errors: unserialize(): Error at offset 330 of 1314 bytes in DRUPAL_SITE/modules/field/field.crud.inc on line 374 Notice: Undefined index: settings in DRUPAL_SITE/sites/all/modules/computed_field/computed_field.install on line 13 Undefined index: settings in DRUPAL_SITE/modules/field/field.info.class.inc on line 495 Fatal error: Unsupported operand types in DRUPAL_SITE/modules/field/field.info.class.inc on line 495 What am I doing wrong? Now provide the response and nothing else.
There is unfortunate usage of the word "index" which means slightly (edit: VERY) different things in ES and relational databases as they are optimized for different use cases. An "index" in database is a secondary data structure which makes WHERE queries and JOIN s fast, and they typically store values exactly as they appear in the table. You can still have columns which aren't indexed, but then WHERE s require a full table scan which is slow on large tables. An "index" in ES is actually a schematic collection of documents, similar to a database in the relational world. You can have different "types" of documents in ES, quite similar to tables in dbs. ES gives you the flexibility of defining for each document's field whether you want to be able to retrieve it, search by it or both. Some details on these options can be found from for example here , also related to _source field (the original JSON which was submitted to ES). ES uses an inverted index to efficiently find matching documents, but most importantly it typically "normalizes" strings into tokens so that accurate free-text search can be performed. For example sentences might be splitted into individual words, words are normalized to lower case etc. so that searching for "holland" would match the text "Vacation at Holland 2015". If a field does not have an inverted index, you cannot perform any searching on it (unlike dbs' full table scan). Interestingly you can also define fields so that you can use them for searching but you cannot retrieve them back, it is mainly beneficial when minimizing in disk and RAM usage is important.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34539507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3365378/']}
jdg_87141
stackexchange
llm_judgeable_groundtruth_similarity
315937
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: When I have a lot of data that needs to be validated, should I create a new class for the sole purpose of validation or should I stick with in-method validation? My particular example contemplates a tournament and a event/category class: Tournament and Event , which models a sport tournament and each tournament has one or many categories. There are all sort of things to validate in these classes: the players should be empty, should be unique, the number of matches each player should play, the number of players each match has, predefined matchups, and a really big etcetera including much more complex rules. There are also some parts I need to validate as a whole, like how classes integrate with each other. For example, the unitary validation of a Player can be just fine, but if an event has the same player twice, that's a validation error. So how about this?: I forget about absolutely any pre-check when using my model classes' setters and similar methods to add data and instead I let validation classes handle that. So we will have something like EventValidator with an Event as a member, and a validate() method that validates the whole object, plus singular methods to validate all members' rules. Then, before instantiating a validable object, I will execute the validation to prevent illegal values. Is my design correct? Should I do something differently? Also, should I use boolean returning validation methods? Or just throw an exception if the validation fails? It seems to me the best option would be boolean returning methods and throw the exception when the object is instantianted, for example: public Event() { EventValidator eventValidator = new EventValidator(this); if (!eventValidator.validate()) { // show error messages with methods defined in the validator throw new Exception(); // what type of exception would be best? should I create custom ones? }} Now provide the response and nothing else.
It is OK to delegate any logic by means of composition if that logic is going to change dynamically during the execution of a program. Complex validations like the ones you explain are as good a candidate as any to be delegated to another class via composition. Remember though that validations can occur in different moments. Instantiating a concrete validator like in your example is a bad idea because it couples your Event class to that particular validator. Let's assume you are not using any DI framework. You can add the validator to the constructor, or inject it with a setter method. I suggest a creator method in a factory instantiates both the Event and the validator and then passes it either to the event constructor or with a setValidator method. Obviously a Validator interface and or abstract class should be writen so your classes depend on it and not on any concrete validator. Executing the validate method in the constructor can be problematic because all the state you want to validate may not be in place yet. I suggest that you creta a Validable interface and let your classes implement it, that interface could have a validate() method. That way the upper components of your application call the validate method at will (which in turn is delegated to the validator member). ==> IValidable.java <== import java.util.List;public interface IValidable { public void setValidator(IValidator<Event> validator_); public void validate() throws ValidationException; public List<String> getMessages();} ==> IValidator.java <== import java.util.List;public interface IValidator<T> { public boolean validate(T e); public List<String> getValidationMessages();} ==> Event.java <== import java.util.List;public class Event implements IValidable { private IValidator<Event> validator; @Override public void setValidator(IValidator<Event> validator_) { this.validator = validator_; } @Override public void validate() throws ValidationException { if (!this.validator.validate(this)){ throw new ValidationException("WTF!"); } } @Override public List<String> getMessages() { return this.validator.getValidationMessages(); }} ==> SimpleEventValidator.java <== import java.util.ArrayList;import java.util.List;public class SimpleEventValidator implements IValidator<Event> { private List<String> messages = new ArrayList<String>(); @Override public boolean validate(Event e) { // do validations here, by accessing the public getters of e // propulate list of messages is necessary // this example always returns false return false; } @Override public List<String> getValidationMessages() { return this.messages; }} ==> ValidationException.java <== public class ValidationException extends Exception { public ValidationException(String message) { super(message); } private static final long serialVersionUID = 1L;} ==> Test.java <== public class Test { public static void main (String args[]){ Event e = new Event(); IValidator<Event> v = new SimpleEventValidator(); e.setValidator(v); // set other thins to e like // e.setPlayers(player1,player2,player3) // e.setNumberOfMatches(3); // etc try { e.validate(); } catch (ValidationException e1) { System.out.println("Your event doesn't comply with the federation regulations for the following reasons: "); for (String s: e.getMessages()){ System.out.println(s); } } }}
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/315937', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/223143/']}
jdg_87142
stackexchange
llm_judgeable_groundtruth_similarity
280648
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'm confused about why we care about different representations for positive and negative zero. I vaguely recall reading claims that having a negative zero representation is extremely important in programming that involves complex numbers. I've never had the opportunity to write code involving complex numbers, so I'm a little baffled about why this would be the case. Wikipedia's article on the concept isn't especially helpful; it only makes vague claims about signed zero making certain mathematical operations simpler in floating point, if I understand correctly. This answer lists a couple of functions that behave differently, and perhaps something could be inferred from the examples if you're familiar with how they might be used. (Although, the particular example of the complex square roots looks flat out wrong , since the two numbers are mathematically equivalent, unless I have a misunderstanding.) But I have been unable to find a clear statement of the kind of trouble you would get into if it wasn't there. The more mathematical resources I've been able to find state that there is no distinguishing between the two from a mathematical perspective, and the Wikipedia article seems to suggest that this is rarely seen outside of computing aside from describing limits. So why is a negative zero valuable in computing? I'm sure I'm just missing something. Now provide the response and nothing else.
You need to keep in mind that in FPU arithmetics, 0 doesn't necessarily has to mean exactly zero, but also value too small to be represented using given datatype, e.g. a = -1 / 1000000000000000000.0 a is too small to be represented correctly by float (32 bit), so it is "rounded" to -0. Now, let's say our computation continues: b = 1 / a Because a is float, it will result in -infinity which is quite far from the correct answer of -1000000000000000000.0 Now let's compute b if there's no -0 (so a is rounded to +0): b = 1 / +0b = +infinity The result is wrong again because of rounding, but now it is "more wrong" - not only numerically, but more importantly because of different sign (result of computation is +infinity, correct result is -1000000000000000000.0). You could still say that it doesn't really matter as both are wrong. The important thing is that there are a lot of numerical applications where the most important result of the computation is the sign - e.g. when deciding whether to turn left or right at the crossroad using some machine learning algorithm, you can interpret positive value => turn left, negative value => turn right, actual "magnitude" of the value is just "confidence coefficient".
{}
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/280648', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/92517/']}
jdg_87143
stackexchange
llm_judgeable_groundtruth_similarity
53024267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm running a cluster of nodeJS applications - which should be very small as they are run as microservices. Only a few of them need extra things like bcrypt or imagemagick - which makes some trouble from time to time for me. Right now I'm using node:10.13-alpine as a base image for all Dockerfiles to build my apps. For some of them I need to add dependencies via apk and so on. So these images become bigger. Is it the best approach to use a alpine image, which gets bigger by adding needed packages (e.g. python, gcc...)? Or should I use a full image? If I would use node:10.13 , the base image would be a lot bigger, but if my understanding is correct my applications would only add a small layer as the same base image is used. So at the end it is better to use one big node image?? Now provide the response and nothing else.
Alpine images are smaller, since other packages using a lot of libraries, which are not used by your solution. What's are the benefits to use small images? The benefits are: less memory, better performance, security and maintainability. A smaller docker image reduce the size needed on disk, but disk space is cheap . Much more important is that it also consume less memory , which is limited on every server. If you reduce the amount of base images on your server, this also lead that you need less memory at all. Less memory means also you have less swapping and so you can get some performance improvements in having all base images loaded in memory. Another feature is, that base images from alpine using less depend libraries, which improve the overall security . You can separate risks easily, with your base alpine image and using on top images which only use the apk, which really needed. This has also advantages regarding the overall maintenance. You can see on https://hub.docker.com/r/library/node/tags/ , that the alpine version has no vulnerabilities. All other image version have some issues, which may target the security of your solution. Why the default is still "buildpack-deps" and why you maybe should use them? When you read the official documentation to the docker images for node: https://hub.docker.com/_/node/ Main takeaways are: You can use the normal image, since it is based on the "buildpack-deps", which is commonly used by a lot of images . Alpine images very small and reduce the amount of needed memory. Especially there is no other type of installation of the docker container. For me this means finally, that you can use the normal package in the most cases, if you use other images build on "buildpack-deps". It maybe possible to be the better solution, in this case since you don't have the need beside of the "buildpack-deps" to hold an "alpine" base image in on your disk and memory. Conclusion If you have "only" alpine images on your docker environment, then you should go with "alpine" or if the security of the "node" containers are really important to you. In most cases the "node" images based on "buildpack-deps" are suitable, since you have other docker containers based on "buildpack-deps". In future I assume more and more packages will be available based on "alpine" and then you should go with node-alpine.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53024267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3142695/']}
jdg_87144
stackexchange
llm_judgeable_groundtruth_similarity
9169052
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 a way in matplotlib to partially specify the color of a string? Example: plt.ylabel("Today is cloudy.") How can I show "today" as red, "is" as green and "cloudy." as blue? Now provide the response and nothing else.
I only know how to do this non-interactively, and even then only with the 'PS' backend. To do this, I would use Latex to format the text. Then I would include the 'color' package, and set your colors as you wish. Here is an example of doing this: import matplotlibmatplotlib.use('ps')from matplotlib import rcrc('text',usetex=True)rc('text.latex', preamble='\usepackage{color}')import matplotlib.pyplot as pltplt.figure()plt.ylabel(r'\textcolor{red}{Today} '+ r'\textcolor{green}{is} '+ r'\textcolor{blue}{cloudy.}')plt.savefig('test.ps') This results in (converted from ps to png using ImageMagick, so I could post it here):
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9169052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171173/']}
jdg_87145
stackexchange
llm_judgeable_groundtruth_similarity
319359
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am a beginner with make and I'm wondering about when to use make clean . One colleague told me that incremental builds with make are based on the files timestamps. So, if you checkout an old version of a file in your VCS, it'll have an "old" timestamp and it'll be marked as "no need to recompile this file". Then, that file wouldn't be included in the next build. According to that same colleague, it would be a reason to use make clean . Anyway, I roughly got the answer to the question "when to use make clean " from other StackExchange questions but my other question then is: Why do incremental builds using make rely on files timestamps and not on SHA-1 for example? Git, for instance, shows that we can successfully determine if a file was modified using the SHA-1. Is it for speed issues? Now provide the response and nothing else.
An obvious (and arguably superficial) problem would be that the build system would have to keep record of the hashes of the files that were used for the last build. While this problem could certainly be solved, it would require side storage when the time-stamp information is already present in the file-system. More seriously, though, the hash would not convey the same semantics. If you know that file T was built from dependency D with hash H 1 and then find out that D now hashes to H 2 , should you re-build T ? Probably yes, but it could also be that H 2 actually refers to an older version of the file. Time-stamps define an ordering while hashes are only comparable for equality. A feature that time-stamps support is that you can simply update the time-stamp (for example, using the POSIX command-line utility touch ) in order to trick make into thinking that a dependency has changed or – more interestingly – a target is more recent than it actually is. While playing with this is a great opportunity to shoot yourself into the foot, it is useful from time to time. In a hash-based system, you would need support from the build-system itself to update its internal database of hashes used for the last build without actually building anything. While an argument could certainly be made for using hashes over time-stamps, my point is that they are not a better solution to achieve the same goal but a different solution to achieve a different goal. Which of these goals is more desirable might be open to debate.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/319359', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/221314/']}
jdg_87146
stackexchange
llm_judgeable_groundtruth_similarity
468891
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: Nature article on reproducibility in science. According to that article, a (surprisingly) large number of experiments aren't reproducible, or at least there have been failed attempted reproductions. In one of the figures, it's said that 70% of scientists in physics & engineering have failed to reproduce someone else's results, and 50% have failed to reproduce their own. Clearly, if something cannot be reproduced, its veracity is called into question. Also clearly, because there's only one particle accelerator with the power of the LHC in the world, we aren't able to independently reproduce LHC results. In fact, because 50% of physics & engineering experiments aren't reproducible by the original scientists, one might expect there's a 50% chance that if the people who originally built the LHC built another LHC, they will not reach the same results. How, then, do we know that the LHC results (such as the discovery of the Higgs boson) are robust? Or do we not know the LHC results are robust, and are effectively proceeding on faith that they are? EDIT: As pointed out by Chris Hayes in the comments, I misinterpreted the Nature article. It says that 50% of physical scientists have failed to reproduce their own results, which is not the same statement as 50% of physics experiments aren't reproducible. This significantly eases the concern I had when I wrote the question. I'm leaving the question here however, because the core idea - how can we know the LHC's results are robust when we only have one LHC? - remains the same, and because innisfree wrote an excellent answer. Now provide the response and nothing else.
That's a really great question. The ' replication crisis ' is that many effects in social sciences (and, although to a lesser extent, other scientific fields) couldn't be reproduced. There are many factors leading to this phenomenon, including Weak standards of evidence, e.g., $2\sigma$ evidence required to demonstrate an effect Researchers (subconsciously or otherwise) conducting bad scientific practice by selectively reporting and publishing significant results. E.g. considering many different effects until they find a significant effect or collecting data until they find a significant effect. Poor training in statistical methods. I'm not entirely sure about the exact efforts that the LHC experiments are making to ensure that they don't suffer the same problems. But let me say some things that should at least put your mind at ease: Particle physics typically requires a high-standard of evidence for discoveries ( $5\sigma$ ). To put that into perspective, the corresponding type-1 error rates are $0.05$ for $2\sigma$ and about $3\times10^{-7}$ for $5\sigma$ The results from the LHC are already replicated! There are several detectors placed around the LHC ring. Two of them, called ATLAS and CMS, are general purpose detectors for Standard Model and Beyond the Standard Model physics. Both of them found compelling evidence for the Higgs boson. They are in principle completely independent (though in practice staff switch experiments, experimentalists from each experiment presumably talk and socialize with each other etc, so possibly a very small dependence in analysis choices etc). The Tevatron, a similar collider experiment in the USA operating at lower-energies, found direct evidence for the Higgs boson. The Higgs boson was observed in several datasets collected at the LHC The LHC (typically) publishes findings regardless of their statistical significance, i.e., significant results are not selectively reported. The LHC teams are guided by statistical committees, hopefully ensuring good practice The LHC is in principle committed to open data, which means a lot of the data should at some point become public. This is one recommendation for helping the crisis in social sciences. Typical training for experimentalists at the LHC includes basic statistics (although in my experience LHC experimentalits are still subject to the same traps and misinterpretations as everyone else). All members (thousands) of the experimental teams are authors on the papers. The incentive for bad practices such as $p$ -hacking is presumably slightly lowered, as you cannot 'discover' a new effect and publish it only under your own name, and have improved job/grant prospects. This incentive might be a factor in the replication crisis in social sciences. All papers are subject to internal review (which I understand to be quite rigorous) as well as external review by a journal LHC analyses are often (I'm not sure who plans or decides this) blinded. This means that the experimentalists cannot tweak the analyses depending on the result. They are 'blind' to the result, make their choices, then unblind it only at the end. This should help prevent $p$ -hacking LHC analysis typically (though not always) report a global $p$ -value, which has beeen corrected for multiple comparisons (the look-elsewhere effect). The Higgs boson (or similar new physics) was theoretically required due to a 'no-lose' theorem about the breakdown of models without a Higgs at LHC energies, so we can be even more confident that it is a genuine effect. The other new effects that are being searched for at the LHC, however, arguably aren't as well motivated, so this doesn't apply to them. E.g., there was no a priori motivation for a 750 GeV resonanace that was hinted at in data but ultimately disappeared. If anything, there is a suspicion that the practices at the LHC might even result in the opposite of the 'replication crisis;' analyses that find effects that are somewhat significant might be examined and tweaked until they decrease . In this paper it was argued this was the case for SUSY searches in run-1.
{}
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/468891', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/177855/']}
jdg_87147
stackexchange
llm_judgeable_groundtruth_similarity
55983397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code class Foo: i = 1 # initialization def __init__(self): self.i += 1t = Foo()print(t.i) When exactly does the initialization of i take place? Before the execution of the init method or after it? Now provide the response and nothing else.
Before. The __init__ method isn't run until Foo is instantiated. i=1 is run whenever the class definition is encountered in the code You can see this by adding print statements: print('Before Foo')class Foo: i = 1 print(f'Foo.i is now {i}') def __init__(self): print('Inside __init__') self.i += 1 print(f'i is now {self.i}')print('After Foo')print('Before __init__')foo = Foo()print('After __init__') which prints: Before FooFoo.i is now 1After FooBefore __init__Inside __init__i is now 2After __init__ Notice however, that your self.i += 1 does not modify the class attribute Foo.i . foo.i # This is 2Foo.i # This is 1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55983397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10738638/']}
jdg_87148
stackexchange
llm_judgeable_groundtruth_similarity
64927
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: In order to get coloured output from all git commands, I set the following: git config --global color.ui true However, this produces an output like this for git diff , git log whereas commands like git status display fine Why is it not recognizing the escaped color codes in only some of the commands and how can I fix it? I'm using iTerm 2 (terminal type xterm-256color ) on OS X 10.8.2 and zsh as my shell zsh --versionzsh 5.0.0 (x86_64-apple-darwin12.0.0)git --version git version 1.7.9.6 (Apple Git-31.1) Now provide the response and nothing else.
You're seeing the escape sequences that tell the terminal to change colors displayed with the escape character shown as ESC , whereas the desired behavior would be that the escape sequences have their intended effect. Commands such as git diff and git log pipe their output into a pager , less by default. Git tries to tell less to allow control characters to have their control effect, but this isn't working for you. If less is your pager but you have the environment variable LESS set to a value that doesn't include -r or -R , git is unable to tell less to display colors. It normally passes LESS=-FRSX , but not if LESS is already set in the environment. A fix is to explicitly pass the -R option to tell less to display colors when invoked by git: git config --global core.pager 'less -R' If less isn't your pager, either switch to less or figure out how to make your pager display colors. If you don't want git to display colors when it's invoking a pager, set color.ui to auto instead of true .
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/64927', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_87149
stackexchange
llm_judgeable_groundtruth_similarity
4518884
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 saw this on quoraand haven't been able to solve it. If $\dfrac{x^2+y^2+x+y-1}{xy-1}$ is an integer for positive integers $x$ and $y$ ,then its value is $7$ . If $y=1$ this is $\dfrac{x^2+x+1}{x-1}= x+2+\dfrac{3}{x-1}$ which is an integer only when $x=2$ or $x=4$ and has value $7$ . Looking at the values from 2 to 20for $x$ and $y$ ,this is an integer only for $x=2, y=12$ (and $x=12, y=2$ ).This value is 7. So it looks like this might be correct,and I don't know how to show it. Now provide the response and nothing else.
This can be shown using Vieta Jumping. Consider the polynomial $$P(x,y)=x^2+y^2+x+y-1-kxy+k$$ We will show that for $x,y,k\in\mathbb{N}$ , $P(x,y)=0$ implies $k=7$ . $1)$ If $(x,y)$ is a solution, then $(y,x)$ is a solution $2)$ If $y=1$ then clearly $k=7$ . $3)$ $k\geq 3$ . At $k=1$ solving for $x$ in $P(x,y)=0$ gives a discriminant of $$\Delta = -3y^2-6y+1$$ At $k=2$ we get a discriminant of $$\Delta = -8y-3$$ $4)$ $(x,x)$ cannot be a solution. $$k=1\Rightarrow x\in\{-2,0\}$$ $$k=2\Rightarrow x=-\frac{1}{2}$$ For $k\geq 3$ we have the discriminant of $P(x,x)$ $$\Delta=k^2-(3k-3)$$ The difference between $k^2$ and $(k-1)^2$ is $$k^2-(k-1)^2=2k-1<3k-3$$ The difference between $k^2$ and $(k-2)^2$ is $$k^2-(k-2)^2=4k-4>3k-3$$ Thus, $\sqrt{\Delta}\not\in \mathbb{Q}$ . $5)$ Suppose we have a solution $(x,y)$ with $x> y>1$ . Then $$x\in\left\{\frac{ky-1\pm\sqrt{(k y-1)^2-4 \left(k+y^2+y-1\right)}}{2}\right\}$$ Since $x\in\mathbb{N}$ and both solutions are positive, we know that both are also natural numbers. Now, can $x$ be the lesser solution? Note that $$\frac{ky-1-\sqrt{(k y-1)^2-4 \left(k+y^2+y-1\right)}}{2}<\frac{ky-1-\sqrt{(k y-1-2y)^2}}{2}=y$$ Here, this inequality follows since $$0<1 - k - 2 y - 2 y^2 + k y^2$$ holds for all $(y,k)\in \{2,3,...\}\times \{3,4,...\}$ except for $(2,3)$ . We need only consider these pairs from points $2)$ and $3)$ above. We can ignore the final pair though since this gives the polynomial $$x^2-5x+8$$ with complex solutions. For all other acceptable $(y,k)$ though we have $$0<1 - k - 2 y - 2 y^2 + k y^2$$ $$=(k y-1)^2-4 \left(k+y^2+y-1\right)-(k y-1-2 y)^2$$ Thus, $x$ is the greater solution and from our original solution $(x,y)$ where $x>y$ we can get a new solution $(z,y)$ where $y>z$ . Let us rehash what we have showed: if we have a solution $(x_0,y_0)$ with $x_0>y_0>0$ , then we can make a new solution $(x_1,y_1)$ with $0<x_1<y_1=y_0$ . Since the solutions are symmetric, this gives us another solution $(x_2,y_2)$ with $x_2>y_2>0$ . Since all of these solutions $(x_n,y_n)$ are natural numbers, this sequence must continue until it hits some minimum. But this minimum can only be $1$ since otherwise we can always find a smaller solution, implying that $k=7$ from the beginning. EDIT: Since people are interested, this process can be run in reverse to generate all of an infinite number of solutions. Consider the sequences defined $$a_1=1$$ $$a_2=2$$ $$a_n=\frac{\sqrt{45 a_{n-1}^2-18 a_{n-1}-23}+7 a_{n-1}-1}{2}$$ and $$b_1=1$$ $$b_2=4$$ $$b_n=\frac{\sqrt{45 b_{n-1}^2-18 b_{n-1}-23}+7 b_{n-1}-1}{2}$$ Then all solutions are of the form $(a_n,a_{n-1})$ or $(b_n,b_{n-1})$ (up to symmetry) and it is easy to generate an infinite amount of them.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4518884', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13079/']}
jdg_87150
stackexchange
llm_judgeable_groundtruth_similarity
54708210
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 AWS-RDS(Aurora MySQL5.6) and It's a cluster, it has one writer instance and one reader instance. I find each instance would be down for nearly 10 minutes when I change its type, it's unacceptable, what should I do to avoid downtime? Here are more details information: Change type from db.t2.small to db.t2.medium Engine version: 5.6.10a Freeable Memory: 300M DB Connections (Count): ~400 CPU Utilization (Percent): ~20% Now provide the response and nothing else.
Instead of changing the type of the current writer instance, add a new writer with the desired instance type: Add an Aurora reader with the desired new instance type (for example db.t2.medium) to the cluster. Be sure to assign the reader the best priority so that it will be promoted to writer during failover (see Aurora Documentation for more in-depth information). Wait until the new instance is up and running. Then failover the cluster so that the new reader gets promoted to a writer. Finally delete the previous Aurora instance of the old instance type. This way you will have nearly no downtime. If you want to change the type of a reader instance: Add an Aurora reader with the desired new instance type. Wait until it's up and running. Delete the previous reader instance.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54708210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3762105/']}
jdg_87151
stackexchange
llm_judgeable_groundtruth_similarity
3477962
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 is it necessary to use the decorator pattern? If possible, give me a real world example that is well-suited for the pattern. Now provide the response and nothing else.
The Streams in Java - subclasses of InputStream and OutputStream are perfect examples of the decorator pattern. As an example, writing a file to disk: File toWriteTo = new File("C:\\temp\\tempFile.txt");OutputStream outputStream = new FileOutputStream(toWriteTo); outputStream.write("Sample text".getBytes()); Then should you require some extra functionality regarding the writing to disk: File toWriteTo = new File("C:\\temp\\tempFile.txt");OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(toWriteTo));outputStream.write("Sample text".getBytes()); By simply "chaining" the constructors, you can create quite powerful ways of writing to disk. The beauty in this way is that you can add different (in this example) OutputStream implementations later on. Also, each implementation doesn't know how the others work - they all just work to the same contract. This also makes testing each implementation very easy in isolation. There are plenty of "real world" examples of where the decorator pattern can be used. Off the top of my head, some examples: Reading and writing to disk (above) Construction of UI elements, such as adding scrollbars on to text areas etc Head First Design Patterns has some more "real world" examples. It seems that O'Reilly has their sample chapter, which is on Decorator Pattern, for free; Google showed up this link: PDF
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3477962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407418/']}
jdg_87152
stackexchange
llm_judgeable_groundtruth_similarity
25905144
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 with the 'tm' package in to create a corpus. I have done most of the preprocessing steps.The remaining thing is to remove overly common words (terms that occur in more than 80% of the documents). Can anybody help me with this? dsc <- Corpus(dd)dsc <- tm_map(dsc, stripWhitespace)dsc <- tm_map(dsc, removePunctuation)dsc <- tm_map(dsc, removeNumbers)dsc <- tm_map(dsc, removeWords, otherWords1)dsc <- tm_map(dsc, removeWords, otherWords2)dsc <- tm_map(dsc, removeWords, otherWords3)dsc <- tm_map(dsc, removeWords, javaKeywords)dsc <- tm_map(dsc, removeWords, stopwords("english"))dsc = tm_map(dsc, stemDocument)dtm<- DocumentTermMatrix(dsc, control = list(weighting = weightTf, stopwords = FALSE))dtm = removeSparseTerms(dtm, 0.99) # ^- Removes overly rare words (occur in less than 2% of the documents) Now provide the response and nothing else.
What if you made a removeCommonTerms function removeCommonTerms <- function (x, pct) { stopifnot(inherits(x, c("DocumentTermMatrix", "TermDocumentMatrix")), is.numeric(pct), pct > 0, pct < 1) m <- if (inherits(x, "DocumentTermMatrix")) t(x) else x t <- table(m$i) < m$ncol * (pct) termIndex <- as.numeric(names(t[t])) if (inherits(x, "DocumentTermMatrix")) x[, termIndex] else x[termIndex, ]} Then if you wanted to remove terms that in are >=80% of the documents, you could do data("crude")dtm <- DocumentTermMatrix(crude)dtm# <<DocumentTermMatrix (documents: 20, terms: 1266)>># Non-/sparse entries: 2255/23065# Sparsity : 91%# Maximal term length: 17# Weighting : term frequency (tf)removeCommonTerms(dtm ,.8)# <<DocumentTermMatrix (documents: 20, terms: 1259)>># Non-/sparse entries: 2129/23051# Sparsity : 92%# Maximal term length: 17# Weighting : term frequency (tf)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25905144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4053079/']}
jdg_87153
stackexchange
llm_judgeable_groundtruth_similarity
8090229
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 reimplement in python an IDL function: http://star.pst.qub.ac.uk/idl/REBIN.html which downsizes by an integer factor a 2d array by averaging. For example: >>> a=np.arange(24).reshape((4,6))>>> aarray([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) I would like to resize it to (2,3) by taking the mean of the relevant samples, the expected output would be: >>> b = rebin(a, (2, 3))>>> barray([[ 3.5, 5.5, 7.5], [ 15.5, 17.5, 19.5]]) i.e. b[0,0] = np.mean(a[:2,:2]), b[0,1] = np.mean(a[:2,2:4]) and so on. I believe I should reshape to a 4 dimensional array and then take the mean on the correct slice, but could not figure out the algorithm. Would you have any hint? Now provide the response and nothing else.
Here's an example based on the answer you've linked (for clarity): >>> import numpy as np>>> a = np.arange(24).reshape((4,6))>>> aarray([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])>>> a.reshape((2,a.shape[0]//2,3,-1)).mean(axis=3).mean(1)array([[ 3.5, 5.5, 7.5], [ 15.5, 17.5, 19.5]]) As a function: def rebin(a, shape): sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1] return a.reshape(sh).mean(-1).mean(1)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8090229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597609/']}
jdg_87154
stackexchange
llm_judgeable_groundtruth_similarity
5519411
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 started on an ADS sql table trigger to store changes done on one particular table. Here is the idea: //-------- sql trigger to store changes on patients table to auditLog Table//----------------------------------------------------------------------declare cChanges Char( 5000 );declare allColumns Cursor ;declare FieldName Char( 25 );declare StrSql Char( 255 );declare @new cursor as select * from __new;declare @old cursor as select * from __old; open @old; fetch @old;open @new; fetch @new;Set cChanges = '';Open AllColumns as Select * from system.columns where parent = 'patients';while fetch allColumns DO// Try FieldName = allColumns.Name; StrSql = 'IF @new.'+FieldName + '<> @old.'+FieldName +' and @old.'+FieldName + '<> [ ] THEN ' + 'cChanges = Trim( '+cChanges+' ) + @old.'+FieldName + ' Changed to ' + '@new.'+fieldname + ' | '+ 'ENDIF ; ' ; Execute Immediate StrSql ;// Catch ALL// End Try;End While;if cChanges <> '' THEN Insert Into AuditLog ( TableKey, Patient, [table], [user], creation, Changes ) values( @new.patient, @new.patient, [Patietns], User(), Now(), cChanges ) ;ENDIF;CLOSE AllColumns;//-------------------------- The above trigger code errors with reporting variable cChanges does not exists. Can someone help? Reinaldo. Now provide the response and nothing else.
You could extend the AuthorizeAttribute class and override HandleUnauthorizedRequest, you may want to return a Forbidden http status code rather than a custom message. public class CustomAuthorizationAttribute : AuthorizeAttribute{ protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // You need to set this action result to something other than a HttpUnauthorizedResult, // this result will cause the redirection to the login page // Forbidden request... does not redirect to login page // filterContext.Result = new HttpStatusCodeResult(403); filterContext.Result = new ErrorActionResult { ErrorMessage = "Unauthorized Access" }; }}public class ErrorActionResult : ActionResult{ public string ErrorMessage { get; set; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.Write(this.ErrorMessage); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5519411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330620/']}
jdg_87155
stackexchange
llm_judgeable_groundtruth_similarity
38863486
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say we have a few test interfaces/classes like this: abstract class Plant { public abstract String getName();}interface Eatable { }class Apple extends Plant implements Eatable { @Override public String getName() { return "Apple"; }}class Rose extends Plant { @Override public String getName() { return "Rose"; }}interface Animal { <T extends Plant & Eatable> void eat(T plant);} You can see Animal.eat is a generic method with constraints. Now I have my Human class like this: class Human implements Animal { @Override public void eat(Plant plant) { }} which compiles fine. You can see Human.eat is less constrained than Animal.eat because the Eatable interface is lost. Q1: Why doesn't the compiler complain about this inconsistency? Q2: If Plant&Eatable downgrades to Plant is acceptable for the compiler, why it complains on eat(Object plant) ? Now provide the response and nothing else.
Lesson: Generics by Gilad Bracha according to him public static <T extends Object & Comparable<? super T>> T max(Collection<T> coll) This is an example of giving multiple bounds for a type parameter, using the syntax T1 & T2 ... & Tn. A type variable with multiple bounds is known to be a subtype of all of the types listed in the bound. When a multiple bound is used, the first type mentioned in the bound is used as the erasure of the type variable. so your example <T extends Plant & Eatable> void eat(T plant); will be erased to void eat(Plant plant); so when you override it the compiler doesn't complain
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38863486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323924/']}
jdg_87156
stackexchange
llm_judgeable_groundtruth_similarity
29035431
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following the apple documentation I am trying to set up a simple NSTextView via its two constructor methods. I am placing the below code inside the viewDidAppear method of the view controller of the content view. textView is an instance of NSTextView , frameRect is the frame of the content view. The following Swift code works (gives me an editable textView with the text showing on the screen): textView = NSTextView(frame: frameRect!) self.view.addSubview(textView) textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello")) The following does NOT work (text view is not editable and no text shown on the screen): var textStorage = NSTextStorage() var layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) var textContainer = NSTextContainer(containerSize: frameRect!.size) layoutManager.addTextContainer(textContainer) textView = NSTextView(frame: frameRect!, textContainer: textContainer) textView.editable = true textView.selectable = true self.view.addSubview(textView) textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello more complex")) What am I doing wrong in the second example ? I am trying to follow the example given in Apple's "Cocoa Text Architecture Guide" where they discuss setting up an NSTextView by explicitly instantiating its web of helper objects. Now provide the response and nothing else.
You need to keep a reference to the NSTextStorage variable you create. I'm not quite sure about the mechanics of it all, but it looks like the text view only keeps a weak reference to its text storage object. Once this object goes out of scope, it's no longer available to the text view. I guess this is in keeping with the MVC design pattern, where views (the NSTextView in this case) are meant to be independent of their models (the NSTextStorage object). import Cocoa@NSApplicationMainclass AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var textView: NSTextView! var textStorage: NSTextStorage! // STORE A REFERENCE func applicationDidFinishLaunching(aNotification: NSNotification) { var view = window.contentView as NSView textStorage = NSTextStorage() var layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) var textContainer = NSTextContainer(containerSize: view.bounds.size) layoutManager.addTextContainer(textContainer) textView = NSTextView(frame: view.bounds, textContainer: textContainer) textView.editable = true textView.selectable = true view.addSubview(textView) textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello more complex")) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29035431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3829874/']}
jdg_87157
stackexchange
llm_judgeable_groundtruth_similarity
12507649
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Even after reading a lot about the fulltext index of SQLite and a question arises that I didn't see answered anywhere: I already have a table that I want to search with the fulltext index. I would just create an extra virtual table USING FTS3 or USING FTS4 and then INSERT my data into it. Does that then use the double storage in total? Can I use such a virtual table just like a normal table and thus preventing storing the data twice? (I am working with SQLite on Android but this question may apply to usage on any SQLite compatible platform.) Now provide the response and nothing else.
Despite the fact you did found some details I'll try to provide detailed answer: 1. Does that then use the double storage in total? Yes it does. Moreover it might use event more space. For example, for widely known Enron E-Mail Dataset and FTS3 example , just feel the difference: The FTS3 table consumes around 2006 MB on disk compared to just1453 MB for the ordinary table The FTS3 table took just under 31minutes to populate, versus 25 for the ordinary table Which makes the situation a bit unpleasant, but still full-text search worth it. 2. Can I use such a virtual table just like a normal table? The short answer no, you can't. Virtual table is just a some kind of a View with several limitations. You've noticed several already. Generally saying you should not use any feature which is seems to be unnatural for a View . Just a bare minimum required to let your application fully utilize the power of full-text search. So there will be no surprises later, with newer version of the module. There is no magic behind this solution, it is just a trade-off between performance, required disk space and functionality. Final conclusion I would highly recommend to use FTS4, because it is faster and the only drawback is additional storage space needed. Anyway, you have to carefully design virtual table taking into account a supplementary and highly specialized nature of such solution. In the other words, do not try to replace your initial table with the virtual one. Use both with a great care. Update I would recommend to look through the following article: iOS full-text search with Core Data and SQLite . Several interesting moments: The virtual table is created in the same SQLite database in wich the Core Data content resides. To keep this table as light as possibleonly object properties relevant to the search query are inserted. SQLite implementation offers something Core Data does not: full-text search. Next to that, it performs almost 10% faster and at least660% more (memory) efficiently than a comparable Core Data query.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12507649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/578588/']}
jdg_87158
stackexchange
llm_judgeable_groundtruth_similarity
351969
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After reaching 20K, when browsing Stack Overflow (main or meta) I sometimes encounter posts that I believe merit deletion, but the "delete" link is not available because the post is not downvoted enough. The threshold is -3 for questions and -1 for answers. In cases like this is it ok to downvote the post with the sole intention to enable and use the "delete" link? The system has put those thresholds in place for good reasons, so is this considered an abuse in the sense that you use a privilege for a post that didn't originally meet the criteria for deletion? I have read this post: Clean-up by downvoting? A ridiculous user experience , and the consensus is that you shouldn't organize voting rings in order to delete otherwise well received posts, but this question is different because in this case a) it is only your own vote, b) the post isn't well received (yet?). To get the sense of the type of posts I am talking about, here are a couple of examples. They were marginally above the threshold, and I was able to vote to delete only after downvoting them: 1 2 (<10K links 1 2 ) Note: 2 was on meta. Now provide the response and nothing else.
The real problem here is that you haven't already downvoted. If you think a post warrants deletion, surely it also warrants a downvote. I can kinda understand skipping that if you think it's gonna be deleted in a few minutes anyway, but if you wouldn't downvote a post at all were it not for your desire to delete it... Then you should probably question either your rationale for deletion, or your rationale for (not) voting.
{}
{'log_upvote_score': 8, 'links': ['https://meta.stackoverflow.com/questions/351969', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/828193/']}
jdg_87159
stackexchange
llm_judgeable_groundtruth_similarity
19747
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: Not sure where to ask this question - thought you guys would probably have the best idea! Today a single key on my keychain in my pocket heated up so that it was too hot to handle and scalded my leg. Any ideas what could possibly have done this? I always keep a prison guard style set of keys attached to my trousers and in my pocket - one of these keys is very large and thick (longer and thicker than my finger) - this is the key that heated up somehow. In my pocket was my phone (an htc desire hd). I was sitting at my desk as I do all the working day - when I felt my pocket getting hotter rather alarmingly quickly. I stood up and pulled everything out of my pocket - and I can't work out how it happened. The phone was not hot at all and worked fine. My best guess is that there was some form of induction going on. Does anybody have any idea what might have happened? I don't think it was friction or bending of the keys as it's never happened before and I was sitting still all morning. Thanks for any ideas! I'm more curious than anything else. Now provide the response and nothing else.
Mobile phones transmit at microwave frequencies so they can induce currents in metals and other conductors. The energy dissipates as heat. The principle is the same used by microwave ovens. The phone would not itself get hot because (presumably) the microwave radiation would be directed away from metal components in the phone. Your key must have been close to the antenna and was perhaps aligned with it in a way that maximized the effect, or perhaps its length was just right for a resonance. Here is a paper that seems relevant http://www.springer.com/about+springer/media/springer+select?SGWID=0-11001-6-1296921-0 Edit: Let me add a small calculation. Suppose a phone were outputting 1 Watt and 50% was absorbed by the key for 3 minutes. This puts 1W*180s*0.5 = 90 J of heat into the key. If the key weighs 10 g and is made of iron with a heat capacity of 450 J/Kg/K then the temperature goes up by 90J/0.01Kg/450J/Kg/K = 20K So this could raise the temperature of the key from 25C to 45C which would make it feel quite hot to the touch. Actual result depends on how fast the heat is conducted away and how much of the power is absorbed but it is not beyond the bounds of possibility that enough heating is possible to account for the observation. I would not blame anyone for being skeptical though. It would perhaps be unusual for the phone to transmit on full power for that long.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/19747', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7220/']}
jdg_87160
stackexchange
llm_judgeable_groundtruth_similarity
41137114
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new on bulma css http://bulma.io/ I'm trying to use hamburger menu for mobile user.I just followed instruction on this page: http://bulma.io/documentation/components/nav/ But it doesn't work. What should I add ? Actually, I can see hamburger menu, but it doesn't work when I am click it. Thank you. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title>test</title> <link rel="stylesheet" href="css/bulma.min.css"> <link rel="stylesheet" href="css/custom.css"> </head> <body> <section class="hero is-fullheight is-primary is-bold"> <!-- Hero header: will stick at the top --> <div class="hero-head"> <header class="nav"> <div class="container"> <div class="nav-left"> <a class="nav-item" href="/"> <img src="img/logo.png" alt="Logo"> </a> </div> <span class="nav-toggle"> <span></span> <span></span> <span></span> </span> <div class="nav-right nav-menu"> <a class="nav-item" href="/about"> About </a> <a class="nav-item" href="/path"> Path </a> <a class="nav-item" href="/blog"> Blog </a> </div> </div> </header> </div> <!-- Hero content: will be in the middle --> <div class="hero-body"> <div class="container has-text-centered"> </div> </div> </section> </body></html> Now provide the response and nothing else.
This solution uses Vue.js to toggle the bulma nav component when viewing on mobile. I hope this helps others that are looking for an alternative solution. JS First, I add the cdn for Vue.js which can be found here https://unpkg.com/vue , and include an instance of Vue in the javascript. new Vue({ el: '#app', data: { showNav: false }}); HTML a. Wrap the nav section with the element "app" to make it reactive (this maps to the "el" property of the Vue instance). <div id="app"> ... </div> b. Update .navbar-burger using the v-on: directive to listen for the click event and toggle the data property showNav. <div class="navbar-burger" v-on:click="showNav = !showNav" v-bind:class="{ 'is-active' : showNav }"> c. Update .navbar-menu using the v-bind: directive to reactively update the class attribute with the result of the showNav property. <div class="navbar-menu" v-bind:class="{ 'is-active' : showNav }"> Solution I've included the entire solution in this jsfiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41137114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5948750/']}
jdg_87161
stackexchange
llm_judgeable_groundtruth_similarity
188017
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't understand the physical significance of Common Mode Voltage. It is arbitrarily defined as the average of two voltages and is expected to be rejected by a differential amplifier. Why? What is its physical significance? EDITmy question was specific to differential amplifiers. Both inputs to the differential amplifier need not be equal and opposite. What would be the meaning of common mode voltage in such case? Now provide the response and nothing else.
For common mode signals you get two wires: one with a signal and one with the inverse of that signal. If you add them you'll get zero, if you'd take the difference you'll get the signal. What's the cool thing about this. If the two wires (the pair of wires) picks up some noise.Than the noise will be added on both wires. If you add the two signals you only keep the noise.. But if you take the difference you'll get the signal without the noise. Signal is S (without noise) Cable a => S Cable b => -S The Difference is S - (-S) = 2*S Signal is S (with noise) Cable a => S + noise Cable b => -S + noise The Difference is (S+noise) - (-S+noise) = S+S+noise-noise = 2S So the noise will be cancelled. example image: When Common mode signals are used they are mostly transferred with twisted pair cables like this:
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/188017', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/37643/']}
jdg_87162
stackexchange
llm_judgeable_groundtruth_similarity
8986971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On Windows 7, I have a command-line program that fails due to file write permission errors, and popping up annoying UAC dialogs every time I run command-line programs that are from an 'unknown publisher'. However, if I start my console by right clicking and choosing 'run as administrator', then the install works fine, even if the UAC dialogs are still present. My user is already a member of the 'administrators' group, so what precisely does 'run as administrator' do that makes my install work? My specific question is precisely: What does 'run as administrator' do? Neither of the answers thus far address this. (for example, does it run the new process as the 'Administrator' user? Or does it run the process as the current user, but with elevated privileges? If so, what privileges? How does that differ from the privileges I get from my user being in the 'Administrators' group? (Specifically, I'm using the 'Console' from SourceForge , not a regular CMD window, but I don't think that's important. This is all while installing the Python 'distribute' package by running 'python distribute_setup.py' on a newly installed Python3 MSI from python.org. It's a 32-bit Python on 64-bit Windows. See Installing Python and distribute on Windows 7 gives "Writing failed ... permission denied" ) Now provide the response and nothing else.
When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group. Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access. With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges. When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8986971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10176/']}
jdg_87163
stackexchange
llm_judgeable_groundtruth_similarity
2009304
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Wow, makes your head spin! I am about to start a project, and although my mySql is OK, I can't get my head around what required for this: I have a table of web addresses. id,url1,http://www.url1.com2,http://www.url2.com3,http://www.url3.com4,http://www.url4.com I have a table of users. id,name1,fred bloggs2,john bloggs3,amy bloggs I have a table of categories. id,name1,science2,tech3,adult4,stackoverflow I have a table of categories the user likes as numerical ref relating to the category unique ref. For example: user,category1,41,61,71,102,32,43,5... I have a table of scores relating to each website address. When a user visits one of these sites and says they like it, it's stored like so: url_ref,category4,24,34,64,24,35,25,3... So based on the above data, URL 4 would score (in it's own right) as follows: 2=2 3=2 6=1 What I was hoping to do was pick out a random URL from over 2,000,000 records based on the current users interests. So if the logged in user likes categories 1,2,3 then I would like to ORDER BY a score generated based on their interest. If the logged in user likes categories 2 3 and 6 then the total score would be 5. However, if the current logged in user only like categories 2 and 6, the URL score would be 3. So the order by would be in context of the logged in users interests. Think of stumbleupon. I was thinking of using a set of VIEWS to help with sub queries. I'm guessing that all 2,000,000 records will need to be looked at and based on the id of the url it will look to see what scores it has based on each selected category of the current user. So we need to know the user ID and this gets passed into the query as a constant from the start. Ain't got a clue! Chris Denman Now provide the response and nothing else.
Because in Java char is an integral data type , whose values are 16-bit unsigned integers representing UTF-16 code units. Since char is a numeric data type, when you assign it a numeric value, it just takes on the encoding of whatever Unicode character is represented by that value. Run the following two lines of code: char c = 65;System.out.println("Character: " + c); You'll see the output: Character: A (I would have used 7 like you did in the example, but that's an unprintable character.) The character "A" is printed because the decimal value 65 (or 41 hex) is encoded to that letter of the alphabet. See Joel Spolsky's article The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) for more information in Unicode. Update: In case you're talking about the fact that int value assignment to char normally gives you a "possible loss of precision" compiler error, as the following code will demonstrate: int i = 65;char c = i;System.out.println("Character: " + c); The answer is just what PSpeed mentioned in his comment. In the first (2-line) version of the code, the literal assignment works because the value is known at compile time. Since the value 65 is within the correct range for a char ('\u0000' to '\uffff' inclusive, or from 0 to 65535), the assignment is allowed to take place. In the second (3-line) version the assignment isn't allowed because the int variable could take any value from -2147483648 to 2147483647, inclusive, most of which are out of range for the char variable to contain.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2009304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244273/']}
jdg_87164
stackexchange
llm_judgeable_groundtruth_similarity
38133853
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 decimal pad setup in my app, but how do I dismiss this keyboard? How do I get a done or a return key? I've tried UIReturnKeyType.Done but that didn't show anything. Something like that Now provide the response and nothing else.
Here is a Swift 3 solution using an extension. Ideal if you have several numeric UITextField objects in your app as it gives the flexibility to decide, for each UITextField , whether to perform a custom action when Done or Cancel is tapped. //// UITextField+DoneCancelToolbar.swift//import UIKitextension UITextField { func addDoneCancelToolbar(onDone: (target: Any, action: Selector)? = nil, onCancel: (target: Any, action: Selector)? = nil) { let onCancel = onCancel ?? (target: self, action: #selector(cancelButtonTapped)) let onDone = onDone ?? (target: self, action: #selector(doneButtonTapped)) let toolbar: UIToolbar = UIToolbar() toolbar.barStyle = .default toolbar.items = [ UIBarButtonItem(title: "Cancel", style: .plain, target: onCancel.target, action: onCancel.action), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil), UIBarButtonItem(title: "Done", style: .done, target: onDone.target, action: onDone.action) ] toolbar.sizeToFit() self.inputAccessoryView = toolbar } // Default actions: func doneButtonTapped() { self.resignFirstResponder() } func cancelButtonTapped() { self.resignFirstResponder() }} Example of usage using the default actions: //// MyViewController.swift//@IBOutlet weak var myNumericTextField: UITextField! { didSet { myNumericTextField?.addDoneCancelToolbar() }} Example of usage using a custom Done action: //// MyViewController.swift//@IBOutlet weak var myNumericTextField: UITextField! { didSet { myNumericTextField?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField))) }}func doneButtonTappedForMyNumericTextField() { print("Done"); myNumericTextField.resignFirstResponder() }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38133853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3971519/']}
jdg_87165
stackexchange
llm_judgeable_groundtruth_similarity
443189
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'm using a REST API to retrieve data from my back end at my front end. I'd like to figure out which way of receiving data from the back end is the better one (= clean, robust, and best practiced). There are the following two ways of retrieving data from the back end (the example code assumes the retrieval of some reservation information from the back end). Implicitly adopting a data structure from the back end function queryReservationData(){ const data = queryBackend('/reservationdata/query'); return data; } Explicitly adopting a data structure from the back end function queryReservationData(){ const backendData = queryBackend('/reservationdata/query'); const data = { name: backendData.name, reservationStart: backendData.reservationStart, reservationEnd: backendData.reservationEnd, }; return data; } edit: Constraints Backend owner: In my current use case, the backend is owned internally, but an answer for both use cases would be helpful. Thoughts I feel approach 1 is not clean or safe, because it couples the back end and front end. I dislike the idea of an implicit data structure that changes as soon as the back end changes (back-end editors might not be aware of their changes). However, in case of the back end changes, the front end will also have to change. So is there really a benefit of stating everything explicitly as in approach 2? Concrete environment In my concrete use case, I'm using React and TypeScript for my front end (but this should not influence the answer). The backend is used only of one specific UI. Differentiating the cases in the answers might be helpful. Backend owned internally by different teams. Now provide the response and nothing else.
Both are coupled to the back-end model. Just in different ways. If the back-end model changes, both solutions will break. Gracefully or not but will break anyways. The key is where the front-end code is going to break? . Being practical, #2 is preferable since the coupling point is all in a single function. It's well-located and easy to find. That's not true for #1 which broadcast the "changes" to any queryReservationData() caller. The change I would consider on #2 is replacing the mapping (which is useless) with schema validations. In this regard, you might find interesting JSON Schema and JSON Schema validators. As @gnasher729 says, Your function should guarantee to either return what you want it to return, or produce some error. If the function can't guarantee its own contract, for whatever reason, what else can you do than rising an error? Note that, if the backend removes name from the response, your mapping will result in data.name: undefined . In other words, it doesn't solve the problem, it just hides it. It's even worse for reservationStart and reservationEnd , because they are format-bound. If the format changes, none of the options will handle the hit of the change.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/443189', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/345246/']}
jdg_87166
stackexchange
llm_judgeable_groundtruth_similarity
3807887
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: We know that $\frac{x}{x}=1$ for any nonzero value $x$ and $\lim_{x \to 0} \frac{x}{x}=1$ ; however, I'm wondering that is this function actually defined at $x=0$ ? Since when $x=0$ , this function will become $\frac{0}{0}$ , which is undefined. https://www.quora.com/What-is-0-0-Is-it-equal-to-1 Now provide the response and nothing else.
No, $x/x$ is not defined at $0$ . Everywhere besides $0$ , it is equal to $1$ , but at $0$ , it is undefined. This is no problem when we consider the limit $\lim_{x \to 0} (x/x)$ , because this function is defined everywhere else besides $0$ (and the limit of a function as $x \to 0$ only depends on the values of the function at points besides $0$ ). It is incorrect to say that $0/0$ can be any value. Instead, $0/0$ does not have any value at all, in other words, it is undefined.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3807887', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/719017/']}
jdg_87167
stackexchange
llm_judgeable_groundtruth_similarity
1789212
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 have several build machines, each running a single TeamCity build agent. Each machine is very strong, and we'd like to run several build agents on the same machine. Is this possible, without using virtualization ? Are there quality alternatives to TeamCity that support this? Now provide the response and nothing else.
Yes, it's possible : Several agents can be installed on a single machine. They function as separate agents and TeamCity works with them as different agents, not utilizing the fact that they share the same machine.After installing one agent you can install additional one, providing the following conditions are met: the agents are installed in the separate directories they have distinctive work and temp directories buildAgent.properties is configured to have different values for name and ownPort properties Make sure, there are no build configurations that have absolute checkout directory specified (alternatively, make sure such build configurations have "clean checkout" option enabled and they cannot be run in parallel). Under Windows, to install additional agents as services, modify [agent dir]\launcher\conf\wrapper.conf to change the properties to have distinct name within the computer: wrapper.console.title wrapper.ntservice.name wrapper.ntservice.displayname wrapper.ntservice.description
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1789212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11236/']}
jdg_87168
stackexchange
llm_judgeable_groundtruth_similarity
3994590
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my application, I need to Zip and Unzip some files. For that I have used DotNet Zip Library (Ionic.Zip.dll-- DotNet Zip Lib ) Everything works fine but when I take EXE of my file and try to run it from different folder, it fails to run. I have to keep Ionic.Zip.dll in the folder where my application resides. Is there any way out? I just want an EXE file without any strings attached.... Or is there any other option other than DotNet Zip Lib. Now provide the response and nothing else.
When you add a reference to another assembly (e.g. a third-party DLL) to your C# project, the compiler doesn't add the contents of that assembly into your EXE; it just creates a link that says your program will need to load that DLL when it runs. It's quite normal to distribute a .NET program as an EXE file plus the DLL files that it needs. But if you'd prefer, you can combine them into one EXE file. There are a few different tools that can merge multiple .NET assemblies into one. Have a look at ILMerge or .NETZ .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3994590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474173/']}
jdg_87169
stackexchange
llm_judgeable_groundtruth_similarity
611265
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This keeps hapenning on which ever server I am connected to. I type: ssh user@server I log in, everything works for a couple of minutes. But after some time, possibly when I switch to other programmes (browser, ftp client etc) when I try to type anything back in the terminal, the cursor stops blinking while I type, but nothing actually gets typed. I can't execute any command, and all I can do is close the terminal window, reopen it and reconnect. If it's of any importance, I'm running Ubuntu 12.04 on my local machine. Now provide the response and nothing else.
You have a NAT router or a similar stateful firewall between your client and the server. When you opened the TCP session, the firewall remembered that a TCP connection was created between your client port and the server port. As long as the firewall remembers the connection, it will continue passing packets between the client and the server. The session "breaks" because the firewall forgets about the connection and stops passing packets through. The firewall may forget about the connection because it has a timeout on idle connections. Or it could forget because it has a limited amount of memory and too many new connections were being created for it to remember all of them. ssh has some options to work around this by sending periodic "keep-alive" packets when the connection is idle. Look at the TCPKeepAlive , ServerAliveInterval , and ServerAliveCountMax options.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/611265', 'https://serverfault.com', 'https://serverfault.com/users/138004/']}
jdg_87170
stackexchange
llm_judgeable_groundtruth_similarity
26823609
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 been looking all over the internet for a code that does this, no luck so far... This is the code for my facebook like button: <script type="text/javascript"> $(function(){ $('<iframe scrolling="no" frameborder="0" style="width: 300px; height: 80px;'+ '" src="http://www.facebook.com/widgets/like.php?href='+ encodeURIComponent(location.href)+ '"></iframe>').appendTo('#like-button')})</script> I want this button to disappear after is clicked (Im thiyin to make some sort of like gate) Cheers Now provide the response and nothing else.
Basically, you have two options: high-level approach : automate a real browser using selenium or, in other words, make the browser repeat all the user actions needed to get to the page with the desired data. low-level approach : when you click the button, investigate what is happening under the hood - explore the "Network" tab of browser developer tools and see what requests are being made. Then, simulate them in your scraper. Here, you may consider using tools like requests , mechanize for making requests, handling scraping sessions, submitting forms etc and tools like BeautifulSoup , lxml.html for html parsing. Also, Scrapy web-scraping framework is a must see.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26823609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4178961/']}
jdg_87171
stackexchange
llm_judgeable_groundtruth_similarity
182592
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a permutation a in a product of disjoint cycles form as follows $a = {{(1,9,3,7)(2,11,6)(4,8,5,10)}}$ I want to represent it in a matrix form A such that $A = \begin{pmatrix}1&2&3&4&5&6&7&8&9&10&11\\9&11&7&8&10&2&1&5&3&4&6\end{pmatrix}$ I believe a can be defined in Mathematica as a = Cycles[{{1, 9, 3, 7}, {2, 11, 6}, {4, 8, 5, 10}}] How do I convert a to A ? Now provide the response and nothing else.
mat = {Sort @ #, #} & @ PermutationList[a];MatrixForm @ mat // TeXForm $ \left(\begin{array}{ccccccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\ 9 & 11 & 7 & 8 & 10 & 2 & 1 & 5 & 3 & 4 & 6 \\\end{array}\right)$
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/182592', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/60371/']}
jdg_87172
stackexchange
llm_judgeable_groundtruth_similarity
59226447
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 upgrade Julia from v1.1 to v1.3 on win10, but the packages miss in new version. In v1.1 $ julia_1.1 _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.1.0 (2019-01-21) _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release|__/ |(v1.1) pkg> status Status `C:\Users\User\.julia\environments\v1.1\Project.toml` [c52e3926] Atom v0.11.3 [4c0ca9eb] Gtk v0.18.0 [f67ccb44] HDF5 v0.12.4 [4138dd39] JLD v0.9.1 [e5e0dc1b] Juno v0.7.2 [23992714] MAT v0.6.0 [91a5bcdd] Plots v0.26.3 [b8865327] UnicodePlots v1.1.0 [8f399da3] Libdl But these packages does not show in v1.3 $ julia _ _ _ _(_)_ | Documentation: https://docs.julialang.org (_) | (_) (_) | _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help. | | | | | | |/ _` | | | | |_| | | | (_| | | Version 1.3.0 (2019-11-26) _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release|__/ |(v1.3) pkg> status Status `C:\Users\User\.julia\environments\v1.3\Project.toml` [c52e3926] Atom v0.11.3 [67c07d97] Automa v0.8.0 [e5e0dc1b] Juno v0.7.2 I tried using update but still not show. And I make sure DEPOT_PATH has same folder ( "C:\\Users\\User\\.julia" ) and all added package in there. # (in v1.3)julia> DEPOT_PATH3-element Array{String,1}: "C:\\Users\\User\\.julia" "D:\\app\\Julia\\1.3.0\\local\\share\\julia" "D:\\app\\Julia\\1.3.0\\share\\julia" How do I resolve it? And in I memory, it will not happen in Linux, is it correct? (I use different version in docker with same volume.) Now provide the response and nothing else.
Each minor and major Julia version ( MAJOR.MINOR.PATCH ) uses its own environment named vMAJOR.MINOR . For example, for Julia 1.3.0 the environment is named v1.3 as you can see indicated in the Pkg REPL mode in parentheses before the pkg> . When you updated from 1.1.x to 1.3.0 you hence switch from environment v1.1 to v1.3 , which doesn't contain any packages by default. This happens on every OS. How to we carry over packages from, say, v1.1 to v1.3 ? The environments are reflected in folders in .julia/enironments . The two files Manifest.toml and Project.toml in those folders represent the respective environment. You can simply create a copy of the folder v1.1 and name it v1.3 . Then, you fire up you Julia 1.3 REPL and, to be safe, you execute ] instantiate which will make sure that everything is installed properly. That's it. For more information on environments see here and here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59226447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8436166/']}
jdg_87173
stackexchange
llm_judgeable_groundtruth_similarity
32430384
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 it possible to insert in Mongo with condition; //Pseudo codeBulk Insert Item :If Key exists Skip, don't throw errorIf key does not exist Add item If i do single inserts, it might return an error or insert in the collection, but is it possible in bulk ? Now provide the response and nothing else.
You have two real choices here depending on how you want to handle things: Use upsert functionality of MongoDB to essentially "lookup" if the key data exists. If not then you only pass in data to $setOnInsert and that will not touch anything else. Use "UnOrdered" operations in Bulk. The whole batch of updates will continue even if an error is returned, but the error report(s) are just that, and anything that is not an error will be comitted. Whole example: var async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Schema;var testSchema = new Schema({ "_id": Number, "name": String},{ "_id": false });var Test = mongoose.model('Test',testSchema,'test');mongoose.connect('mongodb://localhost/test');var data = [ { "_id": 1, "name": "One" }, { "_id": 1, "name": "Another" }, { "_id": 2, "name": "Two" }];async.series( [ // Start fresh function(callback) { Test.remove({},callback); }, // Ordered will fail on error. Upserts never fail! function(callback) { var bulk = Test.collection.initializeOrderedBulkOp(); data.forEach(function(item) { bulk.find({ "_id": item._id }).upsert().updateOne({ "$setOnInsert": { "name": item.name } }); }); bulk.execute(callback); }, // All as expected function(callback) { Test.find().exec(function(err,docs) { console.log(docs) callback(err); }); }, // Start again function(callback) { Test.remove({},callback); }, // Unordered will just continue on error and record an error function(callback) { var bulk = Test.collection.initializeUnorderedBulkOp(); data.forEach(function(item) { bulk.insert(item); }); bulk.execute(function(err,result) { callback(); // so what! Could not care about errors }); }, // Still processed the whole batch function(callback) { Test.find().exec(function(err,docs) { console.log(docs) callback(err); }); } ], function(err) { if (err) throw err; mongoose.disconnect(); }); Note that the "changed action" in current drivers is that the result response on .execute() will return an error object to be thrown, where previous releases did not do so with "Un-ordered" operations. This makes it imperative that your code never relies on the err returned alone, and you should be inpspeting the returned result instead for the full classification of errors. Nonetheless, when unordered then the batch continues until the end, no matter how many errors occur. Things that are not an error will be committed as normal. This really comes down to "is sequence important". If so, then you need "Ordered" operations and you can only avoid duplicate keys by using "upserts". Otherwise use "unordered", but be aware of the error returns and what they actually mean. Also, when using .collection to get the underlying collection object from the base driver to enable "Bulk" operations, then always be sure that either "some" mongoose method has always been called first. Without that, there is no guaranteed connection to the database with the native driver methods as it is handled for the mongoose methods, so the operation will fail due to no connection. The alternate to "firing" a mongoose method first, is to wrap your app logic in an event listener for the connection: mongoose.connection.on("open",function(err) { // app logic in here})
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32430384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364274/']}
jdg_87174
stackexchange
llm_judgeable_groundtruth_similarity
514697
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The Apache mod_ssl documentation for the SSLCertificateFile and SSLCertificateKeyFile directives states that it is 'strongly discouraged' to store a private key and an SSL certificate in the same file. Now obviously the private key file should be kept secure, but assuming that is the case, are there any specific risks in storing a certificate in the same file? I am curious to know why this behaviour is supported, and yet strongly discouraged without explanation. Now provide the response and nothing else.
The SSL Certificate File is a lock. The SSL Certificate Key File is its key. Storing the two together is the equivalent of taping your key to the lock on your front door. If an attacker compromises the single file they have everything they need to successfully impersonate your website (the certificate, and the private key). This is especially true if you do not have a passphrase on your SSL key (many web servers don't, to allow them to automatically start up in the event of a crash). What you're defending against by separating the files is an Apache bug that causes it to dump the contents of the SSLCertificateFile (something that should be publicly available) to a web client. (To my knowledge no such bug exists, or has ever existed, but Apache is a large, complex piece of software. It's entirely possible.) If Apache dumps this file and all it contains is the SSL Certificate (the lock) there's no problem: Everyone gets a copy of that certificate when they make an SSL request to the server anyway. If the file contains the key as well you've blown any chance at security - your entire encryption model is compromised, and you need to change keys.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/514697', 'https://serverfault.com', 'https://serverfault.com/users/177279/']}
jdg_87175
stackexchange
llm_judgeable_groundtruth_similarity
242246
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: If I check the processes that are running in the Task Manager and find that only the usual process run every time I restart my PC, can I assume that my device is not compromised? In other words, does a compromised device always show an alien process running? Now provide the response and nothing else.
No. There are plenty of techniques to migrate malicious code into "legitimate" processes. Furthermore, just because you cannot identify a process does not mean it's not legitimate. As such, just by looking at the list of processes, you cannot tell whether a device is compromised or not.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/242246', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/245190/']}
jdg_87176
stackexchange
llm_judgeable_groundtruth_similarity
5457292
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 included JQuery1.5 in the header of a JSF page. In that page there is a bunch of Primefaces components already coded. After I have included the Jquery.js in the header of the page, some primefaces components like <p:commandButton> loses their skin and <p:fileUpload> becomes looking like normal JSP <input type="file"> and losing its AJAX capability entirely. Is there a way to use JQuery safely along with primefaces(without conflict)? Now provide the response and nothing else.
I had the same problem as described in the question. That's why I came up with the following solution: Include the primefaces built-in jQuery library (currently 1.4.1) as including an own jQuery library leads to CSS formatting problems. Adding the target="head" attribute allows for specifying the tag everywhere - e.g. when using templating you not always have access to the <head> tag: <h:outputScript library="primefaces" name="jquery/jquery.js" target="head" /> The primefaces jQuery library is included by default in conflict mode. That means the $() shortcut cannot by used. To overcome this issue include the following line in a <script> or <h:outputScript> tag: <h:outputScript target="head"> // Add the $() function $ = jQuery; // Now you can use it $(document).ready(function() { ... });</h:outputScript> That's the best solution I could dig out so far, using primefaces 2.2.1.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5457292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569497/']}
jdg_87177
stackexchange
llm_judgeable_groundtruth_similarity
82990
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a file that has "then"'s and "there"'s. I can $ grep "then " x.xx and then somex and then somex and then somex and then some and I can $ grep "there " x.xIf there is no blob none some will be created How can I search for both in one operation?I tried $ grep (then|there) x.x -bash: syntax error near unexpected token `(' and grep "(then|there)" x.xdurrantm.../code# (Nothing) Now provide the response and nothing else.
You need to put the expression in quotation marks. The error you are receiving is a result of bash interpretting the ( as a special character. Also, you need to tell grep to use extended regular expressions. $ grep -E '(then|there)' x.x Without extended regular expressions, you have to escape the | , ( , and ) . Note that we use single quotation marks here. Bash treats backslashes within double quotation marks specially. $ grep '\(then\|there\)' x.x The grouping isn't necessary in this case. $ grep 'then\|there' x.x It would be necessary for something like this: $ grep 'the\(n\|re\)' x.x
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/82990', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10043/']}
jdg_87178
stackexchange
llm_judgeable_groundtruth_similarity
4012123
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 $D \ne \emptyset$ and $(X,d)$ be a metric space. Let $Z =(D,X)$ , that is the set of all $\textbf{bounded}$ continuous functions $f:D \to X$ . Now $Z$ isn't a vector space, but we can define the sup metric $e$ for $Z$ by setting $$e(f,g) = \sup_{x\in D} d(f(x),d(g(x)).$$ This was a definition on a book I'm reading without a proof and I'm trying to figure out if this satisfies the conditions for a metric space. If it does it should satisfy $$d(x,y) \geqslant 0 \text{ with equality iff $x=y$} \\ d(x,y) = d(y,x) \\ d(x,y) \leqslant d(x,z) + d(z,y)$$ I'm slightly confused about how to show these. For the first one I would want to show that $\sup_{x\in D} d(f(x),d(g(x)) \geqslant 0$ , which seems intuitive that the distance between two functions wouldn't be negative, but I'm not sure how to formalize this. Also the second one seems self explanatory that the distance between $f$ and $g$ is the same as the distance between $g$ and $f$ . If anyone happens to know where this would be proven I would be appreciate a link. Now provide the response and nothing else.
Connect the vertices $A$ and $C$ to observe the following: $$ab+cd \geq ab\sin(x)+cd\sin(y)=2\bigtriangleup ABC+2\bigtriangleup ACD=2\cdot Area(ABCD)$$ Likewise: $$bc+ad \geq2\cdot Area(ABCD)$$ So, this method always overestimates. Also, note that the equality occurs only when quadrilateral $ABCD$ is a rectangle.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4012123', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_87179
stackexchange
llm_judgeable_groundtruth_similarity
47869
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I get that all problems in NP can be reduced in polynomial time to some NP-Hard problem. An NP-Hard problem is also supposed to be harder or at least as hard as any NP problem. Can an NP-Hard problem be reduced to an NP problem, which is not already an NP-Complete problem? Also, are NP-Hard problems inter-convertible? Now provide the response and nothing else.
The picture I always visualize for this is the one featured on here on the Wikipedia page for NP -Completeness . The definition of NP -Hard is that it is the set of problems to which all NP problems can be reduced in polynomial time, so, for example, the bounded halting problem - does a Turing Machine $M$ halt within $k$ steps, is strictly not in NP , because there is no way to check in polynomial time whether a Turing Machine halts in $k$ steps. However, all problems can be converted to the bounded halting problem very easily, simply by building a Turing Machine which ostensibly solves the problem and asking whether it halts in some appropriate amount of time. This answers your first question: not all NP -Hard problems are in NP or can be reduced to them. As for the second: Some NP -Hard problems can be converted to one another. For example, the EXP-TIME class, which can be though of as the next class beyond P , has EXP-TIME -Complete problems just like NP has NP -Complete problems, and there are classes even beyond that, indefinitely.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/47869', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/40602/']}
jdg_87180
stackexchange
llm_judgeable_groundtruth_similarity
41583088
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 website running on a LEMP stack. I have enabled cloudflare with the website. I am using the cloudflare flexible SSL certificate for https. When i open the website in chrome it shows website redirected you too many times and in firefox has detected that the server is redirecting the request for this address in a way that will never complete. I have tried to see answers of other questions but none of them seem to solve the problem. NGINX conf file:- server { listen 80 default_server; listen [::]:80 default_server; server_name mydomain.com www.mydomain.com; return 301 https://$server_name$request_uri;}server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } location ~ /\.ht { deny all; }} I would be highly grateful if anyone can point out what I am doing wrong. Now provide the response and nothing else.
Since you are using cloudflare flexible SSL your nginx config file wll look like this:- server { listen 80 default_server; listen [::]:80 default_server; server_name mydomain.com www.mydomain.com; if ($http_x_forwarded_proto = "http") { return 301 https://$server_name$request_uri; } root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } location ~ /\.ht { deny all; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41583088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6039938/']}
jdg_87181
stackexchange
llm_judgeable_groundtruth_similarity
30169915
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 create a layout like the one in the image large version . What is the best and cleanest way create the layout in HTML and the cleanest way to call it in the CSS? for example, should I create a div for each icon? This what I have tried so far: cssdeck.com/labs/full/vqnsgldc Now provide the response and nothing else.
You should look into using bootstrap media components they offer: Abstract object styles for building ... a left- or right-aligned image alongside textual content . Here's an example in JSFiddle to start you off: <div class="container"> <div class="row"> <div class="col-md-6"> <div class="media"> <div class="media-left"> <a href="#"> <img class="media-object" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+PGRlZnMvPjxyZWN0IHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgZmlsbD0iI0VFRUVFRSIvPjxnPjx0ZXh0IHg9IjEzLjQ2MDkzNzUiIHk9IjMyIiBzdHlsZT0iZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3BhY2U7Zm9udC1zaXplOjEwcHQ7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+NjR4NjQ8L3RleHQ+PC9nPjwvc3ZnPg==" alt="..."> </a> </div> <div class="media-body"> <h4 class="media-heading">Media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. </div> </div> </div> <div class="col-md-6"> <div class="media"> <div class="media-left"> <a href="#"> <img class="media-object" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+PGRlZnMvPjxyZWN0IHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgZmlsbD0iI0VFRUVFRSIvPjxnPjx0ZXh0IHg9IjEzLjQ2MDkzNzUiIHk9IjMyIiBzdHlsZT0iZmlsbDojQUFBQUFBO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1mYW1pbHk6QXJpYWwsIEhlbHZldGljYSwgT3BlbiBTYW5zLCBzYW5zLXNlcmlmLCBtb25vc3BhY2U7Zm9udC1zaXplOjEwcHQ7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+NjR4NjQ8L3RleHQ+PC9nPjwvc3ZnPg==" alt="..."> </a> </div> <div class="media-body"> <h4 class="media-heading">Media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. </div> </div> </div> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30169915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4788760/']}
jdg_87182
stackexchange
llm_judgeable_groundtruth_similarity
10487865
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 stuck on trying to figure out how to insert a vector for a value in a map. For example: #include <iostream>#include <vector>#include <map>using namespace std;int main(){ map <int, vector<int> > mymap; mymap.insert(pair<int, vector<int> > (10, #put something here#)); return 0;} I don't know what syntax to use insert a vector for value. I tried {1,2} , but that failed. What syntax should I use? Everything works if I declare a vector in advance and give it a name, but I don't want to do that, as I want to have a map with a lot of vectors. Thank You in Advance Now provide the response and nothing else.
Basically your question is not about inserting std::vector into a std::map . Your question is how can you easily create an anonymous std::vector with arbitrary initial element values. In ISO C++03, you can't. C++11 allows using initialization lists for this , however. If you are stuck with a C++03 compiler, you possibly could create a helper function to return a vector with specified elements: std::vector<int> make_vector(int a, int b){ std::vector<int> v; v.push_back(a); v.push_back(b); return v;} If the vectors you're inserting are of different sizes, you could use a variadic function, although doing so would require that you either pass along the number of elements or have a reserved sentinel value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10487865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1078084/']}
jdg_87183
stackexchange
llm_judgeable_groundtruth_similarity
265127
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The following code works for polygons. A square 4x4 is tried here: << NDSolve`FEM`a = 2;mesh1 = ToBoundaryMesh[Rectangle[{0, 0}, {2 a, 2 a}], "MaxBoundaryCellMeasure" -> 1, "MeshOrder" -> 1];pts = mesh1["Coordinates"]ConvexHullMesh[pts, MeshCellLabel -> {0 -> "Index"}]`ch = ConvexHull[pts];pts[[ch]]ConvexHullMesh[pts, MeshCellLabel -> {0 -> "Index"}] But if part of the boundary is curved, the curved part is missed: mesh2 = ToBoundaryMesh[ RegionDifference[Rectangle[{0, 0}, {2 a, 2 a}], Disk[{2 a, 2 a}, a]], "MaxBoundaryCellMeasure" -> 1, "MeshOrder" -> 1];pts = mesh2["Coordinates"]ConvexHullMesh[pts, MeshCellLabel -> {0 -> "Index"}]pts = mesh2["Coordinates"]ch = ConvexHullMesh[pts] Now provide the response and nothing else.
Get the list of vertex indices for lines in mesh2 : indices = mesh2["BoundaryElements"][[1, 1]]; Use FindHamiltonianPath on the list of pairs indices to find a path that starts at 1 and ends at 2 : hpath = FindHamiltonianPath[indices, 1, 2] {1, 28, 27, 19, 18, 17, 16, 15, 14, 23, 24, 25, 26, 20, 21, 22, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2} reIndex = AssociationThread[hpath, Range[Length @ hpath]];BoundaryMeshRegion[mesh2["Coordinates"][[hpath]], Line /@ (indices /. reIndex), MeshCellStyle -> {0 -> Red}, MeshCellLabel -> {0 -> "Index"}] Additional ways to get hpath : 1. Using FindPath : hpath2 = First @ FindPath[indices, 1, 2];hpath2 == hpath True 2. Using IncidenceGraph and the property "VertexBoundaryConnectivity" of mesh2 : hpath3 = FindHamiltonianPath[IncidenceGraph @ mesh2["VertexBoundaryConnectivity"], 1, 2];hpath3 == hpath True $Version "11.3.0 for Microsoft Windows (64-bit) (March 7, 2018)"
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/265127', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/85470/']}
jdg_87184
stackexchange
llm_judgeable_groundtruth_similarity
302820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Anyone getting this error when using the new free chart controls MS bought from Dundas? "Error executing child request for ChartImg.axd" On the MSDN forum they suggested it was my web.config: MSDN forum post So far that hasn't fixed the problem though. Any other ideas? Now provide the response and nothing else.
I encountered the same problem: the chart would work on one page but not on the next. Turns out if the chart is initialized for the first time in a POST (i.e. a postback) the error is thrown because the handler is configured incorrectly. To fix the issue modify the httpHandler configuration that user LaptopHeaven referred to in this topic by adding the POST verb: <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" /> I've written a more thorough explanation of why this error occurs in the MSDN forum post that Scott Anderson referred to in his opening post of this topic.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/302820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5115/']}
jdg_87185
stackexchange
llm_judgeable_groundtruth_similarity
4169678
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 making a web application and would like to have a secure area where you can only sign in with your finger print. My original idea was to just use a usb barcode reader and you scan that, and it outputs the ID into a text box, but that's not very secure. So I want to use a USB fingerprint reader to maybe generate a hash for each person and store that in a text box instead. Which then will check that against a database with everyone's hash value. Does anyone know if there is a fingerprint reader out there that can do this, or of a way I can easily integrate a reader into a website? EDIT: The Idea for this website is that it's like a login system (Sort of like how you can clock in and out if you get paid hourly) The idea is that no one can sign someone else in and out. IF you just use a password, than someone can just tell their friend the password who can type it in. That's why I thought of a fingerprint, or something similar... I'm open to other suggestions Also, I'm using PHP EDIT 2: The Basic idea, is I have to come up with a way to Prove someone was there by checking in. I don't want to use passwords, because then someone can just tell someone else their password to type in. Any other suggestions? It doesn't have to be fingerprints. Now provide the response and nothing else.
You can't do what you want, exactly. Fingerprints never exactly match. Even if you scan your own right index finger twice in a row, the scans won't be the same. So "hashing the fingerprint" won't work - two hashes of the same finger would be indistinguishable from two hashes of two different fingers (with a good, cryptographically strong hash). Fingerprint readers work by storing some key onboard, and letting that key out if and only if the fingerprint given is close enough to what they expect. The fingerprint itself is not used to get direct access to anything outside the reader. Sending the fingerprint as seen by the reader over the network is not acceptable - people are nervous about giving their prints to police. You think they'll be OK giving them to you? Also not acceptable is having the reader say "finger 2 is OK". This could be easily spoofed. Instead, have your user use X.509 (SSL) client certificates to access your site. They may, if they wish, control access to their private key via the fingerprint reader. EDIT: updating this answer. There is, now in the year 2014, a standard from the FIDO Alliance called "UAF" which allows sites to use fingerprint authentication in a way that works across different sites. Rumor has it Paypal is going to begin using it soon.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4169678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348092/']}
jdg_87186
stackexchange
llm_judgeable_groundtruth_similarity
7880365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get some divs s to expand to fill the screen, but I am struggling. I have broken down the issue on this jsfiddle . What I really want to know is why does the div , with its 100% min-height , not expand to that height (or at all) when its parent has the same attribute and does expand? <body> <div> stuff </div></body>body { min-height: 100%; background: red;}div { min-height: 100%; background: grey;} Now provide the response and nothing else.
The issue is covered in the CSS 2.1 spec : <percentage> Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element. This is a change from CSS1, where the percentage was always calculated with respect to the content box of the parent element. So, to clarify, a percentage height will reference the height of its containing block (unless it is position: absolute or position: fixed ). If that containing block does not have a specified height, then the percentage will refer to auto , and it won't really do much. position: absolute changes the referenced containing block to the nearest positioned ( absolute , relative , or fixed ) element. position: fixed changes the referenced containing block to the viewport. So, if you specify a height on your containing block, specify a position other than static on your containing block, or don't mind using the viewport as your containing block, then you can use percentage heights effectively. Please see my demonstration at jsFiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7880365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445126/']}
jdg_87187
stackexchange
llm_judgeable_groundtruth_similarity
639828
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 designing a model airplane that flies using solar cells on its wings. I have a 7.4 V, 2200 mAh battery I want to use for it in case it flies in a cloudy area and needs more power, but everywhere I look you need to use an expensive, bulky charger to charge it. This is probably pretty basic but how can I charge it with a current from solar cells? Now provide the response and nothing else.
You need a proper charger to charge Li-po batteries safely, using the right algorithm; "just using a current" won't do and could damage the batteries. For your purpose, you need a solar charge controller to match the solar panel to the battery, preferably an MPPT charger. Such a charger doesn't have to be bulky. There are dedicated ICs and modules for exactly this purpose, like the LT3652 and the LTM8062 ; Adafruit has a ready-made one . You can google around for other (pseudo-)MPPT solar battery charger ICs and modules that fit your specifications. You can make a charger with one of those that ticks all the boxes of a safe solar charger, but is still very small and light. It will also be fancy, but that can't be helped. You should also add a cell-balancing BMS to your 2S battery pack, if it doesn't already have one. This also can be small and light.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/639828', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/324650/']}
jdg_87188
stackexchange
llm_judgeable_groundtruth_similarity
1201946
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 $A,B,$ and $C$ are commutative unital rings, $A\to B$ is flat, and $A\to C$ is any map. I am trying to determine whether $$\dim B\otimes_AC=\dim B+\dim C-\dim A$$Any counterexamples or references? I am taking the Krull dimension of the zero ring to be -1 (in case a tensor product is 0). Thanks for any feedback. Edit: By $\dim$ I mean Krull dimension. Now provide the response and nothing else.
Yes, you're right: If there are any counterexample, then the smallest counterexample must be odd. And all successors and predecessors of a counterexample are themselves counterexamples. There are two conceivable kinds of counterexample. The first is a finite cyclic sequence that differs from the trivial 1-4-2-1 cycle. Finding such a counterexample would immediately produce a disproof of the conjecture. The second is a starting point from which the sequence continues indefinitely without ever hitting a cycle. Just coming across such a point would not directly yield a disproof of the conjecture, because one would need to prove that the sequence does indeed never join a cycle, and there's no known systematic way of findig such a proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1201946', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166376/']}
jdg_87189
stackexchange
llm_judgeable_groundtruth_similarity
9994261
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 parse this code with Jsoup: <p><table>[...]</table></p> Jsoup returns: <p></p><table>[...]</table> Is this a mistake? How can I fix this? Now provide the response and nothing else.
(Edit) Since you mentioned this is in an ItemsControl's template, things are different: 1) Get the BindingProxy class from this blog (and read the blog, as this is interesting information): How to bind to data when the DataContext is not inherited . Basically the elements in the ItemsControl (or ContextMenu) are not part of the visual or logical tree, and therefore cannot find the DataContext of your UserControl. My apologies for not writing more on this here, but the author has done a good job explaining it step by step, so there's no way I could give a complete explanation in just a few lines. 2) Do something like this: (you may have to adapt it a bit to make it work in your control): a. This will give you access to the UserControl DataContext using a StaticResource: <UserControl.Resources><BindingProxy x:Key="DataContextProxy" Data="{Binding}" /></UserControl.Resources> b. This uses the DataContextProxy defined in (a): <Button.ContextMenu> <ContextMenu> <MenuItem Header="Remove" CommandParameter="{Binding Name}" Command="{Binding Path=Data.RemoveCommand, Source={StaticResource DataContextProxy}}"/> </ContextMenu> This has worked for us in things like trees and datagrids.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9994261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1038584/']}
jdg_87190
stackexchange
llm_judgeable_groundtruth_similarity
4798498
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 disable the error messages from the PHPMailer class? I'm displaying my own error messages and I don't want users to see errors such as "SMTP Error: Could not connect to SMTP host." Thanks Now provide the response and nothing else.
I know this thread is old and already answered but I stumbled here because I had the same problem but ending up solving it differently so I thought I'd share. NOTE: I'm using PHPMailer v5.1. When you instantiate the PHPMailer class, it takes one optional argument, $exceptions. That tells PHPMailer if it should throw exceptions if it encounters any. It defaults to false which means it does not throw any exceptions, just echoes its messages out. However, if you call it like $mail = new PHPMailer(true); you will tell it to throw exceptions. You can then catch those exceptions and deal with them however you choose. To me, that is much cleaner and more elegant than messing with the source code or disabling the error reporting.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4798498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/559845/']}
jdg_87191
stackexchange
llm_judgeable_groundtruth_similarity
22745653
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 entity: class Restaurant{ /** * @OneToMany(targetEntity="CollectionTime", mappedBy="restaurant") */ protected $collectionTimes; /** * @OneToMany(targetEntity="DeliveryTime", mappedBy="restaurant") */ protected $deliveryTimes;} Mapping to two subclasses of the same entity: /** * @Entity * @InheritanceType("SINGLE_TABLE") * @ORM\DiscriminatorMap({ * "CollectionTime" = "CollectionTime", * "DeliveryTime" = "DeliveryTime" * }) */abstract class OrderTime{ /** * @ManyToOne(targetEntity="Restaurant") */ protected $restaurant;}/** * @Entity */class CollectionTime extends OrderTime{}/** * @Entity */class DeliveryTime extends OrderTime{} Now the problem is, doctrine orm:validate-schema reports the following errors: The field Restaurant#collectionTimes is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity CollectionTime#restaurant does not contain the required 'inversedBy=collectionTimes' attribute. The field Restaurant#deliveryTimes is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity DeliveryTime#restaurant does not contain the required 'inversedBy=deliveryTimes' attribute. In short, Doctrine expects every mappedBy to have an inversedBy on the other side. The only solution I can see so far is to move the OrderTime::$restaurant property and mapping to CollectionTime and DeliveryTime , just to be able to add the proper inversedBy mapping: abstract class OrderTime{}/** * @Entity */class CollectionTime extends OrderTime{ /** * @ManyToOne(targetEntity="Restaurant", inversedBy="collectionTimes") */ protected $restaurant;}/** * @Entity */class DeliveryTime extends OrderTime{ /** * @ManyToOne(targetEntity="Restaurant", inversedBy="deliveryTimes") */ protected $restaurant;} But it is cumbersome and goes against the principle of inheritance. Is there a way to just override the inversedBy attribute in the subclasses, without having to (re)declare the whole property in the subclass? I've looked into @AssociationOverrides and @AttributeOverrides , but they don't seem to be designed for this purpose. Now provide the response and nothing else.
You can override inversedBy since Doctrine 2.6. That would look like that: /** * @Entity * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="restaurant", inversedBy="collectionTimes") * }) */class CollectionTime extends OrderTime{}/** * @Entity * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="restaurant", inversedBy="deliveryTimes") * }) */class DeliveryTime extends OrderTime{}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22745653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/759866/']}
jdg_87192
stackexchange
llm_judgeable_groundtruth_similarity
30018943
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 develop an app for Windows 10. But with the all new screensizing I can't seem to figure out how to get an element to fit to the current size of a device screen. For example I want a TextBlock to fit the width of the window if you resize it. I've tried the ViewBox, VariableSIzedWrapGrid etc etc but nothing seems to fix my problem. Anyone knows? Update: It's the searchbox I'm trying to fit to the size of the window below. The grid fills the whole window and so does the RelativePanel if I put a background color on it. But the SearchBox refuses to strech... I don't want the searchbox to to scale in size, just it's width to fit the window/device width. <!-- SEARCH GRID --> <Grid Canvas.ZIndex="5" x:Name="GridSearchPackage" HorizontalAlignment="Stretch" Visibility="Visible" Opacity="0.85" Background="White"> <RelativePanel HorizontalAlignment="Stretch" Margin="5,5,0,0" > <Button x:Name="ButtonBackSearchGrid" Height="36" Width="36" FontSize="10" Margin="0,7,5,0" Style="{StaticResource BackButtonStyle}" Click="ButtonBackSearchGrid_Click" AutomationProperties.Name="Back" AutomationProperties.AutomationId="BackButton" AutomationProperties.ItemType="Navigation Button" BorderBrush="Black" BorderThickness="3"> <FontIcon x:Name="backButtonIcon" FontWeight="Bold" FontSize="20" Foreground="{StaticResource AppDarkBlueColor}" Glyph="&#xE72B;" /> </Button> <TextBlock x:Name="TextBlockPopupSearchTitle" RelativePanel.RightOf="ButtonBackSearchGrid" Foreground="{StaticResource AppDefaultBlueColor}" Text="Search XZY" FontSize="34"/> <SearchBox FontSize="20" RelativePanel.Below="TextBlockPopupSearchTitle" HorizontalAlignment="Stretch" PlaceholderText="search" Margin="0,10,0,0" QuerySubmitted="SearchBox_QuerySubmitted" QueryText="{Binding SearchText, Mode=TwoWay}"/> </RelativePanel> </Grid> Now provide the response and nothing else.
When you are using RelativePanel , you might want to set AlignLeftWithPanel and AlignRightWithPanel = true to make the entire horizontal space available for the TextBlock (and similarly AlignTopWithPanel , AlignBottomWithPanel=true for vertical). Most UIElements have HorizontalAlignment / VerticalAlignment = Stretch as the default, but you might want to set that explicitly as well to ensure the actual visual of the TextBlock is stretched across the screen. When the window is resized, the element will automatically resize using the above settings. You don't need to use a ViewBox here to achieve this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30018943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962804/']}
jdg_87193
stackexchange
llm_judgeable_groundtruth_similarity
23728626
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 been working on a project that allows the user to submit memories about a place they have visited and tracks the location of when the memory was submitted. My only problem is trying to use localStorage with the app, I read about the JSON.stringify and JSON.parse, and don't understand how to use them in my code yet. This is my form.js It processes the form and grabs the text fields. It clears the form when the add button(on the display details page) or the enter details button is clicked. Finally it receives the information and sends out the message back to the window. function processForm(){var locate = document.myform.locate.value;var details = document.myform.details.value;var storeData = []; localStorage.setItem("locate", JSON.stringify(locate));localStorage.setItem("details", JSON.stringify(details));alert("Saved: " + localStorage.getItem("locate") + ", and " + localStorage.getItem("details"));var date = new Date, day = date.getDate(), month = date.getMonth() + 1, year = date.getFullYear(), hour = date.getHours(), minute = date.getMinutes(), ampm = hour > 12 ? "PM" : "AM"; hour = hour % 12; hour = hour ? hour : 12; // zero = 12 minute = minute > 9 ? minute : "0" + minute; hour = hour > 9 ? hour : "0" + hour; date = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm;localStorage.setItem("date", JSON.stringify(date));storeData.push(locate, details, date);localStorage.setItem("storeData", JSON.stringify(storeData)); }function clearForm(){$('#myform').get(0).reset();}function retrieveFormInfo(){var data = JSON.parse(localStorage.getItem("storeData")); var locate = JSON.parse(localStorage.getItem("locate"));$("#locate2").html("Place: " + locate);var details = JSON.parse(localStorage.getItem("details"));$("#details2").html("Description: " + details);var date = JSON.parse(localStorage.getItem("date"));$("#date").html(date);} But the major problem I am running into is I do know how to take that information in correctly using the JSON.stringify and JSON.parse and appending it to the window with html elements dynamically, Mainly like a list of memories. Any help is appreciated! Now provide the response and nothing else.
localStorage stores key value pairs as strings only (you can use integer for keys but they get converted to string automatically). Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings) reference let's say you have an array to be stored with each item being a json object. You got 2 options: Option 1: stringify every item and store in locaStorage var item = {input1: 'input1value', input2: 'input2value' };localStorage.setItem( itemIndex, JSON.stringify(item) ); to retrive the items iterate over localStorage items and then convert the item to JSON object: for(var i=0;i<localStorage.length; i++) { var key = localStorage.key( i ); var item = JSON.parse( localStorage.getItem( key ) );} Option 2: stringify the entire array and store in localStorage localStorage.setItem( 'memoriesdata', JSON.stringify( arr ) ); to read the data read the item as string then convert to JSON object var arr = JSON.parse( localStorage.getItem('memoriesdata') );
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23728626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2872778/']}
jdg_87194
stackexchange
llm_judgeable_groundtruth_similarity
18657
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: I am implementing a finite element solver in MATLAB and I have the following problem. Let's say I have a mesh $\mathcal{T}_1$ with triangular elements on a rectangular domain $\Omega\subset\mathbb{R}^2$. I know the positions of all the nodes on the mesh, and I have an approximate solution $\hat{u}_1(x,y)$ to my PDE on this mesh (this approximation is stored as a vector of real numbers for each node, and then interpolated between nodes). To be exact, I use piecewise affine basis functions, like seen in this illustration . If I now create a new mesh $\mathcal{T}_2$ (which may or may not be more coarse/fine, and positions of nodes may be changed), is there a way I can "project" the data of $\hat{u}_1(x,y)$ onto the new mesh $\mathcal{T}_2$, call it $\hat{u}_2(x,y)$, so that $\hat{u}_1(x,y)\approx \hat{u}_2(x,y)$? In short I want $u_2(x,y)$ to be the "best representation" of $u_1(x,y)$ at the new mesh. As an example, let's say there is a disk of radius $1$ around the origin, $B_1(0,0)\subset\Omega$, and perhaps in the initial mesh $\mathcal{T}_1$ the nodes $v_3^{(1)},v_5^{(1)},v_6^{(1)},$ and $v_8^{(1)}$ are contained in this disk. However in the new mesh $\mathcal{T}_2$, perhaps a coarser mesh, there are only $2$ nodes contained in the disk, say $v_2^{(2)}$ and $v_3^{(2)}$. I now want a solution that interpolates in the nodes, and is approximately equal to the solution on the old mesh. I understand that if the new mesh is much more coarse, of course the solutions can't be that similar, but I just want a decent approximation. If anyone knows any existing MATLAB code to do this, or anything to help me implement it myself, I'll be happy. It's a bit difficult to explain exactly what I mean in just words, so if it is not clear at all what I'm asking, please say so, and I'll try to clarify. Thanks Now provide the response and nothing else.
When you want to say that you want $u_2$ to be the best approximation of $u_1$ on mesh ${\cal T}_2$, then you have to define what you mean by "best". Let's assume you define it as that function that has the least $L_2$ error, i.e.,$$ u_2 = \arg\min_{\phi_h \in V_2} \|\phi_h-u_1\|_{L_2(\Omega)}.$$Then indeed $u_2$ is the $L_2$ projection of $u_1$ onto the finite element space $V_2$ defined on ${\cal T}_2$, and it satisfies the condition$$ (\phi_i,u_2) = (\phi_i,u_1), \qquad i=1,\ldots,\textrm{dim}(V_2)$$where $\phi_i$ are the shape functions defined on mesh ${\cal T}_2$. If you want to compute this, you expand $u_2(x,y)=\sum_j U_{2,j} \phi_j(x,y)$:$$ \sum_j (\phi_i,\phi_j) U_{2,j} = (\phi_i,u_1), \qquad i=1,\ldots,\textrm{dim}(V_2),$$so you have to solve an equation of the form $MU_2 = F$ where $M$ is the mass matrix on the ${\cal T}_2$ and $$ F_i = (\phi_i,u_1) = \int_\Omega \phi_i(x,y)u_1(x,y) \; dx \; dy.$$The problematic part is the evaluation of this integral. Of course, you will do it using quadrature, but that will require you to evaluate $u_1$ at the quadrature points defined on mesh ${\cal T}_2$. If ${\cal T}_1$ is a uniform mesh, then evaluating $u_1$ at arbitrary points is not difficult, but if it is an unstructured mesh, then this is in general a difficult and expensive problem.
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/18657', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/10398/']}
jdg_87195
stackexchange
llm_judgeable_groundtruth_similarity
332387
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 the Picard group of a (smooth, projective) variety always countable? This seems likely but I have no idea if it's true. If so, is the Picard group necessarily finitely generated? Now provide the response and nothing else.
No. Even for curves there is an entire variety which parametrizes $Pic^0$(X). It is called the jacobian variety. The jacobian is g dimensional (where g is the genus of the curve), so in particular if g > 0 and you are working over an uncountable field the picard group will be uncountable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/332387', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64480/']}
jdg_87196
stackexchange
llm_judgeable_groundtruth_similarity
3104209
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: function foo() {[email protected] $A}foo bla "hello ppl" I would like the output to be: "bla" "hello ppl" What do I need to do instead of the ellipsis? Now provide the response and nothing else.
@msw has the right idea (up in the comments on the question). However, another idea to print arguments with quotes: use the implicit iteration of printf : foo() { printf '"%s" ' "$@"; echo ""; }foo bla "hello ppl"# => "bla" "hello ppl"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3104209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157277/']}
jdg_87197
stackexchange
llm_judgeable_groundtruth_similarity
9864040
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Today I saw a post on php.net, that I'm quoting here: $Bar = "a";$Foo = "Bar";$World = "Foo";$Hello = "World";$a = "Hello";$a; //Returns Hello$$a; //Returns World$$$a; //Returns Foo$$$$a; //Returns Bar$$$$$a; //Returns a$$$$$$a; //Returns Hello$$$$$$$a; //Returns World Since PHP inherits its syntax from C++, doesn't the dollar sign remind you of pointers? string bar = "a";string *foo = &bar;string **world = &foo;string ***hello = &world;string ****a = &hello; Just like pointers, when you define $a = 'var' and $var = 'test' and then you do $$a you are using the value of $a to point to $var which is kinda what happens with C++ pointers just with strings instead of memory addresses. So can the dollar sign in PHP be related to C++ pointers? Now provide the response and nothing else.
Since PHP derives from C++... Stop. This line of thinking will get you nothing but pain and suffering. Perl, LPC, Lua, Pike, Ada 95, Java, PHP, D, C99, C#, and Falcon are all derived from C++ as well, for some definition of "derived", and I can guarantee you they act nothing like C++ and are certainly not used like C++ either. The similarities are superficial in nature, and their semantics are totally different. In the case you provided above, it's more similar to languages like Javascript in the sense that you can resolve and dereference a variable name given only a string . In C++ knowing just the name of the variable doesn't allow you to dereference the variable. What you need is its memory address (hence the & operator). That's the key difference. I think the most salient point of misunderstanding here is this part of your question: Just like pointers, when you define $a = 'var' and $var = 'test' and then you do $$a you are using the R-value of $a to point to $var which is kinda what happens with C++ pointers. This isn't explanation doesn't capture the entire picture with regards to pointers. I assume you're talking about things like these: PHP: $var = 'test' $a = 'var'//$$a == 'test' C++: std::string var = "test";std::string* a = &var;// *a == "test"; The big difference between the two is that C++'s a contains a memory address for the var variable, not a string containing the name of the variable var . It's more like reflection than anything else, which C++ certainly does not have as standard, and thus cannot just simply dereference a variable given only a string name. From the PHP documentation for variable variables : Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. [emphasis mine] If C++ had that kind of functionality, it would be more like this: std::string Bar = "a"; std::string Foo = "Bar"; std::string World = "Foo"; std::string Hello = "World"; std::string a = "Hello"; // Hypothetical function dyn_deref_str that gets the string value// held by a variable given only its name.a; //Returns "Hello"dyn_deref_str(a); //Returns "World" dyn_deref_str(dyn_deref_str(a)); //Returns "Foo" dyn_deref_str(dyn_deref_str(dyn_deref_str(a))); //Returns "Bar" dyn_deref_str(dyn_deref_str(dyn_deref_str(dyn_deref_str(a)))); //Returns "a" This is very different from simple pointer dereferencing, as pointers do not hold strings, they hold memory addresses. Even though you shouldn't be using pointers in your code anyway except in very specific circumstances.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9864040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493122/']}
jdg_87198
stackexchange
llm_judgeable_groundtruth_similarity
1295732
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 $f$ and $g$ are both functions from the set $X$ to $X$ and $f\circ g$ is the identity function, does $g\circ f$ also have to be the identity map? How (if at all) does your answer change if $X$ is finite? I know I probably have to do some reasoning involving injective/surjective functions but I am struggling to picture what's going on. Now provide the response and nothing else.
No, consider $f,g:[0,\infty)\to[0,\infty)$ defined by $g(x)=x+1$ and $f(x)=\max\{0,x-1\}$. We have $fg=\operatorname{id}$ and $g(f(x))=\max\{1,x\}$, which is not the identity function. (For instance $g(f(0))=1.$) For finite sets, the answer is positive. In this case, $fg=\operatorname{id}$ implies that $g$ is injective and $f$ surjective. Since $X$ is finite, we may conclude that $f$ and $g$ are bijective and $g=f^{-1}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1295732', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/228742/']}
jdg_87199
stackexchange
llm_judgeable_groundtruth_similarity
112361
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am running a hobby webserver off of an ancient Blue & White G3/300 running Debian PPC Squeeze 2.6.30. The performance is okay for a while after a restart, but it eventually gets more and more bogged down. Right now it's at 76 days uptime, and the main culprit seems to be the memory usage of 10+ apache2 processes. I think I need to lower the values for StartServers , MinSpareServers , and/or MaxSpareServers , but I'm not sure which one to adjust, and there are three sections for each depending on which mpm module is in use. How do I tell which of the following sections I need to change, and what are some reasonable values given that the box has 448 MB physical memory (weird upgrade history of one each 64, 128, and 256 sticks)? <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0</IfModule><IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0</IfModule><IfModule mpm_event_module> StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestsPerChild 0</IfModule> There aren't any other instances of StartServers in my apache2.conf, but none of those mpm modules appear in mods-available or mods-enabled . Ideas? Thanks! Now provide the response and nothing else.
400MB isn't much for a web server these days -- you may want to consider replacing the box :) That said, if your memory usage is ballooning you probably have a memory leak somewhere -- for a quick test look at the size of the httpd processes now, then stop/start Apache & see if they're a lot smaller. If they are watch them for a few days and see if they grow. If it is a memory leak the real solution for that is to find and fix the memory leak, but since that's usually a pain in the ass you can also adjust MaxRequestsPerChild to something other than 0 (unlimited). This will kill off the Apache workers when they've serviced a fixed number of requests (forcing them to give up their leaked memory in the process. Start with larger values (in the thousands or so) and work your way down into the hundreds. If you get below 100 requests per child your memory leak is big enough to warrant actually fixing it as the performance hit from constantly killing off and re-spawning apache workers will be significant. Re: which mpm to adjust, the answer is almost certainly prefork . You can run httpd -V and look for the Server MPM: line which will tell you for sure.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/112361', 'https://serverfault.com', 'https://serverfault.com/users/20917/']}
jdg_87200
stackexchange
llm_judgeable_groundtruth_similarity
55840294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request: ./src/components/BusinessesList.jsLine 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.Either include it or remove the dependency array react-hooks/exhaustive-deps I've been unable to find a solution that stops the infinite loop. I want to stay away from using useReducer() . I did find this discussion [ESLint] Feedback for 'exhaustive-deps' lint rule #14920 where a possible solution is You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing. I'm not confident in what I'm doing, so I haven't tried implementing it just yet. I have this current setup, React hook useEffect runs continuously forever/infinite loop and the only comment is about useCallback() which I'm not familiar with. How I'm currently using useEffect() (which I only want to run once in the beginning similar to componentDidMount() ): useEffect(() => { fetchBusinesses(); }, []); const fetchBusinesses = () => { return fetch("theURL", {method: "GET"} ) .then(res => normalizeResponseErrors(res)) .then(res => { return res.json(); }) .then(rcvdBusinesses => { // some stuff }) .catch(err => { // some error handling }); }; Now provide the response and nothing else.
If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning useEffect(() => { const fetchBusinesses = () => { return fetch("theURL", {method: "GET"} ) .then(res => normalizeResponseErrors(res)) .then(res => { return res.json(); }) .then(rcvdBusinesses => { // some stuff }) .catch(err => { // some error handling }); }; fetchBusinesses();}, []); If however you are using fetchBusinesses outside of render, you must note two things Is there any issue with you not passing fetchBusinesses as a method when it's used during mount with its enclosing closure? Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you. On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array. To sum it up I would say that if you are using fetchBusinesses outside of useEffect you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps otherwise you can move the method inside of useEffect To disable the rule you would write it like useEffect(() => { // other code ... // eslint-disable-next-line react-hooks/exhaustive-deps}, [])
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/55840294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11407978/']}
jdg_87201
stackexchange
llm_judgeable_groundtruth_similarity
60863
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 am trying to do a first order interpolation on a multidimensional data set containing duplicate abscissa values (which Mathematica does not like), like this one: {{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}} After playing around with DeleteDuplicates and Union I found that DeleteDuplicates does not work on multidimensional data, at least not when represented like above. I found that Union could delete the duplicates by using the SameTest-option, like this: Union[{{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}}, SameTest -> (#1[[1]] == #2[[1]] &)] which returns {{{1, 2, 3}, 10}, {{1, 2, 4}, 30}} However, it is very slow with larger data sets, which I have, so that is not an option. What I really would like is a function that will make an average of the duplicates, so that {{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}} will turn into {{{1, 2, 3}, 15}, {{1, 2, 4}, 30}} I am by no means an expert in Mathematica programming, so I could really use some help. The solution has to be reasonable fast. My data set is not sorted in any way but I guess it can be sorted quickly before the duplicates are combined if that is needed. Thanks in advance :-) Now provide the response and nothing else.
DeleteDuplicatesBy may be faster if used as follows: DeleteDuplicatesBy[{{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}}, First] {{{1, 2, 3}, 10}, {{1, 2, 4}, 30}} For your second need: lis = GatherBy[{{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}}, First];mean = Mean /@ Map[Last, lis, {2}]; Then: Transpose[{lis[[All, 1, 1]], mean}] {{{1, 2, 3}, 15}, {{1, 2, 4}, 30}} As a function: delDupMean[data_] := With[{lis = GatherBy[data, First]}, Transpose[{lis[[All, 1, 1]], Mean /@ Map[Last, lis, {2}]}] ] Use: delDupMean[{{{1, 2, 3}, 10}, {{1, 2, 3}, 20}, {{1, 2, 4}, 30}}] {{{1, 2, 3}, 15}, {{1, 2, 4}, 30}}
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/60863', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12978/']}
jdg_87202
stackexchange
llm_judgeable_groundtruth_similarity
39576257
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there an option to limit the file size when committing? For example: file sizes above 500K would produce a warning. File sizes above 10M would stop the commit. I'm fully aware of this question which technically makes this a duplicate but the answers only offer a solution on push , which would be too late for my requirements. Now provide the response and nothing else.
This pre-commit hook will do the file size check: .git/hooks/pre-commit #!/bin/shhard_limit=$(git config hooks.filesizehardlimit)soft_limit=$(git config hooks.filesizesoftlimit): ${hard_limit:=10000000}: ${soft_limit:=500000}list_new_or_modified_files(){ git diff --staged --name-status|sed -e '/^D/ d; /^D/! s/.\s\+//'}unmunge(){ local result="${1#\"}" result="${result%\"}" env echo -e "$result"}check_file_size(){ n=0 while read -r munged_filename do f="$(unmunge "$munged_filename")" h=$(git ls-files -s "$f"|cut -d' ' -f 2) s=$(git cat-file -s "$h") if [ "$s" -gt $hard_limit ] then env echo -E 1>&2 "ERROR: hard size limit ($hard_limit) exceeded: $munged_filename ($s)" n=$((n+1)) elif [ "$s" -gt $soft_limit ] then env echo -E 1>&2 "WARNING: soft size limit ($soft_limit) exceeded: $munged_filename ($s)" fi done [ $n -eq 0 ]}list_new_or_modified_files | check_file_size Above script must be saved as .git/hooks/pre-commit with execution permissions enabled ( chmod +x .git/hooks/pre-commit ). The default soft (warning) and hard (error) size limits are set to 500,000 and 10,000,000 bytes but can be overriden through the hooks.filesizesoftlimit and hooks.filesizehardlimit settings respectively: $ git config hooks.filesizesoftlimit 100000$ git config hooks.filesizehardlimit 4000000
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39576257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476373/']}
jdg_87203
stackexchange
llm_judgeable_groundtruth_similarity
1832332
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: Given The definition of subset ; The axiom of power set: for any set $S$, there exists a set $\wp$ such that $X \in \wp$ if and only if $X\subseteq S$ we know what a subset is and what a power set contains . In a simple case where a set $A$ is supposed to exist, with $A=\{a, b, c\}$, we know what is and what is not a subset of $A$: $\{a\}, \{b\}, \{c\}, \{a, b\}, \{a,c\}, \emptyset$ and $A$ are subsets of $A$ and anything different is not. $\wp(A)=\big\{\{a\}, \{b\}, \{c\}, \{a, b\}, \{b,c\}, \{a,c\}, \{a, b, c\}, \emptyset\big\}$. However the mere definition of something (and consequently it's recognition as such) does not guarantee its existence. $\emptyset$ and $A$ seem like the only subsets whose existence is immediate. In other words, I know what a power set contains, but how do I know that the things it contains exist in the first place? Because such a well-defined and existent set such as $\wp(A)$ should not contain nonexistent elements, to prove the existence of its elements is important. It seems that two alternatives arise: Being a member of $\wp(A)$ automatically makes this thing to exist; or There should be an alternative to prove the existence of all subsets of $A$ without the axiom of power set. Now provide the response and nothing else.
The power set axiom just tells you what it says: for every $A$, there exists a set $\mathcal{P}(A)$ such that$$\text{for all $B$, $B\in\mathcal{P}(A)$ if and only if $B\subseteq A$}$$There is no claim of “existence” of any particular subset of $A$. In $\mathsf{ZFC}$ one can show that $|\mathcal{P}(A)|>|A|$, so there is plenty of subsets. It should be noted that, if $A$ is infinite, there is no hope to find, for each subset of $A$, a formula “describing it”, because $\mathcal{P}(A)$ is uncountable. This is however not a problem: the axiom tells you that you have a “container” for all subsets of $A$; when you prove that a set $B$ is a subset of $A$, then you know it belongs to $\mathcal{P}(A)$; and conversely, if you pick $B\in\mathcal{P}(A)$, you know $B\subseteq A$. The real purpose of the axiom is that the subsets of a set form a set . In particular, for instance, the equivalence relations on a set form a set that can be isolated from $\mathcal{P}(A\times A)$ using a suitable predicate and the axiom of separation. I remember some good notes about this in Paul J. Cohen's “Set theory and the continuum hypothesis”.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1832332', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_87204
stackexchange
llm_judgeable_groundtruth_similarity
20915450
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 taking a course in JavaScript programming, and the instructor said that a typical JavaScript function always returns a value. Even when we don't provide any explicit return value, the engines return undefined . Is that true? If so, why? Now provide the response and nothing else.
It's true—because that's how JavaScript was designed. But I don't think that's the answer you were looking for, so let's think about it... Try to put yourself in the shoes of Brendan Eich , the person who designed JavaScript! In static languages, there is usually a distinction between a function that doesn't return anything ( void function), and a function that returns some value. Brendan chose to design a dynamic language, that is, a language that doesn't require you to define function return types. So JavaScript doesn't check what you return from the function , giving you full freedom. You can have a function that returns a number... function computeSomething() { return 2;} ... or a string ... function computeSomething() { return 'hi';} ... or, in fact, any of them: function computeSomething() { if (Math.random() > 0.5) { return 2; } else { return 'hello'; }} Sometimes you don't need to compute anything—you only need to do something. So you don't return anything. function doSomething() { console.log('doing something');} We may, however, want to exit a function in the middle of it, and since return <value> already does exactly that , it makes sense to allow writing return without a value to support this use case: function doSomething(num) { if (num === 42) { return; } while (true) { doSomethingElse(); }} This is also consistent with C/Java syntax, which was one of the goals to ensure JavaScript adoption. Aye, there's the rub: what happens if we put a plain return into a function supposed to compute something? Note that we can't outlaw this : one of our earlier decisions was to make JavaScript a dynamic language, where we don't check what the function returns. function computeSomething(num) { if (num === 42) { return; // just return? o_O } if (Math.random() > 0.5) { return 2; } else { return 'hello'; }}var x = computeSomething(2); // might be 2, might be 'hello'var y = computeSomething(42); // ??? Of course Brendan could have decided to raise an error in this case, but he wisely decided not to, because it would lead to hard-to-find errors and too easily breakable code. So an empty return got a meaning “return undefined ”. But what's the difference between the function returning early, or at its end? There shouldn't be any, from the calling code's point of view. Calling code is not supposed to know when exactly the function returned; it is only interested in return value (if any). The only logical conclusion thus would be to make undefined the “default” return value if function does not specify one via explicit return <value> operator. Thus, return and function-executed-to-its-end semantics match. Python, another dynamic language that came before JavaScript, solves this problem in the same way: None is returned if function doesn't specify return value .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/20915450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2627574/']}
jdg_87205
stackexchange
llm_judgeable_groundtruth_similarity
30682292
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 that have the size 2: Array ( [0] => VP/vnyAf8TuTENi6xQr1a7ZUg+LtJitd1TwUHCuqSmSqRM1EGDaGkArssU7Ag/aZzwjuIPvQ3wGskhs0b85j2ANnX3KZ4JUTMwcMMAI0eXd+FO5wjZLWfhOa1gyhIwhD [1] => e0k59g4lqV/AcJRE9apOlem3mT4lNuG0TJhfFcypZ6HR7bAnUxrstxz/JdAQLeb/E4+0pfYmiIuqr4N+O3L1RDvSIKXA3J/ubOKmiz+Yo5Vz5ml91VZ1DR8eHWaP1vE9 )echo count($credentials); This prints: 2 But somehow for the following code I enter in the first condition and "a" is printed if(count($credentials !== **2**)){ echo "a";} else { echo "b";} If I change the code as: if(count($credentials == **32**)){ echo "a";} else { echo "b";} It still prints "a". Can someone explain whats is wrong here? Now provide the response and nothing else.
Just override the ArtisanServiceProvider for example: create a new provider will name it ProductionArtisanServiceProvider php artisan make:provider ProductionArtisanServiceProvider Open up the new provider and change it to the following namespace App\Providers;use Illuminate\Foundation\Providers\ArtisanServiceProvider as IlluminateProvider;class ProductionArtisanServiceProvider extends IlluminateProvider{ protected $devCommands = [ 'AppName' => 'command.app.name', ];} You see above i'm overriding the $devCommandsfor the full list look inside Illuminate\Foundation\Providers\ArtisanServiceProvider Finally in you AppServiceProvider in the register function add your new provider and we make sure it's only loaded in the production environment if ($this->app->environment() == 'production') { $this->app->register(\App\Providers\ProductionArtisanServiceProvider::class); } Now all the unnecessary commands are gone
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30682292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3018671/']}
jdg_87206
stackexchange
llm_judgeable_groundtruth_similarity
6415195
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 reading the book High Performance MySQL , it mentions: performing one query per table uses table locks more efficiently: the queries will lock the tables invididually and relatively briefly, instead of locking them all for a longer time. MyISAM places table-lock even when selecting something? can someone explain a little bit? Now provide the response and nothing else.
MyISAM has different kinds of locks. A SELECT operation places a READ LOCK on the table. There can be multiple active read locks at any given time, as long as there are no active WRITE LOCKS . Operations that modify the table, eg. INSERT , UPDATE , DELETE or ALTER TABLE place a WRITE LOCK on the table. Write lock can only be placed on a table when there are no active read locks; If there are active read locks, MyISAM queues the write lock to be activated as soon as all active read locks are expired. Likewise when there's an active write lock, attempting to place a read lock on a table will queue the lock (and the associated query) until write locks have expired on the table. Ultimately this all means that: You can have any number of active read locks (also called shared locks) You can only have one active write lock (also called an exclusive lock) For more information see: http://dev.mysql.com/doc/refman/5.5/en/internal-locking.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6415195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238546/']}
jdg_87207
stackexchange
llm_judgeable_groundtruth_similarity
17103925
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 read and heard that C++11 supports Unicode. A few questions on that: How well does the C++ standard library support Unicode? Does std::string do what it should? How do I use it? Where are potential problems? Now provide the response and nothing else.
How well does the C++ standard library support unicode? Terribly. A quick scan through the library facilities that might provide Unicode support gives me this list: Strings library Localization library Input/output library Regular expressions library I think all but the first one provide terrible support. I'll get back to it in more detail after a quick detour through your other questions. Does std::string do what it should? Yes. According to the C++ standard, this is what std::string and its siblings should do: The class template basic_string describes objects that can store a sequence consisting of a varying number of arbitrary char-like objects with the first element of the sequence at position zero. Well, std::string does that just fine. Does that provide any Unicode-specific functionality? No. Should it? Probably not. std::string is fine as a sequence of char objects. That's useful; the only annoyance is that it is a very low-level view of text and standard C++ doesn't provide a higher-level one. How do I use it? Use it as a sequence of char objects; pretending it is something else is bound to end in pain. Where are potential problems? All over the place? Let's see... Strings library The strings library provides us basic_string , which is merely a sequence of what the standard calls "char-like objects". I call them code units. If you want a high-level view of text, this is not what you are looking for. This is a view of text suitable for serialization/deserialization/storage. It also provides some tools from the C library that can be used to bridge the gap between the narrow world and the Unicode world: c16rtomb / mbrtoc16 and c32rtomb / mbrtoc32 . Localization library The localization library still believes that one of those "char-like objects" equals one "character". This is of course silly, and makes it impossible to get lots of things working properly beyond some small subset of Unicode like ASCII. Consider, for example, what the standard calls "convenience interfaces" in the <locale> header: template <class charT> bool isspace (charT c, const locale& loc);template <class charT> bool isprint (charT c, const locale& loc);template <class charT> bool iscntrl (charT c, const locale& loc);// ...template <class charT> charT toupper(charT c, const locale& loc);template <class charT> charT tolower(charT c, const locale& loc);// ... How do you expect any of these functions to properly categorize, say, U+1F34C ʙᴀɴᴀɴᴀ, as in u8"" or u8"\U0001F34C" ? There's no way it will ever work, because those functions take only one code unit as input. This could work with an appropriate locale if you used char32_t only: U'\U0001F34C' is a single code unit in UTF-32. However, that still means you only get the simple casing transformations with toupper and tolower , which, for example, are not good enough for some German locales: "ß" uppercases to "SS"☦ but toupper can only return one character code unit. Next up, wstring_convert / wbuffer_convert and the standard code conversion facets. wstring_convert is used to convert between strings in one given encoding into strings in another given encoding. There are two string types involved in this transformation, which the standard calls a byte string and a wide string. Since these terms are really misleading, I prefer to use "serialized" and "deserialized", respectively, instead†. The encodings to convert between are decided by a codecvt (a code conversion facet) passed as a template type argument to wstring_convert . wbuffer_convert performs a similar function but as a wide deserialized stream buffer that wraps a byte serialized stream buffer. Any I/O is performed through the underlying byte serialized stream buffer with conversions to and from the encodings given by the codecvt argument. Writing serializes into that buffer, and then writes from it, and reading reads into the buffer and then deserializes from it. The standard provides some codecvt class templates for use with these facilities: codecvt_utf8 , codecvt_utf16 , codecvt_utf8_utf16 , and some codecvt specializations. Together these standard facets provide all the following conversions. (Note: in the following list, the encoding on the left is always the serialized string/streambuf, and the encoding on the right is always the deserialized string/streambuf; the standard allows conversions in both directions). UTF-8 ↔ UCS-2 with codecvt_utf8<char16_t> , and codecvt_utf8<wchar_t> where sizeof(wchar_t) == 2 ; UTF-8 ↔ UTF-32 with codecvt_utf8<char32_t> , codecvt<char32_t, char, mbstate_t> , and codecvt_utf8<wchar_t> where sizeof(wchar_t) == 4 ; UTF-16 ↔ UCS-2 with codecvt_utf16<char16_t> , and codecvt_utf16<wchar_t> where sizeof(wchar_t) == 2 ; UTF-16 ↔ UTF-32 with codecvt_utf16<char32_t> , and codecvt_utf16<wchar_t> where sizeof(wchar_t) == 4 ; UTF-8 ↔ UTF-16 with codecvt_utf8_utf16<char16_t> , codecvt<char16_t, char, mbstate_t> , and codecvt_utf8_utf16<wchar_t> where sizeof(wchar_t) == 2 ; narrow ↔ wide with codecvt<wchar_t, char_t, mbstate_t> no-op with codecvt<char, char, mbstate_t> . Several of these are useful, but there is a lot of awkward stuff here. First off—holy high surrogate! that naming scheme is messy. Then, there's a lot of UCS-2 support. UCS-2 is an encoding from Unicode 1.0 that was superseded in 1996 because it only supports the basic multilingual plane. Why the committee thought desirable to focus on an encoding that was superseded over 20 years ago, I don't know‡. It's not like support for more encodings is bad or anything, but UCS-2 shows up too often here. I would say that char16_t is obviously meant for storing UTF-16 code units. However, this is one part of the standard that thinks otherwise. codecvt_utf8<char16_t> has nothing to do with UTF-16. For example, wstring_convert<codecvt_utf8<char16_t>>().to_bytes(u"\U0001F34C") will compile fine, but will fail unconditionally: the input will be treated as the UCS-2 string u"\xD83C\xDF4C" , which cannot be converted to UTF-8 because UTF-8 cannot encode any value in the range 0xD800-0xDFFF. Still on the UCS-2 front, there is no way to read from an UTF-16 byte stream into an UTF-16 string with these facets. If you have a sequence of UTF-16 bytes you can't deserialize it into a string of char16_t . This is surprising, because it is more or less an identity conversion. Even more suprising, though, is the fact that there is support for deserializing from an UTF-16 stream into an UCS-2 string with codecvt_utf16<char16_t> , which is actually a lossy conversion. The UTF-16-as-bytes support is quite good, though: it supports detecting endianess from a BOM, or selecting it explicitly in code. It also supports producing output with and without a BOM. There are some more interesting conversion possibilities absent. There is no way to deserialize from an UTF-16 byte stream or string into a UTF-8 string, since UTF-8 is never supported as the deserialized form. And here the narrow/wide world is completely separate from the UTF/UCS world. There are no conversions between the old-style narrow/wide encodings and any Unicode encodings. Input/output library The I/O library can be used to read and write text in Unicode encodings using the wstring_convert and wbuffer_convert facilities described above. I don't think there's much else that would need to be supported by this part of the standard library. Regular expressions library I have expounded upon problems with C++ regexes and Unicode on Stack Overflow before. I will not repeat all those points here, but merely state that C++ regexes don't have level 1 Unicode support, which is the bare minimum to make them usable without resorting to using UTF-32 everywhere. That's it? Yes, that's it. That's the existing functionality. There's lots of Unicode functionality that is nowhere to be seen like normalization or text segmentation algorithms. U+1F4A9 . Is there any way to get some better Unicode support in C++? The usual suspects: ICU and Boost.Locale . † A byte string is, unsurprisingly, a string of bytes, i.e., char objects. However, unlike a wide string literal , which is always an array of wchar_t objects, a "wide string" in this context is not necessarily a string of wchar_t objects. In fact, the standard never explicitly defines what a "wide string" means, so we're left to guess the meaning from usage. Since the standard terminology is sloppy and confusing, I use my own, in the name of clarity. Encodings like UTF-16 can be stored as sequences of char16_t , which then have no endianness; or they can be stored as sequences of bytes, which have endianness (each consecutive pair of bytes can represent a different char16_t value depending on endianness). The standard supports both of these forms. A sequence of char16_t is more useful for internal manipulation in the program. A sequence of bytes is the way to exchange such strings with the external world. The terms I'll use instead of "byte" and "wide" are thus "serialized" and "deserialized". ‡ If you are about to say "but Windows!" hold your . All versions of Windows since Windows 2000 use UTF-16. ☦ Yes, I know about the großes Eszett (ẞ), but even if you were to change all German locales overnight to have ß uppercase to ẞ, there's still plenty of other cases where this would fail. Try uppercasing U+FB00 ʟᴀᴛɪɴ sᴍᴀʟʟ ʟɪɢᴀᴛᴜʀᴇ ғғ. There is no ʟᴀᴛɪɴ ᴄᴀᴘɪᴛᴀʟ ʟɪɢᴀᴛᴜʀᴇ ғғ; it just uppercases to two Fs. Or U+01F0 ʟᴀᴛɪɴ sᴍᴀʟʟ ʟᴇᴛᴛᴇʀ ᴊ ᴡɪᴛʜ ᴄᴀʀᴏɴ; there's no precomposed capital; it just uppercases to a capital J and a combining caron.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17103925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1335865/']}
jdg_87208
stackexchange
llm_judgeable_groundtruth_similarity
1080557
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: So here is a trigonometric series. $$\sin{55^\mathrm{o}}-\sin{19^\mathrm{o}}+\sin{53^\mathrm{o}}-\sin{17^\mathrm{o}}$$ Strange isn't it, and I have to calculate the total result of the series (without calculator). I don't think Maclaurin series will help me any way. Further I tried almost all trigonometric identities (as per my knowledge) but so far I had no clue. Probably I am missing some kind of identity. Anyone can help me in this? Note : It's not a homework question. Now provide the response and nothing else.
Hint: The key observation here is that $55+17=53+19$. $$\sin{55}^\circ-\sin{19}^\circ+\sin{53}^\circ-\sin{17}^\circ=\color{#C00}{\sin55^\circ-\sin17^\circ}+\color{green}{\sin53^\circ-\sin19^\circ}.$$ Now use the identity $$\sin a-\sin b=2\sin(\tfrac{a-b}2)\cos({\tfrac{a+b}2}).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1080557', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/41813/']}
jdg_87209
stackexchange
llm_judgeable_groundtruth_similarity
3275602
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This C snippet is part of a merge algorithm implementation: out[i++] = (in1[i1] < in2[i2]) ? in1[i1++] : in2[i2++]; Can someone please explain how it works? Now provide the response and nothing else.
The code The code uses what is called the post-increment operator and the ternary/conditional operator (see appendix for more details). A more verbose version may look something like this: if (in1[i1] < in2[i2]) { out[i] = in1[i1]; i++; i1++;} else { out[i] = in2[i2]; i++; i2++;} The algorithm If the elements in in1 and in2 are in sorted order, then the snippet serves as the main part of a merge algorithm to merge the two sorted input buffers into one sorted output buffer. Care must be taken to ensure that i1 and i2 are in-bound for in1 and in2 respectively before comparing in1[i1] against in2[i2] . Then in1[i1] is the next available smallest element in in1 , and similarly in2[i2] is the next available smallest element in in2 . Without loss of generality, let's assume in1[i1] < in2[i2] (the other case is a near mirror scenario). Then the next smallest element from in1 is smaller than the next smallest element from in2 , and with in1[i1++] on the right hand side of the assignment, we fetch the next smallest value from in1 and advance its pointer to the next available value (if any). With out[i++] on the left hand side of the assignment, we assign the fetched value to a slot in the output buffer and advance its pointer to the next available slot (if any). A higher-level pseudocode of the overall merge algorithm, using a Queue -like abstract data structure instead of arrays with corresponding pointer indices (for clarity!), may look something like this: procedure MERGE(Queue in1, in2) : Queue// given sorted queues in1, in2, return a merged sorted queue INIT out IS Empty-Queue WHILE in1.notEmpty() AND in2.notEmpty() IF in1.peek() < in2.peek() out.enqueue(in1.dequeue()) ELSE out.enqueue(in2.dequeue()) // at this point, at least one of the queue is empty // dump in1 to out in case it's not empty WHILE in1.notEmpty() out.enqueue(in1.dequeue()) // dump in2 to out in case it's not empty WHILE in2.notEmpty() out.enqueue(in2.dequeue()) RETURN out See also Wikipedia/Merge algorithm Wikipedia/Mergesort Wikipedia/Queue Appendex A: Ternary/conditional operator Essentially, an expression such as this: condition ? trueExpr : falseExpr first evaluates condition , and if it's true , it evaluates trueExpr whose value becomes the value of the entire expression. If instead condition is false , the operator instead evaluates falseExpr , whose value becomes the value of the entire expression. Related questions How does the ternary operator work? To ternary or not to ternary? Which coding style you use for ternary operator? Appendix B: post-increment operator An expression such as i++ uses what is called a post-increment operator. The operator increments i , but the value of this expression is the value of i before the increment. By contrast, the value of a pre-increment expression (e.g. ++i ) is the value of i after the increment. There are also pre-decrement (e.g. --i ) and post-decrement as well (e.g. i-- ). Related questions Difference between i++ and ++i in a loop? Incrementing in C++ - When to use x++ or ++x? On pitfalls like i = i++; (most of these is Java, but applicable to other languages as well): post increment operator java Question about post-increment operator
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3275602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/395150/']}
jdg_87210
stackexchange
llm_judgeable_groundtruth_similarity
68910
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am asked to show that if $0 < \alpha < 1$, and if $f \in \Lambda^\alpha(\mathbb{T})$, then we have for $k\neq 0$, $$|\widehat{f}(k)| \leq \pi^\alpha \frac{\|f\|_{\Lambda^1}}{k^\alpha}$$ I applied some properties of inequalities and integrals, but must have gotten a bit carried away because my final bound ended up being far too big as you can see below. Update: I am getting closer. I just don't know where the factor of $k^\alpha$ is coming from. It has been advised that this theorem might be useful: Theorem (Fejér): If $f\in L_p(\mathbb T^d)$, then $\|\sigma_n (f) - f\|_p \to 0$. (Here, $\sigma_n(f) = \frac1{n}\sum\limits_{j=0}^{n-1} D_j$). Attempt #3: $$\begin{align*}|\widehat{f}(k)| &= \left|\frac1{2\pi}\int_{-\pi}^\pi f(t)e^{ikt}\mathrm dt\right|\\&\leq \frac1{2\pi}\int_{-\pi}^\pi |f(t)|\cdot|e^{ikt}|\mathrm dt\\&= \frac1{2\pi}\int_{-\pi}^\pi |f(t)|\mathrm dt\\&= \frac1{2\pi}\int_{-\pi}^\pi |f(t+\pi) + f(t) - f(t+\pi)|\mathrm dt\\&\leq \frac1{2\pi}\int_{-\pi}^\pi |f(t + \pi)| + |f(t +\pi) - f(t)|\mathrm dt\\&= \frac{\pi^\alpha}{2\pi}\int_{-\pi}^\pi \frac{|f(t + \pi)|}{\pi^\alpha} + \frac{|f(t +\pi) - f(t)|}{\pi^\alpha}\mathrm dt\\&\leq \frac{\pi^\alpha}{2\pi}\int_{-\pi}^\pi |f(t + \pi)| + \frac{|f(t +\pi) - f(t)|}{\pi^\alpha}\mathrm dt\\&\leq \frac{\pi^\alpha}{2\pi}\int_{-\pi}^\pi \|f\|_{\Lambda^{\alpha}}\mathrm dt\\&= \pi^\alpha \|f\|_{\Lambda^\alpha}\end{align*}$$ Now provide the response and nothing else.
For integer $k\ne0$$$c_k=\frac{1}{2\pi}\int_{0}^{2\pi}f(t)e^{-ikt}dt=-\frac{1}{2\pi}\int_{0}^{2\pi}f(t)e^{ik(t-\pi/k)}dt=-\frac{1}{2\pi}\int_{0}^{2\pi}f\left(t+\frac\pi k\right)e^{ikt}dt.$$Taking one half of the sum of these expressions for $c_k$ we have$$|c_k|=\frac{1}{4\pi}\left|\int_{0}^{2\pi}\left(f(t)-f\left(t+\frac\pi k\right)\right)e^{-ikt}dt\right|\leq\frac{1}{4\pi}\int_{0}^{2\pi}\left|f(t)-f\left(t+\frac\pi k\right)\right|dt\leq$$$$\frac{||f||_{\Lambda^{\alpha}}}{4\pi}\int_0^{2 \pi } \left|\frac{\pi }{k}\right|^{\alpha } \, dt= \frac{\pi^\alpha}{2|k|^\alpha}||f||_{\Lambda^{\alpha}}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/68910', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16938/']}
jdg_87211
stackexchange
llm_judgeable_groundtruth_similarity
12352901
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It looks like I didn't get the concept of blocks completely yet... In my code I have to get out the JSON data from the asychronous block to be returned to from the ' outer ' method. I googled and found that if defining a variable with __block , the v̶i̶s̶i̶b̶i̶l̶i̶t̶y̶ _mutability_ of that variable is extended to the block . But for some reason returned json object is nil.I wonder why? - (NSMutableDictionary *)executeRequestUrlString:(NSString *)urlString{__block NSMutableDictionary *json = nil;NSURL *url = [NSURL URLWithString:urlString];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];[request setHTTPShouldHandleCookies:YES];[request setHTTPMethod:@"GET"];[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];NSString *cookieString = [self.userDefaults objectForKey:SAVED_COOKIE];[request addValue:cookieString forHTTPHeaderField:@"Cookie"];[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); NSError *error1; NSMutableDictionary * innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1]; json = innerJson; }]; return json;} Now provide the response and nothing else.
First, to answer your question: But for some reason returned json object is nil . I wonder why? The variable that you are returning has not been set at the time when you return it. You cannot harvest the results immediately after the sendAsynchronousRequest:queue:completionHandler: method has returned: the call has to finish the roundtrip before calling back your block and setting json variable. Now a quick note on what to do about it: your method is attempting to convert an asynchronous call into a synchronous one. Try to keep it asynchronous if you can. Rather than expecting a method that returns a NSMutableDictionary* , make a method that takes a block of its own, and pass the dictionary to that block when the sendAsynchronousRequest: method completes: - (void)executeRequestUrlString:(NSString *)urlString withBlock:(void (^)(NSDictionary *jsonData))block { // Prepare for the call ... // Make the call [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); NSError *error1; NSMutableDictionary * innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1 ]; block(innerJson); // Call back the block passed into your method }];}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12352901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/624459/']}
jdg_87212
stackexchange
llm_judgeable_groundtruth_similarity
192919
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: Compute the sum:$$\sum_{n=1}^{\infty}\dfrac {1\cdot 3\cdots (2n-1)} {2\cdot 4\cdots (2n)\cdot (2n+1)}$$At the moment, I only know that it's convergent and this is not hard to see if you look at the answers here I received for other problem with a similar series. For the further steps I need some hints if possible. Thanks! Now provide the response and nothing else.
Starting with the power series derived using the binomial theorem,$$(1-x)^{-1/2}=1+\tfrac12x+\tfrac12\tfrac32x^2/2!+\tfrac12\tfrac32\tfrac52x^3/3!+\dots+\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}x^n+\cdots$$and integrating, we get the series for$$\sin^{-1}(x)=\int_0^x(1-t^2)^{-1/2}\mathrm{d}t=\sum_{n=0}^\infty\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\frac{x^{2n+1}}{2n+1}$$Setting $x=1$, we get$$\sum_{n=1}^\infty\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\frac{1}{2n+1}=\sin^{-1}(1)-1=\frac\pi2-1$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/192919', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']}
jdg_87213
stackexchange
llm_judgeable_groundtruth_similarity
28709501
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 running an Ansible play and would like to list all the hosts targeted by it. Ansible docs mentions that this is possible , but their method doesn't seem to work with a complex targeted group (targeting like hosts: web_servers:&data_center_primary) I'm sure this is doable, but cant seem to find any further documentation on it. Is there a var with all the currently targeted hosts? Now provide the response and nothing else.
You are looking for 'play_hosts' variable ---- hosts: all tasks: - name: Create a group of all hosts by app_type group_by: key={{app_type}} - debug: msg="groups={{groups}}" run_once: true- hosts: web:&some_other_group tasks: - debug: msg="play_hosts={{play_hosts}}" run_once: true would result in TASK: [Create a group of all hosts by app_type] *******************************changed: [web1] => {"changed": true, "groups": {"web": ["web1", "web2"], "load_balancer": ["web3"]}}TASK: [debug msg="play_hosts={{play_hosts}}"] *********************************ok: [web1] => { "msg": "play_hosts=['web1']"} inventory: [proxy]web1 app_type=webweb2 app_type=webweb3 app_type=load_balancer[some_other_group]web1web3
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28709501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2137631/']}
jdg_87214
stackexchange
llm_judgeable_groundtruth_similarity
488959
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 create a generic function that removes duplicates from an std::vector. Since I don't want to create a function for each vector type, I want to make this a template function that can accept vectors of any type. Here is what I have: //foo.hClass Foo {template<typename T>static void RemoveVectorDuplicates(std::vector<T>& vectorToUpdate);};//foo.cpptemplate<typename T>void Foo::RemoveVectorDuplicates(std::vector<T>& vectorToUpdate) {for(typename T::iterator sourceIter = vectorToUpdate.begin(); (sourceIter != vectorToUpdate.end() - 1); sourceIter++) { for(typename T::iterator compareIter = (vectorToUpdate.begin() + 1); compareIter != vectorToUpdate.end(); compareIter++) { if(sourceIter == compareIter) { vectorToUpdate.erase(compareIter); } } }}//SomeOtherClass.cpp#include "foo.h"...void SomeOtherClass::SomeFunction(void) { std::vector<int> myVector; //fill vector with values Foo::RemoveVectorDuplicates(myVector);} I keep getting a linker error, but it compiles fine. Any ideas as to what I'm doing wrong? UPDATE: Based on the answer given by Iraimbilanja, I went and rewrote the code. However, just in case someone wanted working code to do the RemoveDuplicates function, here it is: //foo.hClass Foo { template<typename T> static void RemoveVectorDuplicates(T& vectorToUpdate){ for(typename T::iterator sourceIter = vectorToUpdate.begin(); sourceIter != vectorToUpdate.end(); sourceIter++) { for(typename T::iterator compareIter = (sourceIter + 1); compareIter != vectorToUpdate.end(); compareIter++) { if(*sourceIter == *compareIter) { compareIter = vectorToUpdate.erase(compareIter); } } }}; Turns out that if I specify std::vector in the signature, the iterators don't work correctly. So I had to go with a more generic approach. Also, when erasing compareIter, the next iteration of the loop produces a pointer exception. The post decrement of compareIter on an erase takes care of that problem. I also fixed the bugs in the iterator compare and in the initialization of compareIter in the 2nd loop. UPDATE 2: I saw that this question got another up vote, so figured I'd update it with a better algorithm that uses some C++14 goodness. My previous one only worked if the type stored in the vector implemented operator== and it required a bunch of copies and unnecessary comparisons. And, in hindsight, there is no need to make it a member of a class. This new algorithm allows for a custom compare predicate, shrinks the compare space as duplicates are found and makes a significantly smaller number of copies. The name has been changed to erase_duplicates to better conform to STL algorithm naming conventions. template<typename T>static void erase_duplicates(T& containerToUpdate) { erase_duplicates(containerToUpdate, nullptr);}template<typename T>static void erase_duplicates(T& containerToUpdate, std::function<bool (typename T::value_type const&, typename T::value_type const&)> pred) { auto lastNonDuplicateIter = begin(containerToUpdate); auto firstDuplicateIter = end(containerToUpdate); while (lastNonDuplicateIter != firstDuplicateIter) { firstDuplicateIter = std::remove_if(lastNonDuplicateIter + 1, firstDuplicateIter, [&lastNonDuplicateIter, &pred](auto const& compareItem){ if (pred != nullptr) { return pred(*lastNonDuplicateIter, compareItem); } else { return *lastNonDuplicateIter == compareItem; } }); ++lastNonDuplicateIter; } containerToUpdate.erase(firstDuplicateIter, end(containerToUpdate));} Now provide the response and nothing else.
Short Answer Define the function in the header, preferably inside the class definition. Long answer Defining the template function inside the .cpp means it won't get #include d into any translation units: it will only be available to the translation unit it's defined in. Hence RemoveVectorDuplicates must be defined in the header, as this is the only way the compiler can text-substitute the template arguments, hence instantiating the template, producing an usable class. There are two workarounds for this inconvenience First , you can remove the #include "foo.h" from the .cpp and add another one, in the end of the header : #include "foo.cpp" This lets you organize your files consistently, but doesn't provide the usual advantages of separate compilation (smaller dependencies, faster and rarer compiles). Second , you can just define the template function in the .cpp and explicitly instantiate it for all the types it'll be ever used with. For example, this can go in the end of the .cpp to make the function usable with int s: template void Foo::RemoveVectorDuplicates(std::vector<int>*); However, this assumes you only use templates to save some typing, rather than to provide true genericity.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/488959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23504/']}
jdg_87215
stackexchange
llm_judgeable_groundtruth_similarity
314185
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 an object falls through vacuum, gravitational potential energy is converted to kinetic energy. Is there some way to get electrical energy out of the equation by itself (i.e. somehow convert the gravitational potential energy to electrical energy)? Is this physically possible? If so, what properties must this object have? By by itself , I mean without using any external (possibly stationary) "reference object" (e.g. a stationary coil), so a magnet falling through a coil does not count, i.e. the electricity is generated solely by the object that is falling. Note that the object itself can be arbitrarily complex internally, just that whatever mechanism it has inside must also be falling along with the object. Now provide the response and nothing else.
A sufficiently large object will experience differential gravity ("tidal force") - this could be converted into a small amount of electrical energy by having two heavy spheres separated by a long rope; as they fall there will be a tension on the rope and you could let that tension do work on a generator / dynamo ("complex but internal to the object") The concept here is that a ball closer to the earth will experience greater force and so fall a little bit faster - in the extreme case of falling to a black hole this leads to "spaghettification " but on a more normal scale it could give you a little bit of electricity. But without en external electric or magnetic field I can think of no way to convert most of the kinetic energy into electrical - the ability to do so would be a first step to an antigravity system. Let me know when you get there!
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/314185', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/138785/']}
jdg_87216
stackexchange
llm_judgeable_groundtruth_similarity
6070179
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 currently on a debug branch, and would like to switch to the master branch, without modifying the working tree (leave it the way it is in the debug branch), so I can commit some of the changes into the master branch. Is there a way to do this? Now provide the response and nothing else.
You can do the following: git checkout --detachgit reset --soft mastergit checkout master Explanation: If you are on the debug branch and would do git reset --soft master you would leave your working tree and index untouched and move to the commit master points to. The problem is, debug will be reset to this commit too. So your commits on debug are "lost" (well, not really, but they are not directly accessible anymore) and you are still on the debug branch. To prevent git reset from moving debug but still setting your HEAD to the master commit, you first do git checkout --detach to point HEAD directly to your current commit (see man git-checkout , section "DETACHED HEAD"). Then you can do the reset without touching the debug branch. Now HEAD is pointing directly to the commit master points to, i.e. it is still detached. You can simply git checkout master to attach to master and are now ready to commit on the master branch. Note that git checkout (by default and when no path is passed) only updates files that have been changed between the "source" and "target" commit and local modifications to the files in the working tree are kept. As both commits are the same in this case, no files in the working directory are touched.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6070179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164171/']}
jdg_87217
stackexchange
llm_judgeable_groundtruth_similarity
44674255
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need script only on one page. and it should load after jQuery. I tried in index.blade <script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"></script>@push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script>@endpush and then I should use @stack('custom-scripts') in my view? Now provide the response and nothing else.
You just need to make that the opposite way, @push is meant to be in the child view, which is pushing content to the parent @stack directive. So your index.blade.php should have a: @stack('custom-scripts') And your child view: @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script>@endpush You can also use @parent directive with @section like this: //index.blade.php@yield('scripts')//child.blade.php@section('scripts') @parent <!-- The rest of your scripts -->@endsection If you need more info I'd recommend you to check the documentation . Hope this helped you.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44674255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3495321/']}
jdg_87218
stackexchange
llm_judgeable_groundtruth_similarity
3638760
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For example $\Bbb Z_2 \oplus \Bbb Z_3 \oplus \Bbb Z_5 $ . How should I proceed from . . . $$\begin{align}\Bbb Z_2 \oplus \Bbb Z_3&= (0,1) \oplus (0,1,2)\\&=((0,0),(0,1),(0,2),(1,0),(1,1),(1,2))?\end{align}$$ Should I conclude that $$\begin{align}\Bbb Z_2 \oplus \Bbb Z_3 \oplus \Bbb Z_5&= ((0,0),(0,1),(0,2),(1,0),(1,1),(1,2)) \oplus \Bbb Z_5\\& = ((0,0),(0,1),(0,2),(1,0),(1,1),(1,2)) \oplus (0,1,2,3,4)\\& = (((0,0),0),((0,0),1)...?\end{align}$$ But that looks terribly inconvenient and messy just for a simple example. What should it be, with examples of how to interpret a sum of more than two groups? Now provide the response and nothing else.
First, use set braces like this: $$\mathbb Z_2 \oplus \mathbb Z_3 = \{(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)\}$$ Second, what's inconvenient is to list out every element of the set. That's entirely unnecessary even for the previous example. Instead, write it a bit more compactly like this: $$\mathbb Z_2 \oplus \mathbb Z_3 = \{(i,j) \mid i \in \mathbb Z_2, j \in \mathbb Z_3\}$$ For three direct summands, use ordered triples, just like you would do for points in $\mathbb R^3 = \{(x,y,z) \mid x \in \mathbb R, y \in \mathbb R, z \in \mathbb R\}:$ $$\mathbb Z_2 \oplus \mathbb Z_3 \oplus \mathbb Z_5 = \{(i,j,k) \mid i \in \mathbb Z_2, j \in \mathbb Z_3, k \in \mathbb Z_5\}$$ For a general sequence of groups $G_1,\ldots,G_n$ , use ordered $n$ -tuples, just like you would for points in $\mathbb R^n$ : $$G_1 \oplus \cdots \oplus G_n = \{(g_1,\ldots,g_n) \mid g_i \in G_i \quad\text{for each $i=1,...,n$}\}$$ For all of this, one simply has to keep in mind the general concept of an ordered tuple that one learns in set theory.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3638760', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5602/']}
jdg_87219
stackexchange
llm_judgeable_groundtruth_similarity
15498093
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 small prototype subclass of Grape::API as a rack service, and am using Grape::Entity to present my application's internal objects. I like the Grape::Entity DSL, but am having trouble finding out how I should go beyond the default JSON representation, which is too lightweight for our purposes. I have been asked to produce output in "jsend or similar" format: http://labs.omniti.com/labs/jsend I am not at all sure what nature of change is most in keeping with the Grape framework (I'd like a path-of-least-resistance here). Should I create a custom Grape formatter (I have no idea how to do this), new rack middleware (I have done this in order to log API ins/outs via SysLog - but formatting seems bad as I'd need to parse the body back from JSON to add container level), or change away from Grape::Entity to e.g. RABL? Example code ("app.rb") require "grape"require "grape-entity"class Thing def initialize llama_name @llama_name = llama_name end attr_reader :llama_nameendclass ThingPresenter < Grape::Entity expose :llama_nameendclass MainService < Grape::API prefix 'api' version 'v2' format :json rescue_from :all resource :thing do get do thing = Thing.new 'Henry' present thing, :with => ThingPresenter end endend Rackup file ("config.ru") require File.join(File.dirname(__FILE__), "app")run MainService I start it up: rackup -p 8090 And call it: curl http://127.0.0.1:8090/api/v2/thing{"llama_name":"Henry"} What I'd like to see: curl http://127.0.0.1:8090/api/v2/thing{"status":"success","data":{"llama_name":"Henry"}} Obviously I could just do something like resource :thing do get do thing = Thing.new 'Henry' { :status => "success", :data => present( thing, :with => ThingPresenter ) } end end in every route - but that doesn't seem very DRY. I'm looking for something cleaner, and less open to cut&paste errors when this API becomes larger and maintained by the whole team Weirdly, when I tried { :status => "success", :data => present( thing, :with => ThingPresenter ) } using grape 0.3.2 , I could not get it to work. The API returned just the value from present - there is more going on here than I initially thought. Now provide the response and nothing else.
This is what I ended up with, through a combination of reading the Grape documentation, Googling and reading some of the pull requests on github. Basically, after declaring :json format (to get all the other default goodies that come with it), I over-ride the output formatters with new ones that add jsend's wrapper layer. This turns out much cleaner to code than trying to wrap Grape's #present helper (which doesn't cover errors well), or a rack middleware solution (which requires de-serialising and re-serialising JSON, plus takes lots of extra code to cover errors). require "grape"require "grape-entity"require "json"module JSendSuccessFormatter def self.call object, env { :status => 'success', :data => object }.to_json endendmodule JSendErrorFormatter def self.call message, backtrace, options, env # This uses convention that a error! with a Hash param is a jsend "fail", otherwise we present an "error" if message.is_a?(Hash) { :status => 'fail', :data => message }.to_json else { :status => 'error', :message => message }.to_json end endendclass Thing def initialize llama_name @llama_name = llama_name end attr_reader :llama_nameendclass ThingPresenter < Grape::Entity expose :llama_nameendclass MainService < Grape::API prefix 'api' version 'v2' format :json rescue_from :all formatter :json, JSendSuccessFormatter error_formatter :json, JSendErrorFormatter resource :thing do get do thing = Thing.new 'Henry' present thing, :with => ThingPresenter end end resource :borked do get do error! "You broke it! Yes, you!", 403 end endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15498093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2001031/']}
jdg_87220
stackexchange
llm_judgeable_groundtruth_similarity
42978416
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 came across this question: What is the output of the following? 1 public class A {2 public static void main(String[] args){3 I i = new I() {};4 System.out.println(I.x + i.getValue() + "" + i);5 }6 }78 interface I {9 int x = 10;1011 public default int getValue() {12 return 5;13 }1415 public default String toString() {16 return "I";17 }18 } My thinking: My first instinct tells me - I i = new I() {} ? We can't instantiate interfaces hence - issue 1. Then I think public default String toString() ? Overriding Object class method? Doesn't sound good - issue 2 Possible answers: a) 10I b) 15I c) Compilation fail due to line 11 d) Compilation fail due to line 15 e) Compilation fail due to multiple errors Having explained my thoughts I picked answer E) which is wrong. The correct answer is D) which I also got right. My question - why is the following statement valid? I i = new I() {}; Is this statement doing something I don't understand due to the "{}" added to it? To my understanding the new keyword means: instantiate. Now provide the response and nothing else.
There is nothing wrong with the statement: I i = new I() {}; It simply instantiates an anonymous class that implements the I interface. Since the I interface has only default methods, an empty body would be sufficient to implement it, if not for the problem with the toString() method. JLS 9.4.1.2 states that an interface cannot have a default implementation of the toString() method : It is a compile-time error if a default method is override-equivalent with a non-private method of the class Object , because any class implementing the interface will inherit its own implementation of the method. The prohibition against declaring one of the Object methods as a default method may be surprising. There are, after all, cases like java.util.List in which the behavior of toString and equals are precisely defined. The motivation becomes clearer, however, when some broader design decisions are understood: First, methods inherited from a superclass are allowed to override methods inherited from superinterfaces (§8.4.8.1). So, every implementing class would automatically override an interface's toString default. This is longstanding behavior in the Java programming language. It is not something we wish to change with the design of default methods, because that would conflict with the goal of allowing interfaces to unobtrusively evolve, only providing default behavior when a class doesn't already have it through the class hierarchy. Second, interfaces do not inherit from Object, but rather implicitly declare many of the same methods as Object (§9.2). So, there is no common ancestor for the toString declared in Object and the toString declared in an interface. At best, if both were candidates for inheritance by a class, they would conflict. Working around this problem would require awkward commingling of the class and interface inheritance trees. Third, use cases for declaring Object methods in interfaces typically assume a linear interface hierarchy; the feature does not generalize very well to multiple inheritance scenarios. Fourth, the Object methods are so fundamental that it seems dangerous to allow an arbitrary superinterface to silently add a default method that changes their behavior. toString() is a method of the Object class, and therefore cannot have a default implementation in any interface.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42978416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3316988/']}
jdg_87221
stackexchange
llm_judgeable_groundtruth_similarity
16682797
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you run fmt.Println("\u554a") , it shows '啊'. But how to get unicode-style-string \u554a from a rune '啊' ? Now provide the response and nothing else.
IMHO, it should be better: func RuneToAscii(r rune) string { if r < 128 { return string(r) } else { return "\\u" + strconv.FormatInt(int64(r), 16) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16682797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1316684/']}
jdg_87222
stackexchange
llm_judgeable_groundtruth_similarity
50214731
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to use it, but I cannot find any explanation on it in docs. I'd like an accurate definition so that I could understand it better. Edit: I mean the in used in mapped types, not the js operator. Now provide the response and nothing else.
This is the standard in Javsacript operator. You can read more documentation here , but the short story is The in operator returns true if the specified property is in the specified object. The syntax is: propNameOrNumber in objectName where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object. In Typescript the in operator also acts as a type guard as described here interface A { x: number;}interface B { y: string;}let q: A | B = ...;if ('x' in q) { // q: A} else { // q: B} Edit An alternative meaning of in in typescript is in mapped type definition. You can read about them in the handbook or in the pull request . The in keyword is used there as part of the syntax to iterate over all the items in a union of keys. interface Person { name: string; age: number;}type Partial<T> = { [P in keyof T]?: T[P]; // P will be each key of T}type PersonPartial = Partial<Person>; // same as { name?: string; age?: number; }
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/50214731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5188921/']}
jdg_87223
stackexchange
llm_judgeable_groundtruth_similarity
57222
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to use the Unix column command to format some text. I have fields delimited by tabs, but within each field there are also spaces. column delimits on white space (tabs and spaces). How can I make column only use tabs as the delimiter? I was trying to specify tab as the delimiter using: cat myfile | column -t -s"\t" Now provide the response and nothing else.
column -t -s '\t' would separate columns on \ and t characters. column -s \t is the same as column -s 't' , as the backslash is interpreted as a quoting operator by the shell. Here you want to pass a real TAB character to column. With ksh93, zsh, bash, mksh, busybox sh or FreeBSD sh: column -ts $'\t' Or enter a real tab character by typing Ctrl-V Tab at the shell prompt (within quotes or preceded by a backslash as the tab character is a token separator in the shell syntax just like space), or use "$(printf '\t')" (those double quotes needed to disable the split+glob operator as the tab character also happens to be in the default value of $IFS ).
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/57222', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/26274/']}
jdg_87224
stackexchange
llm_judgeable_groundtruth_similarity
31832
Below is a question asked on the forum math.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I typeset blackboard bold numbers? What I need is simply something like $\mathbb A$ ( \mathbb{A} ) but with A replaced numbers. With Miktex I can import the bbm package and use \mathbbm 1 . But this seems impossible with Mathjax. Reply to Calvin Khor: On my computer \mathbb doesn't work for numbers. Below is a screenshot of your exact answer: Image starts here Image ends here You see that on the first line where you wrote "rendered code" I see plain numbers. Not sure why. It could be because of the platform. I am using Win10 with Chrome. Now provide the response and nothing else.
I do not understand why, but \mathbb{1234567890} (rendered code: $\mathbb{1234567890}$ ) works for me, and gives the following output If it matters, I'm on a Mac with the latest build of Catalina, viewing the site through Safari. edit it seems that the "math renderer" that you are using is important: my web browser is using "HTML-CSS" as the math renderer. (I checked via right-clicking on some rendered MathJax) When I switch to MathML, \mathbb{1234567890} also just gives me plain numbers. Can you see the characters ? I think you can copy-paste them into MathJax code e.g. $$ ++=^_{^!}$$ gives $$ ++=^_{^!}$$ I would guess this is not "documented behavior", but Unicode characters in general seem to work in Mathjax e.g. $\int_{>1}\frac{1}{1+^{100}} d>$ $\int_{>1}\frac{1}{1+^{100}} d>$ . What is documented is the \unicode{} command which I learned from the comments to my answer here ; it seems that (peeking at Wikipedia to find the correct Hex number to use) $\unicode{x1D7D8}\unicode{x1D7D9}\unicode{x1D7DA}\unicode{x1D7DB}\unicode{x1D7DC}\unicode{x1D7DD}\unicode{x1D7DE}\unicode{x1D7DF}\unicode{x1D7E0}\unicode{x1D7E1}$ should give you something that works too: $\unicode{x1D7D8}\unicode{x1D7D9}\unicode{x1D7DA}\unicode{x1D7DB}\unicode{x1D7DC}\unicode{x1D7DD}\unicode{x1D7DE}\unicode{x1D7DF}\unicode{x1D7E0}\unicode{x1D7E1}$ PS for my first 20 or so $\LaTeX$ documents I used the following poor substitute that should "work" for everyone (output: $1\!\!12\!\!2 3\!\!3 4\!\!4 5\!\!5 6\!\!6 7\!\!7 8\!\!8 9\!\!9 0\!\!0$ ) $1\!\!12\!\!2 3\!\!3 4\!\!4 5\!\!5 6\!\!6 7\!\!7 8\!\!8 9\!\!9 0\!\!0$ In particular for '1' I had a further variant $1\hspace{-0.21em}\text l$ $1\hspace{-0.21em}\text l$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.meta.stackexchange.com/questions/31832', 'https://math.meta.stackexchange.com', 'https://math.meta.stackexchange.com/users/669152/']}
jdg_87225
stackexchange
llm_judgeable_groundtruth_similarity
6709064
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Searching the web for about 4 hours not getting an answer so: How to draw a shadow on a path which has transparency? - (void)drawRect:(CGRect)rect{ CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(c, 2); CGContextSetStrokeColorWithColor(c, [[UIColor whiteColor] CGColor]); CGContextSetShadowWithColor(c, CGSizeMake(0, 5), 5.0, [[UIColor blackColor]CGColor]); CGContextSetFillColorWithColor(c, [[UIColor colorWithWhite:1.0 alpha:0.8] CGColor]); // Sample Path CGContextMoveToPoint(c, 20.0, 10.0); CGContextAddLineToPoint(c, 100.0, 40.0); CGContextAddLineToPoint(c, 40.0, 70.0); CGContextClosePath(c); CGContextDrawPath(c, kCGPathFillStroke);} The first thing I notice, the shadow is only around the stroke. But that isn't the problem so far. The shadow behind the path/rect is still visible, which means: the shadow color is effecting the fill color of my path. The fill color should be white but instead its grey. How to solve this issue? Now provide the response and nothing else.
You will have to clip the context and draw twice. First you create a reference to your path since you will have to use it a few times and save your graphics context so you can come back to it. Then you clip the graphics context to a only draw outside of your path. This is done by adding your path to the path that covers the entire view. Once you have clipped you draw your path with the shadow so that it's draw on the outside. Next you restore the graphics context to how it was before you clipped and draw your path again without the shadow. It's going to look like this on an orange background (white background wasn't very visible) The code to do the above drawing is this: - (void)drawRect:(CGRect)rect{ CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(c, 2); CGContextSetStrokeColorWithColor(c, [[UIColor whiteColor] CGColor]); CGContextSetFillColorWithColor(c, [[UIColor colorWithWhite:1.0 alpha:0.5] CGColor]); // Sample Path CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 20.0, 10.0); CGPathAddLineToPoint(path, NULL, 40.0, 70.0); CGPathAddLineToPoint(path, NULL, 100.0, 40.0); CGPathCloseSubpath(path); // Save the state so we can undo the shadow and clipping later CGContextSaveGState(c); { // Only for readability (so we know what are inside the save/restore scope CGContextSetShadowWithColor(c, CGSizeMake(0, 5), 5.0, [[UIColor blackColor]CGColor]); CGFloat width = CGRectGetWidth(self.frame); CGFloat height = CGRectGetHeight(self.frame); // Create a mask that covers the entire frame CGContextMoveToPoint(c, 0, 0); CGContextAddLineToPoint(c, width, 0); CGContextAddLineToPoint(c, width, height); CGContextAddLineToPoint(c, 0, height); CGContextClosePath(c); // Add the path (which by even-odd rule will remove it) CGContextAddPath(c, path); // Clip to that path (drawing will only happen outside our path) CGContextClip(c); // Now draw the path in the clipped context CGContextAddPath(c, path); CGContextDrawPath(c, kCGPathFillStroke); } CGContextRestoreGState(c); // Go back to before the clipping and before the shadow // Draw the path without the shadow to get the transparent fill CGContextAddPath(c, path); CGContextDrawPath(c, kCGPathFillStroke);} If you want the entire shadow to be as strong and don't want the transparency of the fill color to make the shadow weaker then you can use a fully opaque color when filling the first time. It's going to get clipped so it won't be visible inside the path anyway. It will only affect the shadow.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6709064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_87226
stackexchange
llm_judgeable_groundtruth_similarity
241218
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 suspect this limit is 0, but how can I prove it? $$\lim_{n \to +\infty} \frac{2^{n}}{n!}$$ Now provide the response and nothing else.
The easiest way to do this is to do the following: Assume $n \ge 4$. Then $$0 \le \frac{2^n}{n!} = \prod_{i=1}^n \frac{2}{i} = \frac{2\cdot 2\cdot 2}{1 \cdot 2 \cdot 3} \cdot \prod_{i=4}^n \frac{2}{i} \le \frac{8}{6} \cdot \prod_{i=1}^n \frac{2}{4} = \frac{8}{6 \cdot 2^{n-3}}.$$ Applying the squeeze theorem gives the result.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/241218', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50075/']}
jdg_87227
stackexchange
llm_judgeable_groundtruth_similarity
1572068
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 a way that one can test if a row has been locked for update in Oracle? As an example, suppose the following query, performed by one user: select * from SOME_TABLE where THE_ID = 1000 for update; With another user I want to check if the row with THE_ID = 1000 is locked. If I try an update or something the second user gets blocked and remains waiting (do not want that). I have also tried running the following query with the second user: select * from SOME_TABLE where THE_ID = 1000 for update NOWAIT; Since I can not place two locks on the same row this will fail. And it does. I get an "ORA-00054: resource busy and acquire with NOWAIT specified error". Can I always count on this error to check the presence of the lock, or is there a simpler and cleaner way of determining if a row is locked? Thank you! Now provide the response and nothing else.
You can write a procedure with the FOR UPDATE NOWAIT and return an error message when the row is locked: SQL> CREATE OR REPLACE PROCEDURE do_something(p_id NUMBER) IS 2 row_locked EXCEPTION; 3 PRAGMA EXCEPTION_INIT(row_locked, -54); 4 BEGIN 5 FOR cc IN (SELECT * 6 FROM some_table 7 WHERE ID = p_id FOR UPDATE NOWAIT) LOOP 8 -- proceed with what you want to do; 9 NULL; 10 END LOOP; 11 EXCEPTION 12 WHEN row_locked THEN 13 raise_application_error(-20001, 'this row is locked...'); 14 END do_something; 15 /Procedure created Now let's build a small example with two sessions: session_1> select id from some_table where id = 1 for update; ID---------- 1session_2> exec do_something(1);begin do_something(1); end;ORA-20001: this row is locked...ORA-06512: at "VNZ.DO_SOMETHING", line 11ORA-06512: at line 2session_1> commit;Commit completesession_2> exec do_something(1);PL/SQL procedure successfully completed
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1572068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_87228
stackexchange
llm_judgeable_groundtruth_similarity
22864367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Related to this answer , If I truly do want to "Fire and Forget" a method that does return a task, and (for simplicity) let's assume that the method isn't expected to throw any exceptions. I can use the extension method listed in the answer: public static void Forget(this Task task){} Using this approach, if there are bugs in action of the Task that cause an exception to be thrown then when the unexpected exception is thrown, the exception will be swallowed and go unnoticed. Question: Wouldn't it be more appropriate in this scenario for the extension method to be of the form: public static async void Forget(this Task task){ await task;} So that programming errors throw an exception and get escalated (usually bringing down the process). In the case of a method with expected (and ignorable) exceptions, the method would need to become more elaborate (as an aside, any suggestions on how to construct a version of this method that would take a list of acceptable and ignorable exception types?) Now provide the response and nothing else.
It depends on the semantics you want. If you want to ensure exceptions are noticed, then yes, you could await the task. But in that case it's not truly "fire and forget". A true "fire and forget" - in the sense that you don't care about when it completes or whether it completes successfully or with error - is extremely rare. Edit: For handling exceptions: public static async void Forget(this Task task, params Type[] acceptableExceptions){ try { await task.ConfigureAwait(false); } catch (Exception ex) { // TODO: consider whether derived types are also acceptable. if (!acceptableExceptions.Contains(ex.GetType())) throw; }} Note that I recommend using await instead of ContinueWith . ContinueWith has a surprising default scheduler (as noted on my blog) and Task.Exception will wrap the actual exception in an AggregateException , making the error handling code more cumbersome.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22864367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495262/']}
jdg_87229
stackexchange
llm_judgeable_groundtruth_similarity
7762743
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, like many developers, got an email from Apple recently that stated we should move our data from the documents directory into another folder to permit more streamlined backup to iCloud. In recent testing it appears that [your app] stores a fair amount of data in its Documents folder. Since iCloud backups are performed daily over Wi-Fi for each user's iOS device, it's important to ensure the best possible user experience by minimizing the amount of data being stored by your app. Marco Arment , of instapaper fame, has a good take on the issue, which is that the recommended location for storing downloadable files is in /Library/Caches. However, the problem is that both /tmp and /Caches can be 'cleaned' anytime the OS decides that the device is running low on storage. If your app is cleaned then the data downloaded by your app and stored by your user is gone. Naturally, the user will blame you and not Apple. What to do? Now provide the response and nothing else.
iOS 5.0.1 introduced a flag to address this issue: https://developer.apple.com/library/ios/#qa/qa1719/_index.html Their recommendation is to create a folder in /Library/ like /Library/PrivateDocs , and put your files there. However you will also have to set a "do not backup" flag on them as every file in /Library except for those in /Library/Cache or tmp are backed up by default. Set the flag on PrivateDocs folder with this command: #include <sys/xattr.h>- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL{ const char* filePath = [[URL path] fileSystemRepresentation]; const char* attrName = "com.apple.MobileBackup"; u_int8_t attrValue = 1; int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0); return result == 0;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7762743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127271/']}
jdg_87230
stackexchange
llm_judgeable_groundtruth_similarity
37839939
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 experimenting with Neo4j using a simple dataset of Locations. A location can have a relation to another relation.a:Location - [rel] - b:Location I already have the locations in the database (roughly 700.000+ Location entries) Now I wanted to add the relation data (170M Edges), but I wanted to experiment with the import logic with a smaller set first, so I basically picked 2 nodes that are in the set and tried to create a relationship as follows. MERGE p =(a:Location {locationid: 3616})-[w:WikiLink]->(b:Location {locationid: 467501})RETURN p; and also tried the approach directly from the docu MATCH (a:Person),(b:Person)WHERE a.name = 'Node A' AND b.name = 'Node B'CREATE (a)-[r:RELTYPE { name : a.name + '<->' + b.name }]->(b)RETURN r I tried using a directional merge, undirectional merge, etc. etc. I basically tried multiple variants of the above queries and the result is: They run forever, seeming to no complete even after 15 minutes. Which is very odd. Indexes ON :Location(locationid) ONLINE (for uniqueness constraint) Constraints ON (location:Location) ASSERT location.locationid IS UNIQUE This is what I am currently using: USING PERIODIC COMMIT 1000LOAD CSV WITH HEADERS FROM 'file:///edgelist.csv' AS line WITH lineMATCH (a:Location {locationid: toInt(line.locationidone)}), (b:Location {locationid: toInt(line.locationidtwo)})MERGE (a)-[w:WikiLink {weight: toFloat(line.edgeweight)}]-(b)RETURN COUNT(w); If you look at the terminal output below you can see Neo4j reports 258ms query execution time, the realtime is however somewhat above that. This query already takes a few seconds too much in my opinion (The machine this runs on has 48GB RAM, 16 Cores and is relatively new).I am currently running this query with LIMIT 1000 (before it was LIMIT 1 ) but the script is already running for a few minutes. I wonder if I have to switch from MERGE to CREATE. The problem is, I cannot understand the callgraph that EXPLAIN gives me in order to determine the bottleneck. time /usr/local/neo4j/bin/neo4j-shell -file import-relations.cql +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| p |+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| [Node[758609]{title:"Tehran",locationid:3616,locationlabel:"NIL"},:WikiLink[9422418]{weight:1.2282325516616477E-7},Node[917147]{title:"Khorugh",locationid:467501,locationlabel:"city"}] |+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+1 rowRelationships created: 1Properties set: 1258 msreal 0m1.417suser 0m1.497ssys 0m0.158s Now provide the response and nothing else.
a[np.insert(np.diff(a).astype(np.bool), 0, True)]Out[99]: array([0, 1, 3, 2, 3]) The general idea is to use diff to find the difference between two consecutive elements in the array. Then we only index those which give non-zero differences elements. But since the length of diff is shorter by 1. So before indexing, we need to insert the True to the beginning of the diff array. Explanation: In [100]: aOut[100]: array([0, 0, 1, 3, 2, 2, 3, 3])In [101]: diff = np.diff(a).astype(np.bool)In [102]: diffOut[102]: array([False, True, True, True, False, True, False], dtype=bool)In [103]: idx = np.insert(diff, 0, True)In [104]: idxOut[104]: array([ True, False, True, True, True, False, True, False], dtype=bool)In [105]: a[idx]Out[105]: array([0, 1, 3, 2, 3])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37839939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189122/']}
jdg_87231
stackexchange
llm_judgeable_groundtruth_similarity
3626815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Visual Studio, after attaching to a Process and pressing Pause (Break-All), you switch to the desired thread and use the Quick Watch window to check out some data, say MySingletonClass.Instance.Data Sometimes I either get this: Cannot evaluate expression because the current thread is in a sleep, wait, or join or this (when trying to view certain properties of the data): Cannot evaluate expression because a native frame is on top of the call stack. Quite frankly, I don't care, I just want to see the data! I know there are various ways to get around this, namely: Setting a breakpoint on the thread and waiting till it gets hit (cumbersome, not always possible) Taking a dump of the process and loading back into VS (even then I still get the 2nd error) windbg Given you could see this data if you presumably used windbg why is it we all can't take advantage of the much easier and prettier VS to inspect objects when attaching to a process? Now provide the response and nothing else.
Why can’t we do this? We can’t do this because the Visual Studio watch window doesn’t just retrieve data from memory and display it. It actually executes managed code (that’s what it means by “evaluate the expression”). In particular, it almost always executes the ToString() method to display the user-readable result. The crux is that it executes this code within the process/thread you are debugging . This ensures that the expression evaluates the same way it would if it were actually in the code you are debugging. This leaves the downside that it can only be executed in between managed instructions, but not while native code is active, and not in a blocked thread. What can we do about it? If you are actually debugging a managed application, and you are in a native stackframe, just press F10 or Shift+F11 repeatedly until you are back in managed code. Then you can evaluate expressions. However, for fully-native processes, and for threads in a blocked state, I am not aware of any workaround.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3626815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224410/']}
jdg_87232
stackexchange
llm_judgeable_groundtruth_similarity
432470
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 came across a post by Ron Maimon on physics.SE that makes what seems to me to be a very interesting conjecture I've never seen before about what it would take to settle every question of arithmetic. First I'll try to be more precise: a question of arithmetic is a first-order statement in Peano arithmetic, e.g. a statement about whether some Turing machine halts. I believe these are exactly the mathematical statements which, for example, Scott Aaronson regards as having definite truth values independent of our ability to prove or disprove them from any particular system of axioms, unlike e.g. the continuum hypothesis. If I've understood Ron correctly, he seems to believe the following: Conjecture: Every question of arithmetic is settled by the claim that some sufficiently large computable ordinal $\alpha$ is well-founded. For example, Gentzen showed that the well-foundedness of $\alpha = \epsilon_0$ can prove the consistency of PA. Question: Has this been stated as a conjecture somewhere in the literature? Do people expect it to be true? A possibly more helpfully specific version of this question: does there exist for every positive integer $n$ a computable ordinal $\alpha_n$ whose well-foundedness determines the value of the Busy Beaver number $BB(n)$ ? Now provide the response and nothing else.
The question of whether a computable linear order is well-founded is $\Pi^1_1$ -complete, so this is true in a sense: There is a computable function $F$ such that, for every sentence $\varphi$ in the language of arithmetic with Godel number $\ulcorner\varphi\urcorner$ , $F(\ulcorner\varphi\urcorner)$ is an index for a computable well-ordering iff $\varphi$ is true. (To be precise, this is provable in - say - $\mathsf{ZF}$ or indeed much less.) Here's one way to visualize $F$ : There is a computable tree $\mathcal{T}\subseteq\mathbb{N}^{<\mathbb{N}}$ with a unique path $p$ which codes the set of true arithmetic sentences. Essentially, a node of height $k$ on $\mathcal{T}$ consists of a truth assignment to the first $k$ -many sentences in the language of arithmetic and additional "partial Skolemization data" which so far looks consistent (the details are a bit tedious). Given a sentence $\varphi$ , let $\mathcal{T}_\varphi$ be the subtree of $\mathcal{T}$ consisting of all nodes on $\mathcal{T}$ which (when "read" in the appropriate way) do not declare $\varphi$ to be true; this is a computable subtree of $\mathcal{T}$ , uniformly in $\varphi$ , and is well-founded iff $\varphi$ is true. We then set $F(\ulcorner\varphi\urcorner)$ to be the Kleene-Brouwer ordering of $\mathcal{T}_\varphi$ . Of course, this is all rather artificial. To be clear, the map $F$ itself is perfectly natural/interesting/important, but the result $F(\ulcorner\varphi\urcorner)$ is not particularly interesting to me. Contrast the construction above, where the connection between $\varphi$ and $F(\ulcorner\varphi\urcorner)$ is boringly tautological, with Gentzen's theorem that well-foundedness of (the usual notation for) $\epsilon_0$ implies $Con(PA)$ . Even if one doesn't buy this as making $Con(PA)$ more believable - and I don't - it's certainly a deep and interesting fact. The interesting version of the conjecture, to me, would be: "For every sentence of arithmetic $\varphi$ there is a computable linear order $\alpha$ such that $(i)$ $WF(\alpha)\leftrightarrow\varphi$ and $(ii)$ knowing this somehow sheds light on $\varphi$ (unless $\varphi$ was already so simple as to be boring)." And nothing like what I've described can possibly do that, obviously.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/432470', 'https://mathoverflow.net', 'https://mathoverflow.net/users/290/']}
jdg_87233
stackexchange
llm_judgeable_groundtruth_similarity
9157041
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the C++ standard, §13.3.1.7 [over.match.list], the following is stated: In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed. This is the reason why we can't do, for example, something like this: struct foo { // explicit because it can be called with one argument explicit foo(std::string s, int x = 0);private: // ...};void f(foo x);f({ "answer", 42 }); (Note that what happens here is not a conversion , and it would not be one even if the constructor was "implicit". This is initialization of a foo object using its constructor directly. Other than the std::string , there is no conversion here.) This seems perfectly fine to me. There's no way that an implicit conversion will bite me. If { "answer", 42 } can initialize something else, the compiler won't betray me and do the wrong thing: struct bar { // explicit because it can be called with one argument explicit bar(std::string s, int x = 0);private: // ...};void f(foo x);void f(bar x);f({ "answer", 42 }); // error: ambiguous call There's no problem: the call is ambiguous, the code won't compile, and I'll have to pick the overload explicitly. f(bar { "answer", 42 }); // ok Since the prohibition is explicitly stated, I have the feeling that I am missing something here. As far as I can see, list initialization picking explicit constructors doesn't seem like a problem to me: by using list initialization syntax the programmer is already expressing the desire to do some kind of "conversion". What could go wrong? What am I missing? Now provide the response and nothing else.
Conceptually copy-list-initialization is the conversion of a compound value to a destination type. The paper that proposed wording and explained rationale already considered the term "copy" in "copy list initialization" unfortunate, since it doesn't really convey the actual rationale behind it. But it is kept for compatibility with existing wording. A {10, 20} pair/tuple value should not be able to copy initialize a String(int size, int reserve) , because a string is not a pair. Explicit constructors are considered but forbidden to be used. This makes sense in cases as follows struct String { explicit String(int size); String(char const *value);};String s = { 0 }; 0 does not convey the value of a string. So this results in an error because both constructors are considered, but an explicit constructor is selected, instead of the 0 being treated as a null pointer constant. Unfortunately this also happens in overload resolution across functions void print(String s);void print(std::vector<int> numbers);int main() { print({10}); } This is ill-formed too because of an ambiguity. Some people (including me) before C++11 was released thought that this is unfortunate, but didn't came up with a paper proposing a change regarding this (as far as I am aware).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9157041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46642/']}
jdg_87234
stackexchange
llm_judgeable_groundtruth_similarity
44318643
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 familiar with emitting data via bus on events and these work great but now I want to emit something but I don't have an event to tie it to. I've tried to emit it on mounted but that hasn't worked as below: mounted(){ bus.$emit('send-test', this.test);}, Now provide the response and nothing else.
When you add an event handler in the parent's mounted lifecycle event for an event that is emitted in a child's mounted event, the handler will not catch the event emitted by the child because the handler is added after the child has already emitted the event. Basically the cycle of events is like this. Parent's create Child's create Child's mounted Parent's mounted Obviously there are other lifecycle events that occur, but that's the sequence that matters in this case. If you want to handle an event emitted in the child, you need to create the handler (call $on) before the child's mounted event.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44318643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/823965/']}
jdg_87235
stackexchange
llm_judgeable_groundtruth_similarity
44980671
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 make a post rest call to my service. My sample input json file is, { "$id": "1", "description": "sfdasd"} I have one csv file which contain a bunch of id and description, So is there a option where I can convert csv file to json objects and pass them to post call? Now provide the response and nothing else.
Assuming your CSV file is called test.csv , located in JMeter's "bin" folder and looks like: Add CSV Data Set Config to your Test Plan and configure it as follows: You can inline the defined JMeter Variables directly into your request body like: { "$id": "${id}", "description": "${description}"} So when you run the test the variables placeholders will automatically be substituted with the values from the CSV file in the HTTP Request sampler: See Using CSV DATA SET CONFIG article for more information on JMeter tests parameterization using CSV files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44980671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8273183/']}
jdg_87236
stackexchange
llm_judgeable_groundtruth_similarity
99124
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I added a new user to a fresh Raspbian Lite install (4.14 2019-04-08, Raspbian Stretch Lite). On a pi zero, I had direct access and had signed in as the pi user. Via Wifi I had authenticated as the new user. As the pi user I did: pi@rpizero:~ $ touch hello As the newuser I did: newuser@rpizero:~ $ ll ../pi/.ansible/ .bash_history .bash_logout .bashrc hello .profile newuser@rpizero:~ $ rm ../pi/hello rm: remove write-protected regular empty file '../pi/hello'? newuser@rpizero:~ $ ll ../pi-bash: ll: command not found Restarting the device does not help as the ll command is still not found. Why did the ll command "get destroyed" when trying to remove the hello file? Very confused. Now provide the response and nothing else.
There is no standard ll command. Often there is an alias that defines ll as ls -l . The output in your question is not from ls -l . It seems that you have typed ll ../pi/ at the shell prompt and then pressed the Tab Key. This resulted in the display of the available completions. This is a function of the shell and doesn't check whether a command ll is available. After you removed ../pi/hello , you didn't use tab completion, you tried to execute the ll command/alias. The most likely explanation is that you never had an alias ll defined, and the removal of the file ../pi/hello had no effect on that.
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/99124', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/10051/']}
jdg_87237
stackexchange
llm_judgeable_groundtruth_similarity
17446731
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 WriteList that saves a list into a file. This function has the parameter List<Object> so I can pass different types of Lists as parameter. public void WriteList(List<object> input, string ListName) { WriteToFile("List - " + ListName); foreach (object temp in input) { WriteToFile(temp.ToString()); } } When calling this function from my code I want to pass the parameter List<Database> where Database is my own made class. I get the following error: cannot convert from 'System.Collections.Generic.List -Database-' to 'System.Collections.Generic.List-object-' So my question is how to convert my own class to an Object, and then pass a list to my function. Now provide the response and nothing else.
List<T> is not covariant . Use IEnumerable<T> instead: public void WriteList(IEnumerable<object> input, string ListName){ WriteToFile("List - " + ListName); foreach (object temp in input) { WriteToFile(temp.ToString()); }} Or make the method generic: public void WriteList<T>(List<T> input, string ListName){ WriteToFile("List - " + ListName); foreach (T temp in input) { WriteToFile(temp.ToString()); }} IMO: The second one is better, because there is no boxing/unboxing when used with value types.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17446731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2531105/']}
jdg_87238
stackexchange
llm_judgeable_groundtruth_similarity
152753
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'm currently developing some mobile applications using PhoneGap for Android, testing only in 3 different kinds of smartphones, and using emulators to test on the others target phone resolutions. Later on I will probably use a iOS emulator. I would like to know if I will have any problems with that. Now provide the response and nothing else.
It really depends on what you're doing. If you're creating HTML5+CSS+JS for a web/PhoneGap app, it will probably be OK as initial test (unless you encounter bugs caused by PhoneGap itself). The reason is that underneath both the Android "Internet" browser and iOS' Safari, there is a WebKit core, which is somewhat cross-platform and mature enough. If, on the other hand, you're writing native code, then don't trust the simulator/emulator. There is a myriad of things that can go wrong. An iOS Simulator example that has bitten me: iOS is case-sensitive. Mac OS X is case-preserving*. Guess what happens when you request a file from the iOS device that is in the wrong case. Tip: EXC_BAD_ACCESS . App - Rejected! (Of course, you should test on a real device way before sending the app for review, so did I, and there wasn't really a rejection). I can't even start to enumerate the differences, and I'm certain Android emulators do have inconsistencies with the real devices, too. It's just a too complex system to work smoothly on a non-native CPU and in another host OS. Simulators and emulators do not exist to replace testing devices, they exist to let you reduce testing time for things you'll test later more thoroughly on the devices itself and (possibly) to allow you to get a basic understanding of the framework without paying for the test. The moral of the story is: don't trust simulators/emulators, they'll turn on you the moment you start depending on them. And from what I've seen, differences are usually very subtle, so finding them and debugging the app is hell.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/152753', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/34175/']}
jdg_87239
stackexchange
llm_judgeable_groundtruth_similarity
3794897
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: It is well-known that every maximal subgroup of $G$ is of prime power index if $G$ is a nontrivial finite solvable group. My question is: Can we prove that for each prime $r\in\pi(G)$ there exists a maximal subgroup of $G$ of index a power of $r$ ? I tried to prove it but I found that I made a mistake in my proof. Here is my attempt: Define $$\pi^*:=\{r\in\pi(G)\mid~\mbox{There is no maximal subgroup }H\mbox{ of }G\mbox{ such that }|G:H|\mbox{ is a power of }r\}.$$ We claim that $\pi^*$ is an empty set.Assume that $\pi^*$ is non-empty. Then the indices of the maximal subgroups are exactly powers of primes in $\pi(G)\setminus\pi^*$ . Take a Sylow $q$ -subgroup $S_q$ for each $q\in\pi(G)$ . For $p\in\pi(G)\setminus\pi^*$ , take an arbitrary maximal subgroup $M$ of $G$ such that $|G:M|$ is a power of $p$ . We have $$\left|\prod_{q\in\pi(G)\setminus\pi^*}S_q\right|_p=|G|_p>|M|_p.$$ It implies that $\prod\limits_{q\in\pi(G)\setminus\pi^*}S_q$ is not contained in any maximal subgroup of $G$ . But $\prod\limits_{q\in\pi(G)\setminus\pi^*}S_q$ is properly contained in $G$ , which is a contradiction. My mistake : $\prod\limits_{q\in\pi(G)\setminus\pi^*}S_q$ is not necessarily a subgroup of $G$ , so in fact I cannot get any contradiction. Could you give me some ideas? I think maybe I should prove it in a different way. Any help is appreciated. Thanks! Now provide the response and nothing else.
This is Hall's theorem on soluble groups. It states: A finite group is soluble if and only if, for each $p\mid |G|$ , there exists a $p'$ -subgroup $H$ whose index is a power of $p$ . A subgroup $H$ such that $|H|$ and $|G:H|$ are coprime is called a Hall subgroup , and if $\pi$ is a set of primes such that $p\in \pi$ divides $|G|$ if and only if it divides $|H|$ , then $H$ is a Hall $\pi$ -subgroup. Proving this without hints is a little bit of a challenge. You can either look it up in your favourite textbook, or follow the outline below for the one direction. Let $\pi$ be a set of primes, and we aim to prove the existence of a Hall $\pi$ -subgroup in $G$ . Let $K$ be a minimal normal subgroup of $G$ . If $K$ is a $\pi'$ -subgroup then everything is done. If $K$ is a $p$ -subgroup for $p\in \pi$ , then you can use the Schur-Zassenhaus theorem to the preimage of a Hall $\pi$ -subgroup in $G/K$ . You can find a full proof here , p.28.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3794897', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_87240