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
9514698
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to show a JQuery dialog conditionally on click event of an hyperlink . I have a requirement like on condition1 open a JQuery dialogue and if condition1 is not satisfied, navigate to the page as referenced by 'href' tag of whose click event is in question. I am able to call a function on link's click event. This function now checks the said condition by executing another URL (that executes my Spring controller and returns response). All works perfect with only window.open being blocked by popup blocker. $('a[href*=/viewpage?number]').live('click', function(e) { e.preventDefault(); redirectionURL = this.href; pageId= getUrlVars(redirectionURL)["number"]; $.getJSON("redirect/" + pageId, {}, function(status) { if (status == null) { alert("Error in verifying the status."); } else if(!status) { $("#agreement").dialog("open"); } else { window.open(redirectionURL); } });}); If I remove e.preventDefault(); from code, popoup blocker doesn't block the page, however for condition1 it then opens the dialogue as well as opens the 'href' page. If I solve one, it creates issue for another. I am not able to give justice to both conditions simultaneously. Could you help me solve this issue please? Once this is solved I have another issue to solve i.e. navigation on dialogue's OK event :) Now provide the response and nothing else.
Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later , not during the event, because $.getJSON is asynchronous. You have two options: Do something else, rather than window.open . Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to: $.ajax({ url: url, dataType: 'json', data: data, success: callback}); ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false : $.ajax({ url: "redirect/" + pageId, async: false, dataType: "json", data: {}, success: function(status) { if (status == null) { alert("Error in verifying the status."); } else if(!status) { $("#agreement").dialog("open"); } else { window.open(redirectionURL); } }}); Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go. Here's an example of code that fails the test because of the asynchronous call: Live example | Live source (The live links no longer work because of changes to JSBin) jQuery(function($) { // This version doesn't work, because the window.open is // not during the event processing $("#theButton").click(function(e) { e.preventDefault(); $.getJSON("http://jsbin.com/uriyip", function() { window.open("http://jsbin.com/ubiqev"); }); });}); And here's an example that does work, using a synchronous call: Live example | Live source (The live links no longer work because of changes to JSBin) jQuery(function($) { // This version does work, because the window.open is // during the event processing. But it uses a synchronous // ajax call, locking up the browser UI while the call is // in progress. $("#theButton").click(function(e) { e.preventDefault(); $.ajax({ url: "http://jsbin.com/uriyip", async: false, dataType: "json", success: function() { window.open("http://jsbin.com/ubiqev"); } }); });});
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9514698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242356/']}
jdg_373641
stackexchange
llm_judgeable_groundtruth_similarity
39951647
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't find information how to write my JSON data to my Realm DB in Swift . I have class: class News: Object { dynamic var newsID: String = "" dynamic var newsTitle: String = "" dynamic var newsFullText: String = "" dynamic var newsAutor: String = "" dynamic var newsCommentCount: String = "" dynamic var newsSeenCount: String = "" dynamic var newsDate: String = "" dynamic var newsCategory: String = ""} In here I take JSON from server: func parseJSONData(data: NSData) -> [News] { do { let temp: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! let myNSData = temp.dataUsingEncoding(NSUTF8StringEncoding)! let jsonResult = try NSJSONSerialization.JSONObjectWithData(myNSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let jsonNews = jsonResult["posts"] as! [AnyObject] for jsonnewes in jsonNews { let newsJson = News() newsJson.newsTitle = jsonnewes["post_title"] as! String newsJson.newsAutor = jsonnewes["author_name"] as! String newsJson.newsFullText = jsonnewes["full_text"] as! String newsJson.newsID = jsonnewes["id"] as! String newsJson.newsCategory = jsonnewes["menu_category_name"] as! String newsJson.newsDate = jsonnewes["create_date"] as! String newsJson.newsSeenCount = jsonnewes["review"] as! String newsJson.newsCommentCount = jsonnewes["comment_count"] as! String newsItems.append(newsJson) } } catch { print(error) } return newsItems} And how to write my data to Realm DB ? Now provide the response and nothing else.
this : func insertOrUpdate(news: News) { try! realm.write({ realm.add(news) })} but it is better you create a model without inherit from object : class News { var newsID: String = "" var newsTitle: String = "" var newsFullText: String = "" var newsAutor: String = "" var newsCommentCount: String = "" var newsSeenCount: String = "" var newsDate: String = "" var newsCategory: String = ""}class NewsRealm: Object { dynamic var newsID: String = "" dynamic var newsTitle: String = "" dynamic var newsFullText: String = "" dynamic var newsAutor: String = "" dynamic var newsCommentCount: String = "" dynamic var newsSeenCount: String = "" dynamic var newsDate: String = "" dynamic var newsCategory: String = ""} then after parse json you call insertOrUpdate and map data with NewsRealm : func insertOrUpdate(news: News) { let realm = try! Realm() try! realm.write({ let newsRealm = NewsRealm() newsRealm.newsTitle = news.newsTitle newsRealm.newsAutor = news.newsAutor newsRealm.newsFullText = news.newsFullText . . . realm.add(newsRealm) })}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39951647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6013170/']}
jdg_373642
stackexchange
llm_judgeable_groundtruth_similarity
64042
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: Given a program that requires some parameters, e.g. program -in file.in -out file.out , what would be the simple-most approach to write a bash script that could be called with or without any of these parameters and use default values for each? script -in otherfile would run program -in otherfile -out file.out , script -out otherout -furtherswitch would run program -in file.in -out otherout -furtherswitch etc. Now provide the response and nothing else.
A default value is easy to define in Bash: foo="${bar-default}" # Sets foo to the value of $bar if defined, "default" otherwisefoo="${bar:-default}" # Sets foo to the value of $bar if defined or empty, "default" otherwise To process your parameters, you can use a simple loop: while truedo case "${1-}" in -in) infile="${2-}" shift 2 ;; -out) outfile="${2-}" shift 2 ;; *) break ;; esacdoneprogram -in "${infile-otherfile}" -out "${outfile-otherout}" "$@" Useful reads: Parameter handling Passing parameters to another script I also recommend using getopt instead, because it is able to handle many special cases which would very quickly complicate and clutter your code ( Non-trivial example ).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/64042', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/863/']}
jdg_373643
stackexchange
llm_judgeable_groundtruth_similarity
501000
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: As any magnetic field $\mathbf{B}$ is divergence-free i.e. $$\nabla\cdot \mathbf B = 0,\tag{1}$$ by the solenoidal theorem there exists a vector potential $\mathbf A$ that satisfies $$\mathbf B = \nabla \times \mathbf A.\tag{2}$$ However, Wikipedia states an additional constraint for the vector potential, that is $$\mathbf E = -\nabla \phi - \frac{\partial \mathbf A}{\partial t}\tag{3}$$ where $\phi$ is the electric potential. How does this constraint arise? Can we derive it from the Maxwell-Heaviside equations? Now provide the response and nothing else.
This is not actually a constraint on $\mathbf{A}$ , rather a way of calculating the electric field from it. Maxwell's equations are \begin{align}\begin{gathered}\nabla\cdot\mathbf{E}=\frac{\rho}{\epsilon_0} &\qquad \nabla\cdot\mathbf{B}=0\\\nabla\times\mathbf{E}=-\frac{\partial\mathbf{B}}{\partial t} &\qquad \nabla\times\mathbf{B}=\mu_0\mathbf{J}+\mu_0\epsilon_0\frac{\partial\mathbf{E}}{\partial t}\end{gathered}\end{align} As you said, $\nabla\cdot\mathbf{B}=0$ implies that there exists some vector potential $\mathbf{A}$ which satisfies $\mathbf{B} = \nabla\times\mathbf{A}$ . This is the only condition which $\mathbf{A}$ must satisfy. Replacing $\mathbf{B}$ with $\nabla\times\mathbf{A}$ in the third equation gives $$\nabla\times\mathbf{E}=-\frac{\partial}{\partial t}(\nabla\times\mathbf{A}) = -\nabla\times\left(\frac{\partial \mathbf{A}}{\partial t}\right)$$ so that $$\nabla\times\left(\mathbf{E}+\frac{\partial \mathbf{A}}{\partial t}\right) =\mathbf{0}.$$ This means that $\mathbf{E}+\frac{\partial \mathbf{A}}{\partial t}$ may be written as the gradient of some scalar field $\phi$ , i.e. $$\mathbf{E}+\frac{\partial \mathbf{A}}{\partial t} = -\nabla\phi.$$ This potential formulation is extremely useful and turns out to be very fundamental.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/501000', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_373644
stackexchange
llm_judgeable_groundtruth_similarity
11071821
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 tried to run flyway in my application before hibernate is hooking in on my JBoss AS 7.1. I tried with an @javax.ejb.Startup annotation, but this gets executed AFTER Hibernate is initialized and the database scheme is checked. So as far as I understand we can use a CDI Extension which hooks in before Hibernate is initialized. Is there some support for that out of the box for flyway? And if not, has anyone tried to do this before? Now provide the response and nothing else.
Ok I finally found out how to do this: I had to use the Hibernate Integration API. This is the whole code I had to write: public class FlywayIntegrator implements Integrator { @Override public void integrate(final Configuration configuration, final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { final Flyway flyway = new Flyway(); flyway.setDataSource(....); flyway.migrate(); } @Override public void integrate(final MetadataImplementor metadataImplementor, final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { //no-op } @Override public void disintegrate(final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { //no-op }} If anyone is interested in more details, I created a github project which demonstrates that: https://github.com/dobermai/Hibernate-Flyway-Integration
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11071821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441467/']}
jdg_373645
stackexchange
llm_judgeable_groundtruth_similarity
523234
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently facing a weird issue. For one of my project I had to design a buck converter circuit in order to step down the voltage of three LiIon batteries to 3.3V so I can power a microcontroller. I'm using the TPS54240 chip. The datasheet can be found here .A typical application schematic is shown on page 31. Since said circuit outputs 3.3V I was able to more or less copy it. My schematic looks as follows: After ordering a PCB prototype the buck converter didn't really work, unfortunately.When I applied ~7.4V (2 LiIon batteries) to VCC the output showed ~3.3V as I was expecting. However once I connect a load, in my case the microcontroller, the voltage dropped to ~3.26V. Why is this happening? I thought a buck converter utilizes a feedback loop in order to maintain a constant voltage. The TPS54240 chip itself is rated for up to 2.5A in this case and my microcontroller isn't even pulling 100mA. Even more confusing was the scenario when I connected ~11.1V (3 LiIon batteries) to VCC. In that case I measured ~2.6V at the output, which again dropped significantly to ~2.4V just when I connected a LED that drawed maybe 20mA. My microcontroller wasn't able to power on on such a low voltage making the circuit more or less useless. Since I don't have a ton of experience with designing a circuit (this was my first project) I don't know how to troubleshoot this problem.I would appreciate any kind of help. Thanks! Edit: This is the PCB layout of the circuit. Edit 2: Here is a possibly fixed PCB layout. Now provide the response and nothing else.
Did you use an autorouter? @Andyaka I kinda did, yes. Routing a PCB was surprisingly timeconsuming and actually wasn't that easy. So I used an autorouter andedited the traces afterwards to, for instance, remove 90° angles intraces. The routing, component placement and track widths are pretty bad in very important areas. Don't use an autorouter unless it's a last resort like for a backplane etc. where there are many repeated steps in the process. Problems In light blue is the tortuous path taken from the inductor around the PCB to connect to C17 and C18 (the main bulk capacitors). In purple is the far-too-long track from the switcher output to the flyback diode and inductor The track widths are far too thin in my opinion and their length makes a big loop that could emit nasty interference to any close-by sensitive circuits. D5 should be right up close to the switcher and should ground directly to C17-C19 forming an island. That island should only connect to the rest of the design (not the power supply) at one unambiguous point to avoid switching currents creeping into ground areas of sensitive circuits. Recommendations L1 should be alongside D5 C17 and C18 should be butted up to the above Then C19 and C20 The ground connection of R31 (not visible in the layout) should make a connection directly to the island of ground for D5, C17, C18, C19 and C20 Any other ground points associated with the switcher should be teed off from that ground island. Regarding the inductor I see nothing in the data sheet that rules it out but, whenever I design a switcher, I pick an inductor that has a specified self-resonant-frequency (SRF) just to ensure that it is fit for purpose; in other words, if your switching frequency is (say) 200 kHz, I would want to pick an inductor that has an SRF of at least 1 MHz. Unfortunately I didn't see this stated in the data sheet nor can I say that the supplier has a decent quality system and decent tolerances. This last bit is about being careful who you choose. For instance, if one of the major recognized electronic component vendors was offering it in their catalogue I would be assured that the original manufacturer was OK. Something like this: -
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/523234', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/242771/']}
jdg_373646
stackexchange
llm_judgeable_groundtruth_similarity
141501
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: gpg --list-sigs gives me somethings like the following (I edited the output only to show the interesting/different rows): pub 2048R/4ACE309C 2016-11-01uid lala_test2 <lala2@test.org>sig 3 4ACE309C 2016-11-01 lala_test2 <lala2@test.org>uid test_key <test_key@test.org>sig 3 4ACE309C 2016-11-01 lala_test2 <lala2@test.org>sub 2048R/EA9FDC87 2016-11-01sig 4ACE309C 2016-11-01 lala_test2 <lala2@test.org>sig 2 03A9DA1F 2014-02-11 [User ID not found]sig 3 5B51CBCF 2011-10-25 [User ID not found]sig 3 06B47049 2011-10-26 [User ID not found]sig 3 00C85EF1 2011-10-31 [User ID not found]sig 3 5A4BEDCE 2011-10-06 [User ID not found]sig 1 F2648165 2011-10-07 [User ID not found]sig X CA57AD7C 2005-07-31 [User ID not found]sig X CA57AD7C 2005-08-01 [User ID not found]sig 2 X DC79FAC9 2003-09-26 [User ID not found]sig 7EE2682F 2016-06-03 [User ID not found]rev 7EE2682F 2016-06-03 [User ID not found] The tags in the first column means: pub -> public key uid -> user id sig -> signature, from another person saying that he trust the key under pub tag sub -> subkey rev -> is this a signature whose key was revoked by the signer? 2048R -> 2048 is the key size and R for RSA.There is also the short key id, the creation date, and the last one is the user ID when available. What do the numbers in a sig row after first column mean? Now provide the response and nothing else.
Certification Levels There are different classes of certifications. Quoting RFC 4880, OpenPGP, 5.2.1. Signature Types : [...]0x10: Generic certification of a User ID and Public-Key packet. The issuer of this certification does not make any particular assertion as to how well the certifier has checked that the owner of the key is in fact the person described by the User ID.0x11: Persona certification of a User ID and Public-Key packet. The issuer of this certification has not done any verification of the claim that the owner of this key is the User ID specified.0x12: Casual certification of a User ID and Public-Key packet. The issuer of this certification has done some casual verification of the claim of identity.0x13: Positive certification of a User ID and Public-Key packet. The issuer of this certification has done substantial verification of the claim of identity.Most OpenPGP implementations make their "key signatures" as 0x10certifications. Some implementations can issue 0x11-0x13certifications, but few differentiate between the types.[...] GnuPG displays the "normal" 0x10 signatures as sig and the advanced signatures distinguishing between different kinds of certification levels with a number following: 0x11 as sig 1 , 0x12 as sig 2 and 0x13 as sig 3 . rev indicates revoked signatures. The output of --list-sigs is also explained by the GnuPG manual pages ( man gpg ): --list-sigs Same as --list-keys, but the signatures are listed too. This command has the same effect as using --list-keys with --with-sig-list. For each signature listed, there are several flags in between the "sig" tag and keyid. These flags give additional information about each signature. From left to right, they are the numbers 1-3 for certificate check level (see --ask-cert-level), "L" for a local or non-exportable signature (see --lsign- key), "R" for a nonRevocable signature (see the --edit-key command "nrsign"), "P" for a signature that contains a policy URL (see --cert-policy-url), "N" for a signature that contains a notation (see --cert-notation), "X" for an eXpired signature (see --ask-cert-expire), and the numbers 1-9 or "T" for 10 and above to indicate trust signature levels (see the --edit-key command "tsign"). Vagueness Also note the first paragraph of the specification's section, which indicates there is no general, rigid definition of the certification levels: There are a number of possible meanings for a signature, which areindicated in a signature type octet in any given signature. Pleasenote that the vagueness of these meanings is not a flaw, but afeature of the system. Because OpenPGP places final authority forvalidity upon the receiver of a signature, it may be that onesigner's casual act might be more rigorous than some otherauthority's positive act. [...] Because of this, some people post certification policies. I provided some discussion in What are you saying when you sign a PGP key?
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/141501', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/129314/']}
jdg_373647
stackexchange
llm_judgeable_groundtruth_similarity
99876
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: Does $(p-n)!\pmod{p}$ have a closed form for any $n>2$ when $p$ is prime? $(p-0)!=0 \pmod{p}$ $(p-1)!=-1\pmod{p}$ $(p-2)!=1\pmod{p}$ Now provide the response and nothing else.
Since $(p-1)! \equiv -1 \mod p$, $$(p-n)! \equiv \frac{(p-1)!}{\prod_{j=1}^{n-1} (p-j)} \equiv (-1)^{n-1} ((n-1)!)^{-1} \mod p$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/99876', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15624/']}
jdg_373648
stackexchange
llm_judgeable_groundtruth_similarity
636810
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 run two piped commands on the results of find on some nested csv files, but I miserably fail. Here is the idea: $ find ./tmp/*/ -name '*.csv' -exec tail -n +2 {} | wc -l \; in order not to count the header row of each CSV file. The command is failing on: wc: ';': No such file or directoryfind: missing argument to `-exec' Do I really need to do a for loop in that case? E.g.: $ for f in ./tmp/*/*.csv; do tail -n +2 ${f} | wc -l; done but with that I'm losing the nice output of find which does include the filename along the count. I'm also losing the file name when using this solution: pipe commands inside find -exec? $ find ./tmp/*/ -type f -name "*.csv" -print0 | while IFS= read -d '' f; do tail -n +2 "${f}" | wc -l; done A little precision; when I speak about the filename that gets printed, it's because I'm used to the following result when calling the commands on a single file: $ tail -n +2 | wc -l ./tmp/myfile.csv 2434 ./tmp/myfile.csv I use Ubuntu 18.04. Now provide the response and nothing else.
If you write find ... -exec foo | bar \; the vertical bar is interpreted by your shell before find is invoked. The left hand of the resulting pipeline is find ... -exec foo , which obviously gives a "missing argument to `-exec'" error; the right hand of the pipeline is bar . Protecting the vertical bar from the shell, as in find ... -exec foo \| bar \; is of no help, because the first token after -exec is interpreted by find as a command and all the following tokens, up to (but not including) the ; or + terminator, are taken as arguments to that command. See Understanding the -exec option of `find` for a thorough explanation. To use a pipeline with -exec you need to invoke a shell. For instance: find ./tmp/*/ -name '*.csv' -exec sh -c ' printf "%s %s\n" "$(tail -n +2 "$1" | wc -l)" "$1"' mysh {} \; Then, to avoid risking an "argument list too long" error, ./tmp/*/ can be rewritten as find ./tmp -path './tmp/*/*' ... or, more precisely, to also exclude tmp 's hidden subdirectories (as ./tmp/*/ would likely do by default), as find ./tmp -path './tmp/.*' -prune -o -path './tmp/*/*' ... Finally, you may use the faster -exec ... {} + variant, which avoids invoking a shell for any single found file. For instance, with awk in place of tail and wc : find ./tmp -path './tmp/.*' -prune -o -path './tmp/*/*' \ -name '*.csv' -exec awk ' BEGIN { skip = 1 } FNR > skip { lc[FILENAME] = (FNR - skip) } END { for (f in lc) print lc[f],f }' {} + (Note that awk also counts those malformed lines that do not end in a newline character, while wc does not).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/636810', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/154644/']}
jdg_373649
stackexchange
llm_judgeable_groundtruth_similarity
11993077
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means? Could someone please explain to me in really simple terms what Static or Class Methods are? Also, could I get a simple explanation on what Instance methods are? This is what they give me in the textbook: There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class. The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial". Now provide the response and nothing else.
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables. However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method. You can do this to execute a static method: MyClass.staticMethod(); // Simply refers to the class's static code But to execute a non-static method, you must do this: MyClass obj = new MyClass(); //Create an instanceobj.nonstaticMethod(); // Refer to the instance's class's code On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11993077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1500291/']}
jdg_373650
stackexchange
llm_judgeable_groundtruth_similarity
283605
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 asked this question some time ago about the shell does not displaying the path. Recently I found out that the .bashrc does not get sourced (and this should be a normal practice ?). Currently, the shell command prompt is like this: -bash-4.3# after I executed source .bashrc , I am able to obtain my expected shell command prompt: root@ubuntu2011:~# where ubuntu2011 is the machine name. How can I make the prompt looks like the latter one every time I login? p.s. the .bashrc is from: cp /etc/skel/.bashrc ~/.bashrc UPDATE : the contents of ~/.profile is as follow: # ~/.profile: executed by Bourne-compatible login shells.if [ "$BASH" ]; then if [ -f ~/.bashrc ]; then . ~/.bashrc fifimesg n and echo $BASH returns /bin/bash UPDATE : Answers of @terdon's questions: How do I login to server? I use ssh root@111.222.333.444 to login as root Are those command executed as root? Yes. UPDATE : The output of ls -l ~/.{profile,bashrc,bash_profile,bash_login} : ls: cannot access /root/.bash_login: No such file or directory-rw-r--r-- 1 root root 63 Dec 24 2012 /root/.bash_profile-rw-r--r-- 1 root root 3637 May 17 17:00 /root/.bashrc-rw-r--r-- 1 root root 140 Apr 23 2010 /root/.profile Now provide the response and nothing else.
This happens because you are logging in through ssh . It comes down to the differences between login and non-login shells. When you connect via ssh, you run a login interactive shell. As explained in man bash , this sort of shell will: When bash is invoked as an interactive login shell, or as a non-inter‐ active shell with the --login option, it first reads and executes com‐ mands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. In other words, ~/.bashrc is ignored by default when running login shells. The simple solution is to explicitly source it from one of the files that are read. As you can see above, login shells will first try to read ~/.bash_profile , and if that doesn't exist ~/.bash_login , and if that also doesn't exist, they read ~/.profile . Since you have a ~/.bash_profile file, you will need to add these lines to it: if [ -f ~/.bashrc ]; then . ~/.bashrcfi
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/283605', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/27309/']}
jdg_373651
stackexchange
llm_judgeable_groundtruth_similarity
21559293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering what type Null is in C. This is probably a duplicate, but I kept getting information about void type on searches. Maybe a better way is can NULL be returned for any type function? For example: int main(){ dosomething(); return NULL;} Does that work? Now provide the response and nothing else.
The type of NULL may be either an integer type or void * . This is because the C standard allows it to be defined as either an integer constant expression or the result of a cast to void * . C 2018 7.19 3 says NULL “expands to an implementation-defined null pointer constant” (when any of several headers have been included: <locale.h> , <stddef.h> , <stdio.h> , <stdlib.h> , <string.h> , <time.h> , or <wchar.h> ). C 6.3.2.3 3 says a null pointer constant is “An integer constant expression with the value 0, or such an expression cast to a type void * .” Thus, a C implementation may define NULL as, for example: 0 , which has type int , ((void *) 0) , which has type void * , or (1+5-6) , which is an integer constant expression with value 0 and type int . Even though NULL may have an integer type, it may be compared to and assigned to pointers, as in if (p == NULL) … . The rules for these operations say that an integer constant zero will be converted to the appropriate pointer type for the operation. Although NULL may be defined to be 0 , it is intended to be used for pointers, not as an integer zero. Programs should avoid doing that, and C implementations are generally better off defining it as ((void *) 0) to help avoid mistakes where it might be accepted as an integer value. In most C implementations, converting NULL to an integer will yield zero. However, this is not guaranteed in the C standard. It is allowed that (int) NULL or (uintptr_t) NULL will produce the address of some special “do not use” location rather than zero. Even (int) (void *) 0 might produce such an address rather than zero. When an integer constant zero is converted to a pointer type, it is treated specially by the C implementation; it produces a null pointer for that implementation even if its null pointer uses an address other than zero. The fact that it is an integer constant means the compiler can apply this special treatment where it recognizes the conversion in the source code. If we have some non-constant expression, such as an int variable x , then (void *) x is not guaranteed to yield a null pointer even if the value of x is zero.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21559293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2133137/']}
jdg_373652
stackexchange
llm_judgeable_groundtruth_similarity
342268
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: Cauchy's Hypothesis or Noll's theorem states that $\vec{t}(\vec{X},t;\partial \Omega) = \vec{t}(\vec{X},t;\vec{N})$ where $\vec{N}$ is the outward unity normal to the positively oriented surface $\partial \Omega$. This translates to words as the dependence of the surface interaction vector on the surface on which it acts is only through the normal $\vec{N}$. My question is what is the significance of the semicolon (;)? How does it differ from the comma (,) used to separated the function's first two arguments? Now provide the response and nothing else.
A semicolon is used to separate variables from parameters. Quite often, the terms variables and parameters are used interchangeably, but with a semicolon the meaning is that we are defining a function of the parameters that returns a function of the variables. For example, if I write $f(x1,x2,\ldots;p1,p2,\ldots)$ then I mean that by supplying the parameters $(p1, p2,\ldots)$ , I create a new function whose arguments are $(x1, x2,\ldots)$ . So the general syntax is $\operatorname{functionName}(\mathrm{variables};\mathrm{parameters})$ . In Noll's theorem it says that the function created by supplying $\partial \Omega$ is the same as that created by supplying $\vec{N}$ . That's rather a nice way of saying that the function created only depends on $\vec{N}$ .
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/342268', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68650/']}
jdg_373653
stackexchange
llm_judgeable_groundtruth_similarity
8040518
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: But I'm having trouble with a "new user" registration form. Can someone explain this bug? I get this error at my signup page: No Method Errorundefined method `users_path' for #<#<Class:0x104b06c60>:0x104b018f0>Extracted source (around line #6):3: <br />4: 5: <div>6: <%= form_for(@user, :id => 'registration_form') do |f| %> 7: <h2>Get started!</h2>8: <%= render 'shared/error_messages', :object => f.object %>9: <table> Now provide the response and nothing else.
You can create a partial to store your plain HTML form, for example this simple one: <form action="{{ path("fos_user_security_check") }}" method="post"> <label>Email</label> <input type="text" name="_username" required="required" /> <label>Password</label> <input type="password" name="_password" required="required" /> <button type="submit">Submit</button></form> Then in your layout just include your brand new partial :) If you need the csrf token (which is highly recommended), just define the provider as a Twig global variable: twig: globals: fos_csrf_provider: "@form.csrf_provider" Then just add the hidden input field in your form: <input type="hidden" name="_csrf_token" value="{{ fos_csrf_provider.generateCsrfToken('authenticate') }}" />
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8040518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/985938/']}
jdg_373654
stackexchange
llm_judgeable_groundtruth_similarity
4029636
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 having a difficult time understanding the use of $A^*$ and how it differs from the usage of a power set. $A^*$ is defined as "the set of all (finite) lists over A" . I understand $\wp(A)$ to be the power set of A defined as "the set of all subsets of A." How is "all lists over A" different from "all subsets of A" ? Here are both definitions as denoted in my textbook: $$A^* := \{[a_1,...,a_n]\ |\ n \in \mathbb N;\ a_1,...,a_n \in A\}$$ $$\wp(A) = \{X\ |\ X \subseteq A\}$$ Now provide the response and nothing else.
There are several differences: Finite lists are ordered (and allow duplicates ) while sets are not: e.g. $$[1,2,1]\quad\mbox{and}\quad[2,1,1]$$ are different lists, while $$\{1,2\}=\{2,1\}=\{1,2,1\}.$$ Finite lists are finite while elements of $\mathcal{P}(A)$ (= subsets of $A$ ) need not be: if we take $A=\mathbb{N}$ , then the set of even numbers is an element of $\mathcal{P}(A)$ but there is no finite sequence which in any sense "corresponds" to it. Meanwhile, subsets of $A$ are at most as big as $A$ , while finite lists can have arbitrarily large finite lengths - this means that if $A$ is finite there will be finite lists of elements of $A$ which are "longer than $A$ is big" (consider e.g. $A=\{1,2\}$ and the finite list $[1,2,1,2,1,2]$ ). So $A^*$ and $\mathcal{P}(A)$ are really very different objects. On a technical note, it's a good idea at this point to give a formal definition of "finite sequence." The definition you've given isn't really rigorous, since the notation " $[...]$ " is itself undefined. The most convenient one winds up being: "a finite list (of elements of some set $X$ ) is a function $f$ with domain $\{i\in\mathbb{N}:i<n\}$ for some $n\in\mathbb{N}$ (and codomain $X$ )." We think of $f(i)$ as the $i$ th term of $f$ . This winds up being a very useful definition in that it generalizes broadly - see e.g. here .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4029636', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/888844/']}
jdg_373655
stackexchange
llm_judgeable_groundtruth_similarity
1756307
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: Edited: It is known that if $f$ is differentiable then the derivative function of $f$ is not always continuous. For instance $f(x)=x^2\sin (\frac{1}{x})$ for $x\neq 0$ and $f(0)=0$ if $x=0$. Then $f^{\prime}$ is discontinue at $x=0$. Is there any differentiable function $f$ whose the derivative of $f$ has countable points of discontinuity? Now provide the response and nothing else.
Such a $q$ is called "sequence covering" and is defined in this paper by Siwiec from 1971. Proposition 2.4 from that paper might be useful: an almost open map defined on a first countable space is sequence covering. Here $f: X \rightarrow Y$ is almost open, iff for all $y \in Y$ there is some $x$ with $f(x) = y$ such that, for every open $O$ in $X$ with $x \in O$, $y \in \operatorname{int}(f[O])$. Any open map satisfies it. A simple example (2.6) shows things can go wrong easily: Let $X$ be the set $\{\frac{1}{n}: n \in \mathbb{N}^+\} \cup \{0\} \cup \{2+\frac{1}{n}: n \in \mathbb{N}^+\} \cup \{2\}$ as a subset of the reals, and let $\sim$ be the equivalence relation that only identifies $0$ and $2$ and leaves the rest alone. Then both $X$ and its quotient are metric compact, and $q$ is perfect (closed map, all inverse images of points are finite (at most size 2) hence compact). But $q$ is not sequence covering, as the sequence $[1],[2+\frac{1}{2}],[\frac{1}{3}],[2+\frac{1}{4}],[\frac{1}{5}],\ldots$ converges to $[0] = [2]$ but there is only one choice of lifting the sequence and this does not converge. So even only one non-trivial class between extremely nice spaces can fail this property. Googling "sequence covering maps" will give you some more papers with generalisations of 2.4. The paper I linked to contains some more counterexamples where we cannot drop some assumption.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1756307', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/319254/']}
jdg_373656
stackexchange
llm_judgeable_groundtruth_similarity
36030887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to create a site for a school project. Doesn't have to be anything special but I want to include some nice effects.I want to make the '#boxje' dissapear when you scroll down but reappear when you're back at the top. I've tried to do it with Javascript but I couldn't really get any further than making it disappear after x amount of seconds. <div id="boxje" class="col-md-4 col-md-offset-4 inner col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3"> <div class="text-box"> <p class="intro">Welkom</p> <h2><img src="images/van-hool-logo.png" height="60px" ></h2> <p>Van Hool uit België bouwt jaarlijks tot 1400 bussen en autocars en zo’n 4000 industriële voertuigen waarvan het 80% wereldwijd exporteert. Met meer dan 4000 werknemers en een compleet gamma autocars en bussen is Van Hool een belangrijke busbouwer in Europa.Daarnaast bouwt Van Hool ook een zeer uitgebreid gamma opleggers en tankcontainers. Van Hool is in deze sector onbetwist marktleider in België en bekleedt een belangrijke plaats op verschillende exportmarkten.<br> Al meer dan 65 jaar is Van Hool gerenommeerd voor het ontwerpen en bouwen van op maat gemaakte hoogtechnologische kwaliteitsproducten.</p> <br> <br> </div></div> Now provide the response and nothing else.
The height is being wrapped because the inflated view is added to the FrameLayout which has layout_height=wrap_content . See FrameLayout (R.id.design_bottom_sheet) at https://github.com/dandar3/android-support-design/blob/master/res/layout/design_bottom_sheet_dialog.xml . The class below makes the bottom sheet full screen, background transparent, and fully expanded to the top. public class FullScreenBottomSheetDialogFragment extends BottomSheetDialogFragment { @CallSuper @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @Override public void onStart() { super.onStart(); Dialog dialog = getDialog(); if (dialog != null) { View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet); bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT; } View view = getView(); view.post(() -> { View parent = (View) view.getParent(); CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) (parent).getLayoutParams(); CoordinatorLayout.Behavior behavior = params.getBehavior(); BottomSheetBehavior bottomSheetBehavior = (BottomSheetBehavior) behavior; bottomSheetBehavior.setPeekHeight(view.getMeasuredHeight()); ((View)bottomSheet.getParent()).setBackgroundColor(Color.TRANSPARENT) }); }} --- EDIT Aug 30, 2018 ---I realized a year later that the background was colored on the wrong view. This dragged the background along with the content while a user was dragging the dialog.I fixed it so that the parent view of the bottom sheet is colored.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36030887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6070516/']}
jdg_373657
stackexchange
llm_judgeable_groundtruth_similarity
51116
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a variable power supply, and want to provide the ability to digitally measure the outputted voltage and current. The digital power supply used to drive the ADC, microcontroller and friends is separate from the unregulated power supply used to derive output voltages. The power supply for the microcontroller is galvanically isolated from the one for the output voltages — the first is an unregulated transformer, while the second one is an SMPS supply. Now, measuring the current while maintaining galvanic isolation is easy, since I'm using a Hall Effect sensor for that, but I don't see a similar method for doing that for voltage measurements. My plan was to use a resistor divider and shoving that voltage into the ADC. However, that completely ruins all the effort I put into galvanic isolation of the two rails, since the downscaled voltage output would get into the ADC, causing all kinds of problems. Is there any kind of solution out there that will let me measure that voltage, while still maintaining galvanic isolation? I don't think optocouplers will work, seeing as they're either on or off, and I'm not familiar with any other kind of isolation, and I'm not really familiar with any other kind of isolation techniques, but I'm thinking that perhaps transformers could be useful in this situation? Now provide the response and nothing else.
You're looking for an isolation amplifier . These are great if you're looking for a monolithic solution that is easy to integrate, but might not be cost-optimized. Some even provide a little isolated (HV-side) power via an internal DC/DC converter to run scaling op-amps, etc. I've had good luck with the Burr Brown ISO series of isolation amplifiers (acquired by TI a few years back). The ISO122 is a general use product, and the ISO124 has higher accuracy. Analog Devices also makes a few general purpose isolation amps . Just be aware that some sort of modulation is required to move the signal across the isolation barrier within an isolation amplifier. Some do it inductively, some optically. Either way, plan on a little ripple on the output signal. The specs usually do a good job of outlining the limitations.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/51116', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6041/']}
jdg_373658
stackexchange
llm_judgeable_groundtruth_similarity
27934512
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I am comfortable with using relative layouts, but whilst getting used to Android Studio I noticed that in my relative layout child views it generated both of the following. android:layout_alignParentLeft="true"android:layout_alignParentStart="true I have checked out the Android docs here , but cannot see a distinction between the two. Certainly swapping one for another in the Android Studio shows no visible difference. Is there one? Now provide the response and nothing else.
It depends on the layout direction. The layout direction can be either left-to-right (start = left, end = right), or right-to-left (vice versa). By default, the layout direction is based on the locale (left-to-right for languages like English, right-to-left for languages like Arabic), but you can override it with the layoutDirection XML attribute or setLayoutDirection function. e.g.: android:layoutDirection="ltr" ^ will make alignParentStart equivalent to alignParentLeft on all devices. android:layoutDirection="rtl" ^ will make alignParentStart equivalent to alignParentRight on all devices. You can also set to "locale" to use the locale or "inherit" to inherit the layout direction from the parent view. You need to add android:supportsRtl="true" to your AndroidManifest.xml to support right-to-left layouts. also related: android:textDirection
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27934512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/966656/']}
jdg_373659
stackexchange
llm_judgeable_groundtruth_similarity
478582
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'm using a MySQL tuning script that in turn uses the socket (.sock) file on the local drive to connect to MySQL. Even though I have a copy of MySQL on this server, however, the MySQL that I want to work with is actually on a different machine-- in my normal app, the DB_HOST is a different IP address, etc. So... is there a way to create a socket file that points to a remote MySQL server, that lives on a different IP? Now provide the response and nothing else.
Yes, we call them network connections. Everything you do on the Internet uses them. Aside from the AF_UNIX socket you are referring to, there are AF_INET sockets and AF_INET6 sockets, which make IPv4 and IPv6 connections, respectively. There are a few other types, but you probably don't care about ancient things like AppleTalk... Unlike Unix sockets, network sockets do not have corresponding files on the filesystem. They can only be created in application code using the socket API (see the socket(7) man page). In the case of the tuning scripts, they should have command line options that allow you to specify the remote host to connect to. The popular mysqltuner.pl script, for instance, accepts --host and --port to specify a remote host. (Though specifying the port isn't necessary unless you moved it from the default of 3306). You still need a username and password with USAGE privileges on the MySQL server, and the firewall must permit you access.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/478582', 'https://serverfault.com', 'https://serverfault.com/users/90246/']}
jdg_373660
stackexchange
llm_judgeable_groundtruth_similarity
9203516
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A struct is a value type, so if I assign a struct to another struct, its fields will be copied in the second struct. But, what happens if some fields of the struct are a reference type? public struct MyIPEndPoint{ public String IP; public UInt16 Port; public MyIPEndPoint(String ipAddress, UInt16 portNumber) { IP = ipAddress; Port = portNumber; } public override string ToString() { return IP+":"+Port; }}...static int Main(string[] args){ MyIPEndPoint address1 = new MyIPEndPoint("127.0.0.1", 8080); MyIPEndPoint address2 = address1; address2.IP = "255.255.255.255"; address2.Port = 9090; Console.WriteLine(address1); Console.WriteLine(address2);} The output is: 127.0.0.1:8080255.255.255.255:9090 Why the IP (a string, that is a reference type) of address1 does not change?The same behavior occurs if I replace string with IPAddress to represent the IP within MyIPEndPoint : although IPAddress is a class (that is a reference type), it does not behave as a reference type. Why? Indeed, if I wrap the string which represent the IP using a new simple class MyIP , the behavior changes. public class MyIP{ public string IpAsString; public MyIP(string s) { IpAsString = s; } public override string ToString() { return IpAsString; }} Of course you should also adjust the MyIPEndPoint struct in the following way: public struct MyIPEndPoint{ public MyIP IP; // modification public UInt16 Port; public MyIPEndPoint(String ipAddress, UInt16 portNumber) { IP = new MyIP(ipAddress); // modification Port = portNumber; } public override string ToString() { return IP+":"+Port; }} Finally in the Main I changed only a statement: MyIPEndPoint address1 = new MyIPEndPoint("127.0.0.1", 8080);MyIPEndPoint address2 = address1;address2.IP.IpAsString = "255.255.255.255"; // modificationaddress2.Port = 9090;Console.WriteLine(address1);Console.WriteLine(address2); Now the output is: 255.255.255.255:8080255.255.255.255:9090 I was expecting this output in the first case.Why in the first case does the reference not behave as expected ? Now provide the response and nothing else.
You have correctly understood that with structs, address1 and address2 are not the same object. The values were copied. However, for the field, this is a simple case of reassignment. It has nothing to do with the fact that string is a reference type or any special rules or any suggestion of immutability. You have simply reassigned a property or field with another value. someStruct.SomeString = "A";anotherStruct = someStruct;anotherStruct.SomeString = "B"; // would never affect someStruct You have overwritten the reference in this example. The fact that for a brief moment, both structs' fields contained the same reference is of no importance. In your second example, you did something very different. someStruct.IP.SomeString = "A";anotherStruct = someStruct;anotherStruct.IP.SomeString = "B"; In this case, the value of IP has not changed. Part of IP's state has changed. Each struct's field is still referencing the same IP. Put in simpler terms var foo = new Foo(); // Foo is classvar other = foo; // other and foo contain same value, a reference to an object of type Fooother = new Foo(); // was foo modified? no! int x = 1;int y = x;y = 2; // was x modified? of course not.string s = "S";string t = s;t = "T"; // is s "T"? (again, no) Variables and fields hold values. For classes, those values are references to objects. Two variables or fields can hold the same reference, but that does not mean those variables themselves are linked. They are not connected in anyway, they simply hold a common value. When you replace a value for one variable or field, the other variable is not affected. Not on the specific topic, but it is worth noting that mutable structs are viewed by many as evil. Others don't quite hold the same view, or at least not as religiously. (However, it is also worth noting that had Address been a class, then address1 and address2 would hold the same value (the reference to the Address object), and modification to the state of address1 would be visible via address2 as long as neither address1 or address2 are themselves reassigned. ) If this is an actual representation of your code, it would be worth doing some research on mutable structs so you at least have a full understanding of various pitfalls you may encounter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9203516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364056/']}
jdg_373661
stackexchange
llm_judgeable_groundtruth_similarity
24868273
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 PowerShell V2 script that moves some files around and installs some services. However I would like to call and run a .cs file about halfway through the PowerShell Script. I have found plenty of articles on calling PowerShell from C# but none the opposite way around. I would just like the C# file to run once then continue running the PowerShell script. If anyone could point me in the direction of an article explaining how to accomplish this or if you know yourself and could help it would be greatly appreciated. Now provide the response and nothing else.
I saw no reason why we couldn't run a .cs file directly from PowerShell, so I took Keith's snip and added the missing Get-Content parts to do literally what the OP asks for. No need to compile your code, just edit the -Path argument to point to your .cs file. $source = Get-Content -Path "A:\basic.cs"Add-Type -TypeDefinition "$source"# Call a static method[BasicTest]::Add(4, 3)# Create an instance and call an instance method$basicTestObject = New-Object BasicTest$basicTestObject.Multiply(5, 2) Basic.cs public class BasicTest{ public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24868273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3748732/']}
jdg_373662
stackexchange
llm_judgeable_groundtruth_similarity
41609155
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For such component <template> <div> <router-link :to="{name:'section', params: { sectionId: firstSectionId }}">Start</router-link> </div></template> <script lang="ts"> import { mapActions } from "vuex" export default { mounted() { this.getSectionId() }, computed: { firstSectionId() { return this.$store.state.firstSectionId } }, methods: mapActions(["getSectionId"]) }</script> Store: const store: any = new Vuex.Store({ state: { firstSectionId: null }, // actions, // mutations}) I have a web request in the getSectionId action and it asynchronously fetches data and calls a mutation that will fill firstSectionId in state . During the initial rendering firstSectionId is null and I get the warning that a required parameter is missing during rendering of router-link . It is not a problem here to add v-if="firstSectionId" . But in general what is the approach for fetching data from a server to be displayed? Currently all my components are checking if there is data present in the store before rendering, is it normal or is there a better way to wait for data to be loaded before rendering it? Now provide the response and nothing else.
One approach for asynchronously fetching data is to use promise in vuex store actions . Vue.http.get(API_URL) .then((response) => { //use response object }) .catch((error) => { console.log(error.statusText) }); To demonstrate that I make request to this route . You can see how response should looks like. Let's save response object in state.users array. store.js const store = new Vuex.Store({ state: { users: [] }, mutations: { FETCH_USERS(state, users) { state.users = users } }, actions: { fetchUsers({ commit }, { self }) { Vue.http.get("https://jsonplaceholder.typicode.com/users") .then((response) => { commit("FETCH_USERS", response.body); self.filterUsers(); }) .catch((error) => { console.log(error.statusText) }); } }}) export default store You noticed that there is self.filteruser() method after commit. That is crucial moment. Before that we are committing a mutation , which is synchronous operation and we are sure that we will have our response in store.state that can be used in filterUsers() method (don't forget to pass self parm) Users.vue import store from "../store/store"export default { name: 'users', created() { this.$store.dispatch("fetchUsers", { self: this }) }, methods:{ filterUsers() { //do something with users console.log("Users--->",this.$store.state.users) } }} Better ways (ES6 & ES7) ES6 Promises for asynchronous programming //User.vuecreated() { this.$store.dispatch("fetchUser").then(() => { console.log("This would be printed after dispatch!!") })}//store.jsactions: { fetchUser({ commit }) { return new Promise((resolve, reject) => { Vue.http.get("https://jsonplaceholder.typicode.com/users") .then((response) => { commit("FETCH_USERS", response.body); resolve(); }) .catch((error) => { console.log(error.statusText); }); }); }} ES7: async/await To get away from callback hell, and to improve asynchronous programming use async function, and you can await on a promise. Code looks much easier to follow (like it is synchronous), but code isn't readable for browsers so you'll need Babel transpiler to run it. actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // wait for actionA to finish commit('gotOtherData', await getOtherData()) }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41609155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72174/']}
jdg_373663
stackexchange
llm_judgeable_groundtruth_similarity
17239
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 toying with designing a simple 8-bit CPU out of basic logic components. I have a fairly good idea of how my ALU and registers will interact, but the one thing I feel can use some improvement is how to toggle when a line is allowed to connect to the main data bus. My initial thought was to use and gates to drive the bus. The output from the various lines in the ALU could all go into a set of quad-AND chips that output onto the bus. Only one set of AND gates at a time would have all of its B inputs pulled high to let it out onto the bus. A couple of things I am unsure about: It seems wasteful to use eight full AND gates per line, when I only need one control line going in. Is there a better chip more suited to this purpose? I'm sure I could also do it with eight transistors, but I would like to stick with fairly common (and cheap) ICs. A solution like this only lets data flow one way from the bus. Is this a problem? I think not, since I have other control lines stopping registers from loading the bus data until I want them to. Is there a standard chip to use for a bus gate like this? Now provide the response and nothing else.
The 74HC244 is the typical device for connecting to/disconnecting from a bus. It's an octal tri-state buffer (or rather a dual quad buffer). You'll need the tri-state feature to disconnect completely from the bus. The gates would set the bus high or low, but that wouldn't allow another device on it. But since you're talking about a data bus you probably want a bidirectional buffer. Then you can use the 74HC245 . You have a DIR pin to control the direction and a /OE which can make the buffer tri-state. edit JustJeff mentions the 74HC374 octal tri-state D flip-flop. ( Note: I'll talk about the 74HC574, which is functionally the same, but has a more logical pinout. ) The 74HC574 is indeed an interesting part, and a classic since the SN74xx series. While the 74HC245 will give you a tri-state buffer, the 74HC574 has a memory function too, in the form of an octal D flip-flop. Great to make registers, and through the tri-state connection to the bus you can route your data flow easily. There's a drawback to this, however. The register's output is only available to the bus, so all communication would have to pass there, so that the bus will become a bottle-neck . Therefore I think it's better to replace the 74HC374 by a 74HC273 octal D flip-flop followed by a separate 74HC244 tri-state buffer for the connection to the bus. That way the register's output is also available internally when some other signal occupies the bus. (I don't know if there's a function compatible part with the more logical pinout. You may also use a 74HC574 with /OE hardwired to ground.)
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/17239', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1686/']}
jdg_373664
stackexchange
llm_judgeable_groundtruth_similarity
132392
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 learning some set theory and logic on the side and am looking Jech's book, "Set Theory". At the moment, I am learning the basic axioms, and what I can and cannot do with them. Most of the axioms are of the form, if such and such set exists, then so does this set (the power set axiom, If X exists, so does it's power set). These sets by themselves do not give us actual sets to deal with, so the entire theory could be empty. Thus we have the axiom of infinity which states, $\exists S (\emptyset\in S \wedge (\forall x\in S)x\cup\{x\}\in S)$.However, this axiom seems to already give the existence of the empty set before one can get the infinite set, $S$. So do we need the empty set in existence before we can state this axiom or does it come from some other place. Again it does not seem to come from the other axioms. Now provide the response and nothing else.
The symbol $\emptyset$ is not part of the formal language of ZFC, so from the strictest viewpoint the subformula "$\emptyset \in S$" is not even syntactically valid in ZFC. One way to handle that problem is to prove there is a set that has no members, as Brian M. Scott indicates, and then make a definitional expansion of ZFC to add a constant symbol $\emptyset$ for this set. Another way to handle it, without making a definitional expansion, is to just mentally replace "$\emptyset \in S$" with something like "$(\exists z)[(\forall w)[\lnot (w \in z)] \land z \in S]$". Obviously this makes the axiom much harder to read, so writing $\emptyset \in S$ is a convenient abbreviation. This same issue comes up in many formal settings: when someone uses a symbol that is not in the formal language, but where you know the intended definition for the symbol, you can simply interpret the formula as an abbreviation for a longer formula that does not use the symbol. For example, the definition in $\{z \in \mathbb{N} : z\text{ is even}\}$ is not a formula of ZFC, but it is an abbreviation for $(\exists w \in \mathbb{N})[z = w + w]$, which in turn is an abbreviation for a much longer formula that does not include the symbols "+" or "$\mathbb{N}$". In most settings the author will not comment much on this sort of thing unless it is unclear that there is a definition in the language of set theory or unless it matters which specific definition is used.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/132392', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25928/']}
jdg_373665
stackexchange
llm_judgeable_groundtruth_similarity
793472
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 process of transforming a given efficient pointer-based hash map implementation into a generic hash map implementation, I stumbled across the following problem: I have a class representing a hash node (the hash map implementation uses a binary tree) THashNode <KEY_TYPE, VALUE_TYPE> = classpublic Key : KEY_TYPE; Value : VALUE_TYPE; Left : THashNode <KEY_TYPE, VALUE_TYPE>; Right : THashNode <KEY_TYPE, VALUE_TYPE>;end; In addition to that there is a function that should return a pointer to a hash node. I wanted to write PHashNode = ^THashNode <KEY_TYPE, VALUE_TYPE> but that doesn't compile (';' expected but '<' found). How can I have a pointer to a generic type? And adressed to Barry Kelly: if you read this: yes, this is based on your hash map implementation. You haven't written such a generic version of your implementation yourself, have you? That would save me some time :) Now provide the response and nothing else.
Sorry, Smasher. Pointers to open generic types are not supported because generic pointer types are not supported, although it is possible (compiler bug) to create them in certain circumstances (particularly pointers to nested types inside a generic type); this "feature" can't be removed in an update in case we break someone's code. The limitation on generic pointer types ought to be removed in the future, but I can't make promises when. If the type in question is the one in JclStrHashMap I wrote (or the ancient HashList unit), well, the easiest way to reproduce it would be to change the node type to be a class and pass around any double-pointers as Pointer with appropriate casting. However, if I were writing that unit again today, I would not implement buckets as binary trees. I got the opportunity to write the dictionary in the Generics.Collections unit, though with all the other Delphi compiler work time was too tight before shipping for solid QA, and generic feature support itself was in flux until fairly late. I would prefer to implement the hash map buckets as one of double-hashing, per-bucket dynamic arrays or linked lists of cells from a contiguous array, whichever came out best from tests using representative data. The logic is that cache miss cost of following links in tree/list ought to dominate any difference in bucket search between tree and list with a good hash function. The current dictionary is implemented as straight linear probing primarily because it was relatively easy to implement and worked with the available set of primitive generic operations. That said, the binary tree buckets should have been an effective hedge against poor hash functions; if they were balanced binary trees ( => even more modification cost), they would be O(1) on average and O(log n) worst case performance.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/793472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62391/']}
jdg_373666
stackexchange
llm_judgeable_groundtruth_similarity
12966
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'm happy to work over an algebraically closed field....) Let $\mathcal{C} \rightarrow Spec (R)$ be a (flat) family of proper, prestable curves where $R$ is a DVR. Suppose the generic fiber is smooth and the special fiber, $C_0$, is reduced but may be reducible. Given a finite map of curves $f_0: D_0 \rightarrow C_0$ with $D_0$ also prestable, can this be extended to some map on some family? That is, is there a flat family of proper curves $\mathcal{D} \rightarrow Spec(R)$ and an $R$-morphism $f: \mathcal{D} \rightarrow \mathcal{C}$ which reduces to $f_0$ on the special fiber? Perhaps such an extension is possible only after a ramified cover of $Spec(R)$? If so, can it be arranged that the generic fiber of $\mathcal{D}$ is smooth? Now provide the response and nothing else.
Stated as such, the question is really too vague. For example, if $C_0, D_0$ are smooth of genus bigger than 1, and $f_0$ is purely inseparable, then $f_0$ can not lift to $R$ (even after extention) if $R$ has characteristic zero. Actually, as the generic fibers of $\mathcal C$ and $\mathcal D$ are equal to $g(C_0)=g(D_0)$, this will contradict Riemann-Hurwitz formula. In this survey paper you can find some sufficient conditions. For instance, the lifting property for finite generically étale morphisms of semi-stable curves are characterized.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/12966', 'https://mathoverflow.net', 'https://mathoverflow.net/users/397/']}
jdg_373667
stackexchange
llm_judgeable_groundtruth_similarity
2363365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From the book: 1) int i = 7;2) Object o = i; // Implicit boxing int-->Object3) Object[] a3 = new int[] { 1, 2 }; // Illegal: no array conversion The assignments in 3) is illegal because int is not a reference type and so int[] is not implicitly convertible to Object[] I don't get this . on line 2) it shows that int is implicitly convertible to Object, and in the third line, it says int[] is not implicitly convertable. wha ?? Now provide the response and nothing else.
Not to restate the problem, but it's because int[] is not implicitly (or explicitly, for that matter) convertible to Object[] . Arrays are types in and of themselves. int[] simply means "a series of int variables", just like Object[] means "a series of Object variables". Incidentally, all arrays are reference types, it's just that int[] is a reference type representing a series of a particular value type . EDIT Don't allow the talk about covariance to confuse you. This is a widely misunderstood topic, and one that's not really beneficial for a beginning developer to try to tackle. Yes, .NET 4.0 introduces the ability to specify an operation as being covariant or contravariant, but that won't allow for assignment compatibility between incompatible types like Object[] and int[] . Consider the following example, assuming that it would compile. int[] ints = new int[] { 1, 2, 3 };Object[] objects = ints;objects[1] = "hello";int foo = ints[1]; Now we have a problem. If it were legal to assign an int[] to an Object[] , then I now suddenly (magically) have a string value in my int[] array--something that should never happen, and actually can't happen, since an int variable cannot hold a string value. Others have (correctly) pointed out that something like this does compile: string[] strings = new string[] { "a", "b", "c" };Object[] objects = strings;objects[1] = 4; I'll leave it to someone like Eric Lippert to explain why this sort of operation works (it's essentially assuming covariance when it isn't necessarily the case) [ EDIT: Thanks to Tim Goodman, who actually posts Eric's explanation, or at least statement, about this ], but fundamentally any reference type is technically capable of holding a reference to any type. In other words, when I declare a string variable it allocates the same amount of memory (for the variable) as if I were to declare a DbConnection variable; they're both reference types. For value types, the amount of memory allocated depends on the type, and they are fundamentally incompatible. You will note, however, that you will get a runtime exception ( ArrayTypeMismatchException ) when performing the last step (assigning an int to the second array element), since the underlying array is actually a string[] .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2363365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257412/']}
jdg_373668
stackexchange
llm_judgeable_groundtruth_similarity
28782928
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 ASP.NET 5 MVC 6 application, I want to post with Ajax some data to my controller. I already done this with ASP.NET MVC 5 and I tested the exact same code in an blank ASP.NET MVC 5 project and it worked, but with the new version I can't and I don't know why. With the Ajax call, I can go to the controller, the model is created but the fields are null (or false for the boolean). Here is my code : script.js : var data = { model: { UserName: 'Test', Password: 'Test', RememberMe: true } }; $.ajax({ type: "POST", url: "/Account/Login/", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { // Do something interesting here. } }); AccountController.cs : [HttpPost] public JsonResult Login(LoginViewModel model) { if (ModelState.IsValid) { //var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false); //if (result.Succeeded) //{ // //return RedirectToLocal(returnUrl); //} ModelState.AddModelError("", "Identifiant ou mot de passe invalide"); return Json("error-model-wrong"); } // If we got this far, something failed, redisplay form return Json("error-mode-not-valid"); } LoginViewModel.cs : public class LoginViewModel{ [Required] [Display(Name = "UserName")] [EmailAddress] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; }} Any ideas ?Thanks Now provide the response and nothing else.
You need to explicit use FromBody on MVC6 if you are using json public JsonResult Login([FromBody]LoginViewModel model) EDIT I think you are mixing different errors. I will try to describe how you should make the request: content-type must be : application/json your request body must be in JSON format (as JasonLind suggested): { UserName: 'Test', Password: 'Test', RememberMe: true}; this is what you should see when inspecting the request (via chrome debugger tools F12) or using a request inspector like fiddler. If you see something in the form of UserName=Test&Password=Test&RememberMe=true then you are doing it wrong, that's form format. you don't need the model variable. if you see your request with a "wrapper" then you should remove it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28782928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1444803/']}
jdg_373669
stackexchange
llm_judgeable_groundtruth_similarity
1560
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is well-known that by utilizing quantum parallelism we can calculate a function $f(x)$ for many different values of $x$ simultaneously. However, some clever manipulations is needed to extract the information of each value, i.e. with Deutsch's algorithm. Consider the reverse case: can we use quantum parallelism to calculate many functions (say $f(x),g(x),\dots$) simultaneously for a single value $x_0$? Now provide the response and nothing else.
The exact answer depends on the exact kind of superposition you want. The answers by pyramids and Niel both give you something like $$A\sum_{t=1}^n |\,\,f_t (x)\,\,\rangle \otimes |F_t\rangle$$ Here I've followed Niel in labelling the different functions $f_1$, $f_2$, etc, with $n$ as the total number of functions you want to superpose. Also I've used $F_t$ to denotes some description of the function $f_t$ as a stored program. The $A$ is just whatever number needs to be there for the state to be normalized. Note that this is not simply a superposition of the $f_t(x)$. It is entangled with the stored program. If you were to trace out the stored program, you'd just have a mixture of the $f_t(x)$. This means that the stored program could constitute 'garbage', which prevents interference effects that you might be counting on. Or it might not. It depends on how this superposition will be used in your computation. If you want rid of the garbage, things get more tricky. For example, suppose what you want is a unitary $U$ that has the effect $$U : \,\,\, | x \rangle \otimes |0\rangle^{\otimes N} \rightarrow A \sum_{t=1}^n |\,\,f_t (x)\,\,\rangle$$ for all possible inputs $x$ (which I am assuming are bit strings written in the computational basis). Note that I've also included some blank qubits on the input side, in case the functions have longer outputs than inputs. From this we can very quickly find a condition that the functions must satisfy: since the input states form an orthogonal set, so must the outputs. This will put a significant restriction on the kinds of functions that can be combined in this way.
{}
{'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/1560', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/1341/']}
jdg_373670
stackexchange
llm_judgeable_groundtruth_similarity
3000767
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f(x) \in \mathbb{Z}[x]$ . Prove that $f(x)$ has a root in $\mathbb{Q}$ iff there is a ring homomorphism from $\mathbb{Z}[x]/(f(x)) \rightarrow \mathbb{Q}$ . I tried using a homomorphism from $\mathbb{Z}[x] \rightarrow \mathbb{Q}$ defined by $\varphi(f(x)) = f(q)$ for a fixed $q \in \mathbb{Q}$ . When $q$ is a root this could be useful, but that's all I've managed to come up with, and I'm unclear how to proceed. Now provide the response and nothing else.
$$-\int_{0}^{\infty} \frac{\sin\left(\frac{7}{15}x\right)}{x^3}\:dx + \int_{0}^{\infty} \frac{\sin\left(\frac{13}{15}x\right)}{x^3}\:dx +\int_{0}^{\infty} \frac{\sin\left(\frac{17}{15}x\right)}{x^3}\:dx -\int_{0}^{\infty} \frac{\sin\left(\frac{23}{15}x\right)}{x^3}\:dx= \frac{2\pi}{15}$$ You cannot expand the integrals since they are not convergent. Moreover, given that $\int_a^b f(x)+g(x)dx$ converges, $\int_a^b f(x)+g(x)dx=\int_a^b f(x)dx+\int_a^b g(x)dx$ only if $\int_a^b f(x)dx$ and $\int_a^b g(x)dx$ converge.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3000767', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/546218/']}
jdg_373671
stackexchange
llm_judgeable_groundtruth_similarity
45556850
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is the closest I can get to. But instead of the text being black. I want it to have the UNBLURRED background clipped to it. Attempt 1: *{ padding:0; margin:0;}/*Centering*/html,body{ height:100%; overflow:hidden;}.box{ height:100%; display:flex; justify-content:center; align-items:center;}/*Clip text*/.item{ font-size:250px; z-index:1;}.box{ background:url('https://media.timeout.com/images/103444978/image.jpg'); background-size:cover;}/*Blurring*/.box::before{ content:''; background:inherit; filter:blur(10px); position:absolute; top:0;right:0;bottom:0;left:0; margin:-20px;} <div class='box'> <div class='item'>NYC</div></div> The problem seems to be the conflict between the z-index:1 set on .item class, and the -webkit-background-clip:text; property. You cannot have the 2 together, otherwise, the screen will be blank. The z-index:1 is used to put the text in front of the blurred bacground. This is where I try to put the blurring and clipping effect together. I commented out the z-index:1 in .item class, so the page won't go blank. Attemp 2: *{ padding:0; margin:0;}/*Centering*/html,body{ height:100%; overflow:hidden;}.box{ height:100%; display:flex; justify-content:center; align-items:center;}/*Clip text*/.item{ font-size:250px; /*z-index:1;*/}.box{ background:url('https://media.timeout.com/images/103444978/image.jpg');color:#21537a;/*text color for nonwebkit*/ -webkit-text-fill-color: transparent; background-size:cover; -webkit-background-clip:text;}/*Blurring*/.box::before{ content:''; background:inherit; filter:blur(10px); position:absolute; top:0;right:0;bottom:0;left:0; margin:-20px;} <div class='box'> <div class='item'>NYC</div></div> Now provide the response and nothing else.
You can get access of the NgControl through DI. NgControl has all the information about validation status. To retrieve NgControl you should not provide your component through NG_VALUE_ACCESSOR instead you should set the accessor in the constructor. @Component({ selector: 'custom-form-comp', templateUrl: '..', styleUrls: ...})export class CustomComponent implements ControlValueAccessor { constructor(@Self() @Optional() private control: NgControl) { this.control.valueAccessor = this; } // ControlValueAccessor methods and others public get invalid(): boolean { return this.control ? this.control.invalid : false; } public get showError(): boolean { if (!this.control) { return false; } const { dirty, touched } = this.control; return this.invalid ? (dirty || touched) : false; }} Please go through this article to know the complete information.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45556850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4747885/']}
jdg_373672
stackexchange
llm_judgeable_groundtruth_similarity
23268565
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 Questions table which have store so many question. Question related to question_topics so have create has many relationship with question. Now it's look like this: $this->Question->bindModel( array( 'hasMany' => array( 'QuestionTopic'=>array( 'className' => 'QuestionTopic', 'foreignKey' => 'question_id', 'dependent' => true, 'conditions' => array('QuestionTopic.areas_id' => 165), 'type' => 'left' ) ) ));print_r($this->Question->find('all')); die; When i saw the result then it look like this Array( [0] => Array ( [Question] => Array ( [id] => 89 [user_id] => 1 [question_group_id] => 0 [question] => jQuery function here [target_id] => 1 [type] => 1 [order] => 1 [description] => additional info here [privacy_friend_id] => [channel_id] => 1 [status] => 0 [location] => Chandigarh, India [regions] => 307 [select_country] => 381 [select_states] => 515 [created] => 2014-04-15 06:59:44 [modified] => 2014-04-15 06:59:44 ) [QuestionTopic] => Array ( [0] => Array ( [id] => 167 [areas_id] => 165 [question_id] => 89 ) ) ) [1] => Array ( [Question] => Array ( [id] => 90 [user_id] => 1 [question_group_id] => 0 [question] => Art [target_id] => 2 [type] => 1 [order] => 1 [description] => addional infomation here [privacy_friend_id] => [channel_id] => 1 [status] => 0 [location] => Chandigarh, India [regions] => 307 [select_country] => 381 [select_states] => 515 [created] => 2014-04-15 07:52:17 [modified] => 2014-04-15 07:52:17 ) [QuestionTopic] => Array ( ) )) I want first record only which have Question topic id 167 not second one. How can i do this. Now provide the response and nothing else.
Don't use hasMany, Use has one like this $this->Question->bindModel( array( 'hasOne' => array( 'QuestionTopic'=>array( 'className' => 'QuestionTopic', 'foreignKey' => 'question_id', 'dependent' => true, 'type' => 'left' ) ) ) ); print_r($this->Question->find('all',array('conditions'=>array('QuestionTopic.areas_id' => array('165')))));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23268565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3425009/']}
jdg_373673
stackexchange
llm_judgeable_groundtruth_similarity
5435841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a 32-bit machine, so I suppose that the memory alignment should be 4 bytes. Say I have this struct: typedef struct { unsigned short v1; unsigned short v2; unsigned short v3;} myStruct; The plain added size is 6 bytes, and I suppose that the aligned size should be 8, but sizeof(myStruct) returns me 6. However if I write: typedef struct { unsigned short v1; unsigned short v2; unsigned short v3; int i;} myStruct; the plain added size is 10 bytes, aligned size shall be 12, and this time sizeof(myStruct) == 12 . Can somebody explain what is the difference? Now provide the response and nothing else.
At least on most machines, a type is only ever aligned to a boundary as large as the type itself [Edit: you can't really demand any "more" alignment than that, because you have to be able to create arrays, and you can't insert padding into an array]. On your implementation, short is apparently 2 bytes, and int 4 bytes. That means your first struct is aligned to a 2-byte boundary. Since all the members are 2 bytes apiece, no padding is inserted between them. The second contains a 4-byte item, which gets aligned to a 4-byte boundary. Since it's preceded by 6 bytes, 2 bytes of padding is inserted between v3 and i , giving 6 bytes of data in the short s, two bytes of padding, and 4 more bytes of data in the int for a total of 12.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5435841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_373674
stackexchange
llm_judgeable_groundtruth_similarity
6034047
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 standard many-to-one relationship set up. There are a bunch of fields, but for our purposes here, the relevant model is: class Class(models.Model): name = models.CharField(max_length=128)class Student(models.Model): class = models.ForeignKey(Class) name = models.CharField(max_length=128) address = models.CharField(max_length=128) # ...etc I created an admin, and it works great. it even automatically has the ability for me to set the Class when I am editing a Student. However, when I go to create/edit a Class, all I get is an input box for the name. Is there a way to add a box/field where Students can be added as members of Class from the Class admin page? I can make a form inline, but that is to create new Students. I already have all my Students created and am just looking for a quick method to add multiple existing Students to different Class'. Now provide the response and nothing else.
Here is "custom form" solution as Luke Sneeringer suggested. Anyway, I'm suprised by absence of out-of-the-box Django solution to this (rather natural and probably common) problem. Am I missing something? from django import formsfrom django.db import modelsfrom django.contrib import adminclass Foo(models.Model): passclass Bar(models.Model): foo = models.ForeignKey(Foo)class FooForm(forms.ModelForm): class Meta: model = Foo bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all()) def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) if self.instance: self.fields['bars'].initial = self.instance.bar_set.all() def save(self, *args, **kwargs): # FIXME: 'commit' argument is not handled # TODO: Wrap reassignments into transaction # NOTE: Previously assigned Foos are silently reset instance = super(FooForm, self).save(commit=False) self.fields['bars'].initial.update(foo=None) self.cleaned_data['bars'].update(foo=instance) return instanceclass FooAdmin(admin.ModelAdmin): form = FooForm
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6034047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/502816/']}
jdg_373675
stackexchange
llm_judgeable_groundtruth_similarity
4642818
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 a differentiable function $f(x, y)$ with continuous second partial derivatives, $x=r\cos\theta$ and $y=r\sin\theta$ , show that $f_r=f_x\cos\theta+f_y\sin\theta$ and $f_{rr}=f_{xx}\cos^2\theta+2f_{xy}\cos\theta\sin\theta+f_{yy}\sin^2\theta$ . [Note that $f_x=\frac{\partial f}{\partial x}$ and $f_{xx}=\left(f_x\right)_x=\frac{\partial^2f}{\partial x^2}$ ] My attempt: I was able to prove the first part of the question. Here's what I did: $$\begin{align}f_x&=\frac{\partial f}{\partial r}\times\frac{\partial r}{\partial x}+\frac{\partial f}{\partial \theta}\times\frac{\partial \theta}{\partial x}\\&=f_r\times\frac1{\cos\theta}-f_{\theta}\times r\sin\theta\\f_y&=\frac{\partial f}{\partial r}\times\frac{\partial r}{\partial y}+\frac{\partial f}{\partial \theta}\times\frac{\partial \theta}{\partial y}\\&=f_r\times\frac1{\sin\theta}+f_{\theta}\times r\sin\theta\end{align}$$ I eliminated $f_\theta$ from these two equations and got the first part. But I am stuck on the second part. Any hints will be appreciated. Now provide the response and nothing else.
This problem can be done with or without an ellipse. $(1)$ Using ellipse With $A, B$ as foci and $P$ a point on the ellipse, the external angle bisector is just the tangent at $P$ . Since the tangent lies outside the ellipse, it is easy to prove that $$AP+BP \lt AP'+BP'.$$ $(2)$ Without using ellipse. Extend $AP$ to $B'$ such that $PB'=PB$ and join $P'B'$ , $P'B$ as shown. $\Delta PP'B \cong \Delta PP'B' \implies BP'=B'P'$ . Thus \begin{align}AP'+BP' &=AP'+B'P' \\& \gt AB' \\&= AP+PB' \\&= AP+BP\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4642818', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/935059/']}
jdg_373676
stackexchange
llm_judgeable_groundtruth_similarity
42570982
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 3 IDs of the different items that I want to add to my shopping cart.I could use https://url.com/shop/cart/?add-to-cart=3001 but when I want to add 3 items I can't do it. Is there any function/script I can add to add this ability to my shopping website? I tried to add an & after the add-to-cart and tried to add a new value but GETs get overridden right?: https://url.com/shop/cart/?add-to-cart=3001&add-to-cart=2002&add-to-cart=1001 Now provide the response and nothing else.
I found the answer! Simply add the following script to your theme's functions.php: function woocommerce_maybe_add_multiple_products_to_cart() {// Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) { return;}// Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );$product_ids = explode( ',', $_REQUEST['add-to-cart'] );$count = count( $product_ids );$number = 0;foreach ( $product_ids as $product_id ) { if ( ++$number === $count ) { // Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling. $_REQUEST['add-to-cart'] = $product_id; return WC_Form_Handler::add_to_cart_action(); } $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) ); $was_added_to_cart = false; $adding_to_cart = wc_get_product( $product_id ); if ( ! $adding_to_cart ) { continue; } $add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->product_type, $adding_to_cart ); /* * Sorry.. if you want non-simple products, you're on your own. * * Related: WooCommerce has set the following methods as private: * WC_Form_Handler::add_to_cart_handler_variable(), * WC_Form_Handler::add_to_cart_handler_grouped(), * WC_Form_Handler::add_to_cart_handler_simple() * * Why you gotta be like that WooCommerce? */ if ( 'simple' !== $add_to_cart_handler ) { continue; } // For now, quantity applies to all products.. This could be changed easily enough, but I didn't need this feature. $quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( $_REQUEST['quantity'] ); $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity ); if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity ) ) { wc_add_to_cart_message( array( $product_id => $quantity ), true ); }}} // Fire before the WC_Form_Handler::add_to_cart_action callback. add_action( 'wp_loaded', 'woocommerce_maybe_add_multiple_products_to_cart', 15 ); And then you can simply use http://shop.com/shop/cart/?add-to-cart=3001,3282 to add multiple items at once. Put a comma between different IDs. Thanks to dsgnwrks for the solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42570982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7108375/']}
jdg_373677
stackexchange
llm_judgeable_groundtruth_similarity
227911
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 moving my companys source control from TFS to GIT.We have TFS currently defined as. Project Collection / / Client A / Product A / Product B / Product C / Client B / Product D / Product E / Product F What is the best way to do this in Git? I have thought about the following: Repository (Client A) Branch (Product A) Branch (Product B) Branch (Product C) Repository (Client B) Branch (Product D) Branch (Product E) Branch (Product F) What do you think is the best approach as the design is slightly different? Now provide the response and nothing else.
You should create a new repo for each independent project. Why? Someone working on project D does not have to download all the history for E and F. Git repos are cheap to initialize, so you can use as many as you like. It is painful to work with multiple projects at once when they are represented as branches in a repo: When switching from A to B to quickly look up something, you'd have to stash your uncommitted changes, then check out the the other branch (which would rewrite the complete directory structure, expensive for large projects), then check out the original branch again and apply your stashed changes. It's not generally possible to view the projects side-by-side without cloning the repo multiple times. The history will be a mess. When using Git, one will sometimes work on multiple feature branches that get merged back in after a while. But when having a project per (main) branch, you'd have multiple parallel but absolutely unconnected branches. They share nothing, so why should they share the repo? If a project depends on another project, you can use git submodules to connect the repos without having to put everything in a single repo.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/227911', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/67294/']}
jdg_373678
stackexchange
llm_judgeable_groundtruth_similarity
2403212
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, I'm studying mathematics at a college level, and not very long ago I had a teacher tell us that the binomial theorem is as follows: $$(a+b)^n = \sum_{k=0}^n {n \choose k}a^{n-k}b^k$$ With virtually no form of proofing at all. Is there a way of proving this without doing basic crunch work and substituting in as many values as possible? Now provide the response and nothing else.
You can also prove it by induction: For $n=0$, the equation becomes $$1=(a+b)^o = \sum_{k=0}^0 {0\choose k}a^{-k}b^k = 1\cdot a^0\cdot b^0=1$$ which is clearly correct. Now, assume the equation is true for $n$, so we know $$(a+b)^n = \sum_{k=0}^n {n \choose k}a^{n-k}b^k.$$ Now, $$\begin{align}(a+b)^{n+1} &= (a+b)(a+b)^n\\&= (a+b)\sum_{k=0}^n {n \choose k}a^{n-k}b^k \\&=a\sum_{k=0}^n {n \choose k}a^{n-k}b^k + b\sum_{k=0}^n {n \choose k}a^{n-k}b^k\\&=\sum_{k=0}^n{n\choose k}a^{n-k+1}b^k + \sum_{k=0}^n {n \choose k}a^{n-k}b^{k+1}\end{align}$$ Now in the second sum, introduce $l=k+1$ to get $$\begin{align}(a+b)^{n+1} &= \sum_{k=0}^n{n\choose k}a^{n-k+1}b^k + \sum_{l=1}^{n+1} {n \choose {l-1}}a^{n-l+1}b^{l}\\&=\left({n\choose 0} a^{n+1}b^0 + \sum_{k=1}^n{n\choose k}a^{n-k+1}b^k\right) + \left(\sum_{l=1}^{n} {n \choose {l-1}}a^{n-l+1}b^{l}+{n \choose n}a^0b^{n+1}\right)\\&=a^{n+1}b^0 + \sum_{k=1}^n\left({n\choose k} + {n\choose k-1}\right)a^{n+1-k}b^k + a^0b^{n+1}\end{align}$$ Now you just use the fact (that can easily be proven algebraically) that$${n\choose k} + {n\choose k-1} = {n+1\choose k}$$ and get $$(a+b)^{n+1} = a^{n+1}b^0 + \sum_{k=1}^n{n+1\choose k}a^{n+1-k}b^k + a^0b^{n+1} = \sum_{k=0}^{n+1}{n+1\choose k}a^{n+1-k}b^k$$ which concludes the proof. For completeness: $$\begin{align}{n\choose k}+{n\choose k-1} &= \frac{n!}{k!(n-k)!} + \frac{n!}{(k-1)!(n-k+1)!}\\&=\frac{n!}{(k-1)!(n-k)!}\cdot\left(\frac{1}{k} + \frac{1}{n-k+1}\right)\\&=\frac{n!}{(k-1)!(n-k)!}\cdot\frac{n-k+1 + k}{k(n-k+1)}\\&=\frac{n!(n+1)}{(k-1)!\cdot k\cdot (n-k)!\cdot(n-k+1)}\\&=\frac{(n+1)!}{k!((n+1)-k)!}\\&={n+1\choose k}\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2403212', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/464094/']}
jdg_373679
stackexchange
llm_judgeable_groundtruth_similarity
914655
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 $G$ is a finite group and $H$ is a normal subgroup of $G$ of order$p$(prime) such that g.c.d.$(|G|,p-1)=1$ , then how to prove that $H \subseteq Z(G)$ ? Please don't use any Sylow theorem or Cauchy theorem , I want solution with Homorphism techniques (extended Cayley's theorem is also allowed) . Thanks in advance Now provide the response and nothing else.
We have to compute, $$\int_{25\pi/4}^{53\pi/4} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx$$$$=$$$$\int_{25\pi/4}^{32\pi/4} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx + \int_{32\pi/4}^{39\pi/4} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx + \int_{39 \pi/4}^{46\pi/4} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx +\int_{46\pi/4}^{53\pi/4} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx = I_1+I_2+I_3+I_4 $$ Now, in $I_2$ substitute, $u=x-\frac{7 \pi}{4}$ , in $I_3$ substitute, $u = x=\frac{7\pi}{2}$ and in $I_4$ substitute, $u=x-\frac{21\pi}{4}$ . So after substitution limits in each will integral will become same and we can directly add them. So,We have $$\int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{(1+2^{\sin x})(1+2^{\cos x})}\,dx + \frac{1}{(1+2^{\sin x+7\pi/2})(1+2^{\cos x+7\pi/2})}\,dx+ \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{(1+2^{\sin x+7\pi/4})(1+2^{\cos x+7\pi/4})}\,dx + \frac{1}{(1+2^{\sin x+21\pi/4})(1+2^{\cos x+21\pi/4})}\,dx = J_1+J_2$$ Notice that, $ \sin(a+7\pi/2) = -\cos(a) $ and $\cos(a+7\pi/2)=\sin(a) $Using this for $J_1$ and $J_2$ we get $$J_1 = \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{1+2^{\sin(x)}}$$And $$ J_2 = \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{1+2^{\sin(x+7\pi/4)}} $$ Now, using well known result, that is $$\int_{a}^{b} f(x) dx = \int_{a}^{b} f(a+b-x) dx$$ $$ I = J_1+J_2 = \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{1+2^{\sin(x)}} + \frac{1}{1+2^{\sin(x+7\pi/4)}} $$Using that result, $I$ also equals$$ I = \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} \frac{1}{1+2^{-\sin(x)}} + \frac{1}{1+2^{-\sin(x+7\pi/4)}} $$$$ 2I = \int_{\frac{25\pi}{4}}^{\frac{32\pi}{4}} 2 dx $$ $$ I = \frac{7\pi}{4} $$ Note:: In this solution, if i have written $$ \int f(x) + \int g(x) + \cdots = I_1+I_2+\cdots $$Then this means $$ I_1 = \int f(x) , I_2 = \int g(x) \cdots $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/914655', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42041/']}
jdg_373680
stackexchange
llm_judgeable_groundtruth_similarity
52823583
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 two concepts mapping and template in ES. I read the official explanation about these two concepts. I am still confused about it. In the template, we can define mapping. In this case, why we need mapping? If I wanna update mapping, can I just modify it in template? Now provide the response and nothing else.
Templates and mappings are two different things. And to make it a little more confusing, the phrase template is used in two different but related features. Mapping The mapping of an index is the schema definition of all of the data store into that one index. Think of it as what is really there. Index Templates Index Templates are used to make it easier to define mappings for new indices. If you are going to define a lot of indices that share some common mappings or settings, you can define an Index Template with those shared settings and have it apply them for you automatically. In your template you tell ElasticSearch what indices it can apply those templates to. Index Templates Reference dynamic_templates in a Mapping For completeness, there is another place templating shows up in ElasticSearch. When you declare a mapping for a new index you can also define a dynamic_templates section. This allows you to have ElasticSearch define field mappings based upon a new fields type or name. For example you could create an entry that says any field whose name ends with "_date" should be treated as a date field. These let you define your fields by a convention instead of needing to explicitly specify their field mappings for every one. Dynamic Templates Reference It's worth noting that for both Index Templates and the dynamic_templates section, the values are only applied when the index/field is first created. In your mapping definitions, if you explicitly specify something different than the template it will use your value instead. So, back to your questions: In the template, we can define mapping. In this case, why we need mapping? Index Templates are useful for applying a mapping to multiple indices as they are created. If you aren't creating multiple identical indices, you will probably just define your mapping manually. The dynamic_templates in an index definition is useful for defining field types by naming convention. Any changes to this will only affect new fields added to the index. If I wanna update mapping, can I just modify it in template? No, once an index is created, updates to the Index Templates will not affect that index. They are only applied to new indices. Also, updated to dynamic_templates will only affect new fields in an index.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52823583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10509309/']}
jdg_373681
stackexchange
llm_judgeable_groundtruth_similarity
18205915
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 puppet example template: { "servers" : [ { "port" : 9200, "host" : "localhost", "queries" : [ <% @markets.each do |market| -%> { "outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ], "obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache", "attr" : [ "hits","hitratio" ] }, <% end -%> ], "numQueryThreads" : 2 } ],} Applying it with market=['UK','FR','IT'], I get the following: { "servers" : [ { "port" : 9200, "host" : "localhost", "queries" : [ { "outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ], "obj" : "solr/market_UK:type=queryResultCache,id=org.apache.solr.search.LRUCache", "attr" : [ "hits","hitratio" ] }, { "outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ], "obj" : "solr/market_FR:type=queryResultCache,id=org.apache.solr.search.LRUCache", "attr" : [ "hits","hitratio" ] }, { "outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ], "obj" : "solr/market_IT:type=queryResultCache,id=org.apache.solr.search.LRUCache", "attr" : [ "hits","hitratio" ] }, ], "numQueryThreads" : 2 } ],} The problem is the last comma, which makes it an invalid solr config. Instead of applying markets.each do, I could use market.map and join(',').but how to use map in this case? I can use map as follows: <%= @markets.map{ |market| "hello_"+market }.join(',') -%> this would print hello_UK,hello_FR,hello_IT (note that we don't have a comma after hello_IT),but I would need something like this: { "servers" : [ { "port" : 9200, "host" : "localhost", "queries" : [ <% @markets.map |market| -%> { "outputWriters" : [ { "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter" } ], "obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache", "attr" : [ "hits","hitratio" ] }, <% }.join(',') -%> ], "numQueryThreads" : 2 } ],} this does not work. so, how to make it work?or how to modify my puppet template to remove the last comma? Now provide the response and nothing else.
This is actually a Ruby problem rather than a Puppet problem. Since this is an array, just change the .each to .each_with_index . Then you can wrap the final comma in a check to see whether the current index value is one less than the size of the index. For example, the following code adds a comma only if the current market is not the last one in the array: <% @markets.each_with_index do |market, i| -%> and then }<%= ',' if i < (@markets.size - 1) %>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18205915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/280393/']}
jdg_373682
stackexchange
llm_judgeable_groundtruth_similarity
4935979
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 working Facebook app that most users will use just once. Leading into the Facebook workflow, users indicate if they want their wall to be written to or not. Based on that, I either ask for the publish_stream permission or not. Later, a small percentage of users will come back and use the app again. Some of the people who previously did not want to write to the wall (and thusly I didn't ask for publish_stream) now want to write to their wall. How do I request an additional permission after the user has already authorized the app? Similarly, how can I query a user to list which permissions they have already granted? Now provide the response and nothing else.
It's as simple as adding the new permission to a new fb:login-button : <fb:login-button scope="publish_stream"> Let me write on your wall!</fb:login-button> So for example you have the above hidden in a DIV and if the user tick a checkbox you show the DIV and prompt the new permission! A good live example of this is on the Facebook Test Console : Click login to "add" the application Then click on examples Under fb.api choose does-like Now you can see that even after being *connected to the application (test console app), you can actually have another login button to prompt the user! EDIT: To check if the user has granted your application a permission, just use this FQL: SELECT read_stream,offline_access FROM permissions WHERE uid=me() This would return something like: [ { "read_stream": 1, "offline_access": 0 }] To test it, just use the test console posted early. EDIT 2: To construct the link yourself without XFBML or Javascript, you just need to add the scope parameter with the additional perms ( reference ): https://www.facebook.com/dialog/oauth? client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=publish_stream Or if your are using the PHP-SDK : $loginUrl = $facebook->getLoginUrl(array( "scope" => "publish_stream"));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4935979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218967/']}
jdg_373683
stackexchange
llm_judgeable_groundtruth_similarity
10238357
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 plotting a non-normal distribution using boxplot and interested in finding out about outliers using boxplot function of matplotlib. Besides the plot I am interested in finding out the value of points in my code which are shown as outliers in the boxplot. Is there any way I can extract these values for use in my downstream code from the boxplot object? Now provide the response and nothing else.
Do you means those points above and below the two black lines? from pylab import *spread= rand(50) * 100center = ones(25) * 50flier_high = rand(10) * 100 + 100flier_low = rand(10) * -100data =concatenate((spread, center, flier_high, flier_low), 0)r = boxplot(data) Store the return dict from boxplot, and you can get the all the information from it, for example: top_points = r["fliers"][0].get_data()[1]bottom_points = r["fliers"][2].get_data()[1]plot(np.ones(len(top_points)), top_points, "+")plot(np.ones(len(bottom_points)), bottom_points, "+")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10238357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369541/']}
jdg_373684
stackexchange
llm_judgeable_groundtruth_similarity
2494381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to the PHP manual , a class like this: abstract class Example {} cannot be instantiated. If I need a class without instance, e.g. for a registry pattern: class Registry {}// and later:echo Registry::$someValue; would it be considered good style to simply declare the class as abstract? If not, what are the advantages of hiding the constructor as protected method compared to an abstract class? Rationale for asking: As far as I see it, it could a bit of feature abuse, since the manual refers to abstract classes more as like blueprints for later classes with instantiation possibility. Update: First of all, thanks for all the answers! But many answers sound quite alike: 'You cannot instantiate an abstract class, but for a registry, why not using a singleton pattern?' Unfortunately, that was more or less exactly a repeat of my question. What is the advantage of using a singleton pattern (a.k.a. hiding __construct() ) compared to just declaring it abstract and not having to worry about that? (Like, e.g., it is a strong connotation between developers, that abstract classes are not actually used or so.) Now provide the response and nothing else.
If your class is not meant to define some super-type, it should not be declared as abstract , I'd say. In your case, I would rather go with a class : That defines __construct and __clone as private methods so the class cannot be instanciated from outside And, this way, your class could create an instance of itself See the Singleton design pattern , about that, btw Now, why use a Singleton, and not only static methods ? I suppose that, at least a couple of reasons can be valid : Using a singleton means using an instance of the class ; makes it easier to transform a non-singleton class to a singleton one : only have to make __construct and __clone private, and add some getInstance method. Using a singleton also means you have access to everything you can use with a normal instance : $this , properties, ... Oh, a third one (not sure about that, but might have its importance) : with PHP < 5.3, you have less possibilities with static methods/data : __callStatic has only been introduced in PHP 5.3 There is no __getStatic , __setStatic , ... Same for a couple of other Magic methods ! Late Static Binding has only been added with PHP 5.3 ; and not having it often makes it harder, when working with static methods/classes ; especially when using inheritance. This being said, yes, some code like this : abstract class MyClass { protected static $data; public static function setA($a) { self::$data['a'] = $a; } public static function getA() { return self::$data['a']; }}MyClass::setA(20);var_dump(MyClass::getA()); Will work... But it doesn't feel quite natural... and this is a very simple example (see what I said earlier with Late Static Binding, and magic methods) .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2494381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113195/']}
jdg_373685
stackexchange
llm_judgeable_groundtruth_similarity
3047230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a design document and people on my team are willing to do the move from ASP.NET WebForm to ASP.NET MVC. This is great, but I have a hard time to understand how MVC workswith in a 3-tier (Data Layer, Business Layer and Presentation Layer) architecture. Can we say that the Model, View and Controller are part of the Presentation Layer? Is the Model part of the Business Layer? In brief, how MVC and 3-tier architecture can work together? Thanks for the help! Now provide the response and nothing else.
I consider ASP.Net MVC to be in the presentation layer. The "Model" classes it uses are really View Models, which describe the data structures needed by your views. All of your business logic and data access should remain separate from your MVC models and controllers. Also, the general "Best Practice" for MVC is to keep the controller code as simple as possible, which usually means introducing some for of application service into your business layer that handles the heavy lifting.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3047230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42024/']}
jdg_373686
stackexchange
llm_judgeable_groundtruth_similarity
880626
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: You are sitting in a dark room. It is completely dark. You can't see anything and there is no way that you can make light. Basically, just assume that you are blind for this task. There is a table in front of you and you feel a deck of cards in your hand. Now the deck is shuffled. But not only shuffled, 18 cards out of the 53 are right-side up and the rest are upside down. Your task is to separate the deck into 2 piles, which have the same number of right-side up cards. How would you do it? Now provide the response and nothing else.
This is a classic question. Split the cards into two piles. The first pile has 18 cards, the second pile has the remaining 35 cards. Say that there are $n$ upside down cards in the first pile, and therefore $18-n$ upside-down cards in the second pile. Now turn over all the cards in the first pile.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/880626', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50979/']}
jdg_373687
stackexchange
llm_judgeable_groundtruth_similarity
50034966
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 had problems installing data.table for R version 3.5.0, and was advised to check that RTools was properly installed. After installing RTools 3.5 (this seems to be the latest) I typed find_rtools(T) I got the following message: WARNING: Rtools is required to build R packages, but no version of Rtools compatible with R 3.5.0 was found. (Only the following incompatible version(s) of Rtools were found:3.4,3.5)Please download and install the appropriate version of Rtools from http://cran.r-project.org/bin/windows/Rtools/. So on the one hand it looks like I do have 3.5 installed, but it seems to think there is a newer/different version. Any thoughts? Now provide the response and nothing else.
The problem was Rtools 3.5 was not in your Windows system PATH thus find_rtools couldn't find it. Another possibility was that an incompatible version of Rtools was in the PATH Best practice for installing Rtools : Download the latest version Install RTools at default recommended location (at the root of your C drive): C:/Rtools/ < Important > Check the box that allows Rtools to modify system PATH After the installation, we can double check by running this command inside R R> Sys.getenv('PATH')[1] "C:\\Program Files\\R\\R-3.5.0\\bin\\x64;c:\\Rtools\\bin;c:\\Rtools\\mingw_64\\bin; See also this guide Edit : for those who don't have Administration rights, see these links: Rtools with R portable Building R packages on Windows without administrator access Setting up RStudio Portable Default R version
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50034966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8453123/']}
jdg_373688
stackexchange
llm_judgeable_groundtruth_similarity
357434
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If $\ X\ $ is a set, we let $\ \binom X2\,=\, \big\{\{a,b\}: a \neq b \in X \big\}.\ $ Given a simple, undirected graph $\ G=(V,E),\ $ we let $\ \delta(G)\ $ be its minimum degree, and $\ \Delta(G)\ $ its maximum degree. We say that $\ G\ $ is self-complementary if $\ G \cong \bar{G}\ $ where $\ \bar{G} = \left(V, \binom V2\setminus E\right)$ . Given $\ N\in\mathbb{N},\ $ is there a self-complementary graph $\ G\ $ with $\ \Delta(G) \geq N\cdot \delta(G)\,$ ? Now provide the response and nothing else.
Self-complementary graphs exist if $n\equiv0,1\pmod 4$ . Take a self-complementary graph $G$ with $n$ vertices. Append to it a path $u{-}v{-}w{-}x$ of 4 vertices and join $v$ and $w$ to all of $G$ . Now you have a self-complementary graph with $n+4$ vertices, $\delta=1$ and $\Delta=n+2$ . This gives all sizes from 4 onwards.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/357434', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_373689
stackexchange
llm_judgeable_groundtruth_similarity
30855638
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Disclaimer: I've checked the question here and it does not answer mine. I am trying to come up with a way for nested struct parsing of JSONs. Example: {"name": "blah blah", "address": {"street": "smthing"}} I want to reach this result: %User{name: "blah blah", address: %Address{street: "smthing"}} Because then it would be easier to plug validation (using Vex for exapmle). I know that Poison supports the "as struct" option but it does not provide nesting. The above would be parsed: %User{name: "blah blah", address: %{"street" => "smthing"}}. I know I could write a decoder implementation for module User but I guess that is not the intended use case and it would not be generic. When wondering about an implementation I could not find a way to tell if an atom is a module... maybe I have to go with :code.is_loaded(module_name) ? Anyway, before trying an implementation I would like to know if there is something I am not seeing. Now provide the response and nothing else.
I believe the above is now possible with Poison: defmodule User do @derive [Poison.Encoder] defstruct [:address]enddefmodule Address do @derive [Poison.Encoder] defstruct [:street]endPoison.decode(response, as: %User{address: %Address{}})
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30855638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3307993/']}
jdg_373690
stackexchange
llm_judgeable_groundtruth_similarity
1202708
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 figure out how to robustly handle proxy authentication errors (HTTP 407 status code) when using the System.Net.WebClient class. In the field, we see many users receiving a 407 proxy authentication WebException, but I'm not sure what a good default strategy is. In .Net 2.0/3.5, the proxy authentication settings are supposed to be inherited from the Internet Explorer system settings. Firefox, Opera and Chrome use these same settings. Here's the basic code we are using: using System.Net;string url = "http://www.mysite.com";WebClient webClient = new WebClient();byte[] data = webClient.DownloadFile(url); When this code fails, we open the user's browser and send them to a help page. From our web logs, we know these customers can successfully connect in their browsers. Perhaps they are manually entering their proxy user name and password before they get to our help page? We don't know. It seems that we could use WebClient.UseDefaultCredentials, but this seems redundant if WebClient is using the system settings anyway. Any help is appreciated. Now provide the response and nothing else.
Internet Explorer does not persistently cache/reuse proxy authentication credentials if the proxy auth uses BASIC or DIGEST. For Negotiate/NTLM, default credentials will be provided. Hence, even though .NET inherits from IE settings, you won't get any "free" support for proxy authentication for Basic/Digest unless you happen to be running in IE; you'll need to prompt the user or provide a configuration screen. Fiddler (www.fiddler2.com) has the "Request Proxy Authentication" option on the Rules menu that you can use to simulate this scenario for testing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1202708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56581/']}
jdg_373691
stackexchange
llm_judgeable_groundtruth_similarity
17684921
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For example with have this code: var json = { "user1" : { "id" : 3 }, "user2" : { "id" : 6 }, "user3" : { "id" : 1 }} How can I sort this json to be like this - var json = { "user3" : { "id" : 1 }, "user1" : { "id" : 3 }, "user2" : { "id" : 6 }} I sorted the users with the IDs.. I don't know how to do this in javascript.. Now provide the response and nothing else.
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax. Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure. One option might be to make your data look like this: var json = [{ "name": "user1", "id": 3}, { "name": "user2", "id": 6}, { "name": "user3", "id": 1}]; Now you have an array of objects, and we can sort it. json.sort(function(a, b){ return a.id - b.id;}); The resulting array will look like: [{ "name": "user3", "id" : 1}, { "name": "user1", "id" : 3}, { "name": "user2", "id" : 6}];
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17684921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1703140/']}
jdg_373692
stackexchange
llm_judgeable_groundtruth_similarity
17324286
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 quad-/octree data structure. Im storing the children indexes/ptrs of a cell in an array. Each position in the array represents the location of a child with respect to its parent, e.g. in 2D: // _____________// | | |// | 2 | 3 |// |_____|_____|// | | |// | 0 | 1 |// |_____|_____|// for each cell, 4 children are always stored in row-major orderstd::vector<std::array<Integer,4>> children; I know that the max number of children is a subset of the values that an Integer type can represent. Thus I can identify if a cell is missing a child by using a ''magic'' value like -1 for Integer = int , or std::numeric_limits<unsigned>::max() for Integer = unsigned . This is something that std::optional<Integer> cannot assume. As far as I understood, this usage of magic values is one of the raison d'être of std::optional . Still, I'm worried about the performance of std::vector<std::optional<int>> in inner loops. So, Will the performance of std::vector<std::optional<int>> be worse than that of std::vector<int> ? (I'm already doing the comparison for "non-existent" value). Or, can the implementation of std::optional be optimized to offer the same performance as a raw int ? And how? Mixing std::optional in the return type of my functions and magic values in my data structure sounds like a very bad idea. I prefer to be consistent and either use one or the other (at least within the same context). Although I could overload the function that performs the comparison with the magic number: template<T> bool is_valid(const T& t) { return /* comparison with magic value for t */; } for optional types. Now provide the response and nothing else.
std::optional is going to require additional storage and fit fewer values into cache (it appears you already know the reason for this). I don't think it's wrong to have a different value stored internally in your data structure from the one exposed by the public API, as long as the internal representation is completely hidden from users. Furthermore, I suggest you isolate the magic number into a single pair of inline conversion functions. The compiler should help you remember to use the conversion functions consistently, by generating type errors if you forget. You might even use a thin struct wrapper for an int in your internal data structure, to ensure that no implicit conversion exists (or define a user-defined conversion). class CompressedOptionalUInt{ static const unsigned SENTINEL_MISSING = std::numeric_limits<unsigned>::max(); unsigned value;public: CompressedOptionalUInt(std::optional<unsigned> val) : value(!val? SENTINEL_MISSING: *val) {} operator std::optional<unsigned>() const { ... }}; and then use std::array<CompressedOptionalUInt> . Making that into a template, with just the sentinel needing to be defined for each type, should be pretty straightforward.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17324286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422197/']}
jdg_373693
stackexchange
llm_judgeable_groundtruth_similarity
90938
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: Bash's {} brace expansion syntax allows for creating easy permutations # echo {b,c,d}{a,e,i,o,u}ba be bi bo bu ca ce ci co cu da de di do du However it's not clear to me if/how it's possible to use this along with arrays except in very awkward use of $() echo and eval Is there a simple way to use arrays with curly brace (permutation) expansion? For example sake, imagine something like (which does not work of course): CONS=( b c d )VOWEL=( a e i o u )echo {${CONS[@]}}{${VOWEL[@]}} Now provide the response and nothing else.
You might use eval with IFS=,; "${array[*]}" (which joins the values with commas) or just two for loops: $ CONS=(b c d);VOWEL=(a e i o u)$ IFS=,;eval echo "{${CONS[*]}}{${VOWEL[*]}}"ba be bi bo bu ca ce ci co cu da de di do du$ for c in "${CONS[@]}";do for v in "${VOWEL[@]}";do echo "$c$v";done;done|paste -sd' ' -ba be bi bo bu ca ce ci co cu da de di do du
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/90938', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/8231/']}
jdg_373694
stackexchange
llm_judgeable_groundtruth_similarity
21614
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the few linear algebra texts I have read, the determinant is introduced in the following manner; "Here is a formula for what we call $detA$. Here are some other formulas. And finally, here are some nice properties of the determinant." For example, in very elementary textbooks it is introduced by giving the co-factor expansion formula. In Axler's "Linear Algebra Done Right" it is defined, for $T\in L(V)$ to be $(-1)^{dimV}$ times the constant term in the characteristic polynomial of $T$. However I find this somewhat unsatisfactory. Its like the real definition of the determinant is hidden. Ideally, wouldn't the determinant be defined in the following manner: "Given a matrix $A$, let $detA$ be an element of $\mathbb{F}$ such that x, y and z." Then one would proceed to prove that this element is unique, and derive the familiar formulae. So my question is: Does a definition of the latter type exist, is there some minimal set of properties sufficient to define what a determinant is? If not, can you explain why? Now provide the response and nothing else.
Let $V$ be a vector space of dimension $n$. For any $p$, the construction of the exterior power $\Lambda^p(V)$ is functorial in $V$: it is the universal object for alternating multilinear functions out of $V^p$, that is, functions $$\phi : V^p \to W$$ where $W$ is any other vector space satisfying $\phi(v_1, ... v_i + v, ... v_p) = \phi(v_1, ... v_i, ... v_p) + \phi(v_1, ... v_{i-1}, v, v_{i+1}, ... v_p)$ and $\phi(v_1, ... v_i, ... v_j, ... v_p) = - \phi(v_1, ... v_j, ... v_i, ... v_p)$. What this means is that there is a map $\psi : V^p \to \Lambda^p(V)$ (the exterior product) which is alternating and multilinear which is universal with respect to this property; that is, given any other map $\phi$ as above with the same properties, $\phi$ factors uniquely as $\phi = f \circ \psi$ where $f : \Lambda^p(V) \to W$ is linear. Intuitively, the universal map $\psi : V^p \to \Lambda^p(V)$ is the universal way to measure the oriented $p$-dimensional volumes of paralleletopes defined by $p$-tuples of vectors in $V$, the point being that for geometric reasons oriented $p$-dimensional volume is alternating and multilinear. (It is instructive to work out how this works when $n = 2, 3$ by explicitly drawing some diagrams.) Functoriality means the following: if $T : V \to W$ is any map between two vector spaces, then there is a natural map $\Lambda^p T : \Lambda^p V \to \Lambda^p W$ between their $p^{th}$ exterior powers satisfying certain natural conditions. This natural map comes in turn from the natural action $T(v_1, ... v_p) = (Tv_1, ... Tv_p)$ defining a map $T : V^p \to W^p$ which is compatible with the passing to the exterior powers. The top exterior power $\Lambda^n(V)$ turns out to be one-dimensional. We then define the determinant $T : V \to V$ to be the scalar $\Lambda^n T : \Lambda^n(V) \to \Lambda^n(V)$ by which $T$ acts on the top exterior power. This is equivalent to the intuitive definition that $\det T$ is the constant by which $T$ multiplies oriented $n$-dimensional volumes. But it requires no arbitrary choices , and the standard properties of the determinant (for example that it is multiplicative, that it is equal to the product of the eigenvalues) are extremely easy to verify. In this definition of the determinant, all the work that would normally go into showing that the determinant is the unique function with such-and-such properties goes into showing that $\Lambda^n(V)$ is one-dimensional. If $e_1, ... e_n$ is a basis, then $\Lambda^n(V)$ is in fact spanned by $e_1 \wedge e_2 \wedge ... \wedge e_n$. This is not so hard to prove; it is essentially an exercise in row reduction. Note that this definition does not even require a definition of oriented $n$-dimensional volume as a number. Abstractly such a notion of volume is given by a choice of isomorphism $\Lambda^n(V) \to k$ where $k$ is the underlying field, but since $\Lambda^n(V)$ is one-dimensional its space of endomorphisms is already canonically isomorphic to $k$. Note also that just as the determinant describes the action of $T$ on the top exterior power $\Lambda^n(V)$, the $p \times p$ minors of $T$ describe the action of $T$ on the $p^{th}$ exterior power $\Lambda^p(V)$. In particular, the $(n-1) \times (n-1)$ minors (which form the matrix of cofactors) describe the action of $T$ on the second-to-top exterior power $\Lambda^{n-1}(V)$. This exterior power has the same dimension as $V$, and with the right extra data can be identified with $V$, and this leads to a quick and natural proof of the explicit formula for the inverse of a matrix. As an advance warning, the determinant is sometimes defined as an alternating multilinear function on $n$-tuples of vectors $v_1, ... v_n$ satisfying certain properties; this properly defines a linear transformation $\Lambda^n(V) \to k$, not a determinant of a linear transformation $T : V \to V$. If we fix a basis $e_1, ... e_n$, then this function can be thought of as the determinant of the linear transformation sending $e_i$ to $v_i$, but this definition is basis-dependent.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/21614', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/565/']}
jdg_373695
stackexchange
llm_judgeable_groundtruth_similarity
1040600
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can someone please give me a graphical interpretation/sense of infinite power series? Some functions such as exponentials, sines, and cosines are infinite power series, but what does that mean and how does it look like graphically? I can't really picture what the graph looks like. Now provide the response and nothing else.
The Taylor series (about $x=0$) for $\sin x$ is $$\sin x=\sum_{n=0}^\infty {(-1)^n x^{2n+1}\over (2n+1)!}.$$Here's what the sequence of partial sums (blue)$$S_N(x)=\sum_{n=0}^N {(-1)^n x^{2n+1}\over (2n+1)!}$$looks like as $N$ varies (here from $0$ to $12$) along with $y=\sin x$ (red): The idea is as we add more and more terms to the series, it gets closer and closer to $\sin x$ on a longer and longer interval (in this case since the interval of convergence is $(-\infty,\infty)$.) Here's an example that has a finite interval of convergence to give you an idea what that entails. Using $$\sum_{n=0}^\infty x^n={1\over 1-x}, \quad -1<x<1,$$then substituting $-x^2$ in for $x$, we see$$\sum_{n=0}^\infty (-1)^nx^{2n}={1\over 1+x^2}, \quad -1<x<1.$$Here, the graph of $y={1\over 1+x^2}$ is shown in red and the $N$th partial sums of the series of various values of $N$ in blue. Note that as $N$ becomes larger, the blue graph matches the red graph closer and closer on the interval of convergence $-1<x<1$ (highlighted in yellow), but outside of that interval, it does not. It might be helpful to read this and this which reinforce the idea of a Taylor series as an "infinitely long" Taylor polynomial. Once you are properly grounded in the motivation for and geometric interpretation of Taylor polynomials, you can carry those ideas over to (infinite) Taylor series.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1040600', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/192590/']}
jdg_373696
stackexchange
llm_judgeable_groundtruth_similarity
27065638
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two code which are giving the same output. what would be the difference here if I use Model.ItemPrice and @Model.ItemPrice? both give same result. @if(Model.ItemPrice == "1300"){ @Model.ItemPrice }@if(@Model.ItemPrice == "1300"){ @Model.ItemPrice } Now provide the response and nothing else.
The first version v[0].set (1234); does not compile because it tries to change the vector's first element returned to it by reference. The compiler thinks it's a change because set(int) is not marked const . The second version, on the other hand, only reads from the vector (*v[0]).set(1234); and calls set on the result of the dereference of a constant reference to a pointer that it gets back. When you call v[0] on a const vector, you get back a const reference to A . When element type is a pointer, calling set on it is OK. You could change the second example to v[0]->set(1234); and get the same result as before. This is because you get a reference to a pointer that is constant, but the item pointed to by that pointer is not constant.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27065638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1041205/']}
jdg_373697
stackexchange
llm_judgeable_groundtruth_similarity
4497054
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 a strongly convex function $f$ gradient descent is the celebrated algo that performs the iterates $$x_{t + 1} = x_t - \eta \nabla f(x_t),$$ starting from an arbitrary point $x_0$ in the domain of the function ( $\eta$ must also be chosen small). The convergence of this procedure is well known. Will we also have that $\| \nabla f(x_{t+1})\| \le \| \nabla f(x_t) \| $ for all $t$ ? If not, are there any conditions we can impose on $f$ so that $\| \nabla f(x_{t+1})\| \le \| \nabla f(x_t) \| $ holds for all $t$ ? Now provide the response and nothing else.
First we recall a standard fact: $ \mathbb{P}^{n-1}_{\mathbb{Z}} $ represents the functor which sends a scheme $ Y $ to the data $ (\mathcal{L}, s_1, \cdots , s_n) $ where $ \mathcal{L} $ is a line bundle on $ Y $ and $ (s_1, \cdots, s_n) $ are sections generating $ \mathcal{L} $ . The equivalence relation is given by $ (\mathcal{L}, s_1, \cdots , s_n) \sim (\mathcal{L}' , s_1', \cdots , s_n') $ iff there is an isomorphism $ \beta : \mathcal{L} \rightarrow \mathcal{L}' $ such that $ \beta(s_i) = s_i' $ for all $ i = 1, \cdots, n $ . Suppose now that the functor in question is represented by a scheme $ Z $ . In view of the above remark we see that there is an obvious morphism of functors $ \eta : \mathbb{A}^n - \{ 0 \}/\mathbb{G}_m \rightarrow \mathbb{P}^{n-1}_{\mathbb{Z}} $ such that $ \eta(Y) $ is an injection for every scheme $ Y $ . By the Yoneda lemma, $ \eta $ corresponds to a morphism of schemes $ \phi : Z \rightarrow \mathbb{P}^{n-1}_{\mathbb{Z}} $ which is a monomorphism simply by the above remark. Furthermore, for any field $ k $ and for any local ring $ R $ , the maps $ Z(k) \rightarrow \mathbb{P}^{n-1}_{\mathbb{Z}}(k) $ and $ Z(R) \rightarrow \mathbb{P}^{n-1}_{\mathbb{Z}}(R) $ are bijections. This is because every projective module over $ k $ or $ R $ is free. (Line bundles correspond to projective modules) The previous remark about fields and local rings, applied to a valuation ring (and its field of fractions) immediately shows that the valuative criteria for properness holds for $ \phi $ . So $ \phi $ is a proper monomorphism, hence a closed immersion.(See the stacks project tag 04XV for a reference to this fact.) Noting the fact that $ \phi $ is obviously surjective (being a bijection on field valued points) and that $ \mathbb{P}^{n-1}_{\mathbb{Z}} $ is reduced, we conclude that $ \phi $ is an isomorphism. (Closed immersion + surjection onto a reduced target implies isomorphism, easy to check locally) In summary, we get $ Z = \mathbb{P}^{n-1}_{\mathbb{Z}} $ which is obviously wrong as there are many schemes with non-trivial line bundles having a generating set of size $ n $ . So the functor in question is not representable by a scheme.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4497054', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157701/']}
jdg_373698
stackexchange
llm_judgeable_groundtruth_similarity
73794
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: So I'm having a tad bit of a problem deciphering the formal definition of NP. In my text book (Algorithm Design, Tardos et al) it says that a problem $X$ belongs to $NP$ iff; there exists a "certificate" string $t$ such that $|t| \le p(|s|)$ for a polynomial function $p$ and an input string $s$. there exists an efficient certifier $B$ that takes $s$ and $t$ as inputs and has polynomial time complexity. I'm having a hard time understanding this problem in a more practical sense. Say for example I had to verify a solution for a Graph Coloring problem. Then I would take the graph $G = (V, E)$ and the number of allowed colours $K$ as input (the problem instance) aswell as the proposed solution (Let's call it $S$) that consists of the coloring of the graph $G$. In this example, what would be $s$ and what would be $t$? Now provide the response and nothing else.
For Graph colouring problem Input : A graph $G(V,E)$ and $k$. Decide : Is $G$ $k$-colourable? Certificate : A map $\phi : V \mapsto C $, where $C = \{R,B,Y,\cdots ,P\}$ is the set of colours and $|C| = k$. For example for any $v \in V$, $\phi(v) = Y$ means $v$ has assigned color $Y$. Example : let complete graph $K_4 (\{v_1,v_2,v_3,v_2\},E)$ is input graph and $k=4$ i.e. is it 4-colorable? A possible certificate in this case is $\{v_1(R),v_2(B),v_3(Y),v_4(P)\}$,($v_1(R)$ means vertex $v_1$ has color $R$), which is polynomial in input size. Now you can see that the size of $|\phi| \le p(|G|)$, where $|G|$ is a input graph size. As you have given a map $\phi$, now you can verify in polynomial time whether colouring is valid or not.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/73794', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/65232/']}
jdg_373699
stackexchange
llm_judgeable_groundtruth_similarity
18612872
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 tried a few things to get a last part outI done this: $string = 'Sim-only 500 | Internet 2500';preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$stringANDpreg_match("/[^ ]*$/","",{abo_type[1]}) The first one won't work and the second returns an array but a realy need string. Now provide the response and nothing else.
If you're after the last word in a sentence, why not just do something like this? $string = 'Sim-only 500 | Internet 2500';$pieces = explode(' ', $string);$last_word = array_pop($pieces);echo $last_word; I wouldn't recommend using regular expressions as it's unnecessary, unless you really want to for some reason. $string = 'Retrieving the last word of a string using PHP.';preg_match('/[^ ]*$/', $string, $results);$last_word = $results[0]; // $last_word = PHP. Using a substr() method would be better than both of these if resources/efficiency/overhead is a concern. $string = 'Retrieving the last word of a string using PHP.';$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result$last_word = substr($string, $last_word_start); // $last_word = PHP. it is faster, although it really doesn't make that much of a difference on things like this. If you're constantly needing to know the last word on a 100,000 word string, you should probably be going about it in a different way.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18612872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1749910/']}
jdg_373700
stackexchange
llm_judgeable_groundtruth_similarity
3386662
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two classes. Class A has protected method m() , a is an instance of A . Class B is in the same package as class A . I am trying to access a.m() but I am getting IllegalAccessError ... What's wrong? Now provide the response and nothing else.
The compiler should catch errors like this. As you are apparently getting this at runtime, something odd has happened. Probably you have changed the source code but fully recompiled. Another potential, but obscure, problem is loading the classes through different class loaders. Classes loaded from different class loaders will be in different packages even if the package name is the same (in the same way as classes with the same name loaded by different class loaders will be different classes).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3386662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_373701
stackexchange
llm_judgeable_groundtruth_similarity
1738990
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,] ). I can write code: int[][][] count = new int[10][][];for (int i = 0; i < 10; i++) { count[i] = new int[10][]; for (int j = 0; j < 10; j++) count[i][j] = new int[10];} but I am looking for a more beautiful way for it. May be something like that: int[][][] count = new int[10][10][10]; Now provide the response and nothing else.
int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3); using static T CreateJaggedArray<T>(params int[] lengths){ return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths);}static object InitializeJaggedArray(Type type, int index, int[] lengths){ Array array = Array.CreateInstance(type, lengths[index]); Type elementType = type.GetElementType(); if (elementType != null) { for (int i = 0; i < lengths[index]; i++) { array.SetValue( InitializeJaggedArray(elementType, index + 1, lengths), i); } } return array;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1738990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184842/']}
jdg_373702
stackexchange
llm_judgeable_groundtruth_similarity
26570659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently trying to create an HTML5 Canvas game and I want to be able to attach functions to buttons that activate when clicked. I can do this for unique functions but I'm struggling to find a way to do it when looping through many buttons with a predefined function. I've created an example to show what I've tried so far: jsFiddle: http://jsfiddle.net/ra1rb74w/1/ // The class that we want to create an array ofmyClass = function() { this.aFunction;};myClass.prototype = { // Add a new function to this class addFunction: function (newFunction) { this.aFunction = newFunction; }, // Use the current function useFunction: function () { if (this.aFunction != null) { this.aFunction; } }};// The base function we will use in the classesvar baseFunction = function(x) { console.log(x); }// Create the array of classesvar myClasses = [];// Add 10 classes to the array and add a function to each of themfor (var x = 0; x < 10; x++) { myClasses.push(new myClass()); myClasses[x].addFunction(baseFunction(x));}// Use the function in the first classmyClasses[0].useFunction(); You can see that all the functions get triggered which I don't want, and the useFunction() function doesn't work. Is there a way to do this? Now provide the response and nothing else.
Resolve - plunkr You could make use of modalInstance 's resolve property; this acts as the link between the modal instance and the parent controller. You inject the object in to the ModalInstanceController , and assign it to the scope of your modal instance. UI Bootstraps resolve works exactly the same as ngRouter's; as such if for whatever reason resolve cannot resolve an object, the modal will not open. var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', resolve: { user: function() { return $scope.user; } }}); Scope - plunkr An alternative, and arguably simpler method would be to pass in the parents scope in to the modal. Note that currently this doesn't work when using controllerAs syntax on the parent controller. var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', scope: $scope});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26570659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009573/']}
jdg_373703
stackexchange
llm_judgeable_groundtruth_similarity
175473
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 $\ast$ be defined in $\mathbb Z_8$ as follows:$$\begin{aligned} a \ast b = a +b+2ab\end{aligned}$$ Determine all the invertible elements in $(\mathbb Z_8, \ast)$ and determine, if possibile, the inverse of the class $[4]$ in $(\mathbb Z_8, \ast)$. Identity element We shall say that $(\mathbb Z_8, \ast)$ has an identity element if:$$\begin{aligned} (\forall a \in \mathbb Z_8) \text { } (\exists \varepsilon \in \mathbb Z_8 : a \ast \varepsilon = \varepsilon \ast a = a)\end{aligned}$$ $$\begin{aligned} a+\varepsilon+2a\varepsilon = a \Rightarrow \varepsilon +2a\varepsilon = 0 \Rightarrow \varepsilon(1+2a) = 0 \Rightarrow \varepsilon = 0 \end{aligned}$$As $\ast$ is commutative, similarly we can prove for $\varepsilon \ast a$. $$\begin{aligned} a \ast 0 = a+0+2a0 = a \end{aligned}$$$$\begin{aligned} 0\ast a = 0+a+20a = a\end{aligned}$$ Invertible elements and $[4]$ inverse We shall state that in $(\mathbb Z_8, \ast)$ there is the inverse element relative to a fixed $a$ if and only if exists $\alpha \in (\mathbb Z_8, \ast)$ so that: $$\begin{aligned} a\ast \alpha = \alpha \ast a = \varepsilon \end{aligned}$$ $$\begin{aligned} a+\alpha +2a\alpha = 0 \end{aligned}$$$$\begin{aligned} \alpha(2a+1) \equiv_8 -a \Rightarrow \alpha \equiv_8 -\frac{a}{(2a+1)} \end{aligned}$$ In particular looking at $[4]$ class, it follows:$$\begin{aligned} \alpha \equiv_8 -\frac{4}{(2\cdot 4+1)}=-\frac{4}{9} \end{aligned}$$ therefore:$$\begin{aligned} 9x \equiv_8 -4 \Leftrightarrow 1x \equiv_8 4 \Rightarrow x=4 \end{aligned}$$ which seems to be the right value as$$\begin{aligned} 4 \ast \alpha = 4 \ast 4 = 4+4+2\cdot 4\cdot 4 = 8 + 8\cdot 4 = 0+0\cdot 4 = 0 \end{aligned}$$ Does everything hold? Have I done anything wrong, anything I failed to prove? Now provide the response and nothing else.
Let me mention that your definition of identity is wrong. You write: We shall say that $(\mathbb{Z}_8,\ast)$ has an identity if $$(\forall a \in \mathbb Z_8) \text { } (\exists \varepsilon \in \mathbb Z_8 : a \ast \varepsilon = \varepsilon \ast a = a)$$ Under this formulation, the element $\varepsilon$ is allowed to change depending on $a$. This is not the usual meaning of "identity"! The identity is usually required to be the same for every element. For example, consider the operation $\odot$ on $\mathbb{Z}$ given by$$a\odot b = 2a-b.$$Then this operation satisfies the definition you give: given an integer $a$, let $\varepsilon=a$. Then $a\odot \varepsilon = 2a-a = a$, and $\varepsilon\odot a = 2a-a = a$. However, there is no element $\varepsilon$ that "works" for every integer: for instance, if $1\odot\varepsilon = 1$ then this means that $2-\varepsilon = 1$, so $\varepsilon = 1$. But then $2\odot\varepsilon\neq 2$. The order of the quantifiers matters! By putting the existential quantifier after the universal quantifier, you allow the value of $\varepsilon$ to depend on the value of $a$. The correct formula for the existence of an identity is:$$\exists\varepsilon\in\mathbb{Z}_8(\forall a\in \mathbb{Z}_8\colon a\ast \varepsilon = \varepsilon\ast a = a).$$ Of course, if there is a $\varepsilon$ that works independent of $a$, then then there is one that works if we allow it to depend on $a$. In other words, $\exists a(\forall b P(a,b))$ always implies $\forall a(\exists b P(a,b))$. The converse does not hold, however, as the example above shows. (Or, for another example: it is true that for every person $a$ there is a person $b$ such that $b$ is the mother of $a$; i.e., everyone has someone who is their mother. It is not true, however, that there is a person $b$ such that for every person $a$, $b$ is the mother of $a$; i.e., there isn't someone who is everyone's mother). There is also, in my opinion, a gap in the argument for inverses. You are correct that $\varepsilon = 0$ is an identity; and also that if $a$ has an inverse, then$$a+\alpha + 2a\alpha \equiv 0 \pmod{8}.$$Hence, $\alpha(1+2a)\equiv -a\pmod{8}$ holds. Now, you need to justify that you can "divide by $1+2a$". That is, that $1+2a$ has a multiplicative inverse modulo $8$. This can be done by noting that $1+2a$ is necessarily odd, and hence relatively prime to $8$. Thus, it can be solved in all cases, so every element has a $\ast$-inverse. I will note, also, that you should have "$a\in\mathbb{Z}_8$" and not "$a\in(\mathbb{Z}_8,\ast)$". You want an element of the underlying set of your algebraic object, rather than an element of the ordered pair.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/175473', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34913/']}
jdg_373704
stackexchange
llm_judgeable_groundtruth_similarity
9450394
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 install GCC (the GNU Compiler Collection) piece by piece, using the current version, using the correct versions of dependencies, not using a package manager (like yum, rpm, apt, dpkg), and not using shared libraries? Typical developers will likely want to install GCC the typical way, use your package manager (yum, rpm, apt, dpkg, port, brew, etc.) or follow the instructions here ( http://gcc.gnu.org/wiki/InstallingGCC ). My question is how to install GCC piece by piece, without shared libraries. I want a fully-independent GCC that can be moved around my system without using any shared libraries, and without creating any shared libraries. This is what GCC calls "the difficult way" and it is not recommended for typical users. GCC depends on: GMP: GNU Multiple Precision Arithmetic Library MPFR: GNU Multiple-precision floating-point rounding library MPC: GNU Multiple-precision C library ELF: Executable and Linkable Format library PPL: Parma Polyhedra Library (optional, for memory optimizations) Now provide the response and nothing else.
The Easy Way If you're a typical developer, you can install the easy way, using instructions at http://gcc.gnu.org/wiki/InstallingGCC or your system package manager such as: apt install gcc # for Debian, Ubuntu, etc.yum install gcc # for RedHat, CentOS, etc.brew install gcc # for Mac OS X The Hard Way GCC says the answer here is "the hard way" because it builds everything piece by piece, and does not use shared libraries. GCC infrastructure Get the GCC infrastructure: ftp://gcc.gnu.org/pub/gcc/infrastructure/ Put downloads in a temp directory (you can use whatever directory you want). /opt/downloads Build the infrastructure in a temp directory that is different than the downloads directory or its subdirectories: /tmp/gcc Configure the infrastructure using static libraries like this: ./configure --disable-shared --enable-static --prefix=/tmp/gcc The --disable-shared flag may be worth a closer look depending on your needs. I use --disable-shared because I am building static code only, and I want to make sure that I don't build any shared code. My need is to move the resulting GCC around my drives easily, so I want all static code, and I do not want any shared code. If you prefer shared code, omit the --disable-shared flag. Versions When you run any of the commands in this answer, be sure to update the commands to use the current GCC version number that matches your needs. The commands in this answer are for GCC 4.6.2. Note that the GCC documentation says: "While any sufficiently new version of required tools usually work, library requirements are generally stricter. Newer versions may work in some cases, but it's safer to use the exact versions documented." GMP GMP is the GNU Multiple Precision Arithmetic Library. wget ftp://gcc.gnu.org/pub/gcc/infrastructure/gmp-4.3.2.tar.bz2bunzip2 gmp-4.3.2.tar.bz2tar xvf gmp-4.3.2.tarcd gmp-4.3.2./configure --disable-shared --enable-static --prefix=/tmp/gccmake && make check && make install MPFR MPFR is the GNU Multiple-precision floating-point rounding library. It depends on GMP. wget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpfr-2.4.2.tar.bz2bunzip2 mpfr-2.4.2.tar.bz2tar xvf mpfr-2.4.2.tarcd mpfr-2.4.2./configure --disable-shared --enable-static --prefix=/tmp/gcc --with-gmp=/tmp/gccmake && make check && make install MPC MPC is the GNU Multiple-precision C library. It depends on GMP and MPFR. wget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpc-0.8.1.tar.gztar zxvf mpc-0.8.1.tar.gzcd mpc-0.8.1./configure --disable-shared --enable-static --prefix=/tmp/gcc --with-gmp=/tmp/gcc --with-mpfr=/tmp/gccmake && make check && make install ELF ELF stands for Executable and Linkable Format. This library provides architecture-independent size and endian support. wget http://www.mr511.de/software/libelf-0.8.13.tar.gztar zxvf libelf-0.8.13.tar.gzcd libelf-0.8.13./configure --disable-shared --enable-static --prefix=/tmp/gccmake && make check && make install GCC GCC is the GNU Compiler Collection. It depends on GMP, MPFR, MPC, and ELF. wget http://www.netgull.com/gcc/releases/gcc-4.6.2/gcc-4.6.2.tar.gztar zxvf gcc-4.6.2.tar.gz Build gcc in a scratch directory on thesame mount point. (Building it within /tmp would trigger cross compile host issues) mkdir -p /opt/downloads/gcc-4.6.2-scratchcd /opt/downloads/gcc-4.6.2-scratch The configure command and its flags must be all on one command line (this post shows them on separate lines just because of web page width). Note: We use the full path to configure and do not set library path environment variables. We choose to disable bootstrap and disable shared libraries because we don't want them (typical users may want both), and to use posix threads and to flags that are defaults because we want them (typical users may want to use other threads or skip default flags). YMMV and read about the flags here /opt/downloads/gcc-4.6.2/configure --disable-shared --disable-bootstrap --disable-libstdcxx-pch --enable-languages=all --enable-libgomp --enable-lto --enable-threads=posix --enable-tls --with-gmp=/tmp/gcc --with-mpfr=/tmp/gcc --with-mpc=/tmp/gcc --with-libelf=/tmp/gcc --with-fpmath=ssemake && make install This page is great for GCC installation info, how to build it, various flags, and more: http://www.acsu.buffalo.edu/~charngda/cc_build.html Updates The ppl libraries can be used for memory optimizations: see bugseng.com/products/ppl/Download (Thanks Paul in comments) You could run ./contrib/download_prerequisites from the gcc source directory. (Thanks to N7P on reddit)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9450394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528726/']}
jdg_373705
stackexchange
llm_judgeable_groundtruth_similarity
27869397
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 had trouble finding/understanding documentation on how to compare enums in Swift by their order of definition. Specifically when I create an enumeration such as enum EnumType { case First, Second, Third} Swift does not allow me to directly compare enums by order, such as let type1 = EnumType.Firstlet type2 = EnumType.Secondif type1 < type2 {println("good")} // error it generates the compile error "cannot invoke '<' with argument list of of type {EnumType, EnumType}. So the only solution I've found is to write my own comparison operators as overloads, such as enum EnumType : Int { case First = 0, Second, Third}func <(a: EnumType, b: EnumType) -> Bool { return a.rawValue < b.rawValue}let type1 = EnumType.Firstlet type2 = EnumType.Secondif type1 < type2 {println("good")} // Returns "good" This is all well and good for "heavy weight" enums that have a lot of use and value in my application, but overloading all the operators I might want to use seems excessively burdensome for 'lightweight" enums that I might define on the fly to bring order to some constants for a single small module. Is there way to do this without writing lots of boilerplate overloading code for every enum type I define in my project? Even better, is there something I'm missing to make Swift automatically provide comparison operators for simple enums that don't have associated types, ie. that are untyped or typed as Int? Swift knows how to compare Ints, so why can't it compare enum Ints? Now provide the response and nothing else.
So long as you give your enum an underlying type, it’ll conform to the protocol RawRepresentable . This means you can write a generic comparison operator for any type that is raw representable, and has a raw type that is comparable, like so: func <<T: RawRepresentable where T.RawValue: Comparable>(a: T, b: T) -> Bool { return a.rawValue < b.rawValue} which will mean your enum will automatically have a < operator: enum E: Int { // this would work with Double and String also // btw, no need to give a seed value of 0, // that happens automatically for Ints case A, B, C, D, E}E.A < E.C // returns true The only bit of boilerplate you’ll still have to do is tag your enum as Comparable in case you want to use it with generic algorithms that require that: extension E: Comparable { }// (no need for anything else - requirements are already fulfilled)let a: [E] = [.C, .E, .A]let b = sorted(a)// b will now be [.A, .C, .E] Making it conform to Comparable will also give it <= , > , and >= operators automatically (supplied by the standard library).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27869397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1347202/']}
jdg_373706
stackexchange
llm_judgeable_groundtruth_similarity
164171
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a pretty basic question, but am pretty far removed from stats and modeling. I have historical data (daily, weekly, monthly, however I want to slice) for a few years and I want to predict the probability of hitting an end of month target throughout the month. The data follows very similar trends, if you overlay 1 week over any other week in the year, it's practically the same line. I thought of a few ways to do this, but don't know if they're correct.1) Using a poisson, I can plug in the historical average values from any day X to end of the month. I also have a target from day X to end of month, and with the historicals, I will know how many successful times that amount has been reached. So using P = (e^-u)(x^u)/x!, u = average historicals, x = # times those historicals exceed the remaining target.2) since every day has a very similar outcome, I could count how many Mondays, Tuesdays.... are left in the month, calculate an interval in which I'm 99% sure each day will come in between X and Y. Add the lower and upper limits on each day and by the end of the month can I say I'm 99% sure value will be between X1+X2+... and Y1+Y2+... thoughts and help very much appreciated. Now provide the response and nothing else.
If you're fitting with glm , you can use the win rate as your DV and use the weights option to specify the number of "trials" each rate observation is based on. From ?glm : For a binomial GLM prior weights are used to give the number of trials when the response is the proportion of successes So your call to glm would look something like this: glm(Total_Service_Points_Won/Total_Service_Points_Played ~ ... , family = binomial(link=logit), weights = Total_Service_Points_Played)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/164171', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/83815/']}
jdg_373707
stackexchange
llm_judgeable_groundtruth_similarity
12986234
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 a library that has a dependency on JSF. When I try to run my project, it show following exception massage.. java.util.MissingResourceException: Can't find bundle for base name /Bundle, locale en_USat java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)at java.util.ResourceBundle.getBundle(ResourceBundle.java:705) Any ideas ? Now provide the response and nothing else.
The exception is telling that a Bundle_en_US.properties , or Bundle_en.properties , or at least Bundle.properties file is expected in the root of the classpath, but there is actually none. Make sure that at least one of the mentioned files is present in the root of the classpath. Or, make sure that you provide the proper bundle name. For example, if the bundle files are actually been placed in the package com.example.i18n , then you need to pass com.example.i18n.Bundle as bundle name instead of Bundle . In case you're using Eclipse "Dynamic Web Project", the classpath root is represented by src folder, there where all your Java packages are. In case you're using a Maven project, the classpath root for resource files is represented by src/main/resources folder. See also: Maven and JSF webapp structure, where exactly to put JSF resources
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12986234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1477749/']}
jdg_373708
stackexchange
llm_judgeable_groundtruth_similarity
10274357
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 added a JFreeChart to a JPanel (using a BorderLayout ), and it's huge . Is there something I can do to make it smaller? public void generateChart(){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); //set the values of the chart for(int i=0; i<8; i++) { dataset.setValue(income_array[i], "Income", Double.toString(percent_array[i])); } JFreeChart chart = ChartFactory.createBarChart( "Required Annual Income for a Variety of Interest Rates", "Percent", "Income", dataset, PlotOrientation.VERTICAL, false,true, false); ChartPanel cp = new ChartPanel(chart); chart.setBackgroundPaint(Color.white); chart.getTitle().setPaint(Color.black); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.blue); //cp.setMaximumDrawHeight(5); //cp.setMaximumDrawWidth(5); //cp.setZoomOutFactor(.1); JPanel graph = new JPanel(); graph.add(cp); middle.add(graph, BorderLayout.CENTER);} Now provide the response and nothing else.
When you create your ChartPanel , you have several options that affect the result: Accept the DEFAULT_WIDTH and DEFAULT_HEIGHT : 680 x 420. Specify the preferred width and height in the constructor. Invoke setPreferredSize() explicitly if appropriate . Override getPreferredSize() to calculate the size dynamically. @Overridepublic Dimension getPreferredSize() { // given some values of w & h return new Dimension(w, h);} Choose the layout of the container to which the ChartPanel will be added. Note that the default layout of JPanel is FlowLayout , while that of JFrame is BorderLayout . As a concrete example, ThermometerDemo uses both preferred values in the constructor and a GridLayout for the container to allow dynamic resizing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10274357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1110590/']}
jdg_373709
stackexchange
llm_judgeable_groundtruth_similarity
50651977
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 old angular cli there was a key called defaults : "defaults": { "schematics": { "collection": "@nrwl/schematics", "postGenerate": "npm run format", "newProject": [ "app", "lib" ] }, "styleExt": "scss", "component": { "changeDetection": "OnPush" } } This property no longer exsists. How do I add component/changeDetection on push in angular cli 6+? moreover is there a list of component properties I can add? Now provide the response and nothing else.
I'm not as familiar with the old CLI. Were those properties configured as global CLI settings, or a per-project setting? In the new Angular CLI, you can replicate per-project settings in the angular.json file by updating the schematics object to the following: "projects": { "my-project": { "root": "", "sourceRoot": "src", "projectType": "application", "prefix": "app", "schematics": { "@schematics/angular:component": { "changeDetection": "OnPush" } },
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50651977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191635/']}
jdg_373710
stackexchange
llm_judgeable_groundtruth_similarity
18438907
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 to embed one markdown (or its sub-flavors - I'm using PanDoc) document in another except for using a jQuery().load(url) ? I'd like to have a document that has eg. main.md , chapter1.md , chapter2.md , with main.md loading chapter1.md and chapter2.md automatically. main.md will have text in between the two chapters e.g. main.md : Some opening text......[chapter1.md]Some additional text......[chapter2.md]...something else. So I can't use a cat *.md > final.md approach Now provide the response and nothing else.
Markdown by itself lacks a notation for including files, which rather screws that. pandoc has an example on using a custom haskell filter on code blocks to include files but this a. leaves a code block around the text and (more importantly) b. doesn't parse the new file as markdown, and frankly my haskell isn't up to the task of fixing that. However, you can achieve this by doing a pre-process pass, using perl *. I'm assuming that each include is on a line by itself of the form shown above. perl -ne 's/^\[(.+)\].*/`cat $1`/e;print' main.md > final.md *I dislike having to resort to perl, but sed lacks the ability to read from a file using a match pattern to determine the name.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18438907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1675004/']}
jdg_373711
stackexchange
llm_judgeable_groundtruth_similarity
3644576
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why are mutable strings slower than immutable strings? EDIT: >>> import UserString... def test():... s = UserString.MutableString('Python')... for i in range(3):... s[0] = 'a'... ... if __name__=='__main__':... from timeit import Timer... t = Timer("test()", "from __main__ import test")... print t.timeit()13.5236170292>>> import UserString... def test():... s = UserString.MutableString('Python')... s = 'abcd'... for i in range(3):... s = 'a' + s[1:]... ... if __name__=='__main__':... from timeit import Timer... t = Timer("test()", "from __main__ import test")... print t.timeit()6.24725079536>>> import UserString... def test():... s = UserString.MutableString('Python')... for i in range(3):... s = 'a' + s[1:]... ... if __name__=='__main__':... from timeit import Timer... t = Timer("test()", "from __main__ import test")... print t.timeit()38.6385951042 i think it is obvious why i put s = UserString.MutableString('Python') on second test. Now provide the response and nothing else.
In a hypothetical language that offers both mutable and immutable, otherwise equivalent, string types (I can't really think of one offhand -- e.g., Python and Java both have immutable strings only, and other ways to make one through mutation which add indirectness and therefore can of course slow things down a bit;-), there's no real reason for any performance difference -- for example, in C++, interchangeably using a std::string or a const std::string I would expect to cause no performance difference (admittedly a compiler might be able to optimize code using the latter better by counting on the immutability, but I don't know any real-world ones that do perform such theoretically possible optimizations;-). Having immutable strings may and does in fact allow very substantial optimizations in Java and Python. For example, if the strings get hashed, the hash can be cached, and will never have to be recomputed (since the string can't change) -- that's especially important in Python, which uses hashed strings (for look-ups in sets and dictionaries) so lavishly and even "behind the scenes". Fresh copies never need to be made "just in case" the previous one has changed in the meantime -- references to a single copy can always be handed out systematically whenever that string is required. Python also copiously uses "interning" of (some) strings, potentially allowing constant-time comparisons and many other similarly fast operations -- think of it as one more way, a more advanced one to be sure, to take advantage of strings' immutability to cache more of the results of operations often performed on them. That's not to say that a given compiler is going to take advantage of all possible optimizations, of course. For example, when a slice of a string is requested, there is no real need to make a new object and copy the data over -- the new slice might refer to the old one with an offset (and an independently stored length), potentially a great optimization for big strings out of which many slices are taken. Python doesn't do that because, unless particular care is taken in memory management, this might easily result in the "big" string being all kept in memory when only a small slice of it is actually needed -- but it's a tradeoff that a different implementation might definitely choose to perform ( with that burden of extra memory management, to be sure -- more complex, harder-to-debug compiler and runtime code for the hypothetical language in question). I'm just scratching the surface here -- and many of these advantages would be hard to keep if otherwise interchangeable string types could exist in both mutable and immutable versions (which I suspect is why, to the best of my current knowledge at least, C++ compilers actually don't bother with such optimizations, despite being generally very performance-conscious). But by offering only immutable strings as the primitive, fundamental data type (and thus implicitly accepting some disadvantage when you'd really need a mutable one;-), languages such as Java and Python can clearly gain all sorts of advantages -- performance issues being only one group of them (Python's choice to allow only immutable primitive types to be hashable, for example, is not a performance-centered design decision -- it's more about clarity and predictability of behavior for sets and dictionaries!-).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3644576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422100/']}
jdg_373712
stackexchange
llm_judgeable_groundtruth_similarity
48288861
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to fetch IDs from my state as separate Observable s, combine all of them into one Observable and subscribe() to it.I need that my subscriber will eventually get an array of resolved Observable results. Also I need to keep this subscription open, so if one of my inner Observable s changes my subscriber will be notified. This is my code: getTransactionsByIDs(transactionsIDs){return Observable.of(transactionIDs .map(transactionID => this.getTransactionByID(transactionID)));}this.transactionsService.getTransactionsByIDs(transactionsIDs).subscribe(transactions=>{ ....}) The result of the above code in the subscriber function is an array of unresolved stores. How can I resolve each store and combine all of them together? I've also tried to use Observable.from() on the transactionsID s to transform each ID into an Observable and then resolve it. It works fine, but then my subscriber getting notified on every ID separately. If there's a way to batch all of the Observable.from() results (while keeping subscription open), please let me know. This is how my Observable.from() looks like: getTransactionsByIDs(transactionsIDs){return transactionIDs .mergeMap(transactionID => this.getTransactionByID(transactionID));}this.transactionsService.getTransactionsByIDs(Observable.from(transactionsIDs)).subscribe(transactions=>{ ....}) Now provide the response and nothing else.
I think that what you want is combineLatest . It wont emit any value till all inner observables emit at least one value. After that it will emit the latest from all each time there is a new emit from one of the inner observables. Here is some reading material: https://www.learnrxjs.io/operators/combination/combinelatest.html Here is an example: function getTransactionByID(transactionId) { let count = 0; return Rx.Observable.of(transactionId) .delay(Math.random() * 4000) .map(x => `${x}: ${count++} `) .repeat();}function getTransactionsByIDs(transactionsIDs){ return Rx.Observable.combineLatest(transactionsIDs.map(transactionID => getTransactionByID(transactionID)));}const transactionsIDs = [1,2,3];getTransactionsByIDs(transactionsIDs) .take(10) .subscribe(x => { console.log(x); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.min.js"></script> The take(10) is just the keep the example from going on forever.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48288861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2661999/']}
jdg_373713
stackexchange
llm_judgeable_groundtruth_similarity
53583286
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Visual Studio 2017 has integrated C++ unit testing (native, google test, ctest, etc.). How can I create a CMakeLists.txt file that will create a project like this that will use the integrated IDE testing, for example using either google test or the native microsoft unit testing framework? All of Microsoft's examples unfortunately just create the project in Visual Studio, rather than starting from a CMake file. Any help is appreciated, thanks! Now provide the response and nothing else.
Mikewho, I setup a small example using Google Test project that works with integrated IDE testing. Create an empty directory and save these two files: CMakeLists.txt cmake_minimum_required(VERSION 3.0)project(test_me)# GTestenable_testing()find_package(GTest REQUIRED)include_directories(${GTEST_INCLUDE_DIRS})# Unit Tests# Add test cpp fileadd_executable( runUnitTests tests.cpp)# Link test executable against gtest & gtest_maintarget_link_libraries(runUnitTests ${GTEST_BOTH_LIBRARIES})add_test( runUnitTests runUnitTests ) tests.cpp #include <gtest/gtest.h>TEST(ABC, TEST1) { EXPECT_EQ(true, true);} The in a command prompt type mkdir buildcd buildcmake .. "-DCMAKE_TOOLCHAIN_FILE=C:/dev/vcpkg/scripts/buildsystems/vcpkg.cmake" Note: I had vcpkg install gtest C:\dev\vcpkg>vcpkg.exe install gtest Make sure you have this installed in Visual Studio 2017 In Tools > Options > Test Adapter for Google Test set the regex to .exe Build the solution and press Run all in the Test Explorer The first time it runs it will find the test case [12/3/2018 8:38:41 AM Informational] ------ Run test started ------[12/3/2018 8:38:42 AM Warning] Could not locate debug symbols for 'C:\dev\cpptests\GoogleTest\build\Debug\runUnitTests.exe'. To make use of '--list_content' discovery, ensure that debug symbols are available or make use of '<ForceListContent>' via a .runsettings file.[12/3/2018 8:38:42 AM Informational] Test Adapter for Google Test: Test execution starting...**[12/3/2018 8:38:42 AM Informational] Found 1 tests in executable** C:\dev\cpptests\GoogleTest\build\Debug\runUnitTests.exe[12/3/2018 8:38:42 AM Informational] Running 1 tests...[12/3/2018 8:38:42 AM Informational] Google Test execution completed, overall duration: 00:00:00.2390446[12/3/2018 8:38:42 AM Informational] ========== Run test finished: 1 run (0:00:01.2668844) ========== I hope this helps?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53583286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10735749/']}
jdg_373714
stackexchange
llm_judgeable_groundtruth_similarity
27042935
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 asking this basic question to make the records straight. Have referred this question and its currently accepted answer , which is not convincing. However the second most voted answer gives better insight, but not perfect either. While reading below, distinguish between the inline keyword and “inlining” concept . Here is my take: The inlining concept This is done to save the call overhead of a function. It's more similar to macro-style code replacement. Nothing to be disputed. The inline keyword Perception A The inline keyword is a request to the compiler usually used for smaller functions, so that compiler can optimize it and make faster calls. The Compiler is free to ignore it. I dispute this, for below reasons: Larger and recursive functions are not inlined and the compiler ignores the inline keyword. Smaller functions are automatically inlined by the optimizer irrespective of the inline keyword being mentioned or not. It's quite clear that the user doesn't have any control over function inlining with the use of keyword inline . Perception B inline has nothing to do with the concept of inlining. Putting inline ahead of big / recursive function won't help and smaller function won't need it, for being inlined. The only deterministic use of inline is to maintain the One Definition Rule . i.e. if a function is declared with inline then only below things are mandated: Even if its body is found in multiple translation units (e.g. include that header in multiple .cpp files), the compiler will generate only 1 definition and avoid multiple symbol linker error. (Note: If the bodies of that function are different then it is undefined behavior.) The body of the inline function has to be visible / accessible in all the translation units who use it. In other words, declaring an inline function in .h and defining in any one .cpp file will result in an “undefined symbol linker error” for other .cpp files Verdict The “A” perception is entirely wrong and the “B” perception is entirely right . There are some quotes in standard on this, however I am expecting an answer which logically explains if this verdict is true or false. Now provide the response and nothing else.
I wasn't sure about your claim: Smaller functions are automatically "inlined" by optimizer irrespective of inline is mentioned or not... It's quite clear that the user doesn't have any control over function "inlining" with the use of keyword inline . I've heard that compilers are free to ignore your inline request, but I didn't think they disregarded it completely. I looked through the Github repository for Clang and LLVM to find out. (Thanks, open source software!) I found out that The inline keyword does make Clang/LLVM more likely to inline a function. The Search Searching for the word inline in the Clang repository leads to the token specifier kw_inline . It looks like Clang uses a clever macro-based system to build the lexer and other keyword-related functions, so there's noting direct like if (tokenString == "inline") return kw_inline to be found. But Here in ParseDecl.cpp , we see that kw_inline results in a call to DeclSpec::setFunctionSpecInline() . case tok::kw_inline: isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID); break; Inside that function , we set a bit and emit a warning if it's a duplicate inline : if (FS_inline_specified) { DiagID = diag::warn_duplicate_declspec; PrevSpec = "inline"; return true;}FS_inline_specified = true;FS_inlineLoc = Loc;return false; Searching for FS_inline_specified elsewhere, we see it's a single bit in a bitfield, and it's used in a getter function , isInlineSpecified() : bool isInlineSpecified() const { return FS_inline_specified | FS_forceinline_specified;} Searching for call sites of isInlineSpecified() , we find the codegen , where we convert the C++ parse tree into LLVM intermediate representation: if (!CGM.getCodeGenOpts().NoInline) { for (auto RI : FD->redecls()) if (RI->isInlineSpecified()) { Fn->addFnAttr(llvm::Attribute::InlineHint); break; }} else if (!FD->hasAttr<AlwaysInlineAttr>()) Fn->addFnAttr(llvm::Attribute::NoInline); Clang to LLVM We are done with the C++ parsing stage. Now our inline specifier is converted to an attribute of the language-neutral LLVM Function object. We switch from Clang to the LLVM repository . Searching for llvm::Attribute::InlineHint yields the method Inliner::getInlineThreshold(CallSite CS) (with a scary-looking braceless if block) : // Listen to the inlinehint attribute when it would increase the threshold// and the caller does not need to minimize its size.Function *Callee = CS.getCalledFunction();bool InlineHint = Callee && !Callee->isDeclaration() && Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex, Attribute::InlineHint);if (InlineHint && HintThreshold > thres && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize)) thres = HintThreshold; So we already have a baseline inlining threshold from the optimization level and other factors, but if it's lower than the global HintThreshold , we bump it up. (HintThreshold is settable from the command line.) getInlineThreshold() appears to have only one call site , a member of SimpleInliner : InlineCost getInlineCost(CallSite CS) override { return ICA->getInlineCost(CS, getInlineThreshold(CS));} It calls a virtual method, also named getInlineCost , on its member pointer to an instance of InlineCostAnalysis . Searching for ::getInlineCost() to find the versions that are class members, we find one that's a member of AlwaysInline - which is a non-standard but widely supported compiler feature - and another that's a member of InlineCostAnalysis . It uses its Threshold parameter here : CallAnalyzer CA(Callee->getDataLayout(), *TTI, AT, *Callee, Threshold);bool ShouldInline = CA.analyzeCall(CS); CallAnalyzer::analyzeCall() is over 200 lines and does the real nitty gritty work of deciding if the function is inlineable . It weighs many factors, but as we read through the method we see that all its computations either manipulate the Threshold or the Cost . And at the end: return Cost < Threshold; But the return value named ShouldInline is really a misnomer. In fact the main purpose of analyzeCall() is to set the Cost and Threshold member variables on the CallAnalyzer object. The return value only indicates the case when some other factor has overridden the cost-vs-threshold analysis, as we see here : // Check if there was a reason to force inlining or no inlining.if (!ShouldInline && CA.getCost() < CA.getThreshold()) return InlineCost::getNever();if (ShouldInline && CA.getCost() >= CA.getThreshold()) return InlineCost::getAlways(); Otherwise, we return an object that stores the Cost and Threshold . return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); So we're not returning a yes-or-no decision in most cases. The search continues! Where is this return value of getInlineCost() used? The Real Decision It's found in bool Inliner::shouldInline(CallSite CS) . Another big function. It calls getInlineCost() right at the beginning. It turns out that getInlineCost analyzes the intrinsic cost of inlining the function - its argument signature, code length, recursion, branching, linkage, etc. - and some aggregate information about every place the function is used. On the other hand, shouldInline() combines this information with more data about a specific place where the function is used. Throughout the method there are calls to InlineCost::costDelta() - which will use the InlineCost s Threshold value as computed by analyzeCall() . Finally, we return a bool . The decision is made. In Inliner::runOnSCC() : if (!shouldInline(CS)) { emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc, Twine(Callee->getName() + " will not be inlined into " + Caller->getName())); continue;}// Attempt to inline the function.if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas, InlineHistoryID, InsertLifetime, DL)) { emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc, Twine(Callee->getName() + " will not be inlined into " + Caller->getName())); continue;}++NumInlined; InlineCallIfPossible() does the inlining based on shouldInline() 's decision. So the Threshold was affected by the inline keyword, and is used in the end to decide whether to inline. Therefore, your Perception B is partly wrong because at least one major compiler changes its optimization behavior based on the inline keyword. However, we can also see that inline is only a hint, and other factors may outweigh it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27042935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514235/']}
jdg_373715
stackexchange
llm_judgeable_groundtruth_similarity
5282632
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 seen this Topic : Creating an instance from a class name and written this code: public partial class Form1 : Form{ public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { object obj = Activator.CreateInstance(null, "MyClass"); MyClass t = (MyClass)obj; t.My1 = 100; MessageBox.Show(t.My1.ToString()); }}public class MyClass{ public int My1 { get; set; } public int My2 { get; set; }} However when its runs there's an exception: Could not load type 'MyClass' from assembly 'Test_Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. I have another question. I have a class in one assembly that has some property. In another assembly I want create instance of it and get access to it's properties, by typing one of them just using stringy Class Name. How can I do that? Now provide the response and nothing else.
According to MSDN null actually doesn't mean current assembly . It means that assembly will be searched (its matter when your class is located in another assembly). Also you need specify not only the class name. So, to prevent searching and get type correctly you need to write full assembly-qualified name : Type objType = Type.GetType("YourNamespace.MyClass, YourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");object obj = Activator.CreateInstance(objType);MyClass t = (MyClass)obj; Assembly-qualified name you can retrieve for example with next code (to check that you are not mistaken): string name = typeof(MyClass).AssemblyQualifiedName;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5282632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648723/']}
jdg_373716
stackexchange
llm_judgeable_groundtruth_similarity
23036866
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 doing a simple linear model. I have fire = load_data()regr = linear_model.LinearRegression()scores = cross_validation.cross_val_score(regr, fire.data, fire.target, cv=10, scoring='r2')print scores which yields [ 0.00000000e+00 0.00000000e+00 -8.27299054e+02 -5.80431382e+00 -1.04444147e-01 -1.19367785e+00 -1.24843536e+00 -3.39950443e-01 1.95018287e-02 -9.73940970e-02] How is this possible? When I do the same thing with the built in diabetes data, it works perfectly fine, but for my data, it returns these seemingly absurd results. Have I done something wrong? Now provide the response and nothing else.
There is no reason r^2 shouldn't be negative (despite the ^2 in its name). This is also stated in the doc . You can see r^2 as the comparison of your model fit (in the context of linear regression, e.g a model of order 1 (affine)) to a model of order 0 (just fitting a constant), both by minimizing a squared loss. The constant minimizing the squared error is the mean. Since you are doing cross validation with left out data, it can happen that the mean of your test set is wildly different from the mean of your training set. This alone can induce a much higher incurred squared error in your prediction versus just predicting the mean of the test data, which results in a negative r^2 score. In worst case, if your data do not explain your target at all, these scores can become very strongly negative. Try import numpy as nprng = np.random.RandomState(42)X = rng.randn(100, 80)y = rng.randn(100) # y has nothing to do with X whatsoeverfrom sklearn.linear_model import LinearRegressionfrom sklearn.cross_validation import cross_val_scorescores = cross_val_score(LinearRegression(), X, y, cv=5, scoring='r2') This should result in negative r^2 values. In [23]: scoresOut[23]: array([-240.17927358, -5.51819556, -14.06815196, -67.87003867, -64.14367035]) The important question now is whether this is due to the fact that linear models just do not find anything in your data, or to something else that may be fixed in the preprocessing of your data. Have you tried scaling your columns to have mean 0 and variance 1? You can do this using sklearn.preprocessing.StandardScaler . As a matter of fact, you should create a new estimator by concatenating a StandardScaler and the LinearRegression into a pipeline using sklearn.pipeline.Pipeline .Next you may want to try Ridge regression.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23036866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/354979/']}
jdg_373717
stackexchange
llm_judgeable_groundtruth_similarity
27349612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to the swift language, and haven't done an application with mapkit yet. But I have the map and regions set, but I'm hung up on how to allow users to add pins. Let me clarify, I have no idea of even where to start, All I have at the moment (for the pins) is my variable, but I'm not even sure if that's correct. Any help would be much appreciated!!What I have... var MyPins: MKPinAnnotatoinView! ...... override func viewDidLoad() { super.viewDidLoad() Mapview code ..........} Now provide the response and nothing else.
Your pin variable is correct. Now you just need to add this annotation to MKMapView . You can also create a custom class for MKAnnotation to add custom annotation to map view. A beta demo for MapExampleiOS8 => Which supports Swift 2.1 Follow steps below: 1. Add MapKit.framework to project. 2. Create Storyboard variable IBOutlet of map view control or create it in view controller. Set delegate for this variable to override it's delegate methods: Add delegate signature to view controller interface: class ViewController: UIViewController, MKMapViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Set map view delegate with controller self.mapView.delegate = self }} 3. Override its delegate methods: Here we need to override mapView(_:viewForAnnotation:) method to show annotation pins on map. func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if (annotation is MKUserLocation) { return nil } if (annotation.isKind(of: CustomAnnotation.self)) { let customAnnotation = annotation as? CustomAnnotation mapView.translatesAutoresizingMaskIntoConstraints = false var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomAnnotation") as MKAnnotationView! if (annotationView == nil) { annotationView = customAnnotation?.annotationView() } else { annotationView?.annotation = annotation; } self.addBounceAnimationToView(annotationView) return annotationView } else { return nil }} 4. Add MKPointAnnotation to map view. You can add pin to location in map view. For simplicity add code to viewDidLoad() method. override func viewDidLoad() { super.viewDidLoad() // Set map view delegate with controller self.mapView.delegate = self let newYorkLocation = CLLocationCoordinate2DMake(40.730872, -74.003066) // Drop a pin let dropPin = MKPointAnnotation() dropPin.coordinate = newYorkLocation dropPin.title = "New York City" mapView.addAnnotation(dropPin)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27349612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_373718
stackexchange
llm_judgeable_groundtruth_similarity
26768991
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 single page app using Backbone, and whenever I over over something and then click the "back" button, the popover forever stays. I want to destroy all instances of popover when a new instance is loaded. Now provide the response and nothing else.
Finding the popovers that are created through the data API is not difficult and has been covered in other answers like those of David Mulder and Amir Popovich. You just do: $("[data-toggle='popover']").popover('hide'); Or you can use destroy if you need to or prefer to. The challenge is to handle those popovers that are created dynamically. Marking the Elements with Popovers I would implement something like this. I'd override the default popover method and I'd try to perform this override as early as possible so that everything that needs a popover uses my override. What it does is just mark elements that use a popover with a class. Bootstrap does not mark them itself: // Override popover so as to mark everything that uses a popover.var old_popover = $.fn.popover;function my_popover() { this.addClass('marked-as-having-a-popover'); return old_popover.apply(this, arguments);}$.fn.popover = my_popover; Then to clear everything before the unloading, I'd put in the code that detects the unloading the following: $(".marked-as-having-a-popover").popover('hide'); Or it could use destroy rather than hide if testing shows that it works better for your use-case. Now, the method above will work if the override happens early enough and you do not have a page where multiple jQueries are loaded. (Yep, this is possible.) I use something similar to deal with tooltips in one of my applications so I know the principle is sound. It so happens that in my app, all tooltips are created by my code so there is no risk of missing something. Finding All Elements with Popovers, Even Unmarked If you are in a situation where a popover can be created without being marked (I call this an "escapee"), then you need to query the whole DOM and find which elements have popovers. There is no shortcut here. You cannot rely on attributes like data-content because popovers can be created wholly dynamically (i.e. without any of the data- attributes). Also, all kinds of elements can get popovers, so you cannot reliably assume that only button elements will have a popover. The only surefire way to find everything that needs handling is to look at each element in the DOM and check whether it has a popover: // Obviously this is quite expensive but in a situation where there *can* be escapees// then you have to check all elements to see if they have a popover.$("*").each(function () { // Bootstrap sets a data field with key `bs.popover` on elements that have a popover. // Note that there is no corresponding **HTML attribute** on the elements so we cannot // perform a search by attribute. var popover = $.data(this, "bs.popover"); if (popover) $(this).popover('hide');}); Again, destroy could be used rather than hide . Proof of Concept Here is a fiddle that illustrates the entire thing: "Add a Dynamic Popover" simulates code that would add a popover when the override is in effect. "Add an Escapee" simulates code that would add a popover and somehow manage to use the original Bootstrap code. "Clear Marked" clears only the marked popovers. "Clear All" clears every single popover marked or not.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26768991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179736/']}
jdg_373719
stackexchange
llm_judgeable_groundtruth_similarity
28183473
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 struggling to get my head around why the following test does not work: [Fact]public void repro(){ var scheduler = new TestScheduler(); var count = 0; // this observable is a simplification of the system under test // I've just included it directly in the test for clarity // in reality it is NOT accessible from the test code - it is // an implementation detail of the system under test // but by passing in a TestScheduler to the sut, the test code // can theoretically control the execution of the pipeline // but per this question, that doesn't work when using FromAsync Observable .Return(1) .Select(i => Observable.FromAsync(Whatever)) .Concat() .ObserveOn(scheduler) .Subscribe(_ => Interlocked.Increment(ref count)); Assert.Equal(0, count); // this call initiates the observable pipeline, but does not // wait until the entire pipeline has been executed before // returning control to the caller // the question is: why? Rx knows I'm instigating an async task // as part of the pipeline (that's the point of the FromAsync // method), so why can't it still treat the pipeline atomically // when I call Start() on the scheduler? scheduler.Start(); // count is still zero at this point Assert.Equal(1, count);}private async Task<Unit> Whatever(){ await Task.Delay(100); return Unit.Default;} What I'm trying to do is run some asynchronous code (represented above by Whatever() ) whenever an observable ticks. Importantly, I want those calls to be queued. More importantly, I want to be able to control the execution of the pipeline by using the TestScheduler . It seems like the call to scheduler.Start() is instigating the execution of Whatever() but it isn't waiting until it completes. If I change Whatever() so that it is synchronous: private async Task<Unit> Whatever(){ //await Task.Delay(100); return Unit.Default;} then the test passes, but of course that defeats the purpose of what I'm trying to achieve. I could imagine there being a StartAsync() method on the TestScheduler that I could await, but that does not exist. Can anyone tell me whether there's a way for me to instigate the execution of the reactive pipeline and wait for its completion even when it contains asynchronous calls? Now provide the response and nothing else.
Let me boil down your question to its essentials: Is there a way, using the TestScheduler , to execute a reactive pipeline and wait for its completion even when it contains asynchronous calls? I should warn you up front, there is no quick and easy answer here, no convenient "trick" that can be deployed. Asynchronous Calls and Schedulers To answer this question I think we need to clarify some points. The term "asynchronous call" in the question above seems to be used specifically to refer to methods with a Task or Task<T> signature - i.e. methods that use the Task Parallel Library (TPL) to run asynchronously. This is important to note because Reactive Extensions (Rx) takes a different approach to handling asynchronous operations. In Rx the introduction of concurrency is managed via a scheduler, a type implementing the IScheduler interface. Any operation that introduces concurrency should make a available a scheduler parameter so that the caller can decide an appropriate scheduler. The core library slavishly adheres to this principle. So, for example, Delay allows specification of a scheduler but Where does not. As you can see from the source , IScheduler provides a number of Schedule overloads. Operations requiring concurrency use these to schedule execution of work. Exactly how that work is executed is deferred completely to the scheduler. This is the power of the scheduler abstraction. Rx operations introducing concurrency generally provide overloads that allow the scheduler to be omitted, and in that case select a sensible default. This is important to note, because if you want your code to be testable via the use of TestScheduler you must use a TestScheduler for all operations that introduce concurrency. A rogue method that doesn't allow this, could scupper your testing efforts. TPL Scheduling Abstraction The TPL has it's own abstraction to handle concurrency: The TaskScheduler . The idea is very similar. You can read about it here. . There are two very important differences between the two abstractions: Rx schedulers have a first class representation of their own notion of time - the Now property. TPL schedulers do not. The use of custom schedulers in the TPL is much less prevalent, and there is no equivalent best practice of providing overloads for providing specific TaskSchedulers to a method introducing concurrency (returning a Task or Task<T> ). The vast majority of Task returning methods assume use of the default TaskScheduler and give you no choice about where work is run. Motivation for TestScheduler The motivation to use a TestScheduler is generally two-fold: To remove the need to "wait" for operations by speeding up time. To check that events occurred at expected points in time. The way this works depends entirely on the fact that schedulers have their own notion of time. Every time an operation is scheduled via an IScheduler , we specify when it must execute - either as soon as possible, or at a specific time in the future. The scheduler then queues work for execution and will execute it when the specified time (according to the scheduler itself) is reached. When you call Start on the TestScheduler , it works by emptying the queue of all operations with execution times at or before its current notion of Now - and then advancing its clock to the next scheduled work time and repeating until its queue is empty. This allows neat tricks like being able to test that an operation will never result in an event! If using real time this would be a challenging task, but with virtual time it's easy - once the scheduler queue is completely empty, then the TestScheduler concludes that no further events will ever happen - since if nothing is left on its queue, there is nothing there to schedule further tasks. In fact Start returns at this precisely this point. For this to work, clearly all concurrent operations to be measured must be scheduled on the TestScheduler . A custom operator that carelessly makes its own choice of scheduler without allowing that choice to be overriden, or an operation that uses its own form of concurrency without a notion of time (such as TPL based calls) will make it difficult, if not impossible, to control execution via a TestScheduler . If you have an asynchronous operation run by other means, judicious use of the AdvanceTo and AdvanceBy methods of the TestScheduler can allow you to coordinate with that foreign source of concurrency - but the extent to which this is achievable depends on the control afforded by that foreign source. In the case of the TPL, you do know when a task is done - which does allow the use of waits and timeouts in tests, as ugly as these can be. Through the use of TaskCompleteSources (TCS) you can mock tasks and use AdvanceTo to hit specific points and complete TCSs, but there is no one simple approach here. Often you just have to resort to ugly waits and timeouts because you don't have sufficient control over foreign concurrency. Rx is generally free-threaded and tries to avoid introducing concurrency wherever possible. Conversely, it's quite possible that different operations within an Rx call chain will need different types of scheduler abstraction. It's not always possible to simulate a call chain with a single test scheduler. Certainly, I have had cause to use multiple TestSchedulers to simulate some complex scenarios - e.g. chains that use the DispatcherScheduler and TaskScheduler sometimes need complex coordination that means you can't simply serialize their operations on to one TestScheduler . Some projects I have worked on have mandated the use of Rx for all concurrency specifically to avoid these problems. That is not always feasible, and even in these cases, some use of TPL is generally inevitable. One particular pain point One particular pain point of Rx that leaves many testers scratching their heads, is the fact that the TPL -> Rx family of conversions introduce concurrency. e.g. ToObservable , SelectMany 's overload accepting Task<T> etc. don't provide overloads with a scheduler and insidiously force you off the TestScheduler thread, even if mocking with TCS. For all the pain this causes in testing alone, I consider this a bug. You can read all about this here - dig through and you'll find Dave Sexton's proposed fix, which provides an overload for specifying a scheduler, and is under consideration for inclusion. You may want to look into that pull request. A Potential Workaround If you can edit your code to use it, the following helper method might be of use. It converts a task to an observable that will run on the TestScheduler and complete at the correct virtual time. It schedules work on the TestScheduler that is responsible for collecting the task result - at the virtual time we state the task should complete. The work itself blocks until the task result is available - allowing the TPL task to run for however long it takes, or until a real amount of specified time has passed in which case a TimeoutException is thrown. The effect of blocking the work means that the TestScheduler won't advance its virtual time past the expected virtual completion time of the task until the task has actually completed. This way, the rest of the Rx chain can run in full-speed virtual time and we only wait on the TPL task, pausing the rest of the chain at the task completion virtual time whilst this happens. Crucially, other concurrent Rx operations scheduled to run in between the start virtual time of the Task based operation and the stated end virtual time of the Task are not blocked and their virtual completion time will be unaffected. So set duration to the length of virtual time you want the task to appear to have taken. The result will then be collected at whatever the virtual time is when the task is started, plus the duration specified. Set timeout to the actual time you will allow the task to take. If it takes longer, a timeout exception is thrown: public static IObservable<T> ToTestScheduledObseravble<T>( this Task<T> task, TestScheduler scheduler, TimeSpan duration, TimeSpan? timeout = null){ timeout = timeout ?? TimeSpan.FromSeconds(100); var subject = Subject.Synchronize(new AsyncSubject<T>(), scheduler); scheduler.Schedule<Task<T>>(task, duration, (s, t) => { if (!task.Wait(timeout.Value)) { subject.OnError( new TimeoutException( "Task duration too long")); } else { switch (task.Status) { case TaskStatus.RanToCompletion: subject.OnNext(task.Result); subject.OnCompleted(); break; case TaskStatus.Faulted: subject.OnError(task.Exception.InnerException); break; case TaskStatus.Canceled: subject.OnError(new TaskCanceledException(task)); break; } } return Disposable.Empty; }); return subject.AsObservable();} Usage in your code would be like this, and your assert will pass: Observable .Return(1) .Select(i => Whatever().ToTestScheduledObseravble( scheduler, TimeSpan.FromSeconds(1))) .Concat() .Subscribe(_ => Interlocked.Increment(ref count)); Conclusion In summary, you haven't missed any convenient trick. You need to think about how Rx works, and how the TPL works and decide whether: You avoid mixing TPL and Rx You mock your interface between TPL and Rx (using TCS or similar), so you test each independently You live with ugly waits and timeouts and abandon the TestScheduler altogether You mix ugly waits and timeouts with TestScheduler to bring some modicum of control over your tests.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28183473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1228288/']}
jdg_373720
stackexchange
llm_judgeable_groundtruth_similarity
28662
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 very slow connection, and I need to use SSH on it. How can I increase "the speed"? I mean is using big RSA keypairs a large overhead? Would lowering the key size increase the effective bandwidth a little? Now provide the response and nothing else.
The RSA key size only matters at the time when the connection is established. The key size can matter if one of the machines is slow, as larger keys mean longer computations, but its impact on connection times is negligible. If throughput is a problem, compress the connection: ssh -C . If connection establishment time is a problem, make sure to activate a single master SSH connection and use slave mode for subsequent connections. If latency is a problem, there's not much you can do except adapt your habits. If the latency is so high that interactive programs are painful to use, type commands locally and send them over when done (Emacs shell mode is nice for that). Do file management over SSHFS (except remote-to-remote copies). Avoid needing remote X as it's both latency-sensitive and bandwidth-consuming. If you really must, NX is the best of the crop (but it's painful to set up because it's not free software so distributions don't provide it; this may change as free clones are emerging).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/28662', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/6960/']}
jdg_373721
stackexchange
llm_judgeable_groundtruth_similarity
387171
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: $$\text{Find} \ \ \sum_{k=0}^{n} (-1)^k k \binom{n}{k}^2$$ I expanded the binomial coefficients within the sum and got $$\binom{n}{0}^2 + \binom{n}{1}^2 + \binom{n}{2}^2 + \dots + \binom{n}{n}^2$$What does this equal to? I think this can help me evaluate the original sum. Now provide the response and nothing else.
First, use $k\binom{n\vphantom{1}}{k}=n\binom{n-1}{k-1}=n\binom{n-1}{n-k}$$$\sum_{k=0}^n(-1)^kk\binom{n}{k}^2=n\sum_{k=0}^n(-1)^k\binom{n}{k}\binom{n-1}{n-k}\tag{1}$$Next compute a generating function. The sum we want is the coefficient of $x^n$$$\begin{align}n\sum_{m,k}(-1)^k\binom{n}{k}\binom{n-1}{m-k}x^m&=n\sum_{m,k}(-1)^k\binom{n}{k}\binom{n-1}{m-k}x^{m-k}x^k\\&=n\sum_k(-1)^k\binom{n}{k}(1+x)^{n-1}x^k\\&=n(1+x)^{n-1}(1-x)^n\\&=n\left(1-x^2\right)^{n-1}(1-x)\tag{2}\end{align}$$The sum we want is the coefficient of $x^n$ in $(2)$:$$\begin{align}\sum_{k=0}^n(-1)^kk\binom{n}{k}^2&=\left\{\begin{array}{}n\binom{n-1}{n/2}(-1)^{n/2}&\quad\text{if $n$ is even}\\[6pt]n\binom{n-1}{(n-1)/2}(-1)^{(n+1)/2}&\quad\text{if $n$ is odd}\end{array}\right.\\[6pt]&=n\binom{n-1}{\lfloor n/2\rfloor}(-1)^{\lceil n/2\rceil}\tag{3}\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/387171', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74645/']}
jdg_373722
stackexchange
llm_judgeable_groundtruth_similarity
36384195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use dlopen() and dlsym() in my code and compile it with gcc . Here is the first file. /* main.c */#include <dlfcn.h>int main(){ void *handle = dlopen("./foo.so", RTLD_NOW); if (handle) { void (*func)() = dlsym(handle, "func"); func(); } return 0;} Here is the second file. /* foo.c */#include <stdio.h>void func(){ printf("hello, world\n");} Here is how I compile and run the code. $ gcc -std=c99 -pedantic -Wall -Wextra -shared -fPIC -o foo.so foo.c$ gcc -std=c99 -pedantic -Wall -Wextra -ldl -o main main.cmain.c: In function ‘main’:main.c:10:26: warning: ISO C forbids initialization between function pointer and ‘void *’ [-Wpedantic] void (*func)() = dlsym(handle, "func"); ^$ ./mainhello, world How can I get rid of the warning? Type casting doesn't help. If I try to type cast the return value of dlsym() into a function pointer, I get this warning instead. main.c:10:26: warning: ISO C forbids conversion of object pointer to function pointer type [-Wpedantic] void (*func)() = (void (*)()) dlsym(handle, "func"); ^ What would convince the compiler that this code is fine? Now provide the response and nothing else.
If you want to be pedantically correct, don't try to resolve the address of a function. Instead, export some kind of structure from the dynamic library: In the library struct export_vtable { void (*helloworld)(void);};struct export_vtable exports = { func }; In the caller struct export_vtable { void (*helloworld)(void);};int main() { struct export_vtable* imports; void *handle = dlopen("./foo.so", RTLD_NOW); if (handle) { imports = dlsym(handle, "exports"); if (imports) imports->helloworld(); } return 0;} This technique is actually quite common, not for portability -- POSIX guarantees that function pointers can be converted to and from void* -- but because it allows more flexibility.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36384195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175080/']}
jdg_373723
stackexchange
llm_judgeable_groundtruth_similarity
5153544
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 access XML data files directly from a zipped file in my Scala program? Are there any direct ways to programmatically unzip and read contents in my Scala code? Now provide the response and nothing else.
Here are a couple of ways of doing it in 2.8.1: cat > root.xml << EOF<ROOT><id>123</id></ROOT>EOFzip root root.xml and then in the REPL: val rootzip = new java.util.zip.ZipFile("root.zip")import collection.JavaConverters._val entries = rootzip.entries.asScalaentries foreach { e => val x = scala.xml.XML.load(rootzip.getInputStream(e)) println(x)} or something like: val rootzip = new java.util.zip.ZipFile("root.zip")import scala.collection.JavaConversions._rootzip.entries. filter (_.getName.endsWith(".xml")). foreach { e => println(scala.xml.XML.load(rootzip.getInputStream(e))) }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5153544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/326879/']}
jdg_373724
stackexchange
llm_judgeable_groundtruth_similarity
36752258
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 tried to collect data from JSON to fill out related Input Text Field after matching results, but it's not working. How can I get populate the input text field from the JSON? JS Code $(document).ready(function(){var filter = document.getElementById('zipcode');var JSONtbl = [ {"zipcode":01702,"address":"334 CONCORD ST","County":"MIDDLESEX"}, {"zipcode":02482,"address":"27 Atwood St","County":"NORFOLK"}, {"zipcode":02459,"address":"189 Cypress St","County":"MIDDLESEX"} ];filter.onkeyup = function() { var zipcodeToSearch = filter.value; var n = zipcodeToSearch.length; if (n < 5) { document.getElementById("address").innerHTML = ""; document.getElementById("County").innerHTML = ""; } else { for (var i = 0; i < JSONtbl.length; i++) { if (JSONtbl[i].zipcode == zipcodeToSearch) { document.getElementById("address").innerHTML = JSONtbl[i].address; document.getElementById("County").innerHTML = JSONtbl[i].County; } } if (document.getElementById("address").innerHTML == "") { alert("ZipCode Out Of Area") } }};}); div { padding: 2px 5px;} <form method="post"><div><input type="text" id="zipcode"/></div><div><input type="text" id="address" disabled="disabled"></div><div><input type="text" id="County" disabled="disabled"></div></form> Now provide the response and nothing else.
Two mistakes in your code. First: Input does't have innerHTML but value. Second You are assigning integer to zipcode starting with zero. Rather you need a string type because value returned by input will be a string. use this code var filter = document.getElementById('zipcode');var JSONtbl = [ {"zipcode":"01702","address":"334 CONCORD ST","County":"MIDDLESEX"}, {"zipcode":"02482","address":"27 Atwood St","County":"NORFOLK"}, {"zipcode":"02459","address":"189 Cypress St","County":"MIDDLESEX"} ];filter.onkeyup = function() { var zipcodeToSearch = filter.value; var n = zipcodeToSearch.length; if (n < 5) { document.getElementById("address").value = ""; document.getElementById("County").value = ""; } else { for (var i = 0; i < JSONtbl.length; i++) { if (JSONtbl[i].zipcode == zipcodeToSearch) { document.getElementById("address").value = JSONtbl[i].address; document.getElementById("County").value = JSONtbl[i].County; } } if (document.getElementById("address").value == "") { alert("ZipCode Out Of Area") } }}; div { padding: 2px 5px;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><form method="post"><div><input type="text" id="zipcode"/></div><div><input type="text" id="address" disabled="disabled"></div><div><input type="text" id="County" disabled="disabled"></div></form>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36752258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6231685/']}
jdg_373725
stackexchange
llm_judgeable_groundtruth_similarity
16082333
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 followed this link to sign my exe application. I installed SDK tool on Windows 7, run C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin>makecert.exe -sv App-O.pvk -n "CN=MY DIGITAL KEY" App-O.cer Dialog opened to provide password: I wrote password : 'fess' new window opened: I entered: 'fess' #Succeeded files App-O.cer and App-O.pvk creaded. now I generate pfx: pvk2pfx.exe -pvk App-O.pvk -spc App-O.cer -pfx App-O.pfx Dialog opened to provide password: i pasted 'fess' file pfx created. Now i run signtool: C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin>signtool.exe sign /f "App-O.pfx" /p fess "C:\Output\setup.exe" Here I got the error: SignTool Error: The specified PFX password is not correct.Number of files successfully Signed: 0Number of warnings: 0Number of errors: 1 What did I miss? BTW, the same error I get from CMD shell of Windows SDK. Thanks, Now provide the response and nothing else.
There are a couple of problems. First of all you are using self-signed certificate, so you should define it explicitly by adding -r key to makecert command or you'll get an error "The signer's certificate is not valid for signing" at sign step. Next, at this step signtool.exe sign /f "App-O.pfx" /p fess "C:\Output\setup.exe" you are trying to open pfx using password "fess". But you actually didn't set any password for pfx file. To do it you should add -po key to pfx creation command. After that you can sign your application. So the correct process will be: makecert.exe -sv App-O.pvk -n "CN=MY DIGITAL KEY" App-O.cer -rpvk2pfx.exe -pvk App-O.pvk -spc App-O.cer -pfx App-O.pfx -po fesssigntool.exe sign /f "App-O.pfx" /p fess "C:\Output\setup.exe" Here is some useful links: How to create certificate: http://msdn.microsoft.com/en-us/library/ff699202.aspx pvk2pfx command keys: http://msdn.microsoft.com/en-us/library/windows/hardware/ff550672%28v=vs.85%29.aspx signtool command keys: http://msdn.microsoft.com/en-us/library/windows/desktop/aa387764%28v=vs.85%29.aspx How to sign a file: http://msdn.microsoft.com/en-us/library/windows/desktop/aa388170%28v=vs.85%29.aspx
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16082333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1631379/']}
jdg_373726
stackexchange
llm_judgeable_groundtruth_similarity
4796109
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 listBox1 object and it contains some items. I have a button to move selected item up and another to move selected item down. What should the code be to the two buttons? Now provide the response and nothing else.
public void MoveUp() { MoveItem(-1); } public void MoveDown() { MoveItem(1); } public void MoveItem(int direction) { // Checking selected item if (listBox1.SelectedItem == null || listBox1.SelectedIndex < 0) return; // No selected item - nothing to do // Calculate new index using move direction int newIndex = listBox1.SelectedIndex + direction; // Checking bounds of the range if (newIndex < 0 || newIndex >= listBox1.Items.Count) return; // Index out of range - nothing to do object selected = listBox1.SelectedItem; // Removing removable element listBox1.Items.Remove(selected); // Insert it in new position listBox1.Items.Insert(newIndex, selected); // Restore selection listBox1.SetSelected(newIndex, true);} UPD 2020-03-24: Extension class for simple reuse and it also supports CheckedListBox (if CheckedListBox is not needed for you, please remove appropriate lines of code). Thanks @dognose and @Chad public static class ListBoxExtension{ public static void MoveSelectedItemUp(this ListBox listBox) { _MoveSelectedItem(listBox, -1); } public static void MoveSelectedItemDown(this ListBox listBox) { _MoveSelectedItem(listBox, 1); } static void _MoveSelectedItem(ListBox listBox, int direction) { // Checking selected item if (listBox.SelectedItem == null || listBox.SelectedIndex < 0) return; // No selected item - nothing to do // Calculate new index using move direction int newIndex = listBox.SelectedIndex + direction; // Checking bounds of the range if (newIndex < 0 || newIndex >= listBox.Items.Count) return; // Index out of range - nothing to do object selected = listBox.SelectedItem; // Save checked state if it is applicable var checkedListBox = listBox as CheckedListBox; var checkState = CheckState.Unchecked; if (checkedListBox != null) checkState = checkedListBox.GetItemCheckState(checkedListBox.SelectedIndex); // Removing removable element listBox.Items.Remove(selected); // Insert it in new position listBox.Items.Insert(newIndex, selected); // Restore selection listBox.SetSelected(newIndex, true); // Restore checked state if it is applicable if (checkedListBox != null) checkedListBox.SetItemCheckState(newIndex, checkState); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4796109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_373727
stackexchange
llm_judgeable_groundtruth_similarity
53000291
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: THE PROBLEM: When I grab the resize border of my Windows app, especially the top or left borders, and resize the window, the contents of the window do resize "live" as I drag, but they resize in a hideous manner that looks like a blatant bug to even the most novice user: the contents at the opposite edge of the window from the edge I am dragging jitter/flicker/jump back and forth wildly. Depending on the situation, the phenomenon may look like: contents that seem to walk off the edge of the window and snap back when we slow down or stop dragging contents that seem to pull into the window, intermittently displaced by a border of varying colors, often black or white a seriously ugly "double image" with two overlapping copies of the content displaced by a distance proportional to how much/how fast we are dragging The ugly phenomenon stops as soon as I stop dragging, but during the dragging it makes the app look amateurish and unprofessional. It is not an understatement to say this Windows problem has driven thousands of app developers crazy . Here are two example pictures of the phenomenon, kindly prepared for a related question by Roman Starkov : Jitter: Border: Another example showing the evil "double image" phenomenon (note the quick flash) from Kenny Liu : Another example video of the phenomenon with Task Manager is here . THE QUESTION: Any developer who has experienced this problem quickly finds that there are at least 30 Stack Overflow questions, some recent and some dating from 2008, full of promising-sounding answers that rarely work. The reality is that this one problem has many causes , and the existing Stack Overflow questions/answers never make the wider context clear. This question seeks to answer: what are the most likely causes of this kind of ugly jitter/flicker/jumping? how do I tell which cause I am seeing? is this cause specific to particular graphics drivers or general for Windows? how do I fix each cause? can an app fix it? (This is meant as a canonical Q&A to explain all the different causes of window resize jitter so that users can identify which of the causes is causing their problem and solve it. As the answers explain, all the permutations above (native/managed, window/dialog, XP-10) boil down to only two root causes, but identifying which you have is the tricky part.) SCOPE OF THIS QUESTION: For the scope of this question, the phenomenon happens with: both native Win32 and managed .NET/WPF/Windows Forms apps both normal Win32 windows and Win32 Dialog windows Windows versions including XP, Vista, 7, 8, and 10 (but see below for the dark truth of multiple causes) NOT IN SCOPE OF THIS QUESTION: If your app has one or more child windows (child HWNDs), the info in this question is useful to you (since the jerk-causing BitBlts we will describe are applied to your child windows along with the parent window), but during window resize you have an additional problem to handle that is beyond the scope of this question: you need to make all your child windows move atomically and in sync with the parent window. For this task, you will probably want BeginDeferWindowPos/DeferWindowPos/EndDeferWindowPos and you can find out about them here and here . This question assumes that if your app draws to a window using GDI, DirectX, or OpenGL, then you have already implemented a WM_ERASEBKGND handler in your wndproc that simply returns 1. WM_ERASEBKGND is an arcane Windows remnant from Windows 3.1 that comes before WM_PAINT to give your app a chance to "erase the background" of your window before you draw your window...uh huh. If you let the WM_ERASEBKGND message go into DefWindowProc() , that will cause your entire window to get painted a solid color, usually white, on each redraw, including redraws that happen during live window resizing. The result is an ugly full-window flicker that is gross, but not the type of jitter/flicker/jumping we are talking about in this question. Intercepting WM_ERASEBKGND fixes this problem immediately. This question is primarily about live-resize by dragging window borders with the mouse. However, much of what is written here also applies to ugly artifacts you can see when an app manually does a one-time window resize using SetWindowPos() . These are less visible though because they only flick on the screen for one instant, rather than over a long period of dragging. This question is not about how to make your app-specific drawing code go faster, even though doing so may be a solution to the ugly resizing problem in many cases. If your app really does take huge amounts of time to redisplay its contents during live window resize, consider optimizing your drawing code in general or at least switching to a faster, lower-quality drawing mode during resize by intercepting the WM_ENTERSIZEMOVE/WM_EXITSIZEMOVE messages to detect resize. If your app fails to resize at all during app resizing (e.g. it "hangs" during resizing, especially if it is OpenGL using GLFW or other library), see these other questions which explain about Microsoft's hideous nested/modal event loop inside WM_SYSCOMMAND during dragging: here especially this good answer , here , here , here , and here . Now provide the response and nothing else.
PART 2: Identifying and Fixing Windows Resize Problems Note: you want to read PART 1 first for this answer to make sense. This answer will not solve all your resizing problems. It organizes the still-usable ideas from other posts and adds a few novel ideas. None of this behavior is at all documented on Microsoft's MSDN, and what follows below is the result of my own experimentation and looking at other StackOverflow posts. 2a. Resize Problems from SetWindowPos() BitBlt and Background Fill The following problems happen on all versions of Windows . They date back to the very first days of live-scrolling on the Windows platform (Windows XP) and are still present on Windows 10. On more recent Windows versions, other resize problems may layer on top of this problem, as we explain below. Here are the Windows events associated with a typical session of clicking a window border and dragging that border. Indentation indicates nested wndproc (nested because of sent (not posted) messages or because of the hideous Windows modal event loop mentioned in "NOT IN SCOPE OF THIS QUESTION" in the question above): msg=0xa1 (WM_NCLBUTTONDOWN) [click mouse button on border] msg=0x112 (WM_SYSCOMMAND) [window resize command: modal event loop] msg=0x24 (WM_GETMINMAXINFO) msg=0x24 (WM_GETMINMAXINFO) done msg=0x231 (WM_ENTERSIZEMOVE) [starting to size/move window] msg=0x231 (WM_ENTERSIZEMOVE) done msg=0x2a2 (WM_NCMOUSELEAVE) msg=0x2a2 (WM_NCMOUSELEAVE) done loop: msg=0x214 (WM_SIZING) [mouse dragged] msg=0x214 (WM_SIZING) done msg=0x46 (WM_WINDOWPOSCHANGING) msg=0x24 (WM_GETMINMAXINFO) msg=0x24 (WM_GETMINMAXINFO) done msg=0x46 (WM_WINDOWPOSCHANGING) done msg=0x83 (WM_NCCALCSIZE) msg=0x83 (WM_NCCALCSIZE) done msg=0x85 (WM_NCPAINT) msg=0x85 (WM_NCPAINT) done msg=0x14 (WM_ERASEBKGND) msg=0x14 (WM_ERASEBKGND) done msg=0x47 (WM_WINDOWPOSCHANGED) msg=0x3 (WM_MOVE) msg=0x3 (WM_MOVE) done msg=0x5 (WM_SIZE) msg=0x5 (WM_SIZE) done msg=0x47 (WM_WINDOWPOSCHANGED) done msg=0xf (WM_PAINT) [may or may not come: see below] msg=0xf (WM_PAINT) donegoto loop; msg=0x215 (WM_CAPTURECHANGED) [mouse released] msg=0x215 (WM_CAPTURECHANGED) done msg=0x46 (WM_WINDOWPOSCHANGING) msg=0x24 (WM_GETMINMAXINFO) msg=0x24 (WM_GETMINMAXINFO) done msg=0x46 (WM_WINDOWPOSCHANGING) done msg=0x232 (WM_EXITSIZEMOVE) msg=0x232 (WM_EXITSIZEMOVE) done [finished size/moving window] msg=0x112 (WM_SYSCOMMAND) donemsg=0xa1 (WM_NCLBUTTONDOWN) done Each time you drag the mouse, Windows gives you the series of messages shown in the loop above. Most interestingly, you get WM_SIZING then WM_NCCALCSIZE then WM_MOVE/WM_SIZE , then you may (more on that below) receive WM_PAINT . Remember we assume you have provided a WM_ERASEBKGND handler that returns 1 (see "NOT IN SCOPE OF THIS QUESTION" in the question above) so that message does nothing and we can ignore it. During the processing of those messages (shortly after WM_WINDOWPOSCHANGING returns), Windows makes an internal call to SetWindowPos() to actually resize the window. That SetWindowPos() call first resizes the non-client area (e.g. the title bars and window border) then turns its attention to the client area (the main part of the window that you are responsible for). During each sequence of messages from one drag, Microsoft gives you a certain amount of time to update the client area by yourself. The clock for this deadline apparently starts ticking after WM_NCCALCSIZE returns. In the case of OpenGL windows, the deadline is apparently satisfied when you call SwapBuffers() to present a new buffer (not when your WM_PAINT is entered or returns). I do not use GDI or DirectX, so I don't know what the equavalent call to SwapBuffers() is, but you can probably make a good guess and you can verify by inserting Sleep(1000) at various points in your code to see when the behaviors below get triggered. How much time do you have to meet your deadline? The number seems to be around 40-60 milliseconds by my experiments, but given the kinds of shenanigans Microsoft routinely pulls, I wouldn't be surprised if the number depends on your hardware config or even your app's previous behavior. If you do update your client area by the deadline, then Microsoft will leave your client area beautifully unmolested. Your user will only see the pixels that you draw, and you will have the smoothest possible resizing. If you do not update your client area by the deadline, then Microsoft will step in and "help" you by first showing some other pixels to your user, based on a combination of the "Fill in Some Background Color" technique (Section 1c3 of PART 1 ) and the "Cut off some Pixels" technique (Section 1c4 of PART 1 ). Exactly what pixels Microsoft shows your user is, well, complicated: If your window has a WNDCLASS.style that includes the CS_HREDRAW|CS_VREDRAW bits (you pass the WNDCLASS structure to RegisterClassEx ): Something surprisingly reasonable happens. You get the logical behavior shown in Figures 1c3-1, 1c3-2, 1c4-1, and 1c4-2 of PART 1 . When enlarging the client area, Windows will fill in newly exposed pixels with the "background color" (see below) on the same side of the window you are dragging. If needed (left and top border cases), Microsoft does a BitBlt to accomplish this. When shrinking the client area, Microsoft will chop off pixels on the same side of the window you are dragging. This means you avoid the truly heinous artifact that makes objects in your client area appear to move in one direction then move back in the other direction. This may be good enough to give you passable resize behavior, unless you really want to push it and see if you can totally prevent Windows from molesting your client area before you have a chance to draw (see below). Do not implement your own WM_NCCALCSIZE handler in this case, to avoid buggy Windows behavior described below. If your window has a WNDCLASS.style that does not include the CS_HREDRAW|CS_VREDRAW bits (including Dialogs, where Windows does not let you set WNDCLASS.style ): Windows tries to "help" you by doing a BitBlt that makes a copy of a certain rectangle of pixels from your old client area and writes that rectangle to a certain place in your new client area. This BitBlt is 1:1 (it does not scale or zoom your pixels). Then, Windows fills in the other parts of the new client area (the parts that Windows did not overwrite during the BitBlt operation) with the "background color." The BitBlt operation is often the key reason why resize looks so bad. This is because Windows makes a bad guess about how your app is going to redraw the client area after the resize. Windows places your content in the wrong location. The net result is that when the user first sees the BitBlt pixels and then sees the real pixels drawn by your code, your content appears to first move in one direction, then jerk back in the other direction. As we explained in PART 1 , this creates the most hideous type of resize artifact. So, most solutions for fixing resize problems involve disabling the BitBlt . If you implement a WM_NCCALCSIZE handler and that handler returns WVR_VALIDRECTS when wParam is 1, you can actually control which pixels Windows copies ( BitBlts ) from the old client area and where Windows places those pixels in the new client area. WM_NCCALCSIZE is just barely documented, but see the hints about WVR_VALIDRECTS and NCCALCSIZE_PARAMS.rgrc[1] and [2] in the MSDN pages for WM_NCCALCSIZE and NCCALCSIZE_PARAMS . You can even provide NCCALCSIZE_PARAMS.rgrc[1] and [2] return values that completely prevent Windows from BitBlting any of the pixels of the old client area to the new client area, or cause Windows to BitBlt one pixel from and to the same location, which is effectively the same thing since no on-screen pixels would get modified. Just set both NCCALCSIZE_PARAMS.rgrc[1] and [2] to the same 1-pixel rectangle. In combination with eliminating the "background color" (see below), this gives you a way to prevent Windows from molesting your window's pixels before you have time to draw them. If you implement a WM_NCCALCSIZE handler and it returns anything other than WVR_VALIDRECTS when wParam is 1, then you get a behavior which (at least on Windows 10) does not at all resemble what MSDN says. Windows seems to ignore whatever left/right/top/bottom alignment flags you return. I advise you do not do this. In particular the popular StackOverflow article How do I force windows NOT to redraw anything in my dialog when the user is resizing my dialog? returns WVR_ALIGNLEFT|WVR_ALIGNTOP and this appears to be completely broken now at least on my Windows 10 test system. The code in that article might work if it is changed to return WVR_VALIDRECTS instead. If you do not have your own custom WM_NCCALCSIZE handler, you get a pretty useless behavior that is probably best avoided: If you shrink the client area, nothing happens (your app gets no WM_PAINT at all)! If you're using the top or left border, your client area contents will move along with the top left of the client area. In order to get any live resizing when shrinking the window, you have to manually draw from a wndproc message like WM_SIZE , or call InvalidateWindow() to trigger a later WM_PAINT . If you enlarge the client area If you drag the bottom or right window border, Microsoft fills in the new pixels with the "background color" (see below) If you drag the top or left window border, Microsoft copies the existing pixels to the top left corner of the expanded window and leaves an old junk copy of old pixels in the newly opened space So as you can see from this sordid tale, there appear to be two useful combinations: 2a1. WNDCLASS.style with CS_HREDRAW|CS_VREDRAW gives you the behavior in Figures 1c3-1, 1c3-2, 1c4-1, and 1c4-2 of PART 1 , which is not perfect but at least your client area content will not move one direction then jerk back in the other direction 2a2. WNDCLASS.style without CS_HREDRAW|CS_VREDRAW plus a WM_NCCALCSIZE handler returning WVR_VALIDRECTS (when wParam is 1) that BitBlts nothing, plus disabling the "background color" (see below) may completely disable Windows' molestation of your client area. There is apparently another way to achieve the effect of combination 2a2. Instead of implementing your own WM_NCCALCSIZE , you can intercept WM_WINDOWPOSCHANGING (first passing it onto DefWindowProc ) and set WINDOWPOS.flags |= SWP_NOCOPYBITS , which disables the BitBlt inside the internal call to SetWindowPos() that Windows makes during window resizing. I have not tried this trick myself but many SO users reported it worked. At several points above, we mentioned the "background color." This color is determined by the WNDCLASS.hbrBackground field that you passed to RegisterClassEx . This field contains an HBRUSH object. Most people set it using the following boilerplate code: wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); The COLOR_WINDOW+1 incantation gives you a white background color. See MSDN dox for WNDCLASS for the +1 explanation and note there is a lot of wrong info about the +1 on StackOverflow and MS forums. You can choose your own color like this: wndclass.hbrBackground = CreateSolidBrush(RGB(255,200,122)); You can also disable the background fill-in using: wndclass.hbrBackground = NULL; which is another key ingredient of combination 2a2 above. But be aware that newly uncovered pixels will take on some essentially random color or pattern (whatever garbage happens to be in your graphics framebuffer) until your app catches up and draws new client area pixels, so it might actually be better to use combination 2a1 and choose a background color that goes with your app. 2b. Resize Problems from DWM Composition Fill At a certain point during the development of Aero, Microsoft added another live resize jitter problem on top of the all-Windows-version problem described above. Reading earlier StackOverflow posts, it is actually hard to tell when this problem was introduced, but we can say that: this problem definitely occurs in Windows 10 this problem almost certainly occurs in Windows 8 this problem may have also occurred in Windows Vista with Aero enabled (many posts with resize problems under Vista do not say if they have Aero enabled or not). this problem probably did not occur under Windows 7, even with Aero enabled. The problem revolves around a major change of architecture that Microsoft introduced in Windows Vista called DWM Desktop Composition . Applications no longer draw directly to the graphics framebuffer. Instead, all applications are actually drawing into an off-screen framebuffer which is then composited with the output of other apps by the new, evil Desktop Window Manager (DWM) process of Windows. So, because there is another process involved in displaying your pixels, there is another opportunity to mess up your pixels. And Microsoft would never miss such an opportunity. Here is what apparently happens with DWM Compostion: The user clicks the mouse on a window border and begins to drag the mouse Each time the user drags the mouse, this triggers the sequence of wndproc events in your application that we described in section 2a above. But, at the same time, DWM (which remember is a separate process that is runnning asynchronously to your app) starts its own deadline timer. Similarly to section 2a above, the timer apparently starts ticking after WM_NCCALCSIZE returns and is satisfied when your app draws and calls SwapBuffers() . If you do update your client area by the deadline, then DWM will leave your client area beautifully unmolested. There is still a definite chance that your client area could still get molested by the problem in section 2a, so be sure to read section 2a as well. If you do not update your client area by the deadline, then Microsoft will do something truly hideous and unbelievably bad (didn't Microsoft learn their lesson?): Suppose this is your client area before the resize, where A, B, C, and D represent pixel colors at the middle of your client area top, left, right, and bottom edges: --------------AAA----------------- | | B C B C B C | | --------------DDD----------------- Suppose you are using the mouse to enlarge your client area in both dimensions. Genius Windows DWM (or perhaps Nvidia: more on that later) will always copy the pixels of your client area to the upper-left corner of the new client area (regardless of which window border you are dragging) and then do the most absurd thing imaginable to the rest of the client area. Windows will take whatever pixel values used to be along the bottom edge of your client area, stretch them out to the new client area width (a terrible idea we explored in Section 1c2 of PART 1 , and replicate those pixels to fill in all the newly opened space at the bottom (see what happens to D). Then Windows will take whatever pixel values used to be along the right edge of your client area, stretch them out to the new client area height, and replicate them to fill in the newly opened space at the top-right: --------------AAA----------------------------------------------- | | | B C | B C | B CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | |CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC --------------DDD-----------------CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDD | | DDDDDDDDD | | DDDDDDDDD | | DDDDDDDDD | | DDDDDDDDD | ------------------------------DDDDDDDDD------------------------- I cannot even imagine what they were smoking. This behavior produces the worst possible result in many cases. First, it's almost guaranteed to generate the horrific back-and-forth motion we showed in Figure 1c3-3 and Figure 1c4-3 of PART 1 when dragging the left and top window borders, since the rectangle copied is always at the upper-left regardless of which window border you are dragging. Second, the even more ridulous thing that's happening with the edge pixels being replicated is going to produce ugly bars if you happen to have any pixels set there other than the background color. Notice how the bars of C and D created do not even line up with the original C and D from the copied old pixels. I can understand why they are replicating the edge, hoping to find background pixels there to "automate" the process of background color detection, but it seems the likelihood of this actually working is heavily outweighed by the hack factor and chance of failure. It would be better if DWM used the app's chosen "background color" (in WNDCLASS.hbrBackground ), but I suspect DWM might not have access to that info since DWM is in a different process, hence the hack. Sigh. But we haven't even gotten to the worst part yet: What actually is the deadline that DWM gives you to draw your own client area before DWM corrupts it with this clumsy hack of a guess? Apparently (from my experiments) the deadline is on the order of 10-15 milliseconds ! Given that 15 milliseconds is close to 1/60, I would guess that the deadline is actually the end of the current frame. And the vast majority of apps are unable to meet this deadline most of the time. That is why, if you launch Windows Explorer on Windows 10 and drag the left border, you will most likely see the scroll bar on the right jitter/flicker/jump around erratically as if Windows were written by a fourth grader. I cannot believe that Microsoft has released code like this and considers it "done." It is also possible that the responsible code is in the graphics driver (e.g. Nvidia, Intel, ...) but some StackOverflow posts led me to believe that this behavior is cross-device. There is very little you can do to prevent this layer of incompetence from generating hideous jitter/flicker/jump when resizing using the left or top window border. That is because the rude, non-consentual modification of your client area is happening in another process. I am really hoping that some StackOverflow user will come up with some magic DWM setting or flag in Windows 10 that we can make to either extend the deadline or disable the horrible behavior completely. But in the meantime, I did come up with one hack that somewhat reduces the frequency of the hideous back-and-forth artifacts during window resize. The hack, inspired by a comment in https://stackoverflow.com/a/25364123/1046167 , is to do a best-effort at synchronizing the app process with the vertical retrace that drives DWM's activity. Actually making this work in Windows is not trivial. The code for this hack should be the very last thing in your WM_NCCALCSIZE handler: LARGE_INTEGER freq, now0, now1, now2;QueryPerformanceFrequency(&freq); // hz// this absurd code makes Sleep() more accurate// - without it, Sleep() is not even +-10ms accurate// - with it, Sleep is around +-1.5 ms accurateTIMECAPS tc;MMRESULT mmerr;MMC(timeGetDevCaps(&tc, sizeof(tc)), {});int ms_granularity = tc.wPeriodMin;timeBeginPeriod(ms_granularity); // begin accurate Sleep() !QueryPerformanceCounter(&now0);// ask DWM where the vertical blank fallsDWM_TIMING_INFO dti;memset(&dti, 0, sizeof(dti));dti.cbSize = sizeof(dti);HRESULT hrerr;HRC(DwmGetCompositionTimingInfo(NULL, &dti), {});QueryPerformanceCounter(&now1);// - DWM told us about SOME vertical blank// - past or future, possibly many frames away// - convert that into the NEXT vertical blank__int64 period = (__int64)dti.qpcRefreshPeriod;__int64 dt = (__int64)dti.qpcVBlank - (__int64)now1.QuadPart;__int64 w, m;if (dt >= 0){ w = dt / period;}else // dt < 0{ // reach back to previous period // - so m represents consistent position within phase w = -1 + dt / period;}// uncomment this to see worst-case behavior// dt += (sint_64_t)(0.5 * period);m = dt - (period * w);assert(m >= 0);assert(m < period);double m_ms = 1000.0 * m / (double)freq.QuadPart;Sleep((int)round(m_ms));timeEndPeriod(ms_granularity); You can convince yourself that this hack is working by uncommenting the line that shows "worst-case" behavior by trying to schedule the drawing right in the middle of a frame rather than at vertical sync, and noticing how many more artifacts you have. You can also try varying the offset in that line slowly and you will see that artifacts abruptly disappear (but not completely) at about 90% of the period and come back again at about 5-10% of the period. Since Windows is not a real-time OS, it is possible for your app to bepreempted anywhere in this code, leading to inaccuracy in the pairing of now1 and dti.qpcVBlank . Preemption in this small code section is rare, but possible. If you want, you can compare now0 and now1 and loop around again if the bound is not tight enough. It is also possible for preemption to disrupt the timing of Sleep() or the code before or after Sleep() . There's not much you can do about this, but it turns out timing errors in this part of the code are swamped by the uncertian behavior of DWM; you are still going to get some window resize artifacts even if your timing is perfect. It's just a heuristic. There is a second hack, and it is an incredibly creative one: as explained in the StackOverflow post Can't get rid of jitter while dragging the left border of a window , you can actually create two main windows in your app, and every time Windows would do SetWindowPos , you intecept that and instead hide one window and show the other! I haven't tried this yet but the OP reports that it bypasses the insane pixel DWM pixel copy described above. There is a third hack, which might work depending on your application (especially in combination with the timing hack above). During live resizing (which you can detect by intercepting WM_ENTERSIZEMOVE/WM_EXITSIZEMOVE ), you could modify your drawing code to initially draw something much simpler that is much more likely to complete within the deadline imposed by problem 2a and 2b, and call SwapBuffers() to claim your prize: that will be enough to prevent Windows from doing the bad blit/fill described in section 2a and 2b. Then, immediately after the partial draw, do another draw that fully updates the window contents and call SwapBuffers() again. That might still look somewhat odd, since the user will see your window update in two parts, but it's likely to look much better than the hideous back-and-forth motion artifact from Windows. One more tantalizing point: some apps in Windows 10, including the console (start cmd.exe ), are rock-solid free of DWM Composition artifacts even when dragging the left border. So there is some way of bypassing the problem. Let's find it! 2c. How to Diagnose Your Problem As you try to solve your particular resize problem, you may wonder which of the overlapping effects from Section 2a and Section 2b you are seeing. One way to separate them is to debug on Windows 7 (with Aero disabled, just to be safe) for a bit. Another way to quickly identify if you are seeing the problem in Section 2b is to modify your app to display the test pattern described in Section 2b, like this example (note the 1-pixel-thin colored lines on each of the four edges): Then grab any window border and start resizing that border rapidly. If you see intermittent giant colored bars (blue or green bars in the case of this test pattern, since there is blue on the bottom edge and green on the right edge) then you know you are seeing the problem in Section 2b. You can test if you are seeing the problem in Section 2a by setting WNDCLASS.hbrBackground to a distinct background color, like red. As you resize the window, newly exposed parts will show up with that color. But read through Section 2a to make sure your message handlers are not causing Windows to BitBlt the entire client area, which would cause Windows not to draw any background color. Remember that the problems in Section 2a and 2b only show up if your app fails to draw by a certain deadline, and each problem has a different deadline. So, without modification, your app might show the Section 2b problem only, but if you modify your app to draw more slowly (insert Sleep() in WM_PAINT before SwapBuffers() for example), you may miss the deadline for both Section 2a and Section 2b and start to see both problems simultaneously. This may also happen when you change your app between a slower DEBUG build and a RELEASE build, which can make chasing these resize problems very frustrating. Knowing what's going on under the hood can help you deal with the confusing results.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53000291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1046167/']}
jdg_373728
stackexchange
llm_judgeable_groundtruth_similarity
39249907
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 change the background color of an activity using a handler, but I am getting an error "Attempt to invoke virtual method". Here is my code public class MainActivity extends AppCompatActivity {private EditText editTextUser, editTextPass;private RelativeLayout relativeLayoutMain;private Random random = new Random();Intent intent;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); relativeLayoutMain = (RelativeLayout) findViewById(R.id.relativeLayoutMain); Button btnSignIn = (Button) findViewById(R.id.buttonSignIn); btnSignIn.setEnabled(false); handler.postDelayed(runner, 2000); Button buttonSignUp = (Button) findViewById(R.id.buttonSignUp); buttonSignUp.setText("Not registered? CLICK HERE"); editTextUser = (EditText) findViewById(R.id.editTextUser); editTextPass = (EditText) findViewById(R.id.editTextPassword); if (editTextUser.getText().toString() != null && editTextPass.getText().toString() != null) { btnSignIn.setEnabled(true); }}android.content.res.Resources res = getResources();int[] clrItems = res.getIntArray(R.array.color_background);List<int[]> arrayOfColor = new ArrayList<int[]>();public List<int[]> getArrayOfColor() { arrayOfColor.add(clrItems); return arrayOfColor;}Runnable runner = new Runnable() { @Override public void run() { Log.e("run: ", "call"); Bitmap bitmap = Bitmap.createBitmap(612, 612, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); final int clr = 0xFF424242; final Paint paint = new Paint(); final Rect destRect = new Rect((612-bitmap.getWidth())/2, 24, (612)-(612-bitmap.getWidth())/2, 612-24); final RectF rectF = new RectF(destRect); final Rect srcRect = new Rect(0, 0, bitmap.getWidth(), 612); final float roundPx = 612; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(clr); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, srcRect, destRect, paint); GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{0xFF616261, 0xFF131313}); gd.setCornerRadius(0f); relativeLayoutMain.setBackground(gd); handler.postDelayed(runner, 4000); }};public void login(View view) { intent = new Intent(this, HomeActivity.class); startActivity(intent);}public void register(View view) { intent = new Intent(this, SignUpActivity.class); startActivity(intent);}} And here is my logcat. 08-31 16:29:47.122 13152-13152/com.example.salimshivani.student E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.salimshivani.student, PID: 13152 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.salimshivani.student/com.example.salimshivani.student.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) at android.app.ActivityThread.access$1100(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.content.ContextWrapper.getResources(ContextWrapper.java:92) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81) at com.example.salimshivani.student.MainActivity.<init>(MainActivity.java:241) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1096) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)  at android.app.ActivityThread.access$1100(ActivityThread.java:229)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:7325)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Please help me where i am wrong to move the backgroundColor constantly of the activity. Thanks in advance Now provide the response and nothing else.
You invoke the method getResources() as part of the class initialisation (outside of any method, so it will be executed as part of the constructor) At this point, the Activity instance does not yet exist so it may not call methods which require the existence of the instance. Statements which will cause an Exception because they take advantage of the fact that an Activity is a kind of Context : android.content.res.Resources res = getResources(); int[] clrItems = res.getIntArray(R.array.color_background); The following statement on the other hand will not cause problems because it's just plain old Java: List arrayOfColor = new ArrayList(); Simply paste the "problem statements" into a method, e.g. onCreate() // declare hereandroid.content.res.Resources res;int[] clrItems; @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise here res = getResources(); clrItems = res.getIntArray(R.array.color_background); relativeLayoutMain = (RelativeLayout) findViewById(R.id.relativeLayoutMain); Button btnSignIn = (Button) findViewById(R.id.buttonSignIn); btnSignIn.setEnabled(false); ...}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39249907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4632372/']}
jdg_373729
stackexchange
llm_judgeable_groundtruth_similarity
28157643
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 this list of buttons button { background-color: grey; color: #fff; border: none; border-radius: 2px; box-shadow: 1px 1px 0 0.8px #C0CBD1; height: 30px; margin: 0; padding: 0; position: relative; width: 30px; font: 500 16px/36px sans-serif;}.special { font-size: 30px;} <button>A</button><button>B</button><button class="special">C</button> Now what I've done is that the special button has a bigger font-size. The weird thing is that increasing the font-size moves this button up. I guess this is all very logic but cannot find the explanation (which should help me to fix this of course!) Now provide the response and nothing else.
The explanation is that buttons are inline-element, and the text in the button determines the vertical alignment. The default vertical alignment for inline elements is to place the bottom of characters on the base line of the text. If you look at the buttons in your example, you see that the bottom of the characters line up exactly. If you add some text around the buttons, you see that the text of the buttons aligns with the text outside the buttons: http://jsfiddle.net/Guffa/q640e8sc/4/ If you specify a different verical alignment for the buttons, they will line up differently. If you for example use vertical-align: middle; , the buttons will line up at the center of the characters, so the edges of the buttons will line up: http://jsfiddle.net/Guffa/q640e8sc/5/ Another way to avoid that alignment is to make the buttons block elements, for example using float: left; . That makes the buttons line up, but it of course make the buttons react differently to surrounding elements: http://jsfiddle.net/Guffa/q640e8sc/6/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28157643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419425/']}
jdg_373730
stackexchange
llm_judgeable_groundtruth_similarity
14423325
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 R predict.lm computes predictions based on the results from linear regression and also offers to compute confidence intervals for these predictions. According to the manual, these intervals are based on the error variance of fitting, but not on the error intervals of the coefficient. On the other hand predict.glm which computes predictions based on logistic and Poisson regression (amongst a few others) doesn't have an option for confidence intervals. And I even have a hard time imagining how such confidence intervals could be computed to provide a meaningful insight for Poisson and logistic regression. Are there cases in which it is meaningful to provide confidence intervals for such predictions? How can they be interpreted? And what are the assumptions in these cases? Now provide the response and nothing else.
The usual way is to compute a confidence interval on the scale of the linear predictor, where things will be more normal (Gaussian) and then apply the inverse of the link function to map the confidence interval from the linear predictor scale to the response scale. To do this you need two things; call predict() with type = "link" , and call predict() with se.fit = TRUE . The first produces predictions on the scale of the linear predictor, the second returns the standard errors of the predictions. In pseudo code ## foo <- mtcars[,c("mpg","vs")]; names(foo) <- c("x","y") ## Working example datamod <- glm(y ~ x, data = foo, family = binomial)preddata <- with(foo, data.frame(x = seq(min(x), max(x), length = 100)))preds <- predict(mod, newdata = preddata, type = "link", se.fit = TRUE) preds is then a list with components fit and se.fit . The confidence interval on the linear predictor is then critval <- 1.96 ## approx 95% CIupr <- preds$fit + (critval * preds$se.fit)lwr <- preds$fit - (critval * preds$se.fit)fit <- preds$fit critval is chosen from a t or z (normal) distribution as required (I forget exactly now which to use for which type of GLM and what the properties are) with the coverage required. The 1.96 is the value of the Gaussian distribution giving 95% coverage: > qnorm(0.975) ## 0.975 as this is upper tail, 2.5% also in lower tail[1] 1.959964 Now for fit , upr and lwr we need to apply the inverse of the link function to them. fit2 <- mod$family$linkinv(fit)upr2 <- mod$family$linkinv(upr)lwr2 <- mod$family$linkinv(lwr) Now you can plot all three and the data. preddata$lwr <- lwr2 preddata$upr <- upr2 ggplot(data=foo, mapping=aes(x=x,y=y)) + geom_point() + stat_smooth(method="glm", method.args=list(family=binomial)) + geom_line(data=preddata, mapping=aes(x=x, y=upr), col="red") + geom_line(data=preddata, mapping=aes(x=x, y=lwr), col="red")
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14423325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695064/']}
jdg_373731
stackexchange
llm_judgeable_groundtruth_similarity
7814688
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 Java, what purpose do the keywords final , finally and finalize fulfil? Now provide the response and nothing else.
final final can be used to mark a variable "unchangeable" private final String name = "foo"; //the reference name can never change final can also make a method not "overrideable" public final String toString() { return "NULL"; } final can also make a class not "inheritable". i.e. the class can not be subclassed. public final class finalClass {...}public class classNotAllowed extends finalClass {...} // Not allowed finally finally is used in a try/catch statement to execute code "always" lock.lock();try { //do stuff} catch (SomeException se) { //handle se} finally { lock.unlock(); //always executed, even if Exception or Error or se} Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable finalize finalize is called when an object is garbage collected. You rarely need to override it. An example: protected void finalize() { //free resources (e.g. unallocate memory) super.finalize();}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7814688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976615/']}
jdg_373732
stackexchange
llm_judgeable_groundtruth_similarity
16079235
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: FileA.hpp:static int a; void change(int);FileA.cpp#include "FileA.hpp"void change(int x) { a = x; }main.cpp#include "FileA.hpp"#include <cstdlib>#include <iostream>int main(){ a = 5; std::cout<<a<<std::endl; change(10); std::cout<<a<<std::endl; a = 20; std::cout<<a<<std::endl; system("Pause"); return 0;} My output is: 5520 Can someone help me with this? Why variable 'a' don't want to change in functionwhich is in FileA.cpp.How to fix this. When I make change(int x) inline in "FileA.hpp" it works fine. Now provide the response and nothing else.
The static keyword on a global variable gives that variable internal linkage. It means that any translation unit that has that definition will have its own copy of the object. So the a object that main.cpp sees and that FileA.cpp sees are different objects. change will modify one of them, but main will output the other. If you were intending static to mean that the object has static storage duration, global variables (or variables at namespace scope in general) have static storage duration anyway. You don't need to mark them static . However, if you remove static , you'll have another problem; you'll have multiple definitions of a across translation units. The correct way to do this is to declare a as extern in the FileA.hpp file: extern int a; Then in a single translation unit (probably in FileA.cpp , define the object: int a; This means that any object that includes FileA.hpp will have the declaration of a (which is fine) and only one translation unit will have the definition of a . Perfect.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16079235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2294235/']}
jdg_373733
stackexchange
llm_judgeable_groundtruth_similarity
20338068
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: 1 - I have this file content on the disc (cs file, not compiled): namespace Test { using System; public class TestClass { public string SomeTestMethod(){ return "test here"; } } } How do I get in run time into a variable the method: public string SomeTestMethod(){ return "test here";} for example: SourceCodeParser.GetMothod("path to file","SomeTestMethod"); 2 - Is it possible the content of accessor member? public string SomeMember { get { return "test here"; } } Now provide the response and nothing else.
Roslyn is what you need. You can easily install it using nuget . Here is a working code for getting a method body: string GetMethod(string filename, string methodName){ var syntaxTree = SyntaxTree.ParseFile(filename); var root = syntaxTree.GetRoot(); var method = root.DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(md => md.Identifier.ValueText.Equals(methodName)) .FirstOrDefault(); return method.ToString();} and code for getting body of property getter: string GetPropertyGetter(string filename, string propertyName){ var syntaxTree = SyntaxTree.ParseFile(filename); var root = syntaxTree.GetRoot(); var property = root.DescendantNodes() .OfType<PropertyDeclarationSyntax>() .Where(md => md.Identifier.ValueText.Equals(propertyName)) .FirstOrDefault(); var getter = property.AccessorList.Accessors.First(a => a.Kind == SyntaxKind.GetAccessorDeclaration); return getter.ToString();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20338068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/936651/']}
jdg_373734
stackexchange
llm_judgeable_groundtruth_similarity
19071601
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Python and trying to do something I do often in Ruby. Namely, iterating over a set of indices, using them as argument to function and comparing its results with an array of fixture outputs. So I wrote it up like I normally do in Ruby, but this resulted in just one test case. def test_output(self): for i in range(1,11): .... self.assertEqual(fn(i),output[i]) I'm trying to get the test for every item in the range. How can I do that? Now provide the response and nothing else.
Using unittest you can show the difference between two sequences all in one test case. seq1 = range(1, 11)seq2 = (fn(j) for j in seq1)assertSequenceEqual(seq1, seq2) If that's not flexible enough, using unittest, it is possible to generate multiple tests, but it's a bit tricky. def fn(i): ...output = ...class TestSequence(unittest.TestCase): passfor i in range(1,11): testmethodname = 'test_fn_{0}'.format(i) testmethod = lambda self: self.assertEqual(fn(i), output[i]) setattr(TestSequence, testmethodname, testmethod) Nose makes the above easier through test generators . import nose.toolsdef test_fn(): for i in range(1, 11): yield nose.tools.assert_equals, output[i], fn(i) Similar questions: Python unittest: Generate multiple tests programmatically? How to generate dynamic (parametrized) unit tests in python?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19071601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32816/']}
jdg_373735
stackexchange
llm_judgeable_groundtruth_similarity
534454
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Since 02.05.2013 some sort of bot is visiting my website, every 5 minutes. Most of the time it calls this URL, which doesn't exist: /viewtopic.php?f=3&t=849 Always with this user agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler ; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727) (= IE 6, Windows XP) Not only it distorts the visitors statistic significantly, it doesn't even identify as a bot, so I guess it is a spammer of some sort. My question here is, what does this client do and why is it calling this page continuously? - And how can I prevent this? I'm using a vServer with Linux Debian. Now provide the response and nothing else.
What does this client do? Difficult to know, but just for curiosity I'd set up a PHP script at that url to play with your pal: get the client IP address and scan it immediately (open ports, reverse address, whois information on the netblock) dump HTTP headers to look into them. If it sends a referrer maybe it's coming from somewhere else. Look for other interesting things. reply with an HTTP redirect to some URL you manage and see if it follows it. Just to know... reply with some Javascript and see if it executes it if you have lots of bandwidth try replying with some gigabytes of garbage :) (and while you're at it, measure how fast he can digest data) when you're bored of playing with him then go tarpitting him (if you have enough resources): everytime it connects enter some long sleep() before completing the HTTP reply. Make him consume more resources. why is it calling this page continuously? Did you try to ask Google? Seems like Tencent Traveler is one of the most popular browser in China. Maybe someone with it visited your site, or tried to visit invalid URLs on your site, maybe there's a spider run by the software house trying to index / scan / cache the sites visited by its browser users. Or maybe it's just a chinese bored boy, or maybe an infected PC, or... who knows, you should also ask him directly, but you need to know who he is. And how can I prevent this? To actually prevent him for trying, you should report it as a spammer to someone/something that has authority over him. Usually this is the Technical Contact (or tech-c, or abuse, or whatever they call it) of the AS responsible for its IP range. You can find that piece of information from whois. If prevention does not succeed and it keeps doing those requests, you can block them in various ways: if they come from a single subnet and you're not interested in that public, block the whole subnet at the IP level (eg. if it comes from a Chinese /8 subnet and you don't mind blocking chinese clients, simply drop traffic from the whole subnet) block all requests matching that User-Agent at the HTTP level if you have no known legitimate users with the very same User-Agent. Why do these aggressive bots always come from China or Russia? Ahhh, life would be easier if that was actually true ;) it distorts the visitors statistic significantly You're talking about one hit per 5 minutes, or roughly 0.003hit/second - should be well below the noise floor.. Please rephrase your question and explain what you mean by "distorts".
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/534454', 'https://serverfault.com', 'https://serverfault.com/users/179708/']}
jdg_373736
stackexchange
llm_judgeable_groundtruth_similarity
5237693
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 source code that opens a csv file and sets up a header to value association. The source code is given below: def ParseCsvFile(source): """Parse the csv file. Args: source: file to be parsed Returns: the list of dictionary entities; each dictionary contains attribute to value mapping or its equivalent. """ global rack_file rack_type_file = None try: rack_file = source rack_type_file = open(rack_file) # Need to mock this line. headers = rack_type_file.readline().split(',') length = len(headers) reader = csv.reader(rack_type_file, delimiter=',') attributes_list=[] # list of dictionaries. for line in reader: # More process to happeng. Converting the rack name to sequence. attributes_list.append(dict((headers[i], line[i]) for i in range(length))) return attributes_list except IOError, (errno, strerror): logging.error("I/O error(%s): %s" % (errno, strerror)) except IndexError, (errno, strerror): logging.error('Index Error(%s), %s' %(errno, strerror)) finally: rack_type_file.close() I am trying to mock the following statement rack_type_file = open(rack_file) How do I mock open(...) function? Now provide the response and nothing else.
This is admittedly an old question, hence some of the answers are outdated. In the current version of the mock library there is a convenience function designed for precisely this purpose . Here's how it works: >>> from mock import mock_open>>> m = mock_open()>>> with patch('__main__.open', m, create=True):... with open('foo', 'w') as h:... h.write('some stuff')...>>> m.mock_calls[call('foo', 'w'), call().__enter__(), call().write('some stuff'), call().__exit__(None, None, None)]>>> m.assert_called_once_with('foo', 'w')>>> handle = m()>>> handle.write.assert_called_once_with('some stuff') Documentation is here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5237693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300327/']}
jdg_373737
stackexchange
llm_judgeable_groundtruth_similarity
17158933
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 do a Form where the user has to click at least one option of the ones given on the ListCheckBox in order to enable a sort of "Next" button. However, its not working as expected since, sometimes, the button is enabled while there is no option chosen. This is the code of the class where I do the validations: class CampoCheckedListBox : AbstractCampo{ private CheckedListBox checkedListBox { get; set; } private string nombre { get; set; } private bool obligatorio { get; set; } public CampoCheckedListBox(string nom, CheckedListBox controller, bool oblig) { this.checkedListBox = controller; this.nombre = nom; this.obligatorio = oblig; } public override void validar() { string mensaje = ""; if (this.obligatorio && checkedListBox.CheckedItems.Count==0) { mensaje += "-Seleccione al menos una de las opciones de " + this.nombre + "." + Environment.NewLine; throw new ValidationException(mensaje); } }} In my form: private void validarCampos() { List<AbstractCampo> campos = new List<AbstractCampo>(); campos.Add(new Campo("Nombre", tBoxRol.Text, true, Controller.TipoValidacion.Alfanumerico)); campos.Add(new CampoCheckedListBox("Funcionalidades", chkBoxFuncionalidades, true)); try { Controller.validarCampos(campos); darAlta_button.Enabled = true; errorBox.Text = ""; } catch (ValidationException vEx) { errorBox.Text = vEx.mensaje; darAlta_button.Enabled = false; } } Controller.validarCampos() just takes each object from a list and send message validar();And I call this validarCampos() in the SelectedIndexChanged event on the ListCheckBox. There are sometimes that I check an option and the button isnt enabled. But if I uncheck the same option and then check it again the button gets enabled. I am pretty lost here... Now provide the response and nothing else.
I've banged my head against a wall until I found out what's happening here. Background information Using .load() isn't possible if the iframe has already been loaded (event will never fire) Using .ready() on an iframe element isn't supported ( reference ) and will call the callback immediately even if the iframe isn't loaded yet Using postMessage or a calling a container function on load inside the iframe is only possible when having control over it Using $(window).load() on the container would also wait for other assets to load, like images and other iframes. This is not a solution if you want to wait only for a specific iframe Checking readyState in Chrome for an alredy fired onload event is meaningless, as Chrome initializes every iframe with an "about:blank" empty page. The readyState of this page may be complete , but it's not the readyState of the page you expect ( src attribute). Solution The following is necessary: If the iframe is not loaded yet we can observe the .load() event If the iframe has been loaded already we need to check the readyState If the readyState is complete , we can normally assume that the iframe has already been loaded. However, because of the above-named behavior of Chrome we furthermore need to check if it's the readyState of an empty page If so, we need to observe the readyState in an interval to check if the actual document (related to the src attribute) is complete I've solved this with the following function. It has been (transpiled to ES5) successfully tested in Chrome 49 Safari 5 Firefox 45 IE 8, 9, 10, 11 Edge 24 iOS 8.0 ("Safari Mobile") Android 4.0 ("Browser") Function taken from jquery.mark /** * Will wait for an iframe to be ready * for DOM manipulation. Just listening for * the load event will only work if the iframe * is not already loaded. If so, it is necessary * to observe the readyState. The issue here is * that Chrome will initialize iframes with * "about:blank" and set its readyState to complete. * So it is furthermore necessary to check if it's * the readyState of the target document property. * Errors that may occur when trying to access the iframe * (Same-Origin-Policy) will be catched and the error * function will be called. * @param {jquery} $i - The jQuery iframe element * @param {function} successFn - The callback on success. Will * receive the jQuery contents of the iframe as a parameter * @param {function} errorFn - The callback on error */var onIframeReady = function($i, successFn, errorFn) { try { const iCon = $i.first()[0].contentWindow, bl = "about:blank", compl = "complete"; const callCallback = () => { try { const $con = $i.contents(); if($con.length === 0) { // https://git.io/vV8yU throw new Error("iframe inaccessible"); } successFn($con); } catch(e) { // accessing contents failed errorFn(); } }; const observeOnload = () => { $i.on("load.jqueryMark", () => { try { const src = $i.attr("src").trim(), href = iCon.location.href; if(href !== bl || src === bl || src === "") { $i.off("load.jqueryMark"); callCallback(); } } catch(e) { errorFn(); } }); }; if(iCon.document.readyState === compl) { const src = $i.attr("src").trim(), href = iCon.location.href; if(href === bl && src !== bl && src !== "") { observeOnload(); } else { callCallback(); } } else { observeOnload(); } } catch(e) { // accessing contentWindow failed errorFn(); }}; Working example Consisting of two files (index.html and iframe.html): index.html : <!doctype html><html><head> <meta charset="utf-8"> <title>Parent</title></head><body> <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script> <script> $(function() { /** * Will wait for an iframe to be ready * for DOM manipulation. Just listening for * the load event will only work if the iframe * is not already loaded. If so, it is necessary * to observe the readyState. The issue here is * that Chrome will initialize iframes with * "about:blank" and set its readyState to complete. * So it is furthermore necessary to check if it's * the readyState of the target document property. * Errors that may occur when trying to access the iframe * (Same-Origin-Policy) will be catched and the error * function will be called. * @param {jquery} $i - The jQuery iframe element * @param {function} successFn - The callback on success. Will * receive the jQuery contents of the iframe as a parameter * @param {function} errorFn - The callback on error */ var onIframeReady = function($i, successFn, errorFn) { try { const iCon = $i.first()[0].contentWindow, bl = "about:blank", compl = "complete"; const callCallback = () => { try { const $con = $i.contents(); if($con.length === 0) { // https://git.io/vV8yU throw new Error("iframe inaccessible"); } successFn($con); } catch(e) { // accessing contents failed errorFn(); } }; const observeOnload = () => { $i.on("load.jqueryMark", () => { try { const src = $i.attr("src").trim(), href = iCon.location.href; if(href !== bl || src === bl || src === "") { $i.off("load.jqueryMark"); callCallback(); } } catch(e) { errorFn(); } }); }; if(iCon.document.readyState === compl) { const src = $i.attr("src").trim(), href = iCon.location.href; if(href === bl && src !== bl && src !== "") { observeOnload(); } else { callCallback(); } } else { observeOnload(); } } catch(e) { // accessing contentWindow failed errorFn(); } }; var $iframe = $("iframe"); onIframeReady($iframe, function($contents) { console.log("Ready to got"); console.log($contents.find("*")); }, function() { console.log("Can not access iframe"); }); }); </script> <iframe src="iframe.html"></iframe></body></html> iframe.html : <!doctype html><html><head> <meta charset="utf-8"> <title>Child</title></head><body> <p>Lorem ipsum</p></body></html> You can also change the src attribute inside index.html to e.g. " http://example.com/ ". Just play around with it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17158933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1784434/']}
jdg_373738
stackexchange
llm_judgeable_groundtruth_similarity
15295677
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's been a while since I last visited arrays (I've been working with vectors recently) and I need to convert an 2D vector back into a 2D array because of a library I am using accepts the paramaters of type double array where the accessors of this array is foo[i][j] for example. Here is my code: double** setupHMM(vector<vector<double> > &vals, int N, int M){ double** temp; temp = new double[N][M]; for(unsigned i=0; (i < N); i++) { for(unsigned j=0; (j < M); j++) { temp[i][j] = vals[i][j]; } }} And with this, I get error: ‘M’ cannot appear in a constant-expression I have also tried the following: double** setupHMM(vector<vector<double> > &vals, int N, int M){ double** temp; for(unsigned i=0; (i < N); i++) { temp[i] = new double[N]; for(unsigned j=0; (j < M); j++) { temp[j] = new double[M]; temp[i][j] = vals[i][j]; } } } However, this produces a segmentation fault 11. Could anyone suggest any advice, or, a better way to convert a vector to a 2D array.. Thanks Now provide the response and nothing else.
You were close. It should be: double** setupHMM(vector<vector<double> > &vals, int N, int M){ double** temp; temp = new double*[N]; for(unsigned i=0; (i < N); i++) { temp[i] = new double[M]; for(unsigned j=0; (j < M); j++) { temp[i][j] = vals[i][j]; } } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15295677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1582478/']}
jdg_373739
stackexchange
llm_judgeable_groundtruth_similarity
30589219
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 use Firebug for web development. Since version Firefox 37 I see the following annoying message in my console: This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1" I understand that it is an important message, but it is duplicated many times and makes my work almost impossible.Moreover, it appears every time my page communicates with other pages, for example with Google Analytics and other counters. So if I were to update my certificate, this message would still appear because these sites would have SHA-1.So any site with GA gives me trouble. How can I disable or filter this message? Now provide the response and nothing else.
you can get rid of the message, but you have to modify firebugs code. Sorry forgot to mention you need to convert the .xpi to .zip and extract the files first. You can leave the folder as is when done or zip it and convert it to an xpi again. You will need to restart Firefox. locate the pluggin in your firefox profile dirctor and go to this file "\extensions\firebug@software.joehewitt.com\content\firebug\console\errors.js". search for "logScriptError: function(context, object, isWarning)". After the code "var error = new ErrorMessageObj(object.errorMessage, object.sourceName, object.lineNumber, object.sourceLine, category, context, null);". input the following code: if(error.message.indexOf('SHA-1') != -1 || error.message.indexOf('Security Policy') != -1){ return false; } should be about line 330.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30589219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4457681/']}
jdg_373740