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
5096538
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple geom_point plot, in which the x variable is ordinal, taking 5 values (coded 1:5). In the plot I would like to replace it with 5 corresponding text labels. Is it possible to do it in ggplot? Now provide the response and nothing else.
You should be able to do this with scale_x_discrete . library(ggplot2)df <- data.frame(x = 1:5, y = sample(1:10, 5, TRUE))qplot(factor(x),y, data = df) + scale_x_discrete(breaks = 1:5, labels=c("foo","bar","baz","phi","fum")) +xlab(NULL)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5096538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143813/']}
jdg_78141
stackexchange
llm_judgeable_groundtruth_similarity
7044671
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 fixed navigation at the top of the page that has links that smoothly scroll you around to different sections (IDs) of the page via jQuery. Would there be any possible way to have a css class (e.g. .current) appended to the navigation links depending on what section of the page you're at? For example, when I click "About", it'll scroll down to the About section and also make the navigation text orange as long as you stay in that section? I've seen this done somewhere a while ago but I don't remember the website or even how to describe this behavior to search for it. EDIT: Here's a link to something siliar to what I'm looking for: http://www.fat-man-collective.com/hello.php The icons change depending on your position on the page. Script: <script> function goToByScroll(id){ $('html,body').animate({scrollTop: $("#"+id).offset().top - 50},'500'); }</script> HTML: <a href="javascript:void(0)" onClick="goToByScroll('about')">About</a>[...]<div id="about"> [...]</div> Any help is greatly appreciated. Now provide the response and nothing else.
If you are using a bitboard for each player, you can use bit shift operations to test a board for a win. The bitboard would have following structure: 6 14 22 30 38 46 545 13 21 29 37 45 534 12 20 28 36 44 523 11 19 27 35 43 512 10 18 26 34 42 501 9 17 25 33 41 490 8 16 24 32 40 48 If the player occupies a position in the game board, then the associated bit would be 1 otherwise 0 (notice that bits 7, 15, 23, ... are 0 ). To check if the player has a winning board you could use following function: bool haswon(int64_t board){ int64_t y = board & (board >> 7); if (y & (y >> 2 * 7)) // check \ diagonal return true; y = board & (board >> 8); if (y & (y >> 2 * 8)) // check horizontal - return true; y = board & (board >> 9); if (y & (y >> 2 * 9)) // check / diagonal return true; y = board & (board >> 1); if (y & (y >> 2)) // check vertical | return true; return false;} With the help of a example I will try to explain: The following bitboard of one player includes beside vertical and diagonal wins a winning combination in the first row. 0101010111011101110111101110000100010101010011110 ... four occupied positions --> winning board The steps for the horizontal check are: y = board & (board >> 8) 0101010 0010101 00000001110111 0111011 01100110111011 0011101 00110011101110 & 0110111 = 01001100001000 0000100 00000001010101 0101010 00000000011110 0001111 0001110 y & (y >> 2 * 8) 0000000 0000000 00000000110011 0001100 00000000011001 0000110 00000000100110 & 0001001 = 00000000000000 0000000 00000000000000 0000000 00000000001110 0000011 0000010 The horizontal check results in a board with one bit set, this means the board includes a win and the function returns true . I have used a similar function to check a connect four game for a win. I saw this fascinating function in the sources to The Fhourstones Benchmark from John Tromp.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7044671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892131/']}
jdg_78142
stackexchange
llm_judgeable_groundtruth_similarity
5981508
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 access the database of an app from another Heroku app. Is that possible in the shared database? Now provide the response and nothing else.
UPDATED Originally, this answer stated that although this was possible with a few tricks, it was strongly discouraged. This was based on advice on the Heroku developer support website. However, recently Heroku issued a communication specifically describing how to achieve this, and have watered down their advice on the developer site. The complete text of this section of their e-mail is included below: Did you know that Heroku apps can share a common database? For example, you can put analytics functions in a separate application from your user-facing code. Simply set the DATABASE_URL config var for several apps to the same value. First, get the DATABASE_URL for your existing app: $ heroku config | grep DATABASE_URL --app sushi DATABASE_URL => postgres://lswlmfdsfos:[email protected]/ldfoiusfsf Then, set the DATABASE_URL for new apps to this value: $ heroku config:add DATABASE_URL=postgres://lswlmfdsfos:[email protected]/ldfoiusfsf --app sushi-analyticsAdding config vars: DATABASE_URL => postgres://lswlm...m/ldfoiusfsf Restarting app... done, v74. That's it — now both apps will share one database. Just as a point of reference, Heroku's original advice was to create and use an API to access data remotely. My personal view is that overall, for many situations this is good advice , (i.e. better than just connecting multiple application to the same DB) although I can see situations where that'd be more trouble than it's worth. UPDATE As per comments on this answer, it's worth noting that Heroku do reserve the right to change database URLs as required. If this occurs, it will cause your secondary connections to fail, and you'll need to update the URLs accordingly.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5981508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435951/']}
jdg_78143
stackexchange
llm_judgeable_groundtruth_similarity
14888
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Approximately, how many families have been identified? I've often often come across figures for the total number of species on Earth. Recently, I found myself wondering about the encompassing ranks above them, specifically family, but I can't recall any figures on family and it's a little difficult finding what I want by typing "family" into a Google search. ;) Now provide the response and nothing else.
The 2011 paper How Many Species Are There on Earth and in the Ocean? indirectly answers this question as well as any other source you'll find I imagine. It estimates how many species there are total based on the rate of discovery of higher taxa; it includes plots of number of taxa over time for the major groups of life in Figure S1. Which gives: Animalia - 5300 families in 2011 (the plots are given with only one significant figure, the second one's my estimate) (estimated total: 5800) Chromista - 270 families (estimated total: 360) Fungi - 550 families (estimated total: 620) Plantae - 750 families (estimated total: 800) Protozoa - 280 families (estimated total: 310) Archaea - 27 families (no estimated total; the number has been increasing exponentially so far) Bacteria - 300 families (same as for Archaea) Which gives us a total of 7477 families in 2011, with an estimated total of (ignoring Archaea and Bacteria, who don't really fall in the same kind of classification anyway) 7890 families. (make that 7500 families discovered by 2011 and 8000 estimated in total given the imprecision involved in my reading the plots).
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/14888', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/5366/']}
jdg_78144
stackexchange
llm_judgeable_groundtruth_similarity
26978
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Raw Food Family, with almost half a million likes, made this post on June 15, 2014. It claims, In 1955, Crest became the first fluoride toothpaste. Fluoride calcifies the pineal gland, otherwise known as your 3rd eye which literally has rods and cones, just like your other eyes! Fluoride is so toxic that it [sic] considered Hazardous Waste by the EPA. Hitler fluoridated the water in the concentration camps to sedate the prisoners. ( FALSE ) Fluoride is the same ingredient in rat poison and Prozac According to Dr. Bill Osmunson, there's the same equivalence of fluoride in an 8 ounce glass of fluoridated tap water as there is in a "pea sized" amount needed to call the Poison Control Center, as recommended on the back of any fluoridated toothpaste. Is there fluoride in rat poison and Prozac? Now provide the response and nothing else.
"Fluoride" is fluoride-containing compounds, such as sodium fluoride or sodium monofluorophosphate . Prozac aka the fluoxetine molecule contains fluorine atoms . The first "rat poison" I thought of was warfarin which doesn't contain fluorine atoms , but looking through a list of other rat poisons there's at least one i.e. fluoroacetamide which does. Although it's true I think it is a slightly silly statement (perhaps analogous to saying that meat and broccoli contain carbon atoms which are an ingredient of the Ebola virus). Fluorine is chemically similar to chlorine (i.e. they are both halogens ). Chlorine too could be used to make dangerous substances, e.g. poison gas, but it's also a main ingredient of common table salt aka sea salt aka sodium chloride. One of the comments to/below this answer said that it's important to: Learn that the dose makes the poison Have a sense of proportion about the amount of fluorine being talked about The adage that the dose makes the poison has been known for at least 500 years . People can even die from having too much water , but that fact must not be used as an argument to stop ingesting water. That adage about 'the dose' happens to be true of an actual "rat poison" too, where for example warfarin (introduced in 1948 as a pesticide against rats and mice) is prescribed medicinally to humans (in carefully administered doses) as an anticoagulant e.g. to treat thrombosis. That's not to say though "that fluoride is a rat poison" is true. Fluorine is an atom, one the elements, which can be used to make diverse chemical compounds (most of which are not rat poison). It's probably better to view fluoride as a type of salt or mineral.It is true that excessive fluoride is bad for you. This kind of 'excessive' fluoride can occur naturally in some water, or occur as a result of industrial contamination: but the amount of fluoride that's recommended when it's added to drinking water is not 'excessive'. Fluoride is a component of the human body : Fluoride anions are found in ivory, bones, teeth, blood, eggs, urine, and hair of organisms. Fluoride anions in very small amounts are essential for humans. There are 0.5 milligrams per liter of fluorine in human blood. Human bones contain 0.2 to 1.2% fluorine. Human tissue contains approximately 50 parts per billion of fluorine. A typical 70-kilogram human contains 3 to 6 grams of fluorine. Note the quantity that is usually in the human body: i.e. 3 to 6 grams . The amount of fluorine in fluoridated drinking water is relatively small : The World Health Organization recommends a guideline maximum fluoride value of 1.5 mg/L as a level at which fluorosis should be minimal. 1.5 mg/L is equivalent to 1.5 g/ton, (i.e. a ton of drinking water to get 1.5 grams of fluorine). One more comment -- even though original research and theoretical answers are not allowed I hope these (trivial) calculations may be allowed. Toothpaste typically contains less than 1,500 ppm F (I see mine contains 1,440 ppm). The Parts-per notation means by weight: Therefore, it is common to equate 1 gram of water with 1 mL of water. Consequently, ppm corresponds to 1 mg/L Therefore toothpaste has approximately 1000 times the concentration as the maximum recommended concentration in water (which was quoted as "1.5 mg/L" above). A "pea-sized" spot of toothpaste might be about 1 cubic centimetre i.e. 1 gram. An "eight-ounce" glass is water is about 200 grams. So the following statement seems to be to be true, within about a factor of 5: an 8 ounce glass of fluoridated tap water as there is in a "pea sized" amount (My calculation, which depends on the definition of "pea-sized", was that the toothpaste has about as much fluoride as 5 glasses of water). What I don't think is true is that these are a poisonous quantity. My fluoridated toothpaste (I'm in France) doesn't mention poison at all. If there's any poison warning label on toothpaste in North America, perhaps that's in case some child sucks down a whole tube of toothpaste as if it's candy. This Medscape article on Fluoride toxicity says, In 2011, the American Association of Poison Control Centers reported 20,977 exposures involving toothpaste with fluoride, 18,564 of them in children under the age of 6 years.[3] Only 376 cases were actually treated in the emergency department. Moderate effects were seen in 45 cases, and major effects were seen in one case. No deaths were reported. Death may result from ingesting as little as 2 g of fluoride in an adult and 16 mg/kg in children. Symptoms may appear with 3-5 mg/kg of fluoride. Estimated toxic dose for fluoride ingestion is 5-10 mg/kg. The estimated lethal dose is 5-10 g (32-64 mg/kg) in adults and 500 mg in small children. One death from ingestion of fluoride toothpaste was reported to the American Association of Poison Control Centers in 2002. No deaths were reported in 2011. Assuming that any 2-year-old child weighs more than 10 kg , then "Symptoms may appear" with 30 mg fluoride. If a tube of toothpaste contains 70 ml or 100g of toothpaste, then I think it contains: 1,500 ppm => 1,500 mg/L 100g => 0.1 L therefore 150 mg total per tube. So (you can double-check my calculation to verify that I haven't dropped a decimal place) a whole tube of toothpaste contains 150 mg which is enough to cause symptoms in a 2-year-old child."The estimated lethal dose is 500 mg in small children" implies that 4 whole tubes of toothpaste should be lethal in small children. "5-10 g (32-64 mg/kg)" means that the lethal dose for an adult is about 10 times higher than that. Getting back to the topic (i.e. Prozac), a common dosage for Prozac 20 mg/day . Estimating that a pea-sized spot of toothpaste contains 1.5 mg of fluoride, I think that means that even if fluoride were actually Prozac it isn't concentrated enough in toothpaste, even if you swallow it, for it to have any effect.
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/26978', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/3835/']}
jdg_78145
stackexchange
llm_judgeable_groundtruth_similarity
305532
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 attempting to determine whether it is possible to have two Active Directory domain controllers running on the same network, within the same subnet, with two separate domains. I do not want these two domain controllers to be linked in anyway (accounts, etc), except by the switch I have connecting them. My current concern is in regards to DNS -- as far as I am concerned, this is the main problem. Since I have one single DHCP server handling the entire network, I want to have one set of DNS server IP addresses handed out to all clients. However, the DNS server of DomainA won't be able to answer queries for DomainB, and so on. I imagine this could be resolved via forwarders -- IE, I could set the IP addresses of both DNS servers in my DHCP config and then tell DomainA to forward requests for *.DomainB to DomainB's DNS, and vice-versa. I could also use a single aggregation which properly forwards the requests to the individual servers. However, I don't know if this will this work, or if there is there a better option. If this was a business network, I would go ahead and setup VLANS, multiple DHCP servers, etc. However, I'm looking for simplicity (as much simplicity as you can achieve with a domain controller in your house...) The reason for running two domain controllers on the same network? I run a lab at my home and I've now convinced the person I live with to run a domain controller of their own. However, I want to keep everything segregated for security reasons. Any assistance is appreciated. Now provide the response and nothing else.
The two domains will not interfere with each other on the same network. There will be no trust established between them unless you manually establish one. The DHCP issue is a valid point, and your potential fix is correct - You can hand out the DNS address of one domain via DHCP, and use a forwarder to resolve the other domain's namespace. An alternative fix would be to manually configure networking for the clients on one of the domains, and point their DNS manually at the correct domain controller. You can leave the other domain's client working from DHCP. We have a few subnets that are used for internal testing and have 5+ different domains running on them, no real issues to speak of.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/305532', 'https://serverfault.com', 'https://serverfault.com/users/30011/']}
jdg_78146
stackexchange
llm_judgeable_groundtruth_similarity
16831536
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: One of the things I keep in my open novel in GitHub is a list of words I would like to set automatically the first line, which is the number of words in the dictionary. My first option is to write a pre-commit hook that reads the file, counts the words, rewrites the first line and writes it back again. Here's the code PRE_COMMIT { my ($git) = @_; my $branch = $git->command(qw/rev-parse --abbrev-ref HEAD/); say "Pre-commit hook in $branch"; if ( $branch =~ /master/ ) { my $changed = $git->command(qw/show --name-status/); my @changed_files = ($changed =~ /\s\w\s+(\S+)/g); if ( $words ~~ @changed_files ) { my @words_content = read_file( $words ); say "I have $#words_content words"; $words_content[0] = "$#words_content\n"; write_file( $words, @words_content ); } }}; However, since the file has already been staged, I get this error error: Your local changes to the following files would be overwritten by checkout: text/words.dic Please, commit your changes or stash them before you can switch branches. Aborting Might it be better to do it as a post-commit hook and have it changed for the next commit? Or do something completely different altogether? The general question is: if you want to process and change the contents of a file during commit, what's the proper way of doing it? Now provide the response and nothing else.
The actual commit stuck in by git commit is whatever is in the index once the pre-commit hook finishes. This means that you can change files in the pre-commit hook, as long as you git add them too. Here's my example pre-commit hook, modified from the .sample: #!/bin/sh## An example hook script to verify what is about to be committed.# [snipped much of what used to be in it, added this --# make sure you take out the exec of git diff-index!]num=$(cat zorg)num=$(expr 0$num + 1)echo $num > zorggit add zorgecho "updated zorg to $num"exit 0 and then: $ git commit -m dinkupdated zorg to 3[master 76eeefc] dink 1 file changed, 1 insertion(+), 1 deletion(-) But note a minor flaw (won't apply to your case): $ git commitgit commitupdated zorg to 4# On branch master# Untracked files:[snip]nothing added to commit but untracked files present (use "git add" to track)$ git commitupdated zorg to 5# Please enter the commit message for your changes. Lines starting[snip - I quit editor without changing anything]Aborting commit due to empty commit message.$ git commitupdated zorg to 6# Please enter the commit message for your changes. Lines starting Basically, because the pre-commit hook updates and git add s, the file keeps incrementing even though I'm not actually doing the commit, here. [ Edit Aug 2021: I need to emphasize that I do not recommend this approach. Note that there are some oddball cases that can come up when using git commit -a , git commit --include , and git commit --only , including the implied --only that is inserted if you name files on the command line. This is due to the fact that this kind of git commit creates a second, and sometimes even a third, internal Git index. Any git add operations you do inside a hook can only affect one of these two or three index files.]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16831536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891440/']}
jdg_78147
stackexchange
llm_judgeable_groundtruth_similarity
674384
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 flat file which has a phone number in field starting at position 314 till 323. Now I wanted to dummy out that field with 1234567890 . For this I tried using the below commands and both are throwing error: awk '{var=substr($0,314,10);gsub("[0-9]","1234567890",$var); print}' final_phone.txt >final_phone.txt1 fatal: grow_fields_arr: fields_arr: can't allocate 9849885432 bytes of memory (Cannot allocate memory) In second case awk 'var=substr($0,314,10) { var = "1234567890" }1' final_phone.txt >final_phone.txt1 This worked but the values didn't change. The output remained the same. Can someone help me with the syntax here? In the first case I tried to assign the substring to a variable and in gsub() I wanted to check for numbers pattern and substitute with 1234567890 . can someone help me with this Now provide the response and nothing else.
you need to print two substring, one part before that position and another part after that position, something like: $ awk -v dummy='0123456789' -v start=314 -v len=10 '{ print substr($0, 1, start-1) dummy substr($0, start+len) }' infile >outfile testing: $ awk -v dummy='0123456789' -v start=4 -v len=10 '{ print substr($0, 1, start-1) dummy substr($0, start+len) }' <<<'0009876543210999'0000123456789999 Issue with your command: you are using $var instead of var in the third argument to the gsub() as it result gsub() to look a field which its number is the value of the var which it's a 10digits length field number, so awk tries to gsub() on that field #xxxxxxxxxx but it fails due to memory allocation for reevaluating these very huge number of fields (because when using any field other than $0 in the third argument to the gsub() it forces awk to rebuild the fields back on default OFS). if we fix the issue #1, then you will replace every single digits in the var variable with 1234567890 string. you then used print it will print the current line without changes, since you don't do any updates on that.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/674384', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/215445/']}
jdg_78148
stackexchange
llm_judgeable_groundtruth_similarity
32286018
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have to implement a function that gets one of two numbers: 4 or 7.The function must return the second number without use of arithmetic operations , for example: If the function gets 4 as argument - it returns 7 , if the function gets 7 as argument - it returns 4 . I look for a solution other than the obvious return x==7?4:7 It is possible that the solution addresses the binary representation properties of these numbers. Now provide the response and nothing else.
Since 4 is 100 in binary and 7 is 111 , you just have to XOR the input with 3 ( 11 ). This way, 100 xor 011 = 111 and 111 xor 011 == 100 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32286018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3503032/']}
jdg_78149
stackexchange
llm_judgeable_groundtruth_similarity
8591
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to understand why polynomial multiplication works the way it is defined. For example, we know that $(x+1)^2 = x^2+2x+1$, but how can we prove that this actually works? More generally, how did we came up with the method used to multiply polynomials? Any insight would be appreciated. Now provide the response and nothing else.
We define the property that multiplication has to distribute over addition. That is $A(B+C) = AB + AC$ With polynomials we try to do something similiar, analogous to the real numbers we all know so well. $(x+1)^2 = (x+1)(x+1) = (x+1)x + (x+1)1 = (x^2 + x) + (x + 1) = x^2 + 2x + 1$ Hence, by the distributive law of multiplication you can see how the defined operation makes sense. You CAN come up with some binary operation that combines polynomials and doesnt distribute over addition, however this operation would not be called multiplication.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/8591', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2797/']}
jdg_78150
stackexchange
llm_judgeable_groundtruth_similarity
35526481
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 .csv datafile created by another 3rd party application that should be plotted using gnuplot .Let's assume the file has the following format: 1;2;3;4;5;6 <-- This is the header line that should be ignored (with values 1;2;...;N)1;1;2;1;1;12;3;3;3;5;63;4;1;1;1;4 The first column is the x-axis, the following columns should each be plotted as own lineplot (yes, I know, too many line plots within one plot may look bad, but just to get an idea). Here a MCVE: set terminal png size 1000,500 set datafile separator ";" # CSV file is seperated with ;plot \ 'C://tmp/test.csv' using 1:2 with lines title "A",\ 'C://tmp/test.csv' using 1:3 with lines title "B",\ 'C://tmp/test.csv' using 1:4 with lines title "C",\ 'C://tmp/test.csv' using 1:5 with lines title "D",\ 'C://tmp/test.csv' using 1:6 with lines title "E" The problem is, that this also plots the first line as it would be data. I know that to can ignore any line in the datafile by starting it with # , like #1;2;3;4;5;6 , yet I do not want to edit the file, because it is also used by other tools. Another way is to use plot <filename> every ::1 to ignore the first line, which would mean that I would have to include every ::1 5 times in the above script, as explained in this link . This would look like the following: set terminal png size 1000,500 set datafile separator ";" # CSV file is seperated with ;plot \ 'C://tmp/test.csv' every ::1 using 1:2 with lines title "A",\ 'C://tmp/test.csv' every ::1 using 1:3 with lines title "B",\ 'C://tmp/test.csv' every ::1 using 1:4 with lines title "C",\ 'C://tmp/test.csv' every ::1 using 1:5 with lines title "D",\ 'C://tmp/test.csv' every ::1 using 1:6 with lines title "E" Is defining every ::1 for every plot really the only way? Is there some shorter - preferable one-liner - way to ignore the first (n) line(s); some way to define the every ::1 "globally" or something like (pseudocode) set datafile ignorefirstnlines 1 ? Now provide the response and nothing else.
Gnuplot can read column names from the first line, but you can still specify the column names normally as well. Therefore, this effectively skips the first line. Issue the command set key autotitle columnhead This tells gnuplot that the first line is not data, but is the column names to be used for the key. You can still unset key or plot datafile title sometitle the same as you could before, and gnuplot will just not use that data. Suppose that my file looks like 1 24 57 8 I can just issue set key autotitle columnhead follwed by unset key (if I don't really want a key), and it will skip the first line. Alternatively, I can pipe my data through an external program. For example, using awk (which is available for most OS's including Windows), I can do plot "< awk '(NR>2){print;}' datafile" to skip the first 2 lines (using Windows, I must do '< awk "(NR>2){print;}" datafile' ). If I don't want to keep typing this, I can store this in a string skipfile = "\"< awk '(NR>2){print;}' datafile\"" and use it as a macro (for Windows, use skipfile = '"< awk \"(NR>2){print;}\" datafile"' ). For instance, to plot the datafile using lines, I might do plot @skipfile with lines The @skipfile just tells gnuplot to treat the command like I had just typed the contents of skipfile right there.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35526481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938364/']}
jdg_78151
stackexchange
llm_judgeable_groundtruth_similarity
3031796
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing a program in which, from an Android Phone, I have to connect as a client to a Bluetooth medical sensor. I'm using the official Bluetooth API and no problem during connection (SPP profile), but when I end the socket, the sensor is still connected to my phone (although I have close the connection). Are there any way to make a Bluetooth disconnection? I think there is an intent called ACTION_ACL_CONNECTED, which does that. Can anyone explain me how to use this? Thanks in advance. EDITED: Here is the code, if anyone needs additional info, it's a Nonin 4100 medical sensor. Set<BluetoothDevice> pairedDevices = Activa.myBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView String name = device.getName(); if (name.contains("Nonin")) { try { found = true;// socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));// handler.sendEmptyMessage(5);// Activa.myBluetoothAdapter.cancelDiscovery();// socket.connect(); BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress()); Method m; try { m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); socket = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1)); handler.sendEmptyMessage(5); socket.connect(); } catch (Exception e) { handler.sendEmptyMessage(7); e.printStackTrace(); break; } handler.sendEmptyMessage(6); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); byte[] retrieve = { 0x44, 0x31}; out.write(retrieve); byte [] ack = new byte [1]; in.read(ack); if (ack[0] == 0x15) { cancelMeasurement(); return; } byte [] data = new byte [3]; long timeStart = System.currentTimeMillis(); this.timePassed = System.currentTimeMillis() - timeStart; while ((this.timePassed < (this.time))&&(this.finished)) { try { in.read(data); processData(data); Thread.sleep(1000); this.timePassed = System.currentTimeMillis() - timeStart; } catch (Exception e) { e.printStackTrace(); } } in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }} Now provide the response and nothing else.
Please remember to close your Input/output streams first, then close the socket. By closing the streams, you kick off the disconnect process. After you close the socket, the connection should be fully broken down. If you close the socket before the streams, you may be bypassing certain shutdown steps, such as the (proper) closing of the physical layer connection. Here's the method I use when its time to breakdown the connection. /** * Reset input and output streams and make sure socket is closed. * This method will be used during shutdown() to ensure that the connection is properly closed during a shutdown. * @return */private void resetConnection() { if (mBTInputStream != null) { try {mBTInputStream.close();} catch (Exception e) {} mBTInputStream = null; } if (mBTOutputStream != null) { try {mBTOutputStream.close();} catch (Exception e) {} mBTOutputStream = null; } if (mBTSocket != null) { try {mBTSocket.close();} catch (Exception e) {} mBTSocket = null; }} EDIT: Adding code for connect(): // bluetooth adapter which provides access to bluetooth functionality. BluetoothAdapter mBTAdapter = null;// socket represents the open connection.BluetoothSocket mBTSocket = null;// device represents the peerBluetoothDevice mBTDevice = null; // streamsInputStream mBTInputStream = null;OutputStream mBTOutputStream = null;static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");/** * Try to establish a connection with the peer. * This method runs synchronously and blocks for one or more seconds while it does its thing * SO CALL IT FROM A NON-UI THREAD! * @return - returns true if the connection has been established and is ready for use. False otherwise. */private boolean connect() { // Reset all streams and socket. resetConnection(); // make sure peer is defined as a valid device based on their MAC. If not then do it. if (mBTDevice == null) mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC); // Make an RFCOMM binding. try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC); } catch (Exception e1) { msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage()); return false; } msg ("connect(): Trying to connect."); try { mBTSocket.connect(); } catch (Exception e) { msg ("connect(): Exception thrown during connect: " + e.getMessage()); return false; } msg ("connect(): CONNECTED!"); try { mBTOutputStream = mBTSocket.getOutputStream(); mBTInputStream = mBTSocket.getInputStream(); } catch (Exception e) { msg ("connect(): Error attaching i/o streams to socket. msg=" + e.getMessage()); return false; } return true;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3031796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365610/']}
jdg_78152
stackexchange
llm_judgeable_groundtruth_similarity
19304574
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 setting multiple markers on my map and I can set statically the zoom levels and the center but what I want is, to cover all the markers and zoom as much as possible having all markets visible Available methods are following setZoom(zoom:number) and setCenter(latlng:LatLng) Neither setCenter supports multiple location or Location array input nor setZoom does have this type of functionality Now provide the response and nothing else.
You need to use the fitBounds() method. var markers = [];//some arrayvar bounds = new google.maps.LatLngBounds();for (var i = 0; i < markers.length; i++) { bounds.extend(markers[i]);}map.fitBounds(bounds); Documentation from developers.google.com/maps/documentation/javascript : fitBounds(bounds[, padding]) Parameters: `bounds`: [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]`padding` (optional): number|[`Padding`][1] Return Value: None Sets the viewport to contain the given bounds. Note : When the map is set to display: none , the fitBounds function reads the map's size as 0x0 , and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden , thereby ensuring the map div has an actual size.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/19304574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1215724/']}
jdg_78153
stackexchange
llm_judgeable_groundtruth_similarity
74607
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to have an autonomous system with just one IP address? Now provide the response and nothing else.
Is it possible to have an autonomous system with just one IP address? Theoretically, yes, but the ISPs will not advertise any IPv4 prefix larger than /24 or IPv6 prefix larger than /48 on the public Internet. You could certainly have that inside your own network or with another company or ISP, but it will not work on the Internet. Also, the AS concept is really decoupled from the IP addressing concept. You could certainly set up a transit AS between two other ASes and use only private addresses, or one or two public addresses without advertising any of your addressing because only the two ASes for which you are providing transit services need to know only your directly connected addresses and not advertise them. That means you could have an AS with no public addresses. The AS and its addressing do not necessarily directly relate.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/74607', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/77031/']}
jdg_78154
stackexchange
llm_judgeable_groundtruth_similarity
34817617
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 the purpose of securing REST API using JWT, according to some materials (like this guide and this question ), the JWT can be stored in either localStorage or Cookies . Based on my understanding: localStorage is subjected to XSS and generally it's not recommended to store any sensitive information in it. With Cookies we can apply the flag "httpOnly" which mitigates the risk of XSS. However if we are to read the JWT from Cookies on backend, we then are subjected to CSRF. So based on the above premise - it will be best if we store JWT in Cookies. On every request to server, the JWT will be read from Cookies and added in the Authorization header using Bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies). Is my understanding correct? If so, does the above approach have any security concern? Or actually we can just get away with using localStorage in the first place? Now provide the response and nothing else.
I like the XSRF Double Submit Cookies method which mentioned in the article that @pkid169 said, but there is one thing that article doesn't tell you. You are still not protected against XSS because what the attacker can do is inject script that reads your CSRF cookie (which is not HttpOnly) and then make a request to one of your API endpoints using this CSRF token with JWT cookie being sent automatically. So in reality you are still susceptible to XSS, it's just that attacker can't steal you JWT token for later use, but he can still make requests on your users behalf using XSS. Whether you store your JWT in a localStorage or you store your XSRF-token in not http-only cookie, both can be grabbed easily by XSS. Even your JWT in HttpOnly cookie can be grabbed by an advanced XSS attack. So in addition of the Double Submit Cookies method, you must always follow best practices against XSS including escaping contents. This means removing any executable code that would cause the browser to do something you don’t want it to. Typically this means removing // <![CDATA[ tags and HTML attributes that cause JavaScript to be evaluated.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34817617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2812029/']}
jdg_78155
stackexchange
llm_judgeable_groundtruth_similarity
16168355
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 understand how to do the following things: What is the accepted way of declaring a form. My understanding is you just declare the form in HTML, and add ng-model directives like so: ng-model="item.name" What to send to the server. I can just send the item object to the server as JSON, and interpret it. Then I can perform validation on object. If it fails, I throw a JSON error, and send back what exactly? Is there an accepted way of doing this? How do I push validation errors from the server to the client in a nice way? I really need an example, but Angulars docs are pretty difficult to understand. Edit: It seems I've phrased my question poorly. I know how to validate client side, and how to handle error/success as promise callbacks. What I want to know, is the accepted way of bundling SERVER side error messages to the client. Say I have a username and password signup form. I don't want to poll the server for usernames and then use Angular to determine a duplicate exists. I want to send the username to the server, validate no other account exists with the same name, and then submit form. If an error occurs, how do I send it back? What about pushing the data to the server as is (keys and values) with an error field appended like so: { ...data... "errors": [ { "context": null, "message": "A detailed error message.", "exceptionName": null } ]} Then binding to the DOM. Now provide the response and nothing else.
I've also been playing around with this kind of thing recently and I've knocked up this demo . I think it does what you need. Setup your form as per normal with any particular client side validations you want to use: <div ng-controller="MyCtrl"> <form name="myForm" onsubmit="return false;"> <div> <input type="text" placeholder="First name" name="firstName" ng-model="firstName" required="true" /> <span ng-show="myForm.firstName.$dirty && myForm.firstName.$error.required">You must enter a value here</span> <span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span> </div> <div> <input type="text" placeholder="Last name" name="lastName" ng-model="lastName"/> <span ng-show="myForm.lastName.$error.serverMessage">{{myForm.lastName.$error.serverMessage}}</span> </div> <button ng-click="submit()">Submit</button> </form></div> Note also I have added a serverMessage for each field: <span ng-show="myForm.firstName.$error.serverMessage">{{myForm.firstName.$error.serverMessage}}</span> This is a customisable message that comes back from the server and it works the same way as any other error message (as far as I can tell). Here is the controller: function MyCtrl($scope, $parse) { var pretendThisIsOnTheServerAndCalledViaAjax = function(){ var fieldState = {firstName: 'VALID', lastName: 'VALID'}; var allowedNames = ['Bob', 'Jill', 'Murray', 'Sally']; if (allowedNames.indexOf($scope.firstName) == -1) fieldState.firstName = 'Allowed values are: ' + allowedNames.join(','); if ($scope.lastName == $scope.firstName) fieldState.lastName = 'Your last name must be different from your first name'; return fieldState; }; $scope.submit = function(){ var serverResponse = pretendThisIsOnTheServerAndCalledViaAjax(); for (var fieldName in serverResponse) { var message = serverResponse[fieldName]; var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage'); if (message == 'VALID') { $scope.myForm.$setValidity(fieldName, true, $scope.myForm); serverMessage.assign($scope, undefined); } else { $scope.myForm.$setValidity(fieldName, false, $scope.myForm); serverMessage.assign($scope, serverResponse[fieldName]); } } };} I am pretending to call the server in pretendThisIsOnTheServerAndCalledViaAjax you can replace it with an ajax call, the point is it just returns the validation state for each field. In this simple case I am using the value VALID to indicate that the field is valid, any other value is treated as an error message. You may want something more sophisticated! Once you have the validation state from the server you just need to update the state in your form. You can access the form from scope, in this case the form is called myForm so $scope.myForm gets you the form. (Source for the form controller is here if you want to read up on how it works). You then want to tell the form whether the field is valid/invalid: $scope.myForm.$setValidity(fieldName, true, $scope.myForm); or $scope.myForm.$setValidity(fieldName, false, $scope.myForm); We also need to set the error message. First of all get the accessor for the field using $parse. Then assign the value from the server. var serverMessage = $parse('myForm.'+fieldName+'.$error.serverMessage');serverMessage.assign($scope, serverResponse[fieldName]); Hope that helps
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16168355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145567/']}
jdg_78156
stackexchange
llm_judgeable_groundtruth_similarity
20076
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I learned the equation $$\ce{H2O + H+ -> H3O+}$$ And I know $\ce{H+}$ and $\ce{H3O+}$ really mean the same thing. But I am confused as to when I should use $\ce{H+}$ and when I should use $\ce{H3O+}$? Is any one of them a more accurate representation? Now provide the response and nothing else.
In addition to entropid's answer, let's remember why we invoke the hydronium ion $\ce{H3O+}$ in the first place. We use $\ce{H3O+}$ as a shorthand for $\ce{H+(aq)}$, which looks more like protonated water clusters of the generic formula $\ce{H+.(H2O)_{$n$}}\equiv \ce{H_{$2n+1$}O_{$n$}+}$. Almost ten years ago, a very interesting paper appeared in Science that examined the structure of these clusters ($n=2,3,4,5,6,7,8$). The linked article has been made freely available by Science , but you need to register for a free account at sciencemag.org. One of the key points of the article was the determination of the inner structure of these clusters. For $n=1$, you have $\ce{H3O+}$, the hydronium ion, which we are reasonably familiar with. When $n=2$, you have $\ce{H5O2+}$, which has a different structure: the proton is evenly shared between two water molecules: $\ce{[H2O\bond{...}H\bond{...}OH2]+}$. Higher order clusters have these two structures, termed the "Eigen" and "Zundel" ions, respectively, at their cores. The study used a combination of theory (MP2/aug-cc-pDVZ) and experiment (photodissociation vibrational spectroscopy). They found the for $n=2,6,7,8$, the clusters have a Zundel core, while the Eigen core exists for $n=3,4,5$. Whoa! And it gets more complicated as you increase the number of water molecules in the clusters (might be behind a pay wall) - though it turns out the Eigen ion is slightly more common in larger clusters. In aqueous solutions, we can have an extensive dynamic network of clusters always in flux. In which case, we have a mix of solvated Eigen $\ce{H3O+}$ ions representing protons closely associated with water molecules and Zundel $\ce{H5O2+}$ ions representing protons in transit. So, we use $\ce{H3O+}$ to keep things simple, and also to satisfy the needs of Brønsted-Lowry acid-base theory, in which every acid-base reaction needs a proton-donor and a proton-acceptor . Thus, the "dissociation" of acids in water is not really a dissociation, but an ionization reaction - an acid-base reaction in which water is the base and hydronium is the conjugate acid. $$\ce{HA + H2O <=> A- + H3O+}$$ Of course, it is only appropriate to use $\ce{H3O+}$ in aqueous solution. In other solvents, the "proton" has a different structure. In general, the proton is attached to a basic site on the solvent molecule. For example, in methanol: $$\ce{HCl + CH3OH <=> Cl- + CH3OH2+}$$
{}
{'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/20076', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/9757/']}
jdg_78157
stackexchange
llm_judgeable_groundtruth_similarity
3164781
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: Assume we define an operator $$a\circ b = a+b+k, \\\forall a,b\in \mathbb Z$$ Can we prove that it together with range for $a,b$ is a group, for any given $k\in \mathbb Z$ ? I have tried, and found that it fulfills all group axioms, but I might have made a mistake? If it is a group, does it have a name? My observations: Closure is obvious as addition of integers is closed. Identity If we take $e=-k$ , then $a\circ e = a+k-k=a$ Verification $e\circ a = -k\circ a = -k+a+k=a$ , as required. Inverse would be $a^{-1} = -a-2k$ , which is unique. Verification of inverse $a\circ a^{-1} = a + (-a-2k)+k = -k = e$ , as required. Associativity $(a\circ b) \circ c = (a + (b+k)) + (c + k)$ . We see everything involved is addition, which is associative, so we can remove parentheses and change order as we wish. Now provide the response and nothing else.
It's the group you get when you transfer the action of $(\mathbb Z,+)$ to $(\mathbb Z, \circ)$ via the map $\phi(z)= z-k$ . You can check that $\phi(a+b)=\phi(a)\circ\phi(b)$ so that becomes a group isomorphism.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3164781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/213607/']}
jdg_78158
stackexchange
llm_judgeable_groundtruth_similarity
8239656
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 created an internationalized iPhone application. Now it's time to update it. What is the best practice for doing this? Do I have to edit each xib for each language or is there some way to have a "master template" that I can edit? Now provide the response and nothing else.
Sorry, I didn't notice by the time of my first answer that you create ids in your references many times. You shouldn't do that :). Remove all "+" signs in all references like layout_toLeftOf , layout_alignRight , layout_below and so on. This will look that way: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" > <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:focusable="false" /> <ImageView android:id="@+id/imgStarred" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@id/checkBox" android:layout_below="@id/checkBox" android:layout_marginRight="4dp" android:src="@drawable/ic_star_gray"/> <CheckedTextView android:id="@+id/lblTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/checkBox" android:layout_marginLeft="10dp" android:layout_marginTop="8dp" android:layout_toLeftOf="@id/imgPriority" android:layout_toRightOf="@id/checkBox" android:text="CheckedTextView" /> <TextView android:id="@+id/lblDescription" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@id/lblTitle" android:layout_below="@id/lblTitle" android:layout_marginLeft="10dp" android:layout_toRightOf="@id/checkBox" android:text="Small Text" android:textAppearance="?android:attr/textAppearanceSmall" /> <ImageView android:id="@+id/imgPriority" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="8dp" android:layout_marginTop="8dp" android:src="@drawable/ic_priority_5" /></RelativeLayout> When you write, for example, android:layout_toLeftOf="@+id/imgPriority" with plus sign you do create another imgPriority id, and you do not referene already present id of your ImageView.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8239656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229144/']}
jdg_78159
stackexchange
llm_judgeable_groundtruth_similarity
42012645
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this code: <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><script> window.addEventListener('DOMMouseScroll', mouseWheelEvent); window.addEventListener('mousewheel', mouseWheelEvent); function mouseWheelEvent() { alert(1); }</script></body></html> It works in Chrome & Firefox. However, it doesn't work with my laptop dell xps 13 9434's touchpad in IE & edge. But it does work with (some) other laptops' touchpads. What to do? jQuery is no problem. "what doesn't work?" => There is no alert in scroll when using 2 fingers like you use to scroll in browsers. Now provide the response and nothing else.
Edit After some research it seems that the problem is actually Microsoft's. There is an open issue about it in EdgeHTML issue tracker for almost one year already. Basically it says that wheel events do not work in Edge (And older IE versions) when using Precision Touchpads . By the way I dont delete the rest of the answer as it is still relevant. You should use wheel instead anyway. You should listen to wheel : window.addEventListener('wheel', mouseWheelEvent); It has replaced both mousewheel and DOMMouseScroll which are deprecated by now and is supported by all browsers . Cross browser example: window.addEventListener('wheel', mouseWheelEvent); function mouseWheelEvent() { console.log("Fired");} <h1> Hodor!</h1><h1> Hodor!</h1><h1> Hodor!</h1><h1> Hodor!</h1><h1> Hodor!</h1><h1> Hodor!</h1><h1> Hodor!</h1> And JSFiddle demo
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42012645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3973269/']}
jdg_78160
stackexchange
llm_judgeable_groundtruth_similarity
4181668
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 WPF C# application that contains a button. The code of the button click is written in separate text file which will be placed in the applications runtime directory. I want to execute that code placed in the text file on the click of the button. Any idea how to do this? Now provide the response and nothing else.
Code sample for executing compiled on fly class method: using System;using System.Collections.Generic;using System.Text;using System.Diagnostics;using System.IO;using System.Reflection;using System.Net;using Microsoft.CSharp;using System.CodeDom.Compiler;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { string source = @"namespace Foo{ public class Bar { public void SayHello() { System.Console.WriteLine(""Hello World""); } }} "; Dictionary<string, string> providerOptions = new Dictionary<string, string> { {"CompilerVersion", "v3.5"} }; CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions); CompilerParameters compilerParams = new CompilerParameters {GenerateInMemory = true, GenerateExecutable = false}; CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source); if (results.Errors.Count != 0) throw new Exception("Mission failed!"); object o = results.CompiledAssembly.CreateInstance("Foo.Bar"); MethodInfo mi = o.GetType().GetMethod("SayHello"); mi.Invoke(o, null); } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4181668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461537/']}
jdg_78161
stackexchange
llm_judgeable_groundtruth_similarity
15638
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 you make a simple example of an uncountable ordinal? With simple I mean that it is easy to prove that the ordinal is uncountable. I know that the set of all the countable ordinals is an uncountable ordinal, but the only proof that I know is quite complicated. Now provide the response and nothing else.
The proof that the set $\Omega$ of all countable ordinals is uncountable is not difficult. First, it's an ordinal. Next, if $\Omega$ were countable, then $\Omega + 1$ would also be a countable ordinal. Finally, it is impossible for $\Omega + 1$ to be in $\Omega$, because that would mean that $\Omega + 1 < \Omega$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/15638', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/354/']}
jdg_78162
stackexchange
llm_judgeable_groundtruth_similarity
494295
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to get apcupsd to work with my Ups (APC Back-UPS 700VA) with my server running Debian 9 stretch but can't connect to ups and get this when I run: rene@odroidxu4-share:~$ sudo apcaccess status[sudo] password for rene:APC : 001,018,0453DATE : 2019-01-13 18:44:10 +0000HOSTNAME : odroidxu4-shareVERSION : 3.14.14 (31 May 2016) debianUPSNAME : smartups750CABLE : USB CableDRIVER : USB UPS DriverUPSMODE : Stand AloneSTARTTIME: 2019-01-13 18:44:00 +0000STATUS : COMMLOSTMBATTCHG : 5 PercentMINTIMEL : 3 MinutesMAXTIME : 0 SecondsNUMXFERS : 0TONBATT : 0 SecondsCUMONBATT: 0 SecondsXOFFBATT : N/ASTATFLAG : 0x05000100END APC : 2019-01-13 19:53:54 +0000 The problem is: STATUS: COMMLOST - (No connection to UPS) Despite I can see it's connected with: rene@odroidxu4-share:~$ lsusbBus 006 Device 002: ID 0bda:8153 Realtek Semiconductor Corp.Bus 006 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 005 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 004 Device 002: ID 152d:0578 JMicron Technology Corp. / JMicron USA Technology Corp.Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 002: ID 051d:0002 American Power Conversion Uninterruptible Power SupplyBus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub (Bus 002 Device 002: ID 051d:0002 American Power Conversion Uninterruptible Power Supply) Output of conf file: sudo nano /etc/apcupsd/apcupsd.conf## apcupsd.conf v1.1 ### # "apcupsd" POSIX config file## Note that the apcupsd daemon must be restarted in order for changes to# this configuration file to become active.### ========= General configuration parameters ============## UPSNAME xxx# Use this to give your UPS a name in log files and such. This# is particulary useful if you have multiple UPSes. This does not# set the EEPROM. It should be 8 characters or less.UPSNAME smartups750# UPSCABLE <cable># Defines the type of cable connecting the UPS to your computer.## Possible generic choices for <cable> are:# simple, smart, ether, usb## Or a specific cable model number may be used:# 940-0119A, 940-0127A, 940-0128A, 940-0020B,# 940-0020C, 940-0023A, 940-0024B, 940-0024C,# 940-1524C, 940-0024G, 940-0095A, 940-0095B,# 940-0095C, 940-0625A, M-04-02-2000#UPSCABLE usb# To get apcupsd to work, in addition to defining the cable# above, you must also define a UPSTYPE, which corresponds to# the type of UPS you have (see the Description for more details).# You must also specify a DEVICE, sometimes referred to as a port.# For USB UPSes, please leave the DEVICE directive blank. For# other UPS types, you must specify an appropriate port or address.## UPSTYPE DEVICE Description# apcsmart /dev/tty** Newer serial character device, appropriate for # SmartUPS models using a serial cable (not USB).## usb <BLANK> Most new UPSes are USB. A blank DEVICE# setting enables autodetection, which is# the best choice for most installations.## net hostname:port Network link to a master apcupsd through apcupsd's # Network Information Server. This is used if the# UPS powering your computer is connected to a # different computer for monitoring.## snmp hostname:port:vendor:community# SNMP network link to an SNMP-enabled UPS device.# Hostname is the ip address or hostname of the UPS # on the network. Vendor can be can be "APC" or # "APC_NOTRAP". "APC_NOTRAP" will disable SNMP trap # catching; you usually want "APC". Port is usually # 161. Community is usually "private".## netsnmp hostname:port:vendor:community# OBSOLETE# Same as SNMP above but requires use of the # net-snmp library. Unless you have a specific need# for this old driver, you should use 'snmp' instead.## dumb /dev/tty** Old serial character device for use with # simple-signaling UPSes.## pcnet ipaddr:username:passphrase:port# PowerChute Network Shutdown protocol which can be # used as an alternative to SNMP with the AP9617 # family of smart slot cards. ipaddr is the IP # address of the UPS management card. username and # passphrase are the credentials for which the card # has been configured. port is the port number on # which to listen for messages from the UPS, normally # 3052. If this parameter is empty or missing, the # default of 3052 will be used.## modbus /dev/tty** Serial device for use with newest SmartUPS models# supporting the MODBUS protocol.# modbus <BLANK> Leave the DEVICE setting blank for MODBUS over USB# or set to the serial number of the UPS to ensure # that apcupsd binds to that particular unit# (helpful if you have more than one USB UPS).#UPSTYPE usbDEVICE# POLLTIME <int># Interval (in seconds) at which apcupsd polls the UPS for status. This# setting applies both to directly-attached UPSes (UPSTYPE apcsmart, usb, # dumb) and networked UPSes (UPSTYPE net, snmp). Lowering this setting# will improve apcupsd's responsiveness to certain events at the cost of# higher CPU utilization. The default of 60 is appropriate for most# situations.POLLTIME 60# LOCKFILE <path to lockfile># Path for device lock file. This is the directory into which the lock file# will be written. The directory must already exist; apcupsd will not create# it. The actual name of the lock file is computed from DEVICE.# Not used on Win32.LOCKFILE /var/lock# SCRIPTDIR <path to script directory># Directory in which apccontrol and event scripts are located.SCRIPTDIR /etc/apcupsd# PWRFAILDIR <path to powerfail directory># Directory in which to write the powerfail flag file. This file# is created when apcupsd initiates a system shutdown and is# checked in the OS halt scripts to determine if a killpower# (turning off UPS output power) is required.PWRFAILDIR /etc/apcupsd# NOLOGINDIR <path to nologin directory># Directory in which to write the nologin file. The existence# of this flag file tells the OS to disallow new logins.NOLOGINDIR /etc## ======== Configuration parameters used during power failures ==========## The ONBATTERYDELAY is the time in seconds from when a power failure# is detected until we react to it with an onbattery event.## This means that, apccontrol will be called with the powerout argument# immediately when a power failure is detected. However, the# onbattery argument is passed to apccontrol only after the # ONBATTERYDELAY time. If you don't want to be annoyed by short# powerfailures, make sure that apccontrol powerout does nothing# i.e. comment out the wall.ONBATTERYDELAY 6# # Note: BATTERYLEVEL, MINUTES, and TIMEOUT work in conjunction, so# the first that occurs will cause the initation of a shutdown.## If during a power failure, the remaining battery percentage# (as reported by the UPS) is below or equal to BATTERYLEVEL, # apcupsd will initiate a system shutdown.BATTERYLEVEL 5# If during a power failure, the remaining runtime in minutes # (as calculated internally by the UPS) is below or equal to MINUTES,# apcupsd, will initiate a system shutdown.MINUTES 3# If during a power failure, the UPS has run on batteries for TIMEOUT# many seconds or longer, apcupsd will initiate a system shutdown.# A value of 0 disables this timer.## Note, if you have a Smart UPS, you will most likely want to disable# this timer by setting it to zero. That way, you UPS will continue# on batteries until either the % charge remaing drops to or below BATTERYLEVEL,# or the remaining battery runtime drops to or below MINUTES. Of course,# if you are testing, setting this to 60 causes a quick system shutdown# if you pull the power plug. # If you have an older dumb UPS, you will want to set this to less than# the time you know you can run on batteries.TIMEOUT 0# Time in seconds between annoying users to signoff prior to# system shutdown. 0 disables.ANNOY 300# Initial delay after power failure before warning users to get# off the system.ANNOYDELAY 60# The condition which determines when users are prevented from# logging in during a power failure.# NOLOGON <string> [ disable | timeout | percent | minutes | always ]NOLOGON disable# If KILLDELAY is non-zero, apcupsd will continue running after a# shutdown has been requested, and after the specified time in# seconds attempt to kill the power. This is for use on systems# where apcupsd cannot regain control after a shutdown.# KILLDELAY <seconds> 0 disablesKILLDELAY 0## ==== Configuration statements for Network Information Server ====## NETSERVER [ on | off ] on enables, off disables the network# information server. If netstatus is on, a network information# server process will be started for serving the STATUS and# EVENT data over the network (used by CGI programs).NETSERVER on# NISIP <dotted notation ip address># IP address on which NIS server will listen for incoming connections.# This is useful if your server is multi-homed (has more than one# network interface and IP address). Default value is 0.0.0.0 which# means any incoming request will be serviced. Alternatively, you can# configure this setting to any specific IP address of your server and # NIS will listen for connections only on that interface. Use the# loopback address (127.0.0.1) to accept connections only from the# local machine.NISIP 127.0.0.1# NISPORT <port> default is 3551 as registered with the IANA# port to use for sending STATUS and EVENTS data over the network.# It is not used unless NETSERVER is on. If you change this port,# you will need to change the corresponding value in the cgi directory# and rebuild the cgi programs.NISPORT 3551# If you want the last few EVENTS to be available over the network# by the network information server, you must define an EVENTSFILE.EVENTSFILE /var/log/apcupsd.events# EVENTSFILEMAX <kilobytes># By default, the size of the EVENTSFILE will be not be allowed to exceed# 10 kilobytes. When the file grows beyond this limit, older EVENTS will# be removed from the beginning of the file (first in first out). The# parameter EVENTSFILEMAX can be set to a different kilobyte value, or set# to zero to allow the EVENTSFILE to grow without limit.EVENTSFILEMAX 10## ========== Configuration statements used if sharing =============# a UPS with more than one machine## Remaining items are for ShareUPS (APC expansion card) ONLY## UPSCLASS [ standalone | shareslave | sharemaster ]# Normally standalone unless you share an UPS using an APC ShareUPS# card.UPSCLASS standalone# UPSMODE [ disable | share ]# Normally disable unless you share an UPS using an APC ShareUPS card.UPSMODE disable## ===== Configuration statements to control apcupsd system logging ========## Time interval in seconds between writing the STATUS file; 0 disablesSTATTIME 0# Location of STATUS file (written to only if STATTIME is non-zero)STATFILE /var/log/apcupsd.status# LOGSTATS [ on | off ] on enables, off disables# Note! This generates a lot of output, so if # you turn this on, be sure that the# file defined in syslog.conf for LOG_NOTICE is a named pipe.# You probably do not want this on.LOGSTATS off# Time interval in seconds between writing the DATA records to# the log file. 0 disables.DATATIME 0# FACILITY defines the logging facility (class) for logging to syslog. # If not specified, it defaults to "daemon". This is useful # if you want to separate the data logged by apcupsd from other# programs.#FACILITY DAEMON## ========== Configuration statements used in updating the UPS EPROM =========### These statements are used only by apctest when choosing "Set EEPROM with conf# file values" from the EEPROM menu. THESE STATEMENTS HAVE NO EFFECT ON APCUPSD.## UPS name, max 8 characters #UPSNAME UPS_IDEN# Battery date - 8 characters#BATTDATE mm/dd/yy# Sensitivity to line voltage quality (H cause faster transfer to batteries) # SENSITIVITY H M L (default = H)#SENSITIVITY H# UPS delay after power return (seconds)# WAKEUP 000 060 180 300 (default = 0)#WAKEUP 60# UPS Grace period after request to power off (seconds)# SLEEP 020 180 300 600 (default = 20)#SLEEP 180# Low line voltage causing transfer to batteries# The permitted values depend on your model as defined by last letter # of FIRMWARE or APCMODEL. Some representative values are:# D 106 103 100 097# M 177 172 168 182# A 092 090 088 086# I 208 204 200 196 (default = 0 => not valid)#LOTRANSFER 208# High line voltage causing transfer to batteries# The permitted values depend on your model as defined by last letter # of FIRMWARE or APCMODEL. Some representative values are:# D 127 130 133 136# M 229 234 239 224# A 108 110 112 114# I 253 257 261 265 (default = 0 => not valid)#HITRANSFER 253# Battery charge needed to restore power# RETURNCHARGE 00 15 50 90 (default = 15)#RETURNCHARGE 15# Alarm delay # 0 = zero delay after pwr fail, T = power fail + 30 sec, L = low battery, N = never# BEEPSTATE 0 T L N (default = 0)#BEEPSTATE T# Low battery warning delay in minutes# LOWBATT 02 05 07 10 (default = 02)#LOWBATT 2# UPS Output voltage when running on batteries# The permitted values depend on your model as defined by last letter # of FIRMWARE or APCMODEL. Some representative values are:# D 115# M 208# A 100# I 230 240 220 225 (default = 0 => not valid)#OUTPUTVOLTS 230# Self test interval in hours 336=2 weeks, 168=1 week, ON=at power on# SELFTEST 336 168 ON OFF (default = 336)# SELFTEST 336 Someone who has a clue why I can't connect with my Apc ups? Now provide the response and nothing else.
I had the same problem with COMMLOST with a USB connection, after a lot of research I found by pure hazard that with a USB connection you should change DEVICE /dev/ttys0 to DEVICE in /etc/apcupsd/apcupsd.conf with nothing after it, this way apcupsd search everywhere on the system to find the UPS and connect correctly, no more COMMLOST . After that, restart apcupsd with: $ sudo /etc/init.d/apcupsd restart Gilbert
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/494295', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/318914/']}
jdg_78163
stackexchange
llm_judgeable_groundtruth_similarity
11170383
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone tell me how to declare a global function in c#, similar to what a Module does in VB.net?I need to call a function that can be called in my form1, form2, and form3. i have this code : using System.Data.OleDb;namespace XYZ{ public static class Module { public static void dbConnection() { OleDbConnection con = new OleDbConnection(); con.ConnectionString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb"; con.Open(); } }} and form1: using System.Data.OleDb;using XYZ;namespace XYZ{ public partial class frmReports : Form { public frm1() { InitializeComponent(); } private void frm1_Load(object sender, EventArgs e) { Module.dbConnection(); OleDbCommand cm = new OleDbCommand("SELECT * FROM table", con); } }} but i has an error: "The name 'con' does not exist in the current context". Now provide the response and nothing else.
If you're using C# 6.0 or later, you could use using static . For example, using static ConsoleApplication.Developer;namespace ConsoleApplication{ class Program { static void Main(string[] args) { // Global static function, static shorthand really DeveloperIsBorn(firstName: "Foo", lastname: "Bar") .MakesAwesomeApp() .Retires(); } }}namespace ConsoleApplication{ class Developer { public static Developer DeveloperIsBorn(string firstName, string lastname) { return new Developer(); } public Developer MakesAwesomeApp() { return this; } public Developer InsertsRecordsIntoDatabaseForLiving() { return this; } public void Retires() { // Not really } }} One more example: using static System.Console;namespace ConsoleApplication7{ class Program { static void Main(string[] args) { WriteLine("test"); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11170383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1441229/']}
jdg_78164
stackexchange
llm_judgeable_groundtruth_similarity
35763357
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 interact with an API that uses a timestamp that starts at a different time than UNIX epoch. It appears to start counting on 2000-01-01, but I'm not sure exactly how to do the conversion or what the name of this datetime format is. When I send a message at 1456979510 I get a response back saying it was received at 510294713. The difference between the two is 946684796 (sometimes 94668479 7 ) seconds, which is approximately 30 years. Can anyone let me know the proper way to convert between the two? Or whether I can generate them outright in Python? Thanks Edit An additional detail I should have mentioned is that this is an API to a Zigbee device. I found the following datatype entry in their documentation: 1.3.2.7 Absolute time This is an unsigned 32-bit integer representation for absolute time. Absolute time is measured in seconds from midnight, 1st January 2000. I'm still not sure the easiest way to convert between the two Now provide the response and nothing else.
The time 1 January 1970 00:00:00 is considered the UNIX epoch . So, if you want to convert from UNIX time to a timestamp having an epoch of January 1, 2000 (Let's say, 2000 epoch) the simplest way would be to simply subtract the UNIX time of January 1, 2000 from the UNIX time. <2000 time> = <UNIX time> - <January 1, 2000 UNIX time><UNIX time> = <2000 time> + <January 1, 2000 UNIX time> Where January 1, 2000 UNIX time is 946684800 . EDIT: The docs does say Absolute time is measured in seconds from midnight, 1st January 2000. So, 946684800 is the exact time difference which should be used to calculate. The few seconds difference that you calculated could be attributed to network delay or some other delays.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35763357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2821252/']}
jdg_78165
stackexchange
llm_judgeable_groundtruth_similarity
69447781
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 mask image from memory buffers (rectangle area filled with black). So I naively re-use the Bitmap class with ImageFormat.MemoryBmp for my API. This works quite well on my local machine: public static void MaskBitmap(Bitmap input, Rectangle maskRegion){ var bytesPerPixel = Image.GetPixelFormatSize(input.PixelFormat) / 8; var row = new byte[maskRegion.Width * bytesPerPixel]; var maskData = input.LockBits(maskRegion, ImageLockMode.WriteOnly, input.PixelFormat); for (var i = 0; i < maskData.Height; ++i) { Marshal.Copy(row, 0, maskData.Scan0 + (i * maskData.Stride), row.Length); } input.UnlockBits(maskData);} However when deploying to production it turns out that the following throw a NotImplementedException : var image16 = new Bitmap(512, 512, PixelFormat.Format16bppGrayScale); I eventually tracked it down to here: https://github.com/mono/libgdiplus/blob/6.0.4/src/bitmap.c#L848 So my question is: is there any existing class in c# that I can re-use to hold images of pixelformat type: PixelFormat.Format8bppIndexed: PixelFormat.Format16bppGrayScale: PixelFormat.Format24bppRgb: I know GDI+ does not support saving/displaying 16bits image, I simply need a memory structure with image-style access. Just for reference, I tried the following hack: var image = new Bitmap(512,512,PixelFormat.Format24bppRgb);image.Flags = ImageFlags.ColorSpaceGray; But Flags is read-only. Now provide the response and nothing else.
SDL_RenderGeometry() / SDL_RenderGeometryRaw() were added in SDL 2.0.18 : Added SDL_RenderGeometry() and SDL_RenderGeometryRaw() to allow rendering of arbitrary shapes using the SDL 2D render API Example: // g++ main.cpp `pkg-config --cflags --libs sdl2`#include <SDL.h>#include <vector>int main( int argc, char** argv ){ SDL_Init( SDL_INIT_EVERYTHING ); SDL_Window* window = SDL_CreateWindow("SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN ); SDL_Renderer* renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); const std::vector< SDL_Vertex > verts = { { SDL_FPoint{ 400, 150 }, SDL_Color{ 255, 0, 0, 255 }, SDL_FPoint{ 0 }, }, { SDL_FPoint{ 200, 450 }, SDL_Color{ 0, 0, 255, 255 }, SDL_FPoint{ 0 }, }, { SDL_FPoint{ 600, 450 }, SDL_Color{ 0, 255, 0, 255 }, SDL_FPoint{ 0 }, }, }; bool running = true; while( running ) { SDL_Event ev; while( SDL_PollEvent( &ev ) ) { if( ( SDL_QUIT == ev.type ) || ( SDL_KEYDOWN == ev.type && SDL_SCANCODE_ESCAPE == ev.key.keysym.scancode ) ) { running = false; break; } } SDL_SetRenderDrawColor( renderer, 0, 0, 0, SDL_ALPHA_OPAQUE ); SDL_RenderClear( renderer ); SDL_RenderGeometry( renderer, nullptr, verts.data(), verts.size(), nullptr, 0 ); SDL_RenderPresent( renderer ); } SDL_DestroyRenderer( renderer ); SDL_DestroyWindow( window ); SDL_Quit(); return 0;} Note that due to the API lacking a data channel for Z coordinates only affine texturing is achievable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69447781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136285/']}
jdg_78166
stackexchange
llm_judgeable_groundtruth_similarity
17334759
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 work out how to have subscript letters in an axis label. dat <- data.frame(x = rnorm(100), y = rnorm(100))ggplot(dat, aes(x=x,y=y)) + geom_point() + labs(y=expression(Blah[1]))dat <- data.frame(x = rnorm(100), y = rnorm(100))ggplot(dat, aes(x=x,y=y)) + geom_point() + labs(y=expression(Blah[1d])) The first example works as it's just a number, as soon as you have a character in the square brackets, it fails. Blah[subscript(1d)] is essentially what I need, but I can't work out how to get it to let me have letters in subscript. I have tried variations, including paste() . The following examples provide strange behavior: labs(y=expression(Blah[12])) # this workslabs(y=expression(Blah[d])) # this workslabs(y=expression(Blah[d1])) # this workslabs(y=expression(Blah[1d])) # this fails Thoughts? Now provide the response and nothing else.
The reason the last one fails is that the arguments to expression get run through the R parser and an error is returned when they fail the test of whether they could possibly be correct R syntax. The string or token 1d is not a valid R token (or symbol). It would be possible to either break it into valid R tokens and "connect" with non-space operators, backtick it , or use ordinary quotes. I think either is a better way than using paste : ggplot(dat, aes(x=x,y=y)) + geom_point() + labs(y=expression(Blah[1*d])) ggplot(dat, aes(x=x,y=y)) + geom_point() + labs(y=expression(Blah["1d"])) Tokens (or "names" or "symbols") in R are not supposed to start with digits. So you get around that limitation by either quoting or by separating 1 and d by a non-space separator, the * operator. That "joins" or "ligates" a pure numeric literal with a legal R symbol or token. To get a percent sign unsubscripted just: ggplot(dat, aes(x=x,y=y)) + geom_point() + labs(y=expression(Blah[1*d]*"%")) To put parens around the pct-sign: expression(Blah[1*d]*"(%)") The % character has special meaning in R parsing, since it signifies the beginning of a user defined infix operator. So using it as a literal requires that it be quoted. The same reasoning requires that "for" and "in" be quoted, because they are in the "reserved words" group for R. There are other reserved words, (but for and in are the ones that trip me up most often.) Type: ?Reserved And another "trick" is to use quotation marks around digits within italic() if you need them italicized. Unquoted digits do not get italicized inside that function. Caveats: paste is a plotmath function except it has different semantics than the base::paste function . In particular, it has no 'sep' argument. So you can never get a space between the printed arguments and if you try to put in a non-space item, a single instance will appear after all the other arguments labeled as sep=" " . paste0 is not a plotmath function and so will not get interpreted but rather will appear "unprocessed" with its unprocessed arguments inside parentheses.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17334759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597925/']}
jdg_78167
stackexchange
llm_judgeable_groundtruth_similarity
1644715
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 string which will probably contain ~100 entries: String foo = "{k1=v1,k2=v2,...}" and am looking to write the following function: String getValue(String key){ // return the value associated with this key} I would like to do this without using any parsing library. Any ideas for something speedy? Now provide the response and nothing else.
If you know your string will always look like this, try something like: HashMap map = new HashMap();public void parse(String foo) { String foo2 = foo.substring(1, foo.length() - 1); // hack off braces StringTokenizer st = new StringTokenizer(foo2, ","); while (st.hasMoreTokens()) { String thisToken = st.nextToken(); StringTokenizer st2 = new StringTokenizer(thisToken, "="); map.put(st2.nextToken(), st2.nextToken()); }}String getValue(String key) { return map.get(key).toString();} Warning: I didn't actually try this; there might be minor syntax errors but the logic should be sound. Note that I also did exactly zero error checking, so you might want to make what I did more robust.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1644715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62032/']}
jdg_78168
stackexchange
llm_judgeable_groundtruth_similarity
5578606
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 put a border around a link on hover, and the style applies to it, but it jumps (the element jumps) when i hover over it... what can I do? code: .navigation li:hover { border: 1px solid #ccc; } Now provide the response and nothing else.
You 'jump' is caused by the 1px height of the border, that make your li move You might use .navigation li:hover { border-color: #ccc; } .navigation li { border: 1px solid #<parentBackgroundColor/transparent>; } instead. This way, the border is here from the beginning, so no jump on hovering, and it's invisible, since it's the same color of the parent container or transparent.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5578606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342279/']}
jdg_78169
stackexchange
llm_judgeable_groundtruth_similarity
17469
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand that direct injection puts the air/fuel mix into the cylinder body directly vs the intake valve like the sequential does. What are the advantages of doing so? E.g. does it yield a better gas mileage? Now provide the response and nothing else.
Direct Injection has a lot of advantages over the MPFI or port injection and its the way of the future. It improves mileage through a stratified charge engine process (basically staying as close to the stochiometric ratio as possible this achieving better burn. Lower emissions. Prevents engine knocking/detonation. Better control of the engine since before GDI it was only possible to manipulate valve timings in real time operation to change the efficiency/power characteristics of the engine, now since you can vary the fuel pressure,amount. there are a whole lot of possibilities to explore. GDI engines are built sturdier compared to MPFI engines and last longer. Better power output compared to mpfi. The ultimate advantage of GDI is that through this technology everything happening inside the engine can be precisely controlled by the electronics and nothing is left to chances.For example in mpfi some amount of fuel can be left over inside the injectors though not causing an issue , causes slight variation in every stroke but when you move over to GDI , its like a German train time table .it will be Perfect.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/17469', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/2618/']}
jdg_78170
stackexchange
llm_judgeable_groundtruth_similarity
349115
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've read several popular articles telling that frequent opening of the fridge highly increases the power consumption. Is it really so significant? Isn't the heat in the room-temperature food which is brought to the fridge so much more relevant that some air which goes into the fridge upon opening the door is nothing compared to that? To make it more concrete: How many times do I have to open and close the fridge so the effect is comparable with putting there a 1 litre box of milk at the room temperature? Let's say the room has 22°C, the fridge 7°C. Now provide the response and nothing else.
That depends on whether the fridge monitors the temperature or not. Where I work, the large walk-in fridge has a temperature monitor. It starts to cool only when the temperature rises above 4.7°C and stops when it sinks to 3.5°C. The fridge is very well insulated, meaning the fridge very rarely has to turn on when the door is closed. I frequently retrieve items from the fridge. This normally means the door is open for less than 15 seconds, but in that time the fridge frequently rises to 5+°C, and you hear the cooler start up again. For that fridge, energy consumption is close to 0 when not opened and reaches its maximum every time it is opened. However, you want to know the difference between opening the fridge and cooling 1l of milk. The Carnot coefficient of refrigeration $$\gamma = {T_c \over T_h-T_c}$$is the ratio of the heat extracted to the work required to extract this heat. $T_c$ is the temperature in the fridge (I'll say 2°C = 275 K), and $T_h$ is room temperature (at 22°C = 295 K), So $\gamma = 13.75$. This means to move one joule of heat energy from the milk to outside it takes 0.073 J from the mains. The energy we want to remove from 1 litre of milk when cooling from $22°C$ to 2°C is ( a , b )$$Q=mc\Delta\theta = 1\text{kg} \times 4181 {\text{J} \over \text{kg} °C} \times 20°C = 83620 \text{J}$$removed from the milk (assuming milk $\approx$ water - it's close, but not perfect ). This will take $83620 \text{J} \times 0.073 = 6104 \text{J}$. My fridge contains about 224l (10 mol) of air. Opening the door raises the temperature from 4°C to around 10°C (I just checked). The $\gamma$ ratio for that is 46.17, so every Joule removed requires 0.02J. Cooling 224l of air from 10°C to 4°C means moving $Q = 0.288 \text{kg} \times 1000 {J \over kg °C} \times 6°C = 1728 \text{J}$. This will take $1728 \times 0.02 = 34.56$. However, when I open my fridge, a 15W bulb is turned on. If I open the fridge for 10 seconds, the bulb has already used 4.3x more electricity than will be used cooling the air. This means you can open the fridge over 175 times before you've reached the energy consumption of cooling your milk (although when including the light bulb, it’s closer to just 33 times). However, at current electricity costs , it's around \$0.00026 to cool that milk - so I doubt the power consumption will ever really matter to you. If you drink the average amount of milk for a French citizen ( 260 litres - Wikipedia has bizarre lists ) you’re spending just \€0.067 per year on your milk. Instead of worrying about the milk here’s a few quick suggestions: turning lightbulbs off, and changing for energy saving ones - up to €180/yr buy a TV which uses very little electricity in standby mode - up to €38/yr don’t boil too much water - up to €58/yr
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/349115', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/72027/']}
jdg_78171
stackexchange
llm_judgeable_groundtruth_similarity
278163
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 catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client. e.g. The Page is loadedEvery control has been rendered correctlyThe Full html of the page is ready to be transferred back to the client Is there a way to that in ASP.NET? Now provide the response and nothing else.
You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example protected override void Render(HtmlTextWriter writer){ StringWriter output = new StringWriter(); base.Render(new HtmlTextWriter(output)); //This is the rendered HTML of your page. Feel free to manipulate it. string outputAsString = output.ToString(); writer.Write(outputAsString);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/278163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32582/']}
jdg_78172
stackexchange
llm_judgeable_groundtruth_similarity
33181748
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this button in my viewController and when I press on it, it should go to the TableViewController. When I do this the app crashes and prints this error in the console. Can someone tell me what Im doing wrong? Thank you! Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] instantiated view controller with identifier "UIViewController-iLh-Fe-Ezq" from storyboard "Main", but didn't get a UITableView.' Now provide the response and nothing else.
When I got this error, I had initially used the boilerplate code for the class UITableViewController , but the actual view controller was a UIViewController . Original code (resulting in the error) : Note that this is connected to a UIViewController in Storyboard. class MainViewController: UITableViewController {//insert rest of code here //note that funcs such as numberOfRowsInSection(_:) will have the override keyword } Working code (removing the error) : class MainViewController: UIViewController {//insert code here //you also must *remove the override keywords* for// some of the included functions or you will get errors} Remember also to reference an IBOutlet for your UITableView in your view controller, and set the delegate and datasource (in Storyboard, you Ctrl+Drag from the UITableView to the yellow circle at the top of the view controller, and click dataSource. Repeat this for the delegate as well).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33181748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4921547/']}
jdg_78173
stackexchange
llm_judgeable_groundtruth_similarity
804483
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: The following integrals look like they might have a closed form, but Mathematica could not find one. Can they be calculated, perhaps by differentiating under the integral sign? $$I_1 = \int_{-\infty }^{\infty } \frac{\sin (x)}{x \cosh (x)} \, dx$$$$I_2 = \int_{-\infty }^{\infty } \frac{\sin ^2(x)}{x \sinh (x)} \, dx$$ Now provide the response and nothing else.
First I'm going to evaluate $$\int_{-\infty}^{\infty} \frac{\cos ax}{\cosh x} \ dx .$$ Integrate the function $ \displaystyle f(z) = \frac{e^{iaz}}{\cosh z}$ around a rectangle on the complex plane with vertices at $z= R$, $ z= R + i \pi$, $z= -R + i \pi$, and $z= - R$. As $R \to \infty$, $ \displaystyle \int f(z) \ dz$ vanishes on the left and right sides of the rectangle. So going around the rectangle counterclockwise, we get $$ \int_{-\infty}^{\infty} f(x) \ dx + \int_{\infty}^{-\infty} f(t + i \pi) \ dt = 2 \pi i \ \text{Res} [f(z),i \pi] ,$$ which implies $$ (1+ e^{- a \pi}) \int_{-\infty}^{\infty} \frac{e^{iax}}{\cosh x} \ dx = 2 \pi i \lim_{z \to i \pi /2} \frac{e^{iaz}}{\sinh z} = 2 \pi \ e^{- a \pi /2} .$$ And equating the real parts on both sides of the equation, we get $$ \int_{-\infty}^{\infty} \frac{\cos ax}{\cosh x} \ dx = \frac{2 \pi}{e^{a \pi /2} + e^{- a \pi/2}} = \pi \ \text{sech} \left( \frac{a \pi}{2}\right) .$$ Then $$ \begin{align} \int_{0}^{a} \int_{-\infty}^{\infty} \frac{\cos ax}{\cosh x} \ dx \ da &= \int_{-\infty}^{\infty} \int_{0}^{a} \frac{\cos ax}{\cosh x} \ da \ dx \\ &= \int_{-\infty}^{\infty} \frac{\sin ax}{x \cosh x} \ dx \\ &= \pi \int_{0}^{a} \text{sech} \left(\frac{a \pi}{2} \right) \ da \\ &= 2 \int_{0}^{a \pi /2} \text{sech}(u) \ du \\ &= 4 \int_{0}^{a \pi /2} \frac{e^{u}}{1+e^{2u}} \ du \\ &= 4 \int_{1}^{e^{a \pi /2}} \frac{1}{1+w^{2}} \ dw \\ &= 4 \left(\arctan (e^{a \pi /2}) - \frac{\pi}{4} \right) . \end{align}$$ Therefore, $$ \int_{-\infty}^{\infty} \frac{\sin x}{x \cosh x} \ dx = 4 \arctan (e^{\pi /2}) - \pi \approx 2.3217507819 . $$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/804483', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111187/']}
jdg_78174
stackexchange
llm_judgeable_groundtruth_similarity
240865
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a list of list of positive integers $s = \{s_1, s_2, ..., s_k\}$ , each list $s_i$ is possibly of different lengths, and I want to find out if there exists a $k$ -tuple of the $s_i$ that sums exactly to $n$ . In other words, I want to partition $n$ into $k$ integers, each taken from the corresponding $s_i$ . I am not aware if there is any theoretical method to prove that such a solution exists, for any $n$ and $s$ in general. IntegerPartitions cannot deal with nonuniform integer lists (3rd argument). Hence I try to generate all tuples and quit at the first matching case found: s = {{1, 2, 3}, {4, 5, 6, 7}, {1, 3}, {2, 4, 6}};n = 16;Catch@Outer[If[Plus[##] == n, Throw[{##}], 0] &, Sequence @@ s](* {1, 6, 3, 6} *) However, this is not compilable, due to Sequence . This may be remedied, but what I would like to have is a construct that: Does not store its found values; Can abort constructing a tuple (shorter than $k$ ) if its partial sum is already above $n$ ; Can find a partial tuple not shorter than $k_{\min}$ ( $k_{\min} \le k_{\max}$ ) if it exactly sums to $n$ . This is an extension of the above described problem, and considers only tuples that are built from the left (i.e. each $s_i$ always corresponds to the $i^{th}$ position in the final tuple). I expect to work with large lists and $n$ , and I do not want to exhaust memory. I am not sure that lazy tuples construction is a viable option here, due to pts. 2 and 3. But feel free to prove me wrong. Addition: The obvious cases, like Total[Min/@ Take[s, kmin]] > n and Total[Max/@s] < n should of course be pre-checked before going into long computations. Now provide the response and nothing else.
You could use LinearProgramming . To use LinearProgramming , convert the list of lists into a single list. For your example we create the list {1, 2, 3, 4, 5, 6, 7, 1, 3, 2, 4, 6} . Since there is no criteria for which tuple to return, I use a cost vector of all 1s. Then, LinearProgramming will try to find a vector v whose dot product with this cost vector is minimized, and which also satisfies various constraints: The first constraint is that each member of v is a nonnegative integer (actually 0 or 1). The second constraint is that at most 1 member of each list of integers can be selected. For example, the constraint that at most 1 member of the first list is selected is given by: {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0} . v <= 1 The third constraint is that the selected members must have a particular total. For example, the constraint that the total must be 16 is given by: {1, 2, 3, 4, 5, 6, 7, 1, 3, 2, 4, 6} . v = 16 The final constraint is that it is not allowed to select a member of a list if the previous list has no member selected. For example, the constraint that the 4th list cannot have a member selected if the third list has no member is given by: {0, 0, 0, 0, 0, 0, 0, 1, 1, -1, -1, -1} . v >= 0 The syntax of LinearProgramming is that the second argument consists of the above lists, while the third argument specifies what the value on the RHS is, and whether < , = or > is used. For example, for the second constraint, using {1, -1} indicates that the RHS is 1 and the -1 . indicates that <= is used. The fourth argument specifies what the range of the values of v are, and using 0 means that all values greater than 0 are allowed. The final argument specifies the domain, which in our case is integers. The following function does this: findTuple[s_, n_] := Module[{len, lens, left, v, indicators}, lens = Length /@ s; len = Total[lens]; left = FoldList[Plus, 0, Most[lens]]; indicators = MapThread[PadRight[ConstantArray[1, #1], len, 0, #2]&, {lens, left}]; v = Quiet[ LinearProgramming[ ConstantArray[1, Total @ lens], Join[ indicators, -Differences[indicators], {Flatten @ s} ], Join[ Table[{1,-1},Length[s]], Table[{0,1}, Length[s]-1], {{n,0}} ], 0, Integers ], LinearProgramming::lpip ]; Pick[Flatten[s],v,1]] Small examples: findTuple[{{1,2,3},{4,5,6,7},{1,3},{2,4,6}}, 16]findTuple[{{1,2,3},{4,5,6,7},{1,3},{2,4,6}}, 19] {3, 6, 3, 4} {3, 7, 3, 6} Bigger example: findTuple[Table[Range[18, 22], {60}], 1000]% //Length {22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 18, 22, 22, 22, 22, 18, 22, 22, 22, 22, 22, 18, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22} 46
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/240865', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/89/']}
jdg_78175
stackexchange
llm_judgeable_groundtruth_similarity
58889992
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Both Hyperledger Aries and Hyperledger Indy are platforms for building distributed ledger applicationsfor identities. What are the main differences between them? When to choose one over the other to implement a blockchain solution? Now provide the response and nothing else.
Aries is the agent (client) part of a decentralized identity (ledger, DIDs, verifiable credentials) application that is intended to be agnostic to the underlying ledger/DIDs/verifiable credentials layer. Indy is a decentralized identity implementation including support for a ledger, DIDs and verifiable credentials. Initial Aries work was to move the agent work in Indy to Aries, and so the first working versions of Aries use Indy underneath for the decentralized identity components. Over time, those components will become pluggable, and additional decentralized identity components will be supported. Thus, major parts of the indy-sdk will be deprecated, as they are implemented in Aries. For building solutions, you should always be looking at Aries to start. You will need to know what Indy does, but not the details. The only time you would need to dive into Indy is if you what to extend its capabilities to support your use case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58889992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5567627/']}
jdg_78176
stackexchange
llm_judgeable_groundtruth_similarity
13790823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm just starting out in Scala. I find myself using tuple variables a lot. For example, here's some code I wrote: /* Count each letter of a string and return in a list sorted by character * countLetter("test") = List(('e',1),('s',1),('t',2))*/def countLetters(s: String): List[(Char, Int)] = { val charsListMap = s.toList.groupBy((c:Char) => c) charsListMap.map(x => (x._1, x._2.length)).toList.sortBy(_._1)} Is this tuple syntax (x._1, x._2 etc) frowned upon by Scala developers? Now provide the response and nothing else.
Are the tuple accessors frowned upon by Scala developers? Short answer: no. Slightly longer (by one character) answer: yes. Too many _n 's can be a code smell, and in your case the following is much clearer, in my opinion: def countLetters(s: String): List[(Char, Int)] = s.groupBy(identity).mapValues(_.length).toList.sortBy(_._1) There are lots of methods like mapValues that are specifically designed to cut down on the need for the noisy tuple accessors, so if you find yourself writing _1 , etc., a lot, that probably means you're missing some nice library methods. But occasionally they're the cleanest way to write something (e.g., the final _1 in my rewrite). One other thing to note is that excessive use of tuple accessors should be treated as a nudge toward promoting your tuples to case classes. Consider the following: val name = ("Travis", "Brown")println("Hello, " + name._1) As opposed to: case class Name(first: String, last: String)val name = Name("Travis", "Brown")println("Hello, " + name.first) The extra case class definition in the second version buys a lot of readability for a single line of code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13790823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24717/']}
jdg_78177
stackexchange
llm_judgeable_groundtruth_similarity
24133022
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Typically, the sqlite store file for core data apps is located in Library>Application Support>iPhone Simulator>7.1(or whichever version you are using)>Applications>(Whichever folder contains your app)>Documents folder, but I can't find it in IOS 8. I would assume they would just add an 8.0 folder inside the iPhone Simulator folder, but it's not there. Has anybody been able to locate it? Now provide the response and nothing else.
I managed to locate the sqlite file, and its in this path now: Library/Developer/CoreSimulator/Devices/(numbers and letters)/data/Containers/Data/Application/(numbers and letters)/Documents/ (numbers and letters) stands for a folder that would be unique to your app/computer, but would look like this: 779AE2245-F8W2-57A9-8C6D-98643B1CF01A I was able to find it by going into appDelegate.m, scrolling down to the - (NSURL *)applicationDocumentsDirectory method, and NSLogging the return path, like this: // Returns the URL to the application's Documents directory.- (NSURL *)applicationDocumentsDirectory{ NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]); return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; } This will give you your unique path, making it easier for you, because it is tricky locating it with the 2 unnamed folders/strings of letters and numbers. Swift 4.2: let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)print(paths[0])
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24133022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3483813/']}
jdg_78178
stackexchange
llm_judgeable_groundtruth_similarity
3247312
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 having the following code which is spitting 'Root Element Missing' during doc.Load() . MemoryStream stream = new MemoryStream();XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);xmlWriter.Formatting = System.Xml.Formatting.Indented;xmlWriter.WriteStartDocument();xmlWriter.WriteStartElement("Root");XmlDocument doc = new XmlDocument();stream.Position = 0;doc.Load(stream);xmlWriter.Close(); I'm not able to figure out the issue. Any insights? Now provide the response and nothing else.
You haven't flushed the xmlWriter , so it may well not have written anything out yet. Also, you're never completing the root element, so even if it has written out <Root> it won't have written the closing tag. You're trying to load it as a complete document . I'm not sure at what point an XmlWriter actually writes out the starting part of an element anyway - don't forget it may have attributes to write too. The most it could write out with the code you've got is <Root . Here's a complete program which works: using System;using System.IO;using System.Text;using System.Xml;class Test{ static void Main(string[] args) { using (MemoryStream stream = new MemoryStream()) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8); xmlWriter.Formatting = System.Xml.Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Root"); xmlWriter.WriteEndElement(); xmlWriter.Flush(); XmlDocument doc = new XmlDocument(); stream.Position = 0; doc.Load(stream); doc.Save(Console.Out); } }} (Note that I'm not calling WriteEndDocument - that only seems to be necessary if you still have open elements or attributes.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3247312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250524/']}
jdg_78179
stackexchange
llm_judgeable_groundtruth_similarity
446
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Mark Dominus collected a few examples of polynomial-time reductions from various NP-hard problems to “regular expression” matching . Envisioning polynomial-time verifications isn't an enormous leap. How do you illustrate the class NP-complete to undergraduates or to friends in other fields who wanted to understand the recent fuss over Deolalikar's paper? Now provide the response and nothing else.
My favorite example to use with non-CS friends is this one: Abraham, A. Blum, Sandholm. Clearing algorithms for barter exchange markets: enabling nationwide kidney exchanges. EC07. Kidney exchange markets are essentially a restricted form of cycle cover. I like this example because a) it's easy to explain the gist(if you leave out some of the more technical details) and b) it's one of the few instances I know of where better algorithms can literally save lives! My second favorite example is the hospitals-and-residents problem (aka the college admissions problem). Each hospital ranks all residents (graduating medical students) and residents rank hospitals. Each hospital has a certain number of slots. From there it's a stable matching problem and can be solved in polynomial time. But in reality, couples can enter the system (yes, there is indeed a system ) together, so that the system won't, for example, split up married couples who are both applying for residency. The addition of couples makes the problem NP-complete. In addition to being easy to explain, this nicely demonstrates how the introduction of long-range connections can induce NP-completeness.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/446', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/362/']}
jdg_78180
stackexchange
llm_judgeable_groundtruth_similarity
970335
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 type: public class IssueForm{ Order Order {get; set;} Item Item {get; set;} Range Range {get; set;}} I created a custom model binder due to requirements on Order and Item, but Range could still use the Default Model Binder. Is there a way from within my custom model binder to call the default model binder to return a Range object? I think I just have to just setup ModelBindingContext correctly, but I don't know how. EDIT Looking at the first comment and answer -- it seems like inheriting from the default model binder could be useful. To add more specifics for my setup so far I have: public IssueFormModelBinder : IModelBinder{ public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { Order = //code to pull the OrderNumber from the context and create an Order Item = //code to pull the ItemNumber from the context and create an Item IssueForm form = IssueFormFactory.Create(Order, Item); form.Range = // ** I'd like to replace my code with a call to the default binder ** return form }} This might be a stupid way of doing it... this is my first model binder. Just pointing out my current implementation. EDIT #2 So the answers to override BindProperty will work if I can hook into like a "I'm all done binding" method and call the Factory method with the properties. I guess I really should look at the DefaultModelBinder implementation and quit being stupid. Now provide the response and nothing else.
Try something like this: public class CustomModelBinder : DefaultModelBinder { protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { if(propertyDescriptor.Name == "Order") { ... return; } if(propertyDescriptor.Name == "Item") { ... return; } base.BindProperty(controllerContext, bindingContext, propertyDescriptor); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/970335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36602/']}
jdg_78181
stackexchange
llm_judgeable_groundtruth_similarity
8800965
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 getting the date from web service like /Date(1326067200000)/ , how can I convert it to the date like DD.MM.YYYY? Now provide the response and nothing else.
You can use NSString *actDate = @"/Date(1326067200000)/"; NSString *nDate = [[[[actDate componentsSeparatedByString:@"("] objectAtIndex:1] componentsSeparatedByString:@")"] objectAtIndex:0]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:([nDate doubleValue] / 1000)]; In date you will get the actual date. Further you can format it in "MM/dd/yyyy" format by using NSDateFormatter *dtfrm = [[NSDateFormatter alloc] init]; [dtfrm setDateFormat:@"MM/dd/yyyy"]; nDate = [dtfrm stringFromDate:date]; In nDate you will get your desired date in a formatted way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8800965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076645/']}
jdg_78182
stackexchange
llm_judgeable_groundtruth_similarity
36283377
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 seen the list of all HTTP status codes.However to me it looks like there is no code for "email not verified" (used for authentication/authorization). Did you ever had the same "problem"? What HTTP status code did you use? I guess it should be a code starting with a 4 as it's a "client error". Now provide the response and nothing else.
The 4xx class of status code is intended for situations in which the client seems to have erred: 6.5. Client Error 4xx The 4xx (Client Error) class of status code indicates that the clientseems to have erred. Except when responding to a HEAD request, theserver SHOULD send a representation containing an explanation of theerror situation, and whether it is a temporary or permanentcondition. These status codes are applicable to any request method.User agents SHOULD display any included representation to the user. For authentication and authorization , 401 and 403 are the proper status codes to be used, respectively. Regardless of the status code, you should always describe that reason of the error in the response payload. 401 Unauthorized Use this status code for problems with HTTP authentication , that is, invalid credentials. 3.1. 401 Unauthorized The 401 (Unauthorized) status code indicates that the request has notbeen applied because it lacks valid authentication credentials forthe target resource . The server generating a 401 response MUST senda WWW-Authenticate header field containing at least onechallenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for thosecredentials . The user agent MAY repeat the request with a new orreplaced Authorization header field. If the 401 response contains the same challenge as the prior response, and theuser agent has already attempted authentication at least once, thenthe user agent SHOULD present the enclosed representation to theuser, since it usually contains relevant diagnostic information. 403 Forbidden Use this status code for problems with authorization , that is, the credentials are valid but they are insufficient to grant access. 6.5.3. 403 Forbidden The 403 (Forbidden) status code indicates that the server understoodthe request but refuses to authorize it . A server that wishes tomake public why the request has been forbidden can describe thatreason in the response payload (if any). If authentication credentials were provided in the request, theserver considers them insufficient to grant access . The clientSHOULD NOT automatically repeat the request with the samecredentials. The client MAY repeat the request with new or differentcredentials. However, a request might be forbidden for reasonsunrelated to the credentials. [...]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36283377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2081129/']}
jdg_78183
stackexchange
llm_judgeable_groundtruth_similarity
11832999
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 question about the sizes: var geometry = new THREE.PlaneGeometry(50, 50); var plane = new THREE.Mesh(geometry, material); plane.doubleSided = true; plane.tile = tile; So the question is : the sizes of PlaneGeometry, not in pixels right? When I have canvas aroun 500x500, it will be less than 50x50 in the end? PS> One more question, how to get size of element when it's already added to scene?Thank you! Now provide the response and nothing else.
50x50 is not pixels. It's "units". Whatever you want a "unit" to be (it's relative to the size of other objects). If you want to resize an object in a controlled way, you could do this: var geometry = new THREE.PlaneGeometry(1, 1);var plane = new THREE.Mesh(geometry, material);plane.scale.x = 50;plane.scale.y = 50;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11832999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1579479/']}
jdg_78184
stackexchange
llm_judgeable_groundtruth_similarity
6482484
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 asymmetric encryption in java. I generate .key and .crt files with own password and .crt file by openssl that said in http://www.imacat.idv.tw/tech/sslcerts.html . How to use these .key and .crt file to extract publickey and private key in Java? Now provide the response and nothing else.
Your .key and .crt files may be in PEM format. To check this open them with a text editor and check whether the content looks like ------BEGIN CERTIFICATE------ (or "begin RSA private key"...). This is generally the default format used by OpenSSL, unless you've explicitly specified DER. It's probably not required (see below), but if your certificate is in DER format (a binary format), you can convert them in PEM format using: openssl x509 -inform DER -in cert.crt -outform PEM -out cert.pem (Check the help for openssl rsa for doing something similar with the private key if needed.) You then get two options: Build a PKCS#12 file openssl pkcs12 -export -in myhost.crt -inkey myhost.key -out myhost.p12 You can then use it directly from Java as a keystore of type "PKCS12". Most Java applications should allow you to specify a keystore type in addition to the file location. For the default system properties, this is done with javax.net.ssl.keyStoreType (but the application you're using might not be using this). Otherwise, if you want to load it explicitly, use something like this: KeyStore ks = KeyStore.getInstance("PKCS12");FileInputStream fis = new FileInputStream("/path/to/myhost.p12");ks.load(fis, "password".toCharArray()); // There are other ways to read the password.fis.close(); (Then, you should be able to iterate through the aliases() of the KeyStore and use getCertificate (and then getPublicKey() for the public key) and getKey() . Use BouncyCastle 's PEMReader . FileReader fr = ... // Create a FileReader for myhost.crt PEMReader pemReader = new PEMReader(fr); X509Certificate cert = (X509Certificate)pemReader.readObject(); PublicKey pk = cert.getPublicKey(); // Close reader... For the private key, you'll need to implement a PasswordFinder (see link from PEMReader doc) for constructing the PEMReader if the private key is password-protected. (You'll need to cast the result of readObject() into a Key or PrivateKey .)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6482484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140934/']}
jdg_78185
stackexchange
llm_judgeable_groundtruth_similarity
1595128
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: $$ \int {\frac{(x-1)dx}{(x-2)(x+1)^2 x^2 }} $$I don't know about decomposition of fractions a lot,but I know that it is method which I have to use in this example. Please, help me. Now provide the response and nothing else.
You have: $$ \int {\frac{(x-1)dx}{(x-2)(x+1)^2 x^2 }} $$So it’s: $$ \frac{x-1}{(x-2)(x+1)^2 x^2} = \frac{a}{(x+1)^2} + \frac{b}{x+1} + \frac{c}{x^2} + \frac{d}{x} + \frac{e}{x-2} $$$$ x-1 = ax^3-2ax^2+bx^2 (x^2+x-2x-2)+c(x-2)(x+1)^2+dx(x-2)(x+1)^2+e(x+1)^2x^2 $$$$ x-1 = ax^3-2ax^2+bx^2(x^2+x-2x-2)+(cx-2c)(x^2+2x+1)+(dx^2-2dx)(x^2+2x+1)+ex^2(x^2+2x+1) $$$$ x-1 = ax^3-2ax^2+bx^4-bx^3-2bx^2+cx^3+2cx^2+cx-2cx^2-4cx-2c+dx^4+2dx^3+dx^2-2dx^3-4dx^2-2dx+ex^4+2ex^3+ex^2 $$$$ x-1 = ax^3-2ax^2+bx^4-bx^3-2bx^2+cx^3-3cx-2c+dx^4-3dx^2-2dx+ex^4+2ex^3+ex^2 $$you have 5 equations: $$ \begin{cases} 0=b+d+e \\ 0=a-b+c+2e \\ 0=-2a-2b-3d+e \\ 1=-3c-2d \\ -1=-2c \end{cases} $$ from 5th equotion: $$ c= \frac{1}{2} $$from 4th: $$ 1+2d=-3c,\quad2d=-3c-1,\quad 2d= \frac{-5}{2},\quad d= \frac{-5}{4} $$from 1st: $$ b=-d-e $$from 2nd: $$ a-(-d-e)+c+2e=0,\quad a+d+e+c+2e=0,\quad a+d+3e+c=0 $$ $$ a- \frac{5}{4} +3e + \frac{1}{2} = 0, \quad a+3e= \frac{3}{4}, \quad a=\frac{3}{4} -3e $$ from 3rd: $$ 0=-2(\frac{3}{4}-3e) -2(-d-e) -3d+e,\quad 0=-\frac{6}{4} + 6e+2d+2e-3d+e $$$$ 0=-\frac{6}{4} + 6e - \frac{10}{4} +2e+ \frac{15}{4} +e,\quad 0=-\frac{1}{4} +9e $$$$ e=\frac{1}{36}, \quad a=\frac{3}{4}-3e=\frac{3}{4}-\frac{3}{36}=\frac{24}{35} , \quad a=\frac{2}{3} $$ $$ b=-d-e=\frac{5}{4}-\frac{1}{36}=\frac{44}{36},\quad b=\frac{11}{9} $$so you have: $$ \begin{cases} a=\frac{2}{3} \\ b=\frac{11}{9} \\ c= \frac{1}{2} \\ d= \frac{-5}{4} \\ e=\frac{1}{36} \end{cases} $$ and now: $$ \int \left( \frac{2}{3}\frac{1}{(x+1)^2} + \frac{11}{9}\frac{1}{x+1} + \frac{1}{2}\frac{1}{x^2} - \frac{5}{4}\frac{1}{x} + \frac{1}{36}\frac{1}{x-2} \right)dx = -\frac{2}{3}\frac{1}{x+1} + \frac{11}{9}\ln|x+1| - \frac{1}{2x}-\frac{5}{4}\ln|x| + \frac{1}{36}\ln|x-2| +C $$ so the answer is: $$ \color{red}{-\frac{2}{3}\frac{1}{x+1}+\frac{11}{9}\ln|x+1|-\frac{1}{2x}-\frac{5}{4}\ln|x|+\frac{1}{36}\ln|x-2|+C} $$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1595128', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301698/']}
jdg_78186
stackexchange
llm_judgeable_groundtruth_similarity
52593360
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My code looks like this CloudFileClient client = ...;client.GetShareReference("fileStorageShare") .GetRootDirectoryReference() .GetDirectoryReference("one/two/three") .Create(); This errors if directories one or two don't exist. Is there a way to create these nested directories with a single call? Now provide the response and nothing else.
It is impossible. The SDK does not support it this way, you should create them one by one. A issue has already submitted here . If you wanna create them one by one, you can use the following sample code: static void NestedDirectoriesTest(){ var cred = new StorageCredentials(accountName, accountKey); var account = new CloudStorageAccount(cred, true); var client = account.CreateCloudFileClient(); var share = client.GetShareReference("temp2"); share.CreateIfNotExists(); var cloudFileDirectory = share.GetRootDirectoryReference(); //Specify the nested folder var nestedFolderStructure = "Folder/SubFolder"; var delimiter = new char[] { '/' }; var nestedFolderArray = nestedFolderStructure.Split(delimiter); for (var i=0; i<nestedFolderArray.Length; i++) { cloudFileDirectory = cloudFileDirectory.GetDirectoryReference(nestedFolderArray[i]); cloudFileDirectory.CreateIfNotExists(); Console.WriteLine(cloudFileDirectory.Name + " created..."); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52593360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476260/']}
jdg_78187
stackexchange
llm_judgeable_groundtruth_similarity
6019764
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 not able to create subscriptions for SSRS reports as it gives the following error: Subscriptions cannot be created because the credentials used to run the report are not stored, or if a linked report, the link is no longer valid. My set up is as following: ServerA - Database Server ServerB - Report Server MachineC - Internet explorer to view the reports So I am viewing reports on Machine C, IE, and ServerB connects to ServerA for Datasource. Now provide the response and nothing else.
The problem sounds like the report expects the user to provide credentials when it is viewed. When you create a subscription, it does not have the credentials to execute the report. Go to the report, click the properties tab, then choose Data Sources in the left pane. Are you using a shared data source? Is it using Windows integrated security? If so, can you change it to use a service account made just to run these reports? You may need to view these properties by viewing the data source itself. If it is a custom data source is the option "Credentials supplied by the user running the report" selected? If so, can you change it to "Credentials stored securely in the report server"? Either way, if you want to set up a subscription, I have made it work by providing credentials in the data source rather than have the user input them. If you are worried about security, I would suggest managing that on the report level rather than the data source level.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6019764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126808/']}
jdg_78188
stackexchange
llm_judgeable_groundtruth_similarity
4858100
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 to enumerate all imported modules? E.g. I would like to get ['os', 'sys'] from this code: import osimport sys Now provide the response and nothing else.
import syssys.modules.keys() An approximation of getting all imports for the current module only would be to inspect globals() for modules: import typesdef imports(): for name, val in globals().items(): if isinstance(val, types.ModuleType): yield val.__name__ This won't return local imports, or non-module imports like from x import y . Note that this returns val.__name__ so you get the original module name if you used import module as alias ; yield name instead if you want the alias.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4858100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62192/']}
jdg_78189
stackexchange
llm_judgeable_groundtruth_similarity
238052
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 one looks at the code for a Turing Machine (TM) with$q$ states and, let's say, $2$ symbols, they all lookpretty much the same:A list of $5$-tuples:$$< state, symbol{-}read, symbol{-}to{-}write, head{-}movement, state > \;.$$Some of the $q$-state TMs are, however, rathermore complex than others:the Busy Beaver (BB) TMs.These TMs exectute an immense number of steps on an emptytape before halting.For example, there is a $6$-state BB that takesmore than $10^{36534}$ steps before halting. (Image from Jeffrey Shallit's notes (PDF) .) My question is: Is there some measure that captures the complexity/intricacy of a TM's behavior? One can replace TM by "computer program" here.I am looking for something beyond the complexity of the description of the program, and which instead captures its possiblycomplex behavior on certain inputs.It seems the Kolmogorov complexity would treat a $q$-stateBB as equally complex to a mundane $q$-state TM. One possibility would be to run the TM on all inputs up tosome length beyond which the TM could not distinguish,and form a measure from the number of steps before halting.(Or perhaps: also before looping?)Have such measures been considered in the literature? Now provide the response and nothing else.
The equivalence of "sublinear shadowing" property and the Oseledec theorem (or, rather, of what is called "Lyapunov regularity") is due to Kaimanovich MR0947327 (89m:22006), and is explained there in detail (actually, this is a purely geometric property which has nothing to do with random products). By the way, your formulation of the Oseledec theorem is incomplete: one should add that (4) the sum of the Lyapunov exponents (taken with their multiplicities) should be equal to the exponent of the determinant (the expectation of $\log\det A(\omega)$).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/238052', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6094/']}
jdg_78190
stackexchange
llm_judgeable_groundtruth_similarity
835016
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 trying to prove that a group of order $p^2q^2$ where $p$ and $q$ are primes is solvable, without using Burnside's theorem. Here's what I have for the moment: If $p = q$, then $G$ is a $p$-group and therefore it is solvable. If $p \neq q$, we shall look at the Sylow $p$-subgroups of $G$. We know from Sylow's theorems that $n_p \equiv 1 \pmod p$ and $n_p \mid q^2$, therefore $n_p \in \{1, q, q^2\}$. If $n_p = 1$, it is over, because the Sylow $p$-Subgroup $P$ is normal in $G$ of order $p^2$, and $G/P$ has order $q^2$. Thus both are solvable and $G$ is solvable. If $n_p = q^2$, we have $q^2(p^2-1)$ elements of order $p$ or $p^2$ in $G$, and we have $q^2$ elements left to form a unique Sylow $q$-subgroup. By the same argument as before, $G$ is solvable. That's where I'm in trouble. I don't know what to do with $n_p = q$. It seems to lead nowhere. Thanks in advance for any help! Laurent Now provide the response and nothing else.
You argument works just as well with $p$ and $q$ switched, so the only time you have trouble is if both $n_p=q$ and $n_q = p$. Since $1\equiv n_p \mod p$ and $1\equiv n_q \mod q$ this puts very strong requirements on $p$ and $q$. Hint 1: Unless $n_p=1$, $n_p > p$. Hint 2: If $n_p=q$, then $q>p$. If $n_q =p$, then $p>q$. Oops. Fix for OP's argument: The OP's argument is currently flawed in the case $n_p=q^2$, so this answer is only truly helpful after that flaw is fixed. A very similar argument to the one given in this answer works. First part of your argument works, and the $p-q$ symmetry helps: If $n_p=1$ or $n_q=1$, then the group is solvable. Now we use the Sylow counting again to get some severe restrictions: If $n_p \neq 1$, then $n_p \in \{q,q^2\}$ and in both cases we have $1 \equiv q^2 \mod p$. Similarly, if $n_q \neq 1$, then $1 \equiv p^2 \mod q$. Unfortunately now we don't get an easy contradiction, but at least we only get one possibility: Since $p$ divides $q^2-1 = (q-1)(q+1)$, we must also have $p$ divides $q-1$ or $q+1$, so $p \leq q+1$ and $q \leq p+1$, so $p-1 \leq q \leq p+1$. If $p=2$ is even, then $q$ is trapped between 1 and 3, so $q=3$. If $p$ is odd, then $p-1$ and $p+1$ are both even, so the only possibility for $q \neq p$ is $q=p-1=2$ (so $p=3$) or $q=p+1=2$ (so $p=1$, nope). Hence the only possibility is $p=2$ and $q=3$ (or vice versa). In this case, we get: If $p=2$ and $q=3$, then $n_q \in \{2,4\}$. Considering the permutation action of $G$ on its Sylow $q$-subgroups, we know that $n_q=2$ is impossible (Sylow normalizers are never normal) and $n_q=4$ means $G$ has a normal subgroup $K$ so that $G/K$ is isomorphic to a transitive subgroup of $S_4$ containing a non-normal Sylow 3-subgroup and having order a divisor of 36. The only such subgroup is $A_4$, so $K$ has order 3. Hence $G/K\cong A_4$ and $K \cong A_3$ are solvable, so $G$ is solvable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/835016', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157160/']}
jdg_78191
stackexchange
llm_judgeable_groundtruth_similarity
92943
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Apache is installed and is used to serve mostly Django/Python content. I want to install nginx to serve static content. How to do it and what is a good configuration. I am on Ubuntu and Apache was installed via apt-get. Now provide the response and nothing else.
first option: do you have few ip addreses? bind apache to one of them, nginx to another. in debian world for apache in /etc/apache2/ports.conf include: Listen 1.1.2.3:80 in vhost file in /etc/apache2/sites-enabled change: NameVirtualHost 1.1.2.3:80; <VirtualHost 1.1.2.3:80>..<VirtualHost/> for nginx in /etc/nginx/sites-enabled/ add: listen 1.1.2.4:80 second option: move apache to listen on different port [ files as above. tell apache to listen on 127.0.0.1:8080 for instance ] and instruct nginx to reverse-proxy dynamic traffic to your apache while serving /static/ by nginx - for instance: server { listen 1.1.2.3:80; server_name some.name another.dname; access_log /var/log/nginx/something-access.log; location / { proxy_pass http://localhost:8080; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~* ^.+\.(jpg|js|jpeg|png)$ { root /some/where/on/your/disks; }; put your static hosting config here.} btw - think about putting static content on another domain. this should improve end-user speed a little.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/92943', 'https://serverfault.com', 'https://serverfault.com/users/28709/']}
jdg_78192
stackexchange
llm_judgeable_groundtruth_similarity
18626696
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I make content of each ListView item expands to 100% width when using a DataTemplate ? I have tried HorizontalContentAlignment="Stretch" in the ListView and HorizontalAlignment="Stretch" in the DataTemplate , but nothing seems to work, content is still aligned to the left. I have something like this: <ListView x:Name="questionsView" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" HorizontalContentAlignment="Stretch"> <ListView.ItemTemplate> <DataTemplate> <Border Background="BlueViolet" HorizontalAlignment="Stretch"> <Grid HorizontalAlignment="Stretch"> <TextBlock Text="{Binding}" /> <TextBlock HorizontalAlignment="Right">16 minutes ago</TextBlock> </Grid> </Border> </DataTemplate> </ListView.ItemTemplate></ListView> I guess there is one more layer between the ListView and the ItemTemplate . Now provide the response and nothing else.
I got it. Setting the ListView.ItemContainerStyle with a HorizontalContentAlignment setter makes the trick. I.e.: <ListView x:Name="questionsView" Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <ListView.ItemTemplate> <DataTemplate> <Border Background="BlueViolet"> <Grid HorizontalAlignment="Stretch" Margin="0"> <TextBlock Text="{Binding}" /> <TextBlock HorizontalAlignment="Right">16 minutes ago</TextBlock> </Grid> </Border> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </ListView.ItemContainerStyle></ListView>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18626696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27211/']}
jdg_78193
stackexchange
llm_judgeable_groundtruth_similarity
65821436
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 programmatically access the email of the currently used Service Account on a GCP instance when no GOOGLE_APPLICATION_CREDENTIALS is set? (ie. when using the default Service Account) I've looked through the GCP documentation, but the only resource I found can't be used with the default Service Account when no GOOGLE_APPLICATION_CREDENTIALS is set. I know that it is possible to do so using gcloud (see this SO question or documentation ), however these solutions aren't applicable when running on a ContainerOptimisedOS . I've spent a couple of weeks back and forth with the GCP support team, but they concluded with not being able to help me and redirected me to Stack Overflow for help. Now provide the response and nothing else.
The solution of John works great, on any language without any external library. However, it works only on Google Cloud environment, when a metadata server is deployed. You can't perform this test on your computer. I propose just bellow a piece of Python code (with Google OAuth library, but it works in other languages that have this library) to ask the library the current credential. If the credential is a service account (from GOOGLE_APPLICATION_CREDENTIALS on your computer, the ADC (Application Default Credential) or from the metadata server), you have the email printed, else, you have warning message because you use your user account credential import google.auth credentials, project_id = google.auth.default() if hasattr(credentials, "service_account_email"): print(credentials.service_account_email) else: print("WARNING: no service account credential. User account credential?") Note that if the default service account is used this method will print default instead of the entire email address. EDIT 1 ctx := context.Background() credential,err := google.FindDefaultCredentials(ctx) content := map[string]interface{}{} json.Unmarshal(credential.JSON,&content) if content["client_email"] != nil { fmt.Println(content["client_email"]) } else { fmt.Println("WARNING: no service account credential. User account credential?") }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65821436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3508719/']}
jdg_78194
stackexchange
llm_judgeable_groundtruth_similarity
105136
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What's the difference between a schematic , a block diagram , a wiring diagram and a PCB layout ? Why do engineers want a schematic instead of a wiring diagram? Where does Fritzing fit into this? Now provide the response and nothing else.
Schematic A schematic shows connections in a circuit in a way that is clear and standardized. It is a way of communicating to other engineers exactly what components are involved in a circuit as well as how they are connected. A good schematic will show component names and values, and provide labels for sections or components to help communicate the intended purpose. Note how connections on wires (or "nets") are shown using dots and non-connections are shown without a dot. Block Diagram A block diagram shows a higher level (or organizational layout) of functional units in a circuit (or a device, machine, or collection of these). It is meant to show data flow or organization between separate units of function. A block diagram gives you an overview of the interconnected nature of circuit assemblies or components. Wiring Diagram A wiring diagram is sometimes helpful to illustrate how a schematic can be realized in a prototype or production environment. A proper wiring diagram will be labeled and show connections in a way that prevents confusion about how connections are made. Typically they are designed for end-users or installers. They focus on connections rather than components . PCB Layout A PCB Layout is the resulting design from taking a schematic with specific components and determining how they will physically be laid out on a printed circuit board. To produce a PCB Layout, you must know the connections of components, component sizes (footprints), and a myriad of other properties (such as current, frequencies, emissions, reflections, high voltage gaps, safety considerations, manufacturing tolerances, etc.). Fritzing Fritzing is a popular open-source software program designed to help you create electronics prototypes. It uses a visual approach to allow you to connect components to Arduino using a virtual breadboard, and even provides ways to design a PCB. Its strength is in the ease with which new users can approach it. One of the principal working views is the virtual breadboard: However, as you can see, it can be time-consuming to tell exactly how components are connected, even if you are very familiar with how breadboard connections work (as most electronics engineers are). As a circuit gets more complex, the visualization becomes more cluttered. Fritzing provides a way to produce a schematic: Be sure to use this to produce a schematic if you need to ask questions about your circuit. It will help others to quickly understand the components and connections involved in your design. Prototype Photo Sometimes a photo can help engineers troubleshoot your design. Especially if quality issues are suspected, such as soldering reliability, improper connections, incorrect polarities, and other problems which might be revealed in a photo. However, realize that most photos are not immediately useful, and if your project is complicated, a picture will do little more than show that you've spent a lot of time and effort on your project! Hint: Not helpful! Images were obtained using internet image searches with license set to public domain or free to use for non-commercial use.
{}
{'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/105136', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2028/']}
jdg_78195
stackexchange
llm_judgeable_groundtruth_similarity
56487679
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a custom color in my app: extension UIColor { static var myControlBackground: UIColor { return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1) }} I use this in a custom control (and other places) as the control's background: class MyControl: UIControl { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { backgroundColor = .myControlBackground } // Lots of code irrelevant to the question} With iOS 13, I wish to have my custom control support both light and dark mode. One solution is to override traitCollectionDidChange and see if the color has changed and then update my background as needed. I also need to provide both a light and dark color. So I update my custom colors: extension UIColor { static var myControlBackgroundLight: UIColor { return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1) } static var myControlBackgroundDark: UIColor { return UIColor(red: 0.4, green: 0.3, blue: 0.2, alpha: 1) }} And I update my control code: extension MyControl { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { backgroundColor = traitCollection.userInterfaceStyle == .dark ? .myControlBackgroundDark : .myControlBackgroundLight } } }} This seems to work but it's clunky and anywhere else I happen to use myControlBackground needs to have the same code added. Is there a better solution to having my custom color and control support both light and dark mode? Now provide the response and nothing else.
As it turns out, this is really easy with the new UIColor init(dynamicProvider:) initializer. Update the custom color to: extension UIColor { static var myControlBackground: UIColor { if #available(iOS 13.0, *) { return UIColor { (traits) -> UIColor in // Return one of two colors depending on light or dark mode return traits.userInterfaceStyle == .dark ? UIColor(red: 0.5, green: 0.4, blue: 0.3, alpha: 1) : UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1) } } else { // Same old color used for iOS 12 and earlier return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 1) } }} That's it. No need to define two separate statics. The control class doesn't need any changes from the original code. No need to override traitCollectionDidChange or anything else. The nice thing about this is that you can see the color change in the app switcher immediately after changing the mode in the Settings app. And of course the color is up-to-date automatically when you go back to the app. On a related note when supporting light and dark mode - Use as many of the provided colors from UIColor as possible. See the available dynamic colors from UI Elements and Standard Colors . And when you need your own app-specific colors to support both light and dark mode, use the code in this answer as an example. In Objective-C, you can define your own dynamic colors with: UIColor+MyApp.h: @interface UIColor (MyApp)@property (class, nonatomic, readonly) UIColor *myControlBackgroundColor;@end UIColor+MyApp.m: + (UIColor *)myControlBackgroundColor { if (@available(iOS 13.0, *)) { return [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traits) { return traits.userInterfaceStyle == UIUserInterfaceStyleDark ? [self colorWithRed:0.5 green:0.4 blue:0.2 alpha:1.0] : [self colorWithRed:0.3 green:0.4 blue:0.5 alpha:1.0]; }]; } else { return [self colorWithRed:0.3 green:0.4 blue:0.5 alpha:1.0]; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56487679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1226963/']}
jdg_78196
stackexchange
llm_judgeable_groundtruth_similarity
163007
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 have seen several questions here on MO regarding large numbers, (uparrow notation, etc.), and different way to construct and compare such numbers. I am curious what the applications are for the study of such numbers, what is the motivation behind such constructs? There are plenty of constructs that produce large numbers, but the results seems to be of the form this quantity is finite, but large , which, surely, is mindboggeling and nice, but it does not reach outside the world of large numbers. Are there any famous results that use these incredibly large numbers?In particularly, where the result itself is not just of the form this number is large . I only know some places where such large numbers appear, (Ramsey theory and computability, such as the busy beaver function), but is this motivation enough for study of really large numbers in general? Clearly, there cannot be many real-world applications, since these numbers vastly exceed the number of particles in the universe. They are so large that we cannot gasp how large they are, so using them in some application will be fruitless. EDIT: I would really appreciate examples where the actual number (or big estimate) plays an essential role, not just finiteness of said numbers. A hypothetical result I am looking for could be of the following form: $f,g$ are special functions defined on positive reals,such that $f(x)$ has its first zero for some $x$ satisfying $N_f < x $ and $g(x)$ has its first zero for some $x<N_g$. Some cool non-trivial result follows only if $g$ is zero before $f$, so this would be implied by proving $N_g < N_f$, where $N_f$ and $N_G$ are explicit, and very large bounds. Thus, I am particularly interested in where working with large numbers is essential for the proof, but the result is not of the form "this number is really large".There are a lot of results of the form If we do this, then this certain number is really large , but theorems that involve explicit large numbers where the consequence other than this is finite, but very large , seems rare. Now provide the response and nothing else.
For the conceptual picture that you seem to be looking for, you probably want to think in terms of fast-growing functions as the primary object of interest, and very large numbers as evaluations of these functions at specific values of interest. One major reason for the interest in fast-growing functions is that they provide a way to calibrate the logical strength of a system of axioms; the stronger the axioms, the more functions they can prove total. In Ramsey theory, often the only known way to construct something is via some complicated iteration, and so fast-growing functions arise naturally as measuring the rate of growth of the iteration. Sometimes, one can prove a lower-bound result that shows that the objects in question really do have to grow very quickly, so the large numbers are not just being introduced to give a loose upper bound but are telling you how fast the objects really are growing. One example that Harvey Friedman likes to give is the following. Block Subsequence Theorem . Let $k\ge 1$. Then there is a longest finite sequence $x_1, \ldots, x_n$ from $\{1,\ldots,k\}$ such that for no $i < j \le n/2$ is $x_i,\ldots,x_{2i}$ a subsequence of $x_j,\ldots,x_{2j}$. For $k\ge1$, let $n(k)$ denote the length of this longest finite sequence. One can show without much difficulty that $n(1)=3$ and $n(2)=11$. It turns out that $n(3)>A(7198,158386)$, where $A$ is (a version of) the Ackermann function. Now I suppose you could argue that the specific value of $n(3)$ is of limited interest—it's just some big finite number—but the point is that the function used to express it isn't arbitrary; its appearance tells you something about the structure of the combinatorial object in question, and it's also a hint that a moderately strong induction axiom will be needed to prove the result.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/163007', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1056/']}
jdg_78197
stackexchange
llm_judgeable_groundtruth_similarity
80154
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In scientific literature, plots often have a design like what I've been trying to make (see below). These images have the following characteristics: 1) Frames on the left and on the right 2) An x-axis with (automatic) ticks but without labels. 3) Tick labels on the bottom but without the ticks themselves Plot[Sin[x], {x, 0, 10}, Frame -> {{True, True}, {True, False}}, FrameTicks -> {{All, All}, {All, None}}, FrameStyle -> {{None, None}, {White, None}}, FrameTicksStyle -> {{None, None}, {Directive[FontColor -> Gray, White], None}}, PlotRangePadding -> 0] The way I've been trying to achieve 1) and 3), is by making the lower frame and frame ticks white. However, this has an unwanted side effect. The bottom of the two frames and the graph are now overlapped by this frame which makes it seem like it is cut off. I haven't even tried 2) yet. Is there a way to get the design I like without this effect? Perhaps by removing only the ticks and not the ticklabels? Ideas for 2) are welcome aswell. In particular I'm interested in implementations that do not require functions like ImageCompose or Overlay. EDIT: I also don't want to use any (custom) packages like 'CustomTicks' Now provide the response and nothing else.
Is this ok? layout = Overlay[{ Show[#, Frame -> {{True, True}, {True, False}}, FrameStyle -> {{Automatic, Automatic}, {{FontOpacity -> 1, Opacity@0}, Automatic}}, FrameTicks -> {{Automatic, All}, {All, None}}, ImagePadding -> 35, Axes -> False] , Show[Delete[#, {1, 1}], Axes -> {True, False}, ImagePadding -> 35, TicksStyle -> FontOpacity -> 0] }] &;layout @ Plot[Sin[x], {x, 0, 10}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/80154', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/27833/']}
jdg_78198
stackexchange
llm_judgeable_groundtruth_similarity
123672
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand the physics behind a single sailed boat. I have read the following questions Sailing against the wind. Is this a fair model? What exactly is the 'lift' of a sailboat as explained by Bernoulli principle I've also been following this explanation which seemed to be helping but I am still confused. Full disclosure: my physics is pretty weak and I've never sailed, but my maths should be sound. I am (now) aware of the two components that provide the force that moves the boat: The "Newtonian aspect" , where the wind collides with the sail and this produces a force and the "Bernoulli aspect" resulting from pressure differences resulting from the air passing around the sail. (If people think this would be better as two questions, happy to break it down, but I suspect one or both will be silly) Update: It has been said by @CarlWittoff that the Bernoulli aspect is pretty trivial, so I would like to focus on how the Newtonian part of the force can achieve a force that goes into the wind. Newtonian Aspect I understand this in the most simplest sense, a sail perpendicular to the wind will produce a force on the boat proportional to the relative wind speed. As the sail is angled in to the wind, you get more "lift" and less "drag" (in plane terms). In the sailing explanation, it implies that the Newtonian aspect can be used to explain going into the wind. This is also hinted at in the first question. However, I don't understand how this can be. Surely the force applied to the sail, and hence the ship, is always in the direction of the wind. Hence it can never provide a force into the wind. The article seems to suggest you can get away without the Bernoulli effect, but I don't see how. This is my attempt at how this translates into sail. The air is pushed around the sail, which exerts a force (in purple) on the boat. However, I can see no way for this force to be into the wind. Bernoulli Aspect This is the area I am even more lost with. My understanding is that somehow, you can angle the sail in such a way that the air that goes past on one side knows to go faster which reduces the pressure, giving a force. However, I cannot seem to connect that intuition to any kind of applicable formula. Specifically, what determines the direction of the force and what is it proportional to? I'm trying to simulate a boat for a game and any help on which formulae I actually need to be plugging in would be hugely appreciated :) Now provide the response and nothing else.
Newtonian Aspect So the force generated by the sail will perpendicular to the sail. This is because only the momentum of the air particles perpendicular to the sail changes the component changes the component along the sail is unchanged. However, most sailing boats have a daggerboard or keel under the boat. Essentially this is a big plank under the boat in the water which provides a large resistance to any lateral motion (also helps prevent capsizing). Therefore the net force is forwards. See my impressive paint skills. Bernoulli Aspect This is pretty much the same in that the force is perpendicular to the sail. The idea is the same as for a plane, ignore the fact that the sail is floppy and missing a part. If anything this strengthens the argument that the Bernoulli effect isn't important. Although I haven't really though about it enough so won't give a definite answer on that. You mentioned in a comment that you don't see how this allows faster than the wind travel. This is due to apparent wind . Basically the wind swings to the front of the boat and feels faster the faster boat moves.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/123672', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/53061/']}
jdg_78199
stackexchange
llm_judgeable_groundtruth_similarity
1261807
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 what positive reals $a^2+b^2+1>(a+1)(b+1)$? A question I've come up with. AM-GM doesn't seem to give anything directly. P.S. I've edited the question to what it originally was (Jack has answered it). Otherwise it's simple. Now provide the response and nothing else.
$$a^2+b^2+1-(a+1)(b+1) = a^2+b^2-ab-a-b = 0$$is the equation of an ellipse with centre in $(a,b)=(1,1)$ and vertices in $$(0,0),(2,2),\left(1+\frac{1}{\sqrt{3}},1-\frac{1}{\sqrt{3}}\right),\left(1-\frac{1}{\sqrt{3}},1+\frac{1}{\sqrt{3}}\right),$$ hence the inequality holds for every $(a,b)$ outside that ellipse: $\hspace1in$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1261807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/236182/']}
jdg_78200
stackexchange
llm_judgeable_groundtruth_similarity
2667634
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 get some more information into my Rails logs, specifically the requested URI or current params, if available (and I appreciate that they won't always be). However I just don't seem able to. Here's what I've done so far: #config/environments/production.rbconfig.logger = Logger.new(config.log_path)config.log_level = :errorconfig.logger.level = Logger::ERROR#config/environment.rbclass Logger def format_message(level, time, progname, msg) "**********************************************************************\n#{level} #{time.to_s(:db)} -- #{msg}\n" end end So I can customize the message fine, yet I don't seem to be able to access the params/request variables here. Does anyone know if this is possible, and if so how? Or if there's a better way to get this information? (Perhaps even something Redis based?) Thanks loads, Dan Now provide the response and nothing else.
(Responding a long time after this was asked, but maybe it will help the next person.) I just did something similar. 1) you need to override your logger separately from logging request-leve details. Looks like you've figured customizing your logger out. Answer is here: Rails logger format string configuration 2) I log the request and response of all requests into my service. Note, that Rails puts a tonne of stuff into the headers, so just straight dumping the request or the headers is probably a bad idea. Also of note, my application is primarily accessed via an API. If yours is primarily a web-app, as I'm guessing most people's are, you probably don't want to inspect the response.body as it will contain your html. class ApplicationController < ActionController::Base around_filter :global_request_logging... def global_request_logging http_request_header_keys = request.headers.keys.select{|header_name| header_name.match("^HTTP.*")} http_request_headers = request.headers.select{|header_name, header_value| http_request_header_keys.index(header_name)} logger.info "Received #{request.method.inspect} to #{request.url.inspect} from #{request.remote_ip.inspect}. Processing with headers #{http_request_headers.inspect} and params #{params.inspect}" begin yield ensure logger.info "Responding with #{response.status.inspect} => #{response.body.inspect}" end end end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2667634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320362/']}
jdg_78201
stackexchange
llm_judgeable_groundtruth_similarity
10555000
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 ASP.NET MVC workflow configured as two websites managed by a load balancer. The websites use Sql Server as the session state provider and have authentication switch off (its not required). Now, sporadically I appear to be losing session state, and I believe this is because the request is being handled by the alternative server, so essentially the user is jumping from server to server, depending how the load balancer sees fit. I am not always "losing session state" at the same stage in the workflow, so I believe it is something related to the web farm configuration + sql server session state. Both applications use the same machine key to encrypt and decrypt session state stored in sql server. The configuration on both servers is as follows: <authentication mode="None" /><sessionState mode="SQLServer" sqlConnectionString="{connection-string}" /><machineKey decryptionKey="777CB456774AF02F7F1AC8570FAF31545B156354D9E2DAAD" validationKey="89B5B536D5D17B8FE6A53CBB3CA8B8695289BA3DF0B1370BC47D362D375CF91525DDB5307D8A288230DCD4B3931D23AED4E223955C45CFF2AF66BCC422EC7ECD" /> I've confirmed that this is identical on both servers, is there something I am missing? This does not occur in my development environment when I am using a single server. I fear I am suffering from the Friday blues, and no doubt will figure out the answer next week, sadly I don't want to wait! Any ideas? Now provide the response and nothing else.
Found the issue. When you create applications that you expect to share session state using Sql Server, they need the same ID configured in IIS. This is because the session ID that is generated is generated based on the application ID. (Internally the application ID is something like LM/W3SVC/1 The two servers had different IDs for each application in IIS. The resolution is to change the ID under `Manage Website -> Advanced Settings' on each server.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10555000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357693/']}
jdg_78202
stackexchange
llm_judgeable_groundtruth_similarity
13653175
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My colleagues and I are a bit stumped over the following code's behavior. def a: String = { None.foreach(return "1") return "2"}def b: String = { None.foreach(x => return "1") return "2"} As expected, invoking b does return "2". However, invoking a returns "1". When exactly is return "1" being evaluated when a is executed? Now provide the response and nothing else.
All* function evaluations of the form f({code}) are equivalent to val temp = { code }f(temp) So, in the first case, val temp = return "1"None.foreach(temp) // Never reach this point! While in the second, val temp = (x: Nothing) => return 1 // Equivalent: new Function1[Nothing,String]{ def apply(x: Nothing) = return "1" }None.foreach(temp) // Never call that weird function! so everything is okay. But, wait, foreach takes an A => Unit . How is return "1" such a function? Well, Scala starts with the most specific type possible ( Nothing , which is a subclass of anything, and therefore promises to do anything you ask of it, except it can't exist). And, then, since no values is produced by the statement (control escapes via a return), it never modifies it from Nothing . So, indeed, Nothing is a subclass of Function1[A,Unit] . And to produce that Nothing --well, to pretend to produce it--you actually run the code, and return. * Actually, if the parameter is passed by name, it's secretly converted to () => { Code } and passed in without evaluation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13653175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446713/']}
jdg_78203
stackexchange
llm_judgeable_groundtruth_similarity
5132759
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 NLog for logging, I use a wrapper to call log methods, my problem is: if I try to print information about the call site ( ${callsite} ), it prints the wrapper method and not the original method that caused the logger to log. Is there any way to get the original method that called the wrapper method instead? Now provide the response and nothing else.
See my answer to this question: Problem matching specific NLog logger name I have copied the example code (for an abbreviated NLog wrapper) from that answer here to save some trouble: class NLogLogger : ILogger { private NLog.Logger logger; //The Type that is passed in is ultimately the type of the current object that //Ninject is creating. In the case of my example, it is Class1 and Class1 is //dependent on ILogger. public NLogLogger(Type t) { logger = NLog.LogManager.GetLogger(t.FullName); } //Trace, Warn, Error, Fatal eliminated for brevity public bool IsInfoEnabled { get { return logger.IsInfoEnabled; } } public bool IsDebugEnabled { get { return logger.IsDebugEnabled; } } public void Info(string format, params object [] args) { if (logger.IsInfoEnabled) { Write(LogLevel.Info, format, args); } } public void Debug(string format, params object [] args) { if (logger.IsDebugEnabled) { Write(LogLevel.Debug, format, args); } } private void Write(LogLevel level, string format, params object [] args) { LogEventInfo le = new LogEventInfo(level, logger.Name, null, format, args); logger.Log(typeof(NLogLogger), le); } } Note that this answer was given in the context of NInject. The same principal applies to wrapping NLog even if you are not using NInject. The key is communicating to NLog the type of your wrapper. This is on example of how to write an NLog wrapper correctly (i.e. to maintain call site info). The key is in the Write method. Notice how it uses NLog's Log method. Notice also that is passes the type of the wrapper class as the first parameter. NLog uses the type information to navigate up the call stack. As soon as it sees a method whose DeclaringType is the passed-in type (i.e. the type of the wrapper), it knows that the next frame up the stack is the calling method. Also see this link (to NLog's source repository) for two more examples of "extending" Logger. One by wrapping, one by inheriting: https://github.com/jkowalski/NLog/tree/master/examples/ExtendingLoggers I am not 100% sure, but I think that you cannot simply wrap NLog and delegate the Info, Debug, Warn, etc method to NLog like this: class MyNLogWrapper{ private readonly Logger logger = LogManager.GetCurrentClassLogger(); public void Info(string msg) { logger.Info(msg); }} You need a way to tell NLog the type of your wrapper and I think that you can only do that by calling NLog via the Logger.Log method (overloaded). If this is not useful enough, post your wrapper for more help.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5132759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247402/']}
jdg_78204
stackexchange
llm_judgeable_groundtruth_similarity
18712749
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 recently switched from VB to C#. One thing that I noticed was that in C#, I have problems using comparisons as part of the case. I am not sure how to explain it in words, so here is an example of what I am trying to do. In VB, my code looks like this and works perfectly fine. Select Case ExamScore Case Is >= 90 Grade = "A" Case Is >= 80 Grade = "B" Case Is >= 70 Grade = "C" Case Is >= 60 Grade = "D" Case Else Grade = "F" End Select In C# on the other hand, Visual Studio tells me that ">=" is an invalid expression. switch (examScore) { case >= 90: grade = "A"; break; case >= 80: grade = "B"; break; case >= 70: grade = "C"; break; case >= 60; grade = "D"; break; default: grade = "F"; break; } Am I doing something wrong here, or is it simply not possible to do this in C#? Thank you very much in advance! Now provide the response and nothing else.
Top part of this answer is true for C# versions before 7. See below the line for an update for version 7 It's not possible. C# switches can only switch on exact equality: Each case label specifies a constant value. Control is transferred to the switch section whose case label contains a constant value that matches the value of the switch expression, You could replace it with a stack of if / else statements, or if you prefer, you can make something that looks quite compact, but some may frown on - a nest of conditional operators: grade = examScore >= 90 ? "A" : examScore >= 80 ? "B" : examScore >= 70 ? "C" : examScore >= 60 ? "D" : "F"; With C# 7, switch has been significantly enhanced , and it's now possible to apply more conditions within case s, although it's still not as "clean" as the VB version. E.g. you could do something like: switch (examScore){ case int es when es >= 90: grade = "A"; break; case int es when es >= 80: grade = "B"; break; case int es when es >= 70: grade = "C"; break; case int es when es >= 60; grade = "D"; break; default: grade = "F"; break;} Assuming that examScore is an int , this somewhat abuses the new "pattern matching on types" facility to be able to have something to say in the case clause, and then using the when clauses to apply arbitrary conditions to the newly introduced variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18712749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763890/']}
jdg_78205
stackexchange
llm_judgeable_groundtruth_similarity
2973284
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 going through the 99 Haskell problems to build my proficiency with the language. On problem 7 ("Flatten a nested list structure"), I found myself wanting to define a conditional behavior based on the type of argument passed to a function. That is, since *Main> :t 11 :: (Num t) => t*Main> :t [1,2][1,2] :: (Num t) => [t]*Main> :t [[1],[2]][[1],[2]] :: (Num t) => [[t]] (i.e. lists nested at different levels have different data types) it seems like I should be able to write a function that can read the type of the argument, and then behave accordingly. My first attempt was along these lines: listflatten l = do if (:t l) /= ((Num t) => [t]) then listflatten (foldl (++) [] l) else id l But when I try to do that, Haskell returns a parse error. Is Haskell flexible enough to allow this sort of type manipulation, do I need to find another way? Now provide the response and nothing else.
1. Use pattern matching instead You can solve that problem without checking for data types dynamically. In fact, it is very rarely needed in Haskell. Usually you can use pattern matching instead. For example, if you have a type data List a = Elem a | Nested [List a] you can pattern match like flatten (Elem x) = ...flatten (Nested xs) = ... Example: data List a = Elem a | Nested [List a] deriving (Show)nested = Nested [Elem 1, Nested [Elem 2, Elem 3, Nested [Elem 4]], Elem 5]main = print $ flatten nestedflatten :: List a -> [a]flatten (Elem x) = [x]flatten (Nested lists) = concat . map flatten $ lists map flatten flattens every inner list, thus it behaves like [List a] -> [[a]] , and we produce a list of lists here. concat merges all lists together ( concat [[1],[2,3],[4]] gives [1,2,3,4] ). concat . map flatten is the same as concatMap flatten . 2. To check types dynamically, use Data.Typeable And if on some rare occasion (not in this problem) you really need to check types dynamically, you can use Data.Typeable type class and its typeOf function. :t works only in GHCI, it is not part of the language. ghci> :m + Data.Typeableghci> typeOf 3 == typeOf "3"Falseghci> typeOf "a" == typeOf "b"True Likely, you will need to use DeriveDataTypeable extension too.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2973284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330826/']}
jdg_78206
stackexchange
llm_judgeable_groundtruth_similarity
42611880
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 create a web server stream. Here is the code: import 'dart:io';main() async { HttpServer requestServer = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000);requestServer.listen((request) { //comment out this or the await for to work request.response ..write("This is a listen stream") ..close();}); await for (HttpRequest request in requestServer) { request.response ..write("This is an await for stream") ..close(); }} What is the difference between listen and await for? They both do not work at the same time. You need to comment out one or the other to work, but there doesn't seem to be a difference in function here. Are there circumstances where there is a difference, and when should you use one over the other? Now provide the response and nothing else.
Given: Stream<String> stream = new Stream<String>.fromIterable(['mene', 'mene', 'tekel', 'parsin']); then: print('BEFORE');stream.listen((s) { print(s); });print('AFTER'); yields: BEFOREAFTERmenemenetekelparsin whereas: print('BEFORE');await for(String s in stream) { print(s); }print('AFTER'); yields: BEFOREmenemenetekelparsinAFTER stream.listen() sets up code that will be put on the event queue when an event arrives, then following code is executed. await for suspends between events and keeps doing so until the stream is done , so code following it will not be executed until that happens. I use `await for when I have a stream that I know will have finite events, and I need to process them before doing anything else (essentially as if I'm dealing with a list of futures). Check https://www.dartlang.org/articles/language/beyond-async for a description of await for .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42611880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3332878/']}
jdg_78207
stackexchange
llm_judgeable_groundtruth_similarity
7865612
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 one list of class type, named storeValues declared as: private List<Myclass> storeValues = new ArrayList<Myclass>(); and a variable of same class type named selected declared as: private Myclass selected; and i am saving them before deleting them(requirement) as: public String deleteAction() { saveValues(selected); fillRows.remove(selected); return null;} //saveValues Functionpublic List<Myclass> saveValues(Myclass selected){ storeValues.add(selected); return storeValues; } Now i want all these values that are stored in this list(storeValues) in some other class. how can i do it. Now provide the response and nothing else.
By default you can only access the current Controller inside a controller with ControllerContext.Controller or inside a view with ViewContext.Context . To access it from some class you need to implement a custom ControllerFactory which stores the controller instance somewhere and retrieve it from there. E.g in the Request.Items : public class MyControllerFactory : DefaultControllerFactory{ public override IController CreateController(RequestContext requestContext, string controllerName) { var controller = base.CreateController(requestContext, controllerName); HttpContext.Current.Items["controllerInstance"] = controller; return controller; }} Then you register it in your Application_Start : ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory()); And you can get the controller instance later: public class SomeClass{ public SomeClass() { var controller = (IController)HttpContext.Current.Items["controllerInstance"]; }} But I would find some another way to pass the controller instance to my class instead of this "hacky" workaround.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7865612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009380/']}
jdg_78208
stackexchange
llm_judgeable_groundtruth_similarity
5366068
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to figure out how to submit the form when the person selects the result from choices of the autocomplete. It needs to work with a mouse click or enter button. I see examples out there but always in pieces. No one shows the entire function. I have this code below but I get errors saying result is not a function. I don't know how to combine this to do what I would like. Any help is appreciated. jQuery(document).ready(function(){ jQuery("#vsearch").autocomplete("ajax/search.php", { minLength: 2});jQuery("#vsearch").result(function(event, data, formatted) { jQuery('#vsearch').value( formatted ); jQuery('#search').submit();});}); Now provide the response and nothing else.
From: http://api.jqueryui.com/autocomplete/#event-select select - Type:autocompleteselect Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing. Code examples Supply a callback function to handle the select event as an init option. $( ".selector" ).autocomplete({ select: function(event, ui) { ... }}); Bind to the select event by type: autocompleteselect. $( ".selector" ).bind( "autocompleteselect", function(event, ui) { ...}); So you would use: EDIT: (modified in case user does not select anything) $("#vsearch").autocomplete({ source: "ajax/search.php", minLength: 2, select: function(event, ui) { if(ui.item){ $('#vsearch').val(ui.item.value); } $('#search').submit(); }}); If I am sure of what you are wanting to do.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5366068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330987/']}
jdg_78209
stackexchange
llm_judgeable_groundtruth_similarity
115578
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can I simply build a webserver, make its hostname " google.com ", create a CSR off that server, and send that to a Certificate Authority for signing? Let's say I pick the cheapest and dodgiest outfit I can find. Will that work? What mechanisms are in place to stop people from doing this? I am well aware that I won't receive any traffic destined to google.com due to the DNS records pointing to the real Google, but I could MitM attack any Google traffic using this method. I could also redirect local traffic to my own server without the users knowing any better. Now provide the response and nothing else.
This is more of a problem than you think, particularly for a company like Google, because they're a frequent target for this type of shenanigans. But there are several layers of safeguards, and our protection is getting better over time. Your first line of defense is the Certificate Authority. They shouldn't let certificates be signed inappropriately. Each CA has its own mechanism for verifying your entitlement to purchase a cert for a given domain, but typically it includes having you do one or more of the following: Verify ownership of the email address listed in the WHOIS info for the domain. Verify ownership of an email address that follows one of several predetermined patterns on the domain (e.g. "administrator@{domain}") Create a specific DNS record on the domain Make a specific change to the website hosted at that domain But with as many CAs as we have, a surprising number of inappropriate certs get issued. This is a case of, "you had literally ONE job," but we have to accept that mistakes will happen. Certificate Transparency was created to help audit the CAs There's a surprising lack of accountability and transparency on the part of CAs, so Google decided to do something about it with Certificate Transparency . This is a public log of every certificate that the CA signs; if a cert doesn't show up in the log then it's not valid, and the log is append-only; you can't go back and scrub your history. It's still relatively new, but Chrome already requires it on certain CAs, including all EV CAs. The idea is that you can follow the log and see if your domain shows up when it shouldn't. Tools are still evolving to make this simpler, but it's a very promising technology. Your final line of defense is key pinning The more secure browsers will allow domain owners to "pin" one or more public keys to their domain. This is an end-around the whole PKI system and injects the trust directly into the browser. Domain owners can, via HTTP header, tell the browser to only allow certs with specific public keys, and can in fact ship that assertion pre-installed on the browser itself. This prevents an unauthorized certificate from being used, even if it has a valid CA signature. DNSSEC and DANE is where this is eventually going to go Probably. With DNSSEC, you can sign your DNS records, which means that you can put your public key signature right there in DNS. Which means you don't need a third-party certificate authority to sign your keys. That's a pretty elegant solution, but DNSSEC is a way off still; you can't use it with a number of OSes, and adoption is positively glacial.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/115578', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/102322/']}
jdg_78210
stackexchange
llm_judgeable_groundtruth_similarity
16224746
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I use C++11 when programming the Arduino? I would be fine using either the Arduino IDE or another environment. I am most interested in the core language improvements, not things that require standard library changes. Now provide the response and nothing else.
As of version 1.6.6 , the Arduino IDE enables C++11 by default. For older versions, read on: It is very easy to change the flags for any element of the toolchain, including the assembler, compiler , linker or archiver. Tested on the Arduino IDE version 1.5.7 (released on July 2014), Locate the platform.txt file, AVR architecture => {install path}\hardware\arduino\avr\platform.txt SAM architecture => {install path}\hardware\arduino\sam\platform.txt Inside that file, you can change any flag , for instance, compiler.c.flags for changing the default compilation flags for C++ files. compiler.cpp.flags for changing the default compilation flags for C++ files. You can also change any of the "recipes" or compile patters , at the corresponding section of the configuration file, under the title "AVR/SAM compile patterns". After making the changes, you must restart the Arduino IDE , at least on version 1.5.7. For instance, To enable support for C++11 (C++0x) , tested on Arduino IDE versions 1.5.7 and 1.5.8, you will simply add the flag "-std=gnu++11" at the end of the line starting with compiler.cpp.flags=". It is expected that C++11 is enabled by default in the near future on the Arduino IDE. However, as of version 1.5.8 (Oct 2014) it is still not the case.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16224746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/811310/']}
jdg_78211
stackexchange
llm_judgeable_groundtruth_similarity
653629
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am designing the architecture of an embedded system, and I have to decide between setting the power rail at 3 V or at 1.8 V. The system will have an MCU, memory and a few sensor ICs. Depending on the voltage I would have to select some ICs or others, but I wanted to understand if there is an advantage from the power consumption side. My intuition is that no, since the power would be the same, so at lower voltage you would have a higher current draw, but I am not sure of this. I haven't been able to find any information on the subject so any help is appreciated. Now provide the response and nothing else.
This can only be general guidance -- for specifics you need to scrutinize data sheets, and since part availability will be an issue, do some competing design studies. All else being equal , a given CMOS circuit will tend to consume power at the clock frequency times the supply voltage squared. But that assumes that you're running the part within its rated supply voltage and clock rate. So for that part -- yes, maybe going low on the supply voltage is good. But keep in mind that you also need to make regulated supplies, and regulators consume power. Also keep in mind that sensors and analog signal processing chips tend to run a generation or two behind in their power supply requirements; that pulls your supply voltage preference upward. Sometimes it's best to have a mixed-voltage system, with the logic powered with a lower-voltage supply than the analog stuff. It may be cheapest to go high, and power everything off of the same voltage. It may be cheapest to go low for the processor, use level converters, and power some stuff at 3.3V or higher. It may be cheapest to power everything off of 1.8V. Frankly, when I'm doing circuit design I find that grinding through the design studies to make this sort of decision is what makes "work" a dirty four-letter word, but it's satisfying to be done and know you're working from a firm basis.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/653629', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/332627/']}
jdg_78212
stackexchange
llm_judgeable_groundtruth_similarity
50856936
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After reading several articles, I am still quite confused about correctness of my implementation of getting last hidden states from BiLSTM. Understanding Bidirectional RNN in PyTorch (TowardsDataScience) PackedSequence for seq2seq model (PyTorch forums) What's the difference between “hidden” and “output” in PyTorch LSTM? (StackOverflow) Select tensor in a batch of sequences (Pytorch formums) The approach from the last source (4) seems to be the cleanest for me, but I am still uncertain if I understood the thread correctly. Am I using the right final hidden states from LSTM and reversed LSTM? This is my implementation # pos contains indices of words in embedding matrix# seqlengths contains info about sequence lengths# so for instance, if batch_size is 2 and pos=[4,6,9,3,1] and # seqlengths contains [3,2], we have batch with samples# of variable length [4,6,9] and [3,1]all_in_embs = self.in_embeddings(pos)in_emb_seqs = pack_sequence(torch.split(all_in_embs, seqlengths, dim=0))output,lasthidden = self.rnn(in_emb_seqs)if not self.data_processor.use_gru: lasthidden = lasthidden[0]# u_emb_batch has shape batch_size x embedding_dimension# sum last state from forward and backward directionu_emb_batch = lasthidden[-1,:,:] + lasthidden[-2,:,:] Is it correct? Now provide the response and nothing else.
In a general case if you want to create your own BiLSTM network, you need to create two regular LSTMs, and feed one with the regular input sequence, and the other with inverted input sequence. After you finish feeding both sequences, you just take the last states from both nets and somehow tie them together (sum or concatenate). As I understand, you are using built-in BiLSTM as in this example (setting bidirectional=True in nn.LSTM constructor). Then you get the concatenated output after feeding the batch, as PyTorch handles all the hassle for you. If it is the case, and you want to sum the hidden states, then you have to u_emb_batch = (lasthidden[0, :, :] + lasthidden[1, :, :]) assuming you have only one layer. If you have more layers, your variant seem better. This is because the result is structured (see documentation ): h_n of shape ( num_layers * num_directions, batch, hidden_size ): tensor containing the hidden state for t = seq_len By the way, u_emb_batch_2 = output[-1, :, :HIDDEN_DIM] + output[-1, :, HIDDEN_DIM:] should provide the same result.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50856936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2174310/']}
jdg_78213
stackexchange
llm_judgeable_groundtruth_similarity
28785833
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 is a good way to add a new value to existing Stream ? All I can imagine is something like this: public <T> Stream<T> addToStream(Stream<T> stream, T elem ) { List<T> result = stream.collect(Collectors.toList()); result.add(elem); return result.stream();} But I'm looking for something more concise that I can use in lambda expression without verbosity. Another question appeared when I tried to implement PECS principle: public <T> Stream<? super T> addToStream(Stream<? super T> stream, T elem ) { List<? super T> result = stream.collect(Collectors.toList()); //error result.add(elem); return result.stream();} Seems like wildcard doesn't work with Stream.collect and I'm wondering why. Thanks in advance. Now provide the response and nothing else.
The question belies an incorrect assumption: that streams actually contain their data. They do not; streams are not data structures, they are a means for specifying bulk operations across a variety of data sources. There are combinators for combining two streams into one, such as Stream.concat , and factories for creating streams from a set of known elements ( Stream.of ) or from collections ( Collection.stream ). So you can combine these if you want to produce a new stream that is the concatenation of the stream you have in hand, along with a new stream describing the new elements. The problem in your PECS example is that you've got three occurrences of ? super T , and you are assuming they describe the same type, but they do not. Each occurrence of a wildcard corresponds to a unique capture, which isn't what you want; you need to give that type variable a name so the compiler knows that the type of the list and the type of the input stream are the same. (Also, don't materialize a collection; that's expensive, and potentially non-terminating if the stream is not finite. Just use concat.) So the answer is: you just got the generics wrong. Here's one way to do it: public<T> Stream<T> appendToStream(Stream<? extends T> stream, T element) { return Stream.concat(stream, Stream.of(element));} You confused yourself with PECS because you were thinking about "inserting" into the stream, when in fact you're consuming from it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28785833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4434651/']}
jdg_78214
stackexchange
llm_judgeable_groundtruth_similarity
23654
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: Is it possible to implement scheme where remote server just share its filesystem (or resizable container file in it) and it's locally encrypted and mounted? And what is best practical method? (On linux.) Example use is backup storage on not very trusted server. Now provide the response and nothing else.
Sounds like what you're looking for is encfs . It's FUSE layer on top of any existing FS which encrypts and decrypts on-the-fly, storing the encrypted version in the underlying filesystem. The catch is that file metadata (ownership, sizes, times) is visible, but content and names are not. You can also use --reverse to go the other way around: make an encrypted view of an unencrypted fs -- useful for making rsync-friendly encrypted backups. EDIT TO ADD As pointed out by Æsahættr, another usable option is eCryptfs . This is an in-kernel FS driver, which means root permission is required. But it's very low performance overhead and much faster then encfs in my own tests. While the implementation is quite a bit different between the two, the way you use them is nearly identical: encfs /base_dir/ /view_dir/# ormount -t ecryptfs /base_dir/ /view_dir/ By default, encfs scrambles filenames while ecryptfs does not, but these options are configurable. Also, ecryptfs adds much more per-file overhead than encfs does because it stores metadata in the file itself, while encfs stores it in a hidden xml file. Also, the --reverse option that encfs has doesn't really translate well to ecryptfs; ecryptfs has ecryptfs_encrypted_view but it probably won't work the way you expect it to. Supposedly this is a work-in-progress. Both can use any filesystem as a base; including, for example sshfs. But bear in mind that file ownership and permissions are stored as-is on the base filesystem, which could mean access-denied errors if you don't match things up correctly, or losing permissions completely if you base on a FS that doesn't support them.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/23654', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/15454/']}
jdg_78215
stackexchange
llm_judgeable_groundtruth_similarity
1651240
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to get the NSKeyedArchiver to write out my data in a human readable form (i.e. not as a binary file) I understand that I can use ... setOutputFormat: NSPropertyListXMLFormat_v1_0 But ... I just can't seem to get the syntax right, can anyone point me in the right direction? NSData *artistData;NSLog(@"(*) - Save All");artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection ];[artistData writeToFile:@"/Users/fgx/Desktop/stuff" atomically:YES]; EDIT I added setOutputFormat (see below) but I get a warning at compile, what am I missing? warning: NSData may not respond to 'setOutputFormat:' Here is the code I used. NSLog(@"(*) - Save All");artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection ];[artistData setOutputFormat: NSPropertyListXMLFormat_v1_0];[artistData writeToFile:@"/Users/fgx/Desktop/stuff" atomically:YES]; gary Now provide the response and nothing else.
This is what you have to do: NSMutableData *data = [NSMutableData data];NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];[archiver setOutputFormat:NSPropertyListXMLFormat_v1_0];[archiver encodeObject:artistCollection forKey:@"root"];[archiver finishEncoding];[data writeToFile:@"/Users/fgx/Desktop/stuff" atomically:YES];[archiver release]; Note that you must use [archiver encodeObject:artistCollection forKey:@"root"] instead of [archiver encodeRootObject:artistCollection]; as suggested by Sean. This is because NSKeyedArchiver does not override NSCoder encodeRootObject: method. I consider this a bug and will report it to Apple. Now, the real question is why do you want to write XML instead of the default binary format? If it's for debugging purpose, I suggest you to use TextWrangler which will allow you to transparently edit binary plist files as if they were XML.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1651240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164216/']}
jdg_78216
stackexchange
llm_judgeable_groundtruth_similarity
25871815
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 set Spanish as development language for an iOS app. I'm already using Xcode 6, and I changed the Localization native development region entry in app's Info.plist ( CFBundleDevelopmentRegion ) from "en" to "es". However, in Project > Info > Localizations, English remains set as Development Language. As said in Information Property List Key Reference , CFBundleDevelopmentRegion specifies the default language. I need to set Spanish to the default language, what am I missing? Thanks Now provide the response and nothing else.
Here's how you can do this: Add the language you want to be your Base language first. Uncheck all of the files that Xcode offers to localize for you. In the Info.plist , change the development region to the language that you want to be your base language. Note that the property is a bit misnamed, because its value should be a language code (with an optional country code), rather than a region or country code. Close your project in Xcode. In another code editor, open projectname.xcodeproj/project.pbxproj and search for developmentRegion . You should see a line like developmentRegion = English; . Change this to reference the same language you put in your Info.plist file. Reopen the project in Xcode. Go through all your localizable files and check the boxes next to English to generate the localizable resources. Note that for storyboards and xibs, Xcode might create a storyboard instead of a strings file. If that happens, just change the filetype to strings file. Here's an example of the result for me using fr as the Base language:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25871815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1833423/']}
jdg_78217
stackexchange
llm_judgeable_groundtruth_similarity
151891
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that sensitive authentication data such CAV2/CVC2/CVV2/CID4,PIN cannot be stored in any format or even encrypted or hashed (Requirement 3.2). But banks are storing these data and they are certified. How they are bypassing these requirements? The second point is about recurring (not tokenization) payment which needs the CVV in order to process the payment. How can this be implemented if the merchants or service providers are not allowed to store the CVV? Now provide the response and nothing else.
So banks are known as "issuers" in PCI DSS, in section 3.2 of PCI DSS you can note in the guidance Entities that issue payment cards or that perform or support issuing services will often create and control sensitive authentication data as part of the issuing function. It is allowable for companies that perform, facilitate, or support issuing services to store sensitive authentication data ONLY IF they have a legitimate business need to store such data. Further it states that, For non-issuing entities, retaining sensitive authentication data post-authorization is not permitted. Because they issue cards, they're allowed. To answer your second question, if you need the CVV code to authenticate a recurring payment, tokenization is generally how to work around needing the CVV. You submit the payment information to the processor, they give you a token back representing the information, which can then be used later to submit a payment with their payment credentials, but does not contain any actual information of the client and can be safely stored. This allows you to submit payment without the CVV for recurring payments.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/151891', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/131039/']}
jdg_78218
stackexchange
llm_judgeable_groundtruth_similarity
44037516
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Beware: I'm not trying to compare if the characters are equals. Because I know how to use the String.equals() method. This question is about String reference I was studying for the OCA exam when I started to learn about the class String and it properties as immutability, etc. According to what I read or may understand about String pool is that when a string is created Java stores this object on what they call String pool and if a new string is created with the same value it is going to make reference to the string on the String pool except is the case we use the new keyword as this creates a new reference even both string contains the same value. For example: String a = "foo";String b = "foo";String c = new String("foo");boolean ab = (a == b); // This return trueboolean ac = (a == c); // This return false To be clear what this code is making is on the first line of code it will create the String a = "foo" and store this on the String pool , and on the second line of code it will create the String b and reference to "foo" because this already exist on the String pool . But line 3 will create a new reference of this string no matter if this already exist. Here is a little graphic example about what is happening: The problem comes on the followings lines of code. When the string is created by concatenation does java make something different or simple == comparator have another behaviour ? Example A: String a = "hello" + " world!";String b = "hello world!";boolean compare = (a == b); // This return true Example B: a = "hello";b = "hel" + "lo";compare = (a == b); // This return true Example C: a = "Bye";a += " bye!";b = "Bye bye!";compare = (a == b); // This return false To watch the code running: ( http://ideone.com/fdk6KL ) What is happening ? EDIT Fixing error on the Example B: b = 'hel' + 'lo' Adding clarification about the problem. It's not a comparison problem cause I know the use of String.equals() the problem is on the reference on the String pool Now provide the response and nothing else.
"When the string is created by concatenation does java make something different or simple == comparator have another behaviour?" No it does not change its behavior, what happens is that: When concatenating two string literals "a" + "b" the jvm joins the two values and then check the string pool, then it realizes the value already exists in the pool so it just simply assign this reference to the String. now in more details: Look at the compiled bytecode below of this simple program: public class Test { public static void main(String... args) { String a = "hello world!"; String b = "hello" + " world!"; boolean compare = (a == b); }} First the JVM loads the string "hello world! and then push it to string pool (in this case) and then loads it to the stack (ldc = Load constant) [see point 1 in Image] Then it assign the reference created in the pool to the local variable (astore_1) [see point 2 in Image] Notice that the reference created in the string pool for this literal is #2 [See point 3 in Image] The next operation is about the same: in concatenates the string, push it to the runtime constant pool (string pool in this case), but then it realizes a literal with the same content already exists so it uses this reference (#2) and assign in to a local variable (astore_2). Thus when you do (a == b) is true because both of them are referencing to the string pool #2 which is "hello world!". Your example C is kind of different tho, because you're using the += operator which when compiled to bytecode it uses StringBuilder to concatenate the strings, so this creates a new instance of StringBuilder Object thus pointing to a different reference. (string pool vs Object)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44037516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3700378/']}
jdg_78219
stackexchange
llm_judgeable_groundtruth_similarity
59735936
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Google published a brand new version to handle the payments in Android but after searching quite a while I cannot find a single example or tutorial from someone who succeeded implementing it. The documentation is very short and provides only a part of the necessary code: https://developer.android.com/google/play/billing/billing_library_overview The only sample provided is made with Kotlin: https://github.com/android/play-billing-samples Seems like they forgot about Java developers... Does anyone know a tutorial online or succeeded to implement it? My current code is far from working to be published yet. Now provide the response and nothing else.
Thanks @Webfreak, your answer for Kotlin guided to me to the right direction. Here is how I implemented it for Java: First add the 'billingclient' library to gradle : implementation 'com.android.billingclient:billing:X.X.X' And add the required permissions in the manifest file: <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="com.android.vending.BILLING" /> The Activity must implements the following interfaces: public class MainActivity extends AppCompatActivity implements ... PurchasesUpdatedListener, AcknowledgePurchaseResponseListener { Then I initialize the billing client inside the onCreate method: /** IN-APPS PURCHASE */ private BillingClient mBillingClient; private long mLastPurchaseClickTime = 0; private List<String> mSkuList = new ArrayList<>(); private List<SkuDetails> mSkuDetailsList = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // AppPrefs is just a standalone class I used to get or set shared preferences easily mPrefs = AppPrefs.getInstance(this); // Rest of your code ... /** IN-APP PURCHASES */ // Initialize the list of all the in-app product IDs I use for this app mSkuList.add(Parameters.UNIT_P1);// NoAdsPurchased mSkuList.add(Parameters.UNIT_P2);// CustomizationPurchased mSkuList.add(Parameters.UNIT_P3);// ChartsPurchased // Initialize the billing client setupBillingClient(); // Apply the upgrades on my app according to the user's purchases applyUpgrades(); } The method setting up the billing client is here, along with the metyhod I use to retrieve the avaialble in-app products fro the app: private void setupBillingClient() { mBillingClient = BillingClient .newBuilder(MainActivity.this) .enablePendingPurchases() // Useful for physical stores .setListener(MainActivity.this) .build(); mBillingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(BillingResult billingResult) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { // Load the available products related to the app from Google Play getAvailableProducts(); Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);// Or SkuType.SUBS if subscriptions // Init all the purchases to false in the shared preferences (security prevention) mPrefs.setNoAdsPurchased(false); mPrefs.setCustomizationPurchased(false); mPrefs.setChartsPurchased(false); // Retrieve and loop all the purchases done by the user // Update all the boolean related to the purchases done in the shared preferences if (purchasesResult.getPurchasesList() != null) { for (Purchase purchase : purchasesResult.getPurchasesList()) { if (purchase.isAcknowledged()) { Log.e(TAG, purchase.getSku()); switch (purchase.getSku()) { case Parameters.UNIT_P1: mPrefs.setNoAdsPurchased(true); break; case Parameters.UNIT_P2: mPrefs.setCustomizationPurchased(true); break; case Parameters.UNIT_P3: mPrefs.setChartsPurchased(true); break; } } } } } } @Override public void onBillingServiceDisconnected() { // Try to restart the connection on the next request to // Google Play by calling the startConnection() method. // TODO Note: It's strongly recommended that you implement your own connection retry policy and override the onBillingServiceDisconnected() method. Make sure you maintain the BillingClient connection when executing any methods. Log.e(TAG, "onBillingServiceDisconnected"); } }); } private void getAvailableProducts() { if (mBillingClient.isReady()) { SkuDetailsParams params = SkuDetailsParams .newBuilder() .setSkusList(mSkuList) .setType(BillingClient.SkuType.INAPP) .build(); mBillingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() { @Override public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { mSkuDetailsList = skuDetailsList; } } }); } } When a purchase is done by the user (I allow purchases on several Fragments in my app), I call this function on the main Activity (using an interface): @Override public void purchase(String sku) { // Mis-clicking prevention, using threshold of 3 seconds if (SystemClock.elapsedRealtime() - mLastPurchaseClickTime < 3000){ Log.d(TAG, "Purchase click cancelled"); return; } mLastPurchaseClickTime = SystemClock.elapsedRealtime(); // Retrieve the SKU details for (SkuDetails skuDetails : mSkuDetailsList) { // Find the right SKU if (sku.equals(skuDetails.getSku())) { BillingFlowParams flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build(); mBillingClient.launchBillingFlow(MainActivity.this, flowParams); break; } } } Here I implement the methods inherited: @Override public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchases) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) { for (Purchase purchase : purchases) { handlePurchase(purchase); } } else { displayError(R.string.inapp_purchase_problem, billingResult.getResponseCode()); } } private void handlePurchase(Purchase purchase) { if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { // Grant entitlement to the user. applyPurchase(purchase); // Acknowledge the purchase if it hasn't already been acknowledged. if (!purchase.isAcknowledged()) { AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.getPurchaseToken()) .build(); mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, MainActivity.this); } } } @Override public void onAcknowledgePurchaseResponse(BillingResult billingResult) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { displayError(R.string.inapp_purchase_success, billingResult.getResponseCode()); } } The method I added to acknowledge a purchase on my app: private void applyPurchase(Purchase purchase) { switch (purchase.getSku()) { case Parameters.UNIT_P1: mPrefs.setNoAdsPurchased(true); break; case Parameters.UNIT_P2: mPrefs.setCustomizationPurchased(true); break; case Parameters.UNIT_P3: mPrefs.setChartsPurchased(true); break; } // I remove the ads right away if purchases if(mPrefs.getNoAdsPurchased()) { destroyAds(); } } This last method is used to apply all the upgrades/purchases on the app (with an example with the removal of the ads): private void applyUpgrades() { // No ads if (mPrefs.getNoAdsPurchased()) { destroyAds(); } else { loadAds(); } if (mPrefs.getCustomizationPurchased()) { // Allow customization // ... } if (mPrefs.getChartsPurchased()) { // Allow charts visualization // ... } } I guess this solution is not perfect yet but it is working, I will modify the code if I find improvements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59735936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2206688/']}
jdg_78220
stackexchange
llm_judgeable_groundtruth_similarity
4443419
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that a sequence of functions $(f_n)$ converges pointwise to $f$ on $[0,1]$ and uniformly to $f$ on $[0,1]/K=\{x \in [0,1]~:~x \notin K\}$ for some $K \subseteq [0,1]$ . On what conditions on $K$ we can ensure the uniform convergence on $[0,1]$ ? I am sure about uniform convergence for a finite set $K=\{k_1,k_2,...,k_m\}$ , since $||f_n-f||_\infty=\max\{|f_n(k_1)-f(k_1)|,...,|f_n(k_m)-f(k_m)|,\sup_{[0,1]/K}|f_n(x)-f(x)|\}$ , Also, I can say $f_n$ need not be uniformly convergent on $[0,1]$ for an uncountable set $K=[0,1/2]$ , But I am not sure about a countable set $K=\{k_1,k_2,...\}$ , How to justify it? Now provide the response and nothing else.
The answer is $\color{blue}{d^2/(12ab)}$ where $\color{blue}{d=\gcd(a,b)}$ . A reasonably short solution is based on $$\newcommand{\saw}[1]{\left(\!\left(#1\right)\!\right)}\saw{x}:=\begin{cases}\{x\}-1/2,&x\notin\mathbb{Z}\\\hfill 0,\hfill&x\in\mathbb{Z}\end{cases}=-\sum_{n=1}^\infty\frac{\sin 2n\pi x}{n\pi}$$ in $L^2(0,1)$ ; the same holds if $x$ is replaced by $ax$ or $bx$ , hence Parseval's theorem yields $$\int_0^1\saw{ax}\saw{bx}dx=\frac1{2\pi^2}\sum_{\substack{m,n>0\\am=bn}}\frac1{mn}=\frac1{2\pi^2}\sum_{k=1}^\infty\frac1{(bk/d)(ak/d)}=\frac{d^2}{12ab}$$ ( $am=bn$ holds if and only if $m=bk/d$ and $n=ak/d$ for some $k\in\mathbb{Z}^+$ ). There's also an elementary one, using $\saw{nx}=\sum_{k=0}^{n-1}\saw{x+k/n}$ for $n\in\mathbb{Z}^+$ , so that $$\int_0^1\saw{ax}\saw{bx}dx=\sum_{m=0}^{a-1}\sum_{n=0}^{b-1}f(m/a,n/b),\\f(u,v):=\int_0^1\saw{x+u}\saw{x+v}dx=f(u-v,0),\\f(t,0)=\frac1{12}-\frac{t(1-t)}2\quad\text{for}\quad 0\leqslant t\leqslant 1.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4443419', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1045464/']}
jdg_78221
stackexchange
llm_judgeable_groundtruth_similarity
190506
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 stuck proving this trivial inequality: on a real inner product space, $(||x||+||y||)\frac{\langle x,y\rangle}{||x|| \cdot ||y||}\leq||x+y||$ I have tried to square both sides and use the Cauchy Schwarz inequality to get to $||x||\cdot||y||\leq\langle x,y\rangle$, which is obviously incorrect. Any help is much appreciated. Now provide the response and nothing else.
When $\langle x,y \rangle \leq 0$ left side is negative (or zero), so the claim is trivial. When $\langle x,y \rangle > 0$, then we can square both sides and$$(\|x\|+\|y\|)^2\frac{{\left\langle x,y \right\rangle} \overbrace{{\left\langle x,y \right\rangle}}^{\text{C-S this}} }{\| x \|^2 \| y \|^2} \leq \left(\|x\|^2+2\|x\|\|y\|+\|y\|^2\right)\frac{\left\langle x,y \right\rangle}{\|x\|\|y\|} \text{.}$$RHS becomes$$\frac{\|x\|}{\|y\|}\overbrace{\left\langle x,y \right\rangle}^\text{C-S this}+2\left\langle x,y \right\rangle+\frac{\|y\|}{\|x\|}\overbrace{\left\langle x,y \right\rangle}^\text{C-S this} \leq \|x\|^2 + 2\left\langle x,y \right\rangle + \|y\|^2 = \| x+y \|^2$$which gives the claim.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/190506', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39348/']}
jdg_78222
stackexchange
llm_judgeable_groundtruth_similarity
15918336
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hy all, It's probably something verry simples and stupid, but i don't see it... I've got an menu that slides in and out. I've got 2 images ( 1 on the left, other on the right ) wich controls the sliding. I want that after the sliding is complete, the image src changes... I've gave the image an class named navArrow <div id="nav2"> <span id="adminMenuWrapperButtonLeft"> <img onClick="myHeight.toggle();changeArrow();" src="<?php echo site_url('media/img/system/'); ?>/SlideArrowBottom.png" width="40px" class="navArrow" /> </span> <span id="adminMenuWrapperButtonRight"> <img onClick="myHeight.toggle();changeArrow();" src="<?php echo site_url('media/img/system/'); ?>/SlideArrowBottom.png" width="40px" class="navArrow" /> </span> <div class="clear"></div> </div> The script looks like this ( the changeArrow func that should change the src of the image ): var typeArrow = 1; function changeArrow(){ if(typeArrow == 1){ $('.navArrow').each(function(){ $(this).attr('src', "<?php echo site_url('media/img/system/'); ?>/SlideArrowTop.png"); }); typeArrow = 0; } else{ $('.navArrow').each(function(){ $(this).attr('src', "<?php echo site_url('media/img/system/'); ?>/SlideArrowBottom.png"); }); typeArrow = 1 } } But i get an error saying: Uncaught TypeError: Cannot call method 'each' of null When i check in the chrome console with $('.navArrow') i get null back... So it seems that Jquery can't find my class? What did i forgot? Hope to hear soon from you guys :D EDIT1 THe full (rendered) HTML looks like this: <html><head> <title>Toegang Verkrijgen - Administrator - CMS WeProgram</title> <meta name="keywords" content=""> <meta name="description" content=""> <link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"> <script src="http://cms.local/jscript/jquery-1.9.1.min.js"></script><style type="text/css"></style> <link rel="stylesheet" href="http://cms.local/css/admin/jquery-ui.css"> <script src="http://cms.local/jscript/jquery-ui.js"></script> <script src="http://cms.local/jscript/nav.js"></script> <script src="http://cms.local/jscript/prototype.lite.js"></script> <script src="http://cms.local/jscript/moo.fx.js"></script> <!-- <link href='http://fonts.googleapis.com/css?family=Tauri&subset=latin,latin-ext' rel='stylesheet' type='text/css'> --> <link rel="stylesheet" type="text/css" href="http://cms.local/css/admin/mainStyle.css"> <link rel="stylesheet" type="text/css" href="http://cms.local/css/admin/adminMenu.css"> </head> <body> <div id="mainWrapper"> <div id="nav" style="overflow: hidden; height: 0px;"> <div id="nav_inner"> <script> document.write(create_menu('http://cms.local/')); </script><table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tbody><tr><td class="td" valign="top"><ul><li><a href="http://cms.local/index.html">User Guide Home</a></li><li><a href="http://cms.local/toc.html">Table of Contents Page</a></li></ul><h3>Basic Info</h3><ul><li><a href="http://cms.local/general/requirements.html">Server Requirements</a></li><li><a href="http://cms.local/license.html">License Agreement</a></li><li><a href="http://cms.local/changelog.html">Change Log</a></li><li><a href="http://cms.local/general/credits.html">Credits</a></li></ul><h3>Installation</h3><ul><li><a href="http://cms.local/installation/downloads.html">Downloading CodeIgniter</a></li><li><a href="http://cms.local/installation/index.html">Installation Instructions</a></li><li><a href="http://cms.local/installation/upgrading.html">Upgrading from a Previous Version</a></li><li><a href="http://cms.local/installation/troubleshooting.html">Troubleshooting</a></li></ul><h3>Introduction</h3><ul><li><a href="http://cms.local/overview/getting_started.html">Getting Started</a></li><li><a href="http://cms.local/overview/at_a_glance.html">CodeIgniter at a Glance</a></li><li><a href="http://cms.local/overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li><li><a href="http://cms.local/overview/features.html">Supported Features</a></li><li><a href="http://cms.local/overview/appflow.html">Application Flow Chart</a></li><li><a href="http://cms.local/overview/mvc.html">Model-View-Controller</a></li><li><a href="http://cms.local/overview/goals.html">Architectural Goals</a></li></ul><h3>Tutorial</h3><ul><li><a href="http://cms.local/tutorial/index.html">Introduction</a></li><li><a href="http://cms.local/tutorial/static_pages.html">Static pages</a></li><li><a href="http://cms.local/tutorial/news_section.html">News section</a></li><li><a href="http://cms.local/tutorial/create_news_items.html">Create news items</a></li><li><a href="http://cms.local/tutorial/conclusion.html">Conclusion</a></li></ul></td><td class="td_sep" valign="top"><h3>General Topics</h3><ul><li><a href="http://cms.local/general/urls.html">CodeIgniter URLs</a></li><li><a href="http://cms.local/general/controllers.html">Controllers</a></li><li><a href="http://cms.local/general/reserved_names.html">Reserved Names</a></li><li><a href="http://cms.local/general/views.html">Views</a></li><li><a href="http://cms.local/general/models.html">Models</a></li><li><a href="http://cms.local/general/helpers.html">Helpers</a></li><li><a href="http://cms.local/general/libraries.html">Using CodeIgniter Libraries</a></li><li><a href="http://cms.local/general/creating_libraries.html">Creating Your Own Libraries</a></li><li><a href="http://cms.local/general/drivers.html">Using CodeIgniter Drivers</a></li><li><a href="http://cms.local/general/creating_drivers.html">Creating Your Own Drivers</a></li><li><a href="http://cms.local/general/core_classes.html">Creating Core Classes</a></li><li><a href="http://cms.local/general/hooks.html">Hooks - Extending the Core</a></li><li><a href="http://cms.local/general/autoloader.html">Auto-loading Resources</a></li><li><a href="http://cms.local/general/common_functions.html">Common Functions</a></li><li><a href="http://cms.local/general/routing.html">URI Routing</a></li><li><a href="http://cms.local/general/errors.html">Error Handling</a></li><li><a href="http://cms.local/general/caching.html">Caching</a></li><li><a href="http://cms.local/general/profiling.html">Profiling Your Application</a></li><li><a href="http://cms.local/general/cli.html">Running via the CLI</a></li><li><a href="http://cms.local/general/managing_apps.html">Managing Applications</a></li><li><a href="http://cms.local/general/environments.html">Handling Multiple Environments</a></li><li><a href="http://cms.local/general/alternative_php.html">Alternative PHP Syntax</a></li><li><a href="http://cms.local/general/security.html">Security</a></li><li><a href="http://cms.local/general/styleguide.html">PHP Style Guide</a></li><li><a href="http://cms.local/doc_style/index.html">Writing Documentation</a></li></ul><h3>Additional Resources</h3><ul><li><a href="http://codeigniter.com/forums/">Community Forums</a></li><li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li></ul></td><td class="td_sep" valign="top"><h3>Class Reference</h3><ul><li><a href="http://cms.local/libraries/benchmark.html">Benchmarking Class</a></li><li><a href="http://cms.local/libraries/calendar.html">Calendar Class</a></li><li><a href="http://cms.local/libraries/cart.html">Cart Class</a></li><li><a href="http://cms.local/libraries/config.html">Config Class</a></li><li><a href="http://cms.local/libraries/email.html">Email Class</a></li><li><a href="http://cms.local/libraries/encryption.html">Encryption Class</a></li><li><a href="http://cms.local/libraries/file_uploading.html">File Uploading Class</a></li><li><a href="http://cms.local/libraries/form_validation.html">Form Validation Class</a></li><li><a href="http://cms.local/libraries/ftp.html">FTP Class</a></li><li><a href="http://cms.local/libraries/table.html">HTML Table Class</a></li><li><a href="http://cms.local/libraries/image_lib.html">Image Manipulation Class</a></li><li><a href="http://cms.local/libraries/input.html">Input Class</a></li><li><a href="http://cms.local/libraries/javascript.html">Javascript Class</a></li><li><a href="http://cms.local/libraries/loader.html">Loader Class</a></li><li><a href="http://cms.local/libraries/language.html">Language Class</a></li><li><a href="http://cms.local/libraries/migration.html">Migration Class</a></li><li><a href="http://cms.local/libraries/output.html">Output Class</a></li><li><a href="http://cms.local/libraries/pagination.html">Pagination Class</a></li><li><a href="http://cms.local/libraries/security.html">Security Class</a></li><li><a href="http://cms.local/libraries/sessions.html">Session Class</a></li><li><a href="http://cms.local/libraries/trackback.html">Trackback Class</a></li><li><a href="http://cms.local/libraries/parser.html">Template Parser Class</a></li><li><a href="http://cms.local/libraries/typography.html">Typography Class</a></li><li><a href="http://cms.local/libraries/unit_testing.html">Unit Testing Class</a></li><li><a href="http://cms.local/libraries/uri.html">URI Class</a></li><li><a href="http://cms.local/libraries/user_agent.html">User Agent Class</a></li><li><a href="http://cms.local/libraries/xmlrpc.html">XML-RPC Class</a></li><li><a href="http://cms.local/libraries/zip.html">Zip Encoding Class</a></li></ul></td><td class="td_sep" valign="top"><h3>Driver Reference</h3><ul><li><a href="http://cms.local/libraries/caching.html">Caching Class</a></li><li><a href="http://cms.local/database/index.html">Database Class</a></li><li><a href="http://cms.local/libraries/javascript.html">Javascript Class</a></li></ul><h3>Helper Reference</h3><ul><li><a href="http://cms.local/helpers/array_helper.html">Array Helper</a></li><li><a href="http://cms.local/helpers/captcha_helper.html">CAPTCHA Helper</a></li><li><a href="http://cms.local/helpers/cookie_helper.html">Cookie Helper</a></li><li><a href="http://cms.local/helpers/date_helper.html">Date Helper</a></li><li><a href="http://cms.local/helpers/directory_helper.html">Directory Helper</a></li><li><a href="http://cms.local/helpers/download_helper.html">Download Helper</a></li><li><a href="http://cms.local/helpers/email_helper.html">Email Helper</a></li><li><a href="http://cms.local/helpers/file_helper.html">File Helper</a></li><li><a href="http://cms.local/helpers/form_helper.html">Form Helper</a></li><li><a href="http://cms.local/helpers/html_helper.html">HTML Helper</a></li><li><a href="http://cms.local/helpers/inflector_helper.html">Inflector Helper</a></li><li><a href="http://cms.local/helpers/language_helper.html">Language Helper</a></li><li><a href="http://cms.local/helpers/number_helper.html">Number Helper</a></li><li><a href="http://cms.local/helpers/path_helper.html">Path Helper</a></li><li><a href="http://cms.local/helpers/security_helper.html">Security Helper</a></li><li><a href="http://cms.local/helpers/smiley_helper.html">Smiley Helper</a></li><li><a href="http://cms.local/helpers/string_helper.html">String Helper</a></li><li><a href="http://cms.local/helpers/text_helper.html">Text Helper</a></li><li><a href="http://cms.local/helpers/typography_helper.html">Typography Helper</a></li><li><a href="http://cms.local/helpers/url_helper.html">URL Helper</a></li><li><a href="http://cms.local/helpers/xml_helper.html">XML Helper</a></li></ul></td></tr></tbody></table> </div> </div> <div id="nav2"> <span id="adminMenuWrapperButtonLeft"> <img onclick="myHeight.toggle();changeArrow();" src="http://cms.local/media/img/system/SlideArrowBottom.png" width="40px" class="navArrow"> </span> <span id="adminMenuWrapperButtonRight"> <img onclick="myHeight.toggle();changeArrow();" src="http://cms.local/media/img/system/SlideArrowBottom.png" width="40px" class="navArrow"> </span> <div class="clear"></div> </div> <script> window.onload = function() { myHeight = new fx.Height('nav', { duration : 400 }); myHeight.hide(); } var typeArrow = 1; function changeArrow(){ if(typeArrow == 1){ $('.navArrow').each(function(){ $(this).attr('src', "http://cms.local/media/img/system/SlideArrowTop.png"); }); typeArrow = 0; } else{ $('.navArrow').each(function(){ $(this).attr('src', "http://cms.local/media/img/system/SlideArrowBottom.png"); }); typeArrow = 1 } } </script> <div id="adminMenuWrapper"> <span id="adminMenuWrapperButton"><img onclick="slideMenu();" src="http://cms.local/media/img/system/SlideArrowRightOver.png" width="25px" id="adminMenuWrapperButtonImg"></span> <script> function slideMenu() { var currentWidth = $('#adminMenuWrapper').width(); if (currentWidth < 149) { $('#adminMenuWrapper').animate({ 'width' : '150px' // to move it towards the right. }, 1000, function() { $('.adminMenuWrapperText').toggle(); $('#adminMenuWrapperButtonImg').attr('src', "http://cms.local/media/img/system/SlideArrowLeftOver.png"); }); } else { $('.adminMenuWrapperText').toggle(); $('#adminMenuWrapper').animate({ 'width' : '50px' // to move it towards the left. }, 1000, function() { $('#adminMenuWrapperButtonImg').attr('src', "http://cms.local/media/img/system/SlideArrowRightOver.png"); }); } } </script> <div class="clear"></div> <br> <a href="http://cms.local/admin" class="linkAdminMenu"><span class="adminMenuWrapperText">Dashboad</span> <img width="50px" src="http://cms.local/media/img/system/dashboard.png" style="vertical-align: middle;"></a> <br><br> <a href="http://cms.local/admin/pages" class="linkAdminMenu"><span class="adminMenuWrapperText">Pagina′s</span> <img width="50px" src="http://cms.local/media/img/system/contentIcon.png" style="vertical-align: middle;"></a> <br> </div> <div id="adminContentWrapper"> <div id="adminHeader"> <div id="adminHeaderLeft"> <h3>Administrator</h3> </div> <div id="adminHeaderRight"> Aangemeld als WeProgram | <a href="http://cms.local/" target="_tab">Website</a> | <a href="http://cms.local/admin/logout">Afmelden</a> </div> <div class="clear"></div> </div> <!-- <div id="adminMainContentWrapper" class="block-shadow block-header"> <span class="adminMainContentHeaderItem"> Dashboard </span> <span class="adminMainContentHeaderItem"> Inhoud </span> </div> <div id="adminMainContentHeaderSubWrapper" class="arrow_box"> Quick Links????: </div> --> <div id="adminMainContentWrapper" class="block-shadow block-header"> <span class="adminMainContentHeaderItem"> <a href="http://cms.local/admin/pages" class="linkSecondMenu">Pagina′s</a> </span> <span class="adminMainContentHeaderItem"> <a href="http://cms.local/admin/menu" class="linkSecondMenu">Menu</a> </span></div></div> <div class="clear"></div></div><!-- <br /><br /><strong>&copy; 2013 WeProgram</strong> --></body></html> Now provide the response and nothing else.
If i have file abc.jpg on the sdcard then: String photoPath = Environment.getExternalStorageDirectory() + "/abc.jpg"; and to get bitmap . BitmapFactory.Options options = new BitmapFactory.Options();options.inPreferredConfig = Bitmap.Config.ARGB_8888;Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options); or Bitmap bitmap1 = BitmapFactory.decodeFile(photoPath); to avoide out of memory error I suggest you use the below code... BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 8;final Bitmap b = BitmapFactory.decodeFile(photoPath, options); To avoid above issue you can use Picasso (A powerful image downloading and caching library for Android) Documentation How To? Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);Picasso.with(context).load(new File(...)).into(imageView3);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15918336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175881/']}
jdg_78223
stackexchange
llm_judgeable_groundtruth_similarity
280571
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 confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call FILE *p = popen("/usr/bin/foo", "w"); forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it? I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...). It can be avoided by writing FILE *p = popen("/usr/bin/foo 2>/dev/null", "w"); in the parent program, but are their better ways? Now provide the response and nothing else.
popen(3) is just a library function, which relies on fork(2) and pipe(2) to do the real work. However pipe(2) can only create unidirectional pipes. To send the child process input, and also capture the output, you need to open two pipes. If you want to capture the stderr too, that's possible, but then you'll need three pipes, and a select loop to arbitrate reads between the stdout and stderr streams. There's an example here for the two-pipe version.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/280571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31330/']}
jdg_78224
stackexchange
llm_judgeable_groundtruth_similarity
3819809
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 trying to optimize C and LISP, looking at the assembler code output by the compiler can be a great help. Clojure presumably compiles to a JVM bytecode that would be equally helpful. How do I see it? Now provide the response and nothing else.
Clojure dynamically compiles all the Clojure code to bytecode at the runtime. I am not sure how you can see this dynamically compiled bytecode. However, you can do Ahead Of Time (AOT) compilation of your Clojure code yourself and that will generate .class files. Then you can use javap to see the bytecode. Use the compile function in Clojure/core to compile your namespace: compile function Usage: (compile lib) Compiles the namespace named by the symbol lib into a set of classfiles. The source for the lib must be in a proper classpath-relative directory. The output files will go into the directory specified by compile-path , and that directory too must be in the classpath. Then use javap : javap -l -c -s -private MyClass
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3819809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254837/']}
jdg_78225
stackexchange
llm_judgeable_groundtruth_similarity
316564
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: TL;DR Where a dupe target has n number of duplicates closed against it, if future questions closed to that dupe target are answered, all the rep for those answers is nullified. This way, there is no reward for lack of research or potential rep farming. A query given to me by Shog9 of answers posted to duplicate questions by month. Deduplicator has created the following query: percentage of answers of confirmed dupes answer by FGITW and non-FGITW Duplicates are not bad things in and of themselves, but there is a limit of how many duplicates are useful. This classic dupe target What is a NullReferenceException, and how do I fix it? has 2380 questions linked to it. Albeit, these won't all be duplicates https://stackoverflow.com/questions/35308571/system-nullreferenceexception-generate-in-association-relationship had 3 answers within 4 minutes; 2 with upvotes, and the top one with 3 upvotes within the first minute or so. There's nothing particularly complex about this question. It's one thing to say 'use your votes and flags to moderate the site to ensure good, on-topic posts', but wonders never cease. Can we have some kind of community penalty if a question that is closed as a duplicate with a target with questions closed against it greater than 20 , that all rep is invalidated? Arguments For: Historically the site has issues with people racing to answer duplicates, and there seems to be divided community support for how to circumvent this. What is with people who answer questions that are known to be dupes? has 12 upvotes and no answer. Discouraging repwhoring - Reverse rep from answers posted shortly before the question gets closed 50 upvotes The answers here discuss the time and effort answerers take to answer a question and how some questions are not clear duplicates. In this case I am referring to well known dupe targets. How to deal with unclear questions and their lightning-fast ("fastest gun in the west") answers? The highest voted answer of 70 suggests using our votes. The issue is, we are and yet these are outvoted by people willing to support this content. What can we do about fastest gun in the west answers that dump out garbage, and then plagiarize existing duplicates? This question is similar and has several answers, none that have a specific solution, nor a community consensus. As I see it, the only way to stop FGITW is to take away the rep incentive. There is also no value in rewarding people asking questions that could be answered with a simple google search. Do we want to reward this? Stack Overflow technology makes me write bad answers We need to implement strategies to reward people improving the content of the site, not endlessly replicating content. Arguments Against: It's clear that the SO community does not like to punish users: Proposal for a punishment system for ninja responders has -45 votes. However this proposal suggests: Ideas for punishment would be: Don't allow up-voting for n hours Don't allow to be accepted for nhours Responder will only gain half the reputation for "accepted" or"up-voted" Responder will not gain any reputation for this answer However this proposal is only on Q&A of specific dupe targets. It does not suggest a post ban, or any penalty, other than to take away the incentive to rush into answering questions, that are quick to answer, and have well established dupe targets. Conclusion This is one viable action we can take that no one can complain unfair on, if a there is a dupe target with 20 questions closed against it, that should offer ample search variations for search engines and address the arguments that maintain that dupes are good. Yes dupes are good, but there is a limit. If you don't agree, what do you think we should do, if anything? Now provide the response and nothing else.
You're making a few assertions here: There's only one common incentive (rep) for answering duplicates Common duplicates are always easy to identify Removing reputation for answers to common duplicates will discourage people from answering them Let's consider each of these in turn... What motivates answerers? Reputation is certainly a motivator; not only can you earn privileges on the site, but it's a way to keep score in "the game": if your number goes up, you're winning. That said, the former is little more than a heavily-constrained token economy , a method of conditioning that works best with cooperative participants (and doesn't work at all for some people). The latter is a form of reinforcement ; specifically, intermittent reinforcement - Aarobot wrote about this years back : What a lot of people don't realize is that with positive reinforcement, the conditioning doesn't really "stick" if you always give the reward. They'll keep doing what you want as long as you keep giving the reward (and as long as they still want it), but as soon as you take the reward away, they will stop. The only reason to perform the behaviour is to get the reward, so in their mind, there's no longer any reason to continue to cooperate. The technical term for this is extinction. You can mostly ignore the token economy bit beyond remembering that you'll make people angry if you cost them privileges that they really want. The intermittent variable reinforcement is pretty critical though if you're trying to manipulate people via rep, specifically that it works because it doesn't guarantee a payoff. More on that later... However, reputation isn't the only motivator here; in fact, it's probably not even the strongest motivator. It's visible and accessible and no doubt gets a lot of folks started... But there's a limit to how much extrinsic motivators can do : Which brings me indirectly to what I think the answer to my question might be: ask and answer questions about topics that I'm actively learning rather than topics I've already formed Platonic ideals about. Looking back at the questions and answers I most enjoyed writing in my time with Stack Overflow, I see that they tended to be on topics I had not yet mastered. Recently, I've been learning Lua and LaTeX, so when I wrote on those topics I found myself completely engaged in the responses I might get. An upvote gave me a rush of excitement not unlike the feeling of victory when scoring points in a game. A downvote led me to scramble to find the source of criticism and correct it. Jon found that the system actually worked best when he wasn't motivated primarily by reputation. When the topic itself or the process of educating and being educated managed were sufficiently engaging then reputation became a tool toward these ends rather than a game to be played for its own sake. This is something I've observed in many others - including myself - over the years: while you never stop looking for reinforcement, beyond a certain point the external, mechanical forms become less compelling than the internal, social ones. When they conflict - when your own sense of what is worthwhile reinforces an action that the system discourages - then you come to believe that the system is broken. Common duplicates are always easy to identify I pulled some data for questions closed as duplicates of the top 100 targets: Median time to first close flag or vote: 7 minutes Median time to answer: 6 minutes Median time to answer where the answer garnered a positive score or accept mark: 5 minutes Median time to actually close the question: 13 minutes So this assertion seems plausible: for common duplicates, it's about as fast to find the duplicate as it is to answer. However it is slightly faster to answer - and the faster you answer, the better chance you have of being rewarded for it. Removing reputation for answers to common duplicates will discourage people from answering them For that same set of 100 most-common duplicate-targets, I counted 41492 answers to duplicate questions (some deleted). Only 21109 of these - not quite 51% - ended up with a positive score or accept mark. I also counted 21011 answers to questions that someone flagged (or voted) as a duplicate of one of those top-100 targets but where the question didn't end up being closed ; that's a bit over 30% of all questions flagged/voted as duplicates of those most-common targets. Conclusion: the real problem and why this isn't a solution Let's step back a minute and get some perspective... We need a problem statement here; why do we even care about answers to duplicate questions? I mean, I love that I can close in lieu of answering duplicates - it saves me time and reduces the fatigue involved in repeatedly answering the same questions - but if someone else wants to waste their time on it, where's the problem? I'm gonna propose this as our guiding principle: Answers to duplicate questions scatter information in a way that makes finding it time-consuming and error-prone for those who need it. In the absence of things like overt plagiarism, I think this covers most of the more specific issues (searching, commentary, voting) that arise. So, is your proposed change likely to help ameliorate this problem? No. It's unlikely that the sole motivation for answering duplicates is actually reputation in all cases... But even when it is , such answers already stand a very good chance - nearly 50/50 - of not rewarding any reputation. This is offset by the fact that it's faster to answer than to find the duplicate, and that even when a duplicate has been proposed there's a decent chance it won't be closed at all. Remember how powerful variable intermittent reinforcement is? That's already at work here, and your solution would merely add slightly more variability to it. And unlike votes or accept marks, many answerers have some amount of direct control over whether the question they're answering gets closed... So as gnat notes , this might actually provide a disincentive to closing duplicates at all! In short, at best this solution would likely do nothing, and at worst it would make the problem more severe. So, what can we do? Well, as your graph illustrates, we've already been doing things. The biggest change we've made has involved making it faster to close duplicates: Gold badge holders can close instantly Askers themselves can trigger the question to be closed by confirming the duplicate The closing system itself prioritizes fast closures, both in review (by showing newly-voted questions to more people) and in general (by aging away votes that haven't been acted on). As a result, for questions asked in the past year the median time to close for those 100 common duplicates has dropped to 6 minutes - the same as the median time to answer. However, the median time to flag has gone up, to 9 minutes. The biggest outstanding issue with preventing answers to duplicate questions is finding the right target. I strongly suspect that this is a problem that feeds on itself; as the number of questions (and duplicates) grows, it becomes harder and harder to sift through them to find the right target. It doesn't help that the UI that was supposed to help with this seems to straight-up ignore common duplicates in many scenarios either. If we want to make an appreciable difference here, making it easier to identify valid duplicate targets is where we should be directing our efforts.
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/316564', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/-1/']}
jdg_78226
stackexchange
llm_judgeable_groundtruth_similarity
40516661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using python's matplotlib and want to create a matplotlib.scatter() with additional line. The line should proceed from the lower left corner to the upper right corner independent of the scatters content. A linear regression through the data, like in this post , is not what I am looking for. Also it should be dynamically and independent of the scatter input. This should be the final plot: EDIT: Doing this got me the result: # Scatter Plotx = data_calc_hourly.tempy = data_obs_hourly.templineStart = data_calc_hourly.temp.min() lineEnd = data_calc_hourly.temp.max() plt.figure()plt.scatter(x, y, color = 'k', alpha=0.5)plt.plot([lineStart, lineEnd], [lineStart, lineEnd], 'k-', color = 'r')plt.xlim(lineStart, lineEnd)plt.ylim(lineStart, lineEnd)plt.show() Is there any better way ? Now provide the response and nothing else.
This draws a diagonal line which is independent of the scatter plot data and which stays rooted to the axes even if you resize the window: import numpy as npimport matplotlib.pyplot as pltimport matplotlib.lines as mlinesimport matplotlib.transforms as mtransformsx, y = np.random.random((2, 100))*2fig, ax = plt.subplots()ax.scatter(x, y, c='black')line = mlines.Line2D([0, 1], [0, 1], color='red')transform = ax.transAxesline.set_transform(transform)ax.add_line(line)plt.show()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40516661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3986785/']}
jdg_78227
stackexchange
llm_judgeable_groundtruth_similarity
17052488
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I think about the best practices with storing historical data in MySQL database. For now, each versionable table has two columns - valid_from and valid_to , both DATETIME type. Records with current data has valid_from filled with its creation day. When I update this row, I fill valid_to with update date and add new record with valid_from the same as valid_to in previous row - easy stuff. But I know that table will be enormous very quick so fetching data can be very slow. I'd like to know if you have any practices with storing historical data? Now provide the response and nothing else.
It's a common mistake to worry about "large" tables and performance. If you can use indexes to access your data, it doesn't really matter if you have 1000 of 1000000 records - at least not so as you'd be able to measure. The design you mention is commonly used; it's a great design where time is a key part of the business logic. For instance, if you want to know what the price of an item was at the point when the client placed the order, being able to search product records where valid_from < order_date and valid_until is either null or > order_date is by far the easiest solution. This isn't always the case - if you're keeping the data around just for archive purposes, it may make more sense to create archive tables. However, you have to be sure that time is really not part of the business logic, otherwise the pain of searching multiple tables will be significant - imagine having to search either the product table OR the product_archive table every time you want to find out about the price of a product at the point the order was placed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17052488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025782/']}
jdg_78228
stackexchange
llm_judgeable_groundtruth_similarity
10584873
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 just learned about recursion in Python and have completed assignments, one of which was to count all the elements within a list of arbitrarily nested lists. I have searched this site and the answers found all seem to use recursive calls. Since it has been taught that anything which could be expressed recursively could be expressed iteratively, and iteration is preferred in Python, how would this be accomplished without recursion or imported modules in Python 2.6 (as a learning exercise)? (A nested list itself would be counted as an element, as would its contents.)For example: >>> def element_count(p):... count = 0... for entry in p:... count += 1... if isinstance(entry, list): ... count += element_count(entry)... return count>>> print element_count([1, [], 3]) 3 >>> print element_count([1, [1, 2, [3, 4]]])7>>> print element_count([[[[[[[[1, 2, 3]]]]]]]])10 How would this be written using iteration? Now provide the response and nothing else.
Here is one way to do it: def element_count(p): q = p[:] count = 0 while q: entry = q.pop() if isinstance(entry, list): q += entry count += 1 return countprint element_count([1, [], 3]) print element_count([1, [1, 2, [3, 4]]])print element_count([[[[[[[[1, 2, 3]]]]]]]]) The code maintains a queue of things to be looked at. Whenever the loop encounters a sub-list, it adds its contents to the queue.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10584873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1028237/']}
jdg_78229
stackexchange
llm_judgeable_groundtruth_similarity
30771156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My app have a viewpager and 4 tabs, each tab have many fragment. But I just want my Toolbar scroll up/down while scrolling recyclerview in 2 specific tabs. But I don't know how to block Toolbar scroll for other tabs. I tried to import toolbar for each fragment but it seems I can't do it.Anyone have idea to solve this problem? Now provide the response and nothing else.
I'd strongly recommend against changing the scrolling flags based on what tab is selected - having the Toolbar automatically return (and the content move down) when scrolling to a non-recyclerview tab can be very jarring and probably not an interaction pattern you want (exasperated if your two RecyclerView tabs are next to one another). However, if you want to see it in person, you can use setScrollFlags() to set the scroll flags programmatically: Toolbar toolbar = ... // your toolbar within an AppBarLayoutAppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); In order to clear flags params.setScrollFlags(0)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30771156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943382/']}
jdg_78230
stackexchange
llm_judgeable_groundtruth_similarity
20007610
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 effect I'm trying to achieve with Bootstrap 3 carousel Instead of just showing one frame at a time, it displays N frames slide by side. Then when you slide (or when it auto slides), it shifts the group of slides like it does. Can this be done with bootstrap 3's carousel? I'm hoping I won't have to go hunting for yet another jQuery plugin... Now provide the response and nothing else.
Bootstrap 5 (Update 2021) While the carousel is mostly the same in Bootstrap 5, the concept of left and right have changed to start and end since Bootstrap now has RTL support. Therefore the left/right classes have changed. Here's an example of the multi-item CSS for 4 items (25% width columns)... @media (min-width: 768px) { .carousel-inner .carousel-item-end.active, .carousel-inner .carousel-item-next { transform: translateX(25%); } .carousel-inner .carousel-item-start.active, .carousel-inner .carousel-item-prev { transform: translateX(-25%); }}.carousel-inner .carousel-item-end,.carousel-inner .carousel-item-start { transform: translateX(0);} Since jQuery is no longer required, we use vanilla JS to clone the slides into the carousel-item divs.. let items = document.querySelectorAll('.carousel .carousel-item')items.forEach((el) => { // number of slides per carousel-item const minPerSlide = 4 let next = el.nextElementSibling for (var i=1; i<minPerSlide; i++) { if (!next) { // wrap carousel by using first child next = items[0] } let cloneChild = next.cloneNode(true) el.appendChild(cloneChild.children[0]) next = next.nextElementSibling }}) Bootstrap 5 Multi-item Carousel Demo Bootstrap 4 (Update 2019) The carousel has changed in 4.x, and the multi-slide animation transitions can be overridden like this... .carousel-inner .carousel-item-right.active,.carousel-inner .carousel-item-next { transform: translateX(33.33%);}.carousel-inner .carousel-item-left.active, .carousel-inner .carousel-item-prev { transform: translateX(-33.33%)} .carousel-inner .carousel-item-right,.carousel-inner .carousel-item-left{ transform: translateX(0);} Bootstrap 4 Alpha.6 Demo Bootstrap 4.0.0 (show 4, advance 1 at a time) Bootstrap 4.1.0 (show 3, advance 1 at a time) Bootstrap 4.1.0 (advance all 4 at once) Bootstrap 4.3.1 responsive (show multiple, advance 1) new Bootstrap 4.3.1 carousel with cards new Another option is a responsive carousel that only shows and advances 1 slide on smaller screens , but shows multiple slides are larger screens . Instead of cloning the slides like the previous example, this one adjusts the CSS and use jQuery only to move the extra slides to allow for continuous cycling (wrap around): Please don't just copy-and-paste this code. First, understand how it works. Bootstrap 4 Responsive (show 3, 1 slide on mobile) @media (min-width: 768px) { /* show 3 items */ .carousel-inner .active, .carousel-inner .active + .carousel-item, .carousel-inner .active + .carousel-item + .carousel-item { display: block; } .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left), .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item, .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item { transition: none; } .carousel-inner .carousel-item-next, .carousel-inner .carousel-item-prev { position: relative; transform: translate3d(0, 0, 0); } .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item { position: absolute; top: 0; right: -33.3333%; z-index: -1; display: block; visibility: visible; } /* left or forward direction */ .active.carousel-item-left + .carousel-item-next.carousel-item-left, .carousel-item-next.carousel-item-left + .carousel-item, .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item, .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item { position: relative; transform: translate3d(-100%, 0, 0); visibility: visible; } /* farthest right hidden item must be abso position for animations */ .carousel-inner .carousel-item-prev.carousel-item-right { position: absolute; top: 0; left: 0; z-index: -1; display: block; visibility: visible; } /* right or prev direction */ .active.carousel-item-right + .carousel-item-prev.carousel-item-right, .carousel-item-prev.carousel-item-right + .carousel-item, .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item, .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item { position: relative; transform: translate3d(100%, 0, 0); visibility: visible; display: block; visibility: visible; }}<div class="container-fluid"> <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000"> <div class="carousel-inner row w-100 mx-auto" role="listbox"> <div class="carousel-item col-md-4 active"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7"> </div> <div class="carousel-item col-md-4"> <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7"> </div> </div> <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev"> <i class="fa fa-chevron-left fa-lg text-muted"></i> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next"> <i class="fa fa-chevron-right fa-lg text-muted"></i> <span class="sr-only">Next</span> </a> </div></div> Example - Bootstrap 4 Responsive (show 4, 1 slide on mobile) Example - Bootstrap 4 Responsive (show 5, 1 slide on mobile) Bootstrap 3 Here is a 3.x example on Bootply: http://bootply.com/89193 You need to put an entire row of images in the item active. Here is another version that doesn't stack the images at smaller screen widths: http://bootply.com/92514 EDIT Alternative approach to advance one slide at a time : Use jQuery to clone the next items.. $('.carousel .item').each(function(){ var next = $(this).next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); if (next.next().length>0) { next.next().children(':first-child').clone().appendTo($(this)); } else { $(this).siblings(':first').children(':first-child').clone().appendTo($(this)); }}); And then CSS to position accordingly... Before 3.3.1 .carousel-inner .active.left { left: -33%; }.carousel-inner .next { left: 33%; } After 3.3.1 .carousel-inner .item.left.active { transform: translateX(-33%);}.carousel-inner .item.right.active { transform: translateX(33%);}.carousel-inner .item.next { transform: translateX(33%)}.carousel-inner .item.prev { transform: translateX(-33%)}.carousel-inner .item.right,.carousel-inner .item.left { transform: translateX(0);} This will show 3 at time, but only slide one at a time: Bootstrap 3.x Demo Please don't copy-and-paste this code. First, understand how it works. This answer is here to help you learn . Doubling up this modified bootstrap 4 carousel only functions half correctly (scroll loop stops working) how to make 2 bootstrap sliders in single page without mixing their css and jquery? Bootstrap 4 Multi Carousel show 4 images instead of 3
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/20007610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/774907/']}
jdg_78231
stackexchange
llm_judgeable_groundtruth_similarity
15510497
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have a container with a width of 1000px, filled with items all of which are 200px in width. How can I calculate that tiles row/column position? To explain in more detail: The only variables I will know is the width of the container (1200px in the above example) , the width of an item (200px above) and the items index (starting at 1). Given only the above information, how can I calculate the row and column of a cell by inputting its index using javascript. e.g. Given a maximum items per row value of 6 (which can easily be calculated from the item width and container width), I need to be able to calculate that item number 7 is at row 2, column 1 . The container and item width's might not always be divisible exactly so the equation will have to account for any extra whitespace requires at the end of each row and naturally wrap the items onto the next row as they would in an html float layout. Thanks in advance EDIT: I have managed to get the row quite accurately by doing the following: var itemsperrow = Math.floor(containerwidth/ itemwidth);var column = Math.ceil(itemindex / itemsperrow ) This is with the items index starting at 1 and not 0; Now provide the response and nothing else.
Find how many elements fit in one row by taking the floor of (row width)/(element width). Divide the index number given by the elements per row (which you just figured out). That will give you the row position. Next find the column position by taking the remainder portion from step 1 (you can use modulus). Multiply the remainder by the number of elements per row. That will be which column it is in. example: 3 elements per row, 4th element:floor(4/3) = 1 (row 1)remainder = (4%3)=1 (column position) Be careful of what index you are starting with (whether it's 0 or 1). This example starts at 1. If you want to start at 0 shift it over by subtracting 1 (the index number).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15510497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884934/']}
jdg_78232
stackexchange
llm_judgeable_groundtruth_similarity
3829597
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 quote from persistence.xml : <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.archive.autodetection" value="class" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> ... </properties></persistence-unit> This is what I see in log output: Sep 30, 2010 12:03:43 PM org.hibernate.tool.hbm2ddl.SchemaExport executeINFO: Running hbm2ddl schema exportSep 30, 2010 12:03:43 PM org.hibernate.tool.hbm2ddl.SchemaExport executeINFO: exporting generated schema to databaseSep 30, 2010 12:03:43 PM org.hibernate.tool.hbm2ddl.SchemaExport executeINFO: schema export complete But I don't see the schema (SQL) exported itself. How to get this information out of Hibernate (3.5.6-Final)? Now provide the response and nothing else.
Activate the logging of the org.hibernate.tool.hbm2ddl category to DEBUG . Update: Here is a simplified logback.xml (I'm using logback as logging backend): <configuration scan="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <!-- ### log just the SQL ### --> <logger name="org.hibernate.SQL" level="DEBUG"/> <!-- ### log JDBC bind parameters ### --> <logger name="org.hibernate.type" level="TRACE"/> <logger name="org.hibernate.tool.hbm2ddl" level="DEBUG"/> <root level="ERROR"> <appender-ref ref="STDOUT"/> </root></configuration> Adapt it if you are using log4j (you'll find working configuration here on SO).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3829597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187141/']}
jdg_78233
stackexchange
llm_judgeable_groundtruth_similarity
222765
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 my microeconomics book, I read that when we have $1+\dfrac{1}{\eta}$ where $\eta$ is an elasticity coefficient, we can write $1-\dfrac{1}{|\eta|}$ "to avoid ambiguities stemming from the negative sign of the elasticity". What does this mean? Is it always legitimate to perform such a transformation? Now provide the response and nothing else.
If the elasticity coefficient $\eta$ is negative, then $|\eta|=-\eta$. The ambiguity arises because some people may suppress the negative sign and write it as a positive number instead. In this case, using $1+\frac{1}{\eta}$ becomes ambiguous. For example, if $\eta=-2$ but people write it as $\eta=2$, then $1+\frac{1}{\eta}$ can mean $1-\frac{1}{2}$ or $1+\frac{1}{2}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/222765', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30657/']}
jdg_78234
stackexchange
llm_judgeable_groundtruth_similarity
22806550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: when you hover over the image you get a caption, but the h1 and p are on the same position, the p element does not come under the h1 element. What am I doing wrong? HTML <section role="main" class="container"> <ol class="thumb-grid group"> <li><img src="img.jpg" alt="img" /> <div class="caption"> <div class="caption-text"> <h1>Header</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div><!-- einde caption-text --> </div><!-- einde caption --> </li> CSS .thumb-grid .caption{cursor: pointer;position: absolute;opacity: 0;-webkit-transition:all 0.6s ease-in-out;-moz-transition:all 0.6s ease-in-out;-o-transition:all 0.6s ease-in-out;-ms-transition:all 0.6s ease-in-out;transition:all 0.6s ease-in-out;}.thumb-grid li:hover .caption{opacity: 1;background-color: rgba(0,0,0,0.65);height: 100%;width: 100%;z-index: 5;position: absolute;}.thumb-grid .caption-text{color: #fff;position: absolute;width: 100%;height: 100%;text-align: left;padding-top:8%;padding-left:8%;}.thumb-grid .caption-text h1{font-size: 1em;}.thumb-grid .caption-text p{font-size: 0.75em;} Now provide the response and nothing else.
As the author of the slides I'll try to clarify. If you write code explicitly allocating a Derived instance with new and destroying it with delete using a base class pointer then you need to define a virtual destructor, otherwise you end up with incompletely destroying the Derived instance. However, I recommend to abstain from new and delete completely and use exclusively shared_ptr for referring to heap-allocated polymorphic objects, like shared_ptr<Base> pb=make_shared<Derived>(); This way, the shared pointer keeps track of the original destructor to be used, even if shared_ptr<Base> is used to represent it. Once, the last referring shared_ptr goes out of scope or is reset, ~Derived() will be called and the memory released. Therefore, you don't need to make ~Base() virtual. unique_ptr<Base> and make_unique<Derived> do not provide this feature, because they don't provide the mechanics of shared_ptr with respect to the deleter , because unique pointer is much simpler and aims for the lowest overhead and thus is not storing the extra function pointer needed for the deleter. With unique_ptr the deleter function is part of the type and thus a uniqe_ptr with a deleter referring to ~Derived would not be compatible with a unique_ptr<Base> using the default deleter, which would be wrong for a derived instance anyway, if ~Base wasn't virtual. The individual suggestions I make, are meant to be easy to follow and followed all together. They try to produce simpler code, by letting all resource management be done by library components and the compiler generated code. Defining a (virtual) destructor in a class, will prohibit a compiler-provided move constructor/assignment operator and might prohibit also a compiler provided copy constructor/assignment operator in future versions of C++. Resurrecting them has become easy with =default , but still looks like a lot of boilerplate code. And the best code is the code you don't have to write, because it can not be wrong (I know there are still exceptions to that rule). To summarize "Don't define a (virtual) destructor" as a corollary to my "Rule of Zero": Whenever you design a polymorphic (OO) class hierarchy in modern C++ and want/need to allocate its instances on the heap and access them through a base class pointer use make_shared<Derived>() to instantiate them and shared_ptr<Base> to keep them around. This allows you to keep the "Rule of Zero". This doesn't mean you must allocate all polymorphic objects on the heap. For example, defining a function taking a (Base&) as parameter, can be called with a local Derived variable without problems and will behave polymorphic, with respect to virtual member functions of Base . In my opinion dynamic OO polymorphism is heavily overused in many systems. We shouldn't program like Java, when we use C++, unless we have a problem, where dynamic polymorphism with heap allocated objects is the right solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22806550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3480982/']}
jdg_78235
stackexchange
llm_judgeable_groundtruth_similarity
3201
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 database containing a large number of experts in a field. For each of those experts i have a variety of attributes/data points like: number of years of experience. licenses num of reviews textual content of those reviews The 5 star rating on each of those reviews, for a number of factors like speed, quality etc. awards, assosciations, conferences etc. I want to provide a rating to these experts say out of 10 based on their importance. Some of the data points might be missing for some of the experts. Now my question is how do i come up with such an algorithm? Can anyone point me to some relevent literature? Also i am concerned that as with all rating/reviews the numbers might bunch up near some some values. For example most of them might end up getting an 8 or a 5. Is there a way to highlight litle differences into a larger difference in the score for only some of the attributes. Some other discussions that i figured might be relevant: Bayesian rating system with multiple categories for each rating How would YOU compute IMDB movie rating? Eliciting priors from experts What are some of the best ranking algorithms with inputs as up and down votes? Now provide the response and nothing else.
People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list. Not well represented there, though, is one of the most defensible methods out there: Multi attribute valuation theory. This includes a set of methods to evaluate trade-offs among sets of criteria in order to (a) determine an appropriate way to re-express values of the individual variables and (b) weight the re-expressed values to obtain a score for ranking. The principles are simple and defensible, the mathematics is unimpeachable, and there's nothing fancy about the theory. More people should know and practice these methods rather than inventing arbitrary scoring systems.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/3201', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1459/']}
jdg_78236
stackexchange
llm_judgeable_groundtruth_similarity
456506
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 asked about the value of an integral here: Hard integral that standard CAS get totally wrong The question got downvoted and voted to close because I didn't understand (and wasn't able to answer) the following question: In which sense is the integral supposed to exist? So in what senses can integrals exist? What are the options here? Now provide the response and nothing else.
In addition to other useful answers... Before giving the standard example of an integral whose convergence is problemmatical, but which does have some sense... we should ask ourselves what it is we are expecting "integrals" to do , what properties the process should have. For example, "integration" should not just produce random numerical outcomes. And which functions, on which intervals, should be expected to be acceptable inputs? At the very least, if $f,g$ are acceptable, then linear combinations $af+bg$ should be, and, letting $I$ denote the integration procedure, $I(af+bg)=aI(f)+bI(g)$. ("Linearity".) Riemann integration works best on finite intervals with nearly-continuous functions, while Lebesgue integration accommodates very-discontinuous functions, etc. In both cases, the integral of $f$ on a set or interval is a limit of finite sums, and the set-up for the game consists of proving these limits will exist (and be finite numbers!) under various assumptions on $f$. A simpler standard example similar to one in your other post is $\int_0^\infty \sin(x^2)\;dx$. This has the disturbing feature that the function doesn't go to $0$ at infinity, so if we think of Cauchy's criterion for convergence of a series (rather than integral), we might conclude that this would diverge, meaning that $\lim_N \int_0^N \sin(x^2)\;dx$ might be $\pm\infty$? Or not exist? However, the oscillation produces enough self-cancellation so that this doesn't happen. In fact, changing variables, replacing $x$ by $\sqrt{x}$, gives integral$\int_0^\infty {\sin(x)\over \sqrt{x}}\;dx$. Now, at least it looks like it decays at infinity, and there is still cancellation due to the oscillation. In fact, the limit can be evaluated by various tricks: I think it is $\pi/2$ or something similar. In fancier circumstances, it often happens that "an integral" is not meant to be taken literally, but only to indicate the structure of some operation on functions. The basic case is with Fourier or Laplace transforms on the real line. Fourier transforms expressed as integrals $\hat{f}(\xi)=\int_{\mathbb R} e^{-i\xi x}\,f(x)\;dx$ make best sense for $\int_{\mathbb R} |f(x)|\;dx<\infty$, but, in fact, via the Plancherel theorem for Fourier transforms, we know that $\int_{\mathbb R} \hat{f}(\xi)\;\hat{g}(\xi)\;dx=\int_{\mathbb R}f(x)\,g(x)\;dx$ (maybe up to a constant multiple), so there is a unique extension of Fourier transform to square-integrable functions $f$, that is, such that $\int_{\mathbb R}|f(x)|^2\;dx<\infty$. This extension has the same properties as the Fourier transform that is literally an integral, but is not quite given by that integral. Similarly, Fourier transforms can be extended to ("tempered") "generalized functions" (="distributions", not in the probabilistic sense), in a way that is completely sensible structurally , but in which the integrals are wildly not-convergent. For example, $\int_{\mathbb R} x^n\cdot e^{-i\xi x}\;dx$ doesn't converge at all, but by other means we can conclude that it is (a constant multiple of) the $n$th derivative of the Dirac delta distribution. And, in case there were any doubt, computer algebra systems have their limitations, especially in dealing with "divergent" (not numerically docile!) integrals.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/456506', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/346/']}
jdg_78237
stackexchange
llm_judgeable_groundtruth_similarity
6665307
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got lots of XLSX files and I need to append a new row after the last one in the file. I'm using OpenXML and so far I know how to open/create spreadsheet, but my search for adding new rows to existing files returned nothing. Any ideas ? Now provide the response and nothing else.
If all you need to do is add a blank row to the end and you don't care if a row already exists at the row index, then the following should work for you: public static void InsertRow(WorksheetPart worksheetPart) { SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); Row lastRow = sheetData.Elements<Row>().LastOrDefault(); if (lastRow != null) { sheetData.InsertAfter(new Row() { RowIndex = (lastRow.RowIndex + 1) }, lastRow); } else { sheetData.Insert(new Row() { RowIndex = 0 }); } } For OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert method, thus use InsertAt as follows: ... } else { sheetData.InsertAt(new Row() { RowIndex = 0 }, 0); } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6665307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567530/']}
jdg_78238
stackexchange
llm_judgeable_groundtruth_similarity
51631786
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is this new feature in TypeScript 3.0 called Project References . It suggests better interaction of *.ts modules between themselves. Unfortunately, this is all I could get from the official documentation although it seems to be written pretty clearly and straightforward. Can anyone help me understand exactly, what problems does it solve, how does it do that, and how would I benefit from it? I have a project with a similar structure, so it might (or might not) be very helpful for it. Thank you in advance! UPD: The project structure is roughly: project/ lib/ index.ts # defines the original code test/ index.spec.ts # requires lib/index.ts package.json tsconfig.json Now provide the response and nothing else.
TL;DR: The feature allows defining parts of the project as separate TypeScript modules. Among other things, this allows configuring those modules differently, building them separately, etc. Before Initially, the project structure , when simplified, is similar to this: / src/ entity.ts # exports an entity test/ entity.spec.ts # imports an entity tsconfig.json An entity is defined in src/entity.ts module , and then used in test/entity.spec.ts file . Notice that there is only one tsconfig.json file here, sitting in the root folder. This basically says that this folder contains one big solid TypeScript project. This project includes a couple of files, organized in folders; some of those files are used for testing other ones. This structure however imposes a problem: the process of compiling the project (namely, tsc ) also compiles the test files, thus creating dist/test/entity.spec.{js|d.ts} files in the output. This should not happen, therefore the tsconfig.json file is slightly altered to include only those files/folders that are intended for outside usage: { "compilerOptions": { // compiler options }, "include": [ "./src" ]} This solves the problem, but in my case, it also led to all files in the /test folder being occasionally ignored by the TypeScript compiler during the development process. Also, this exclusive approach might not fit everybody. After After utilizing the feature , the project structure has changed to this: / src/ entity.ts # exports an entity tsconfig.json test/ entity.spec.ts # imports an entity tsconfig.json tsconfig-base.json Let's go through the changes: Renaming /tsconfig.json to /tsconfig-base.json is a pretty major thing by itself: the root folder is not a TypeScript project anymore, since tsc requires the tsconfig.json file to be present. On the other hand, adding src/tsconfig.json and test/tsconfig.json files turns both src and test into two separate TypeScript projects, independent from each other. The contents of /{src|test}/tsconfig.json files are similar since no changes in the configuration were expected, i.e., the "strictness", the output folder, as well as other such parameters, should be preserved. In order to make them similar without copy-pasting anything, all the configurations are put in an arbitrary file , accessible from both places; in this case, the tsconfig-base.json in the root folder was selected for that: // the contents of /tsconfig-base.json{ "compilerOptions": { // compiler options, common to both projects }} This file is being "inherited" then by /{src|test}/tsconfig.json files, with addition of any other options if needed: // the contents of /{src|test}/tsconfig.json{ "extends": "../tsconfig-base.json", "compilerOptions": { // additional compiler options, specific to a project }} Notice how this pattern is similar to defining an abstract class with incomplete implementation, and then extending it by two separate "concrete" classes. Now, /src and /test folders basically hold two separate TypeScript projects with similar configurations. The last thing to do is to specify the relation between the two. Since test depends on src , the test has to somehow "know" about src . This is done in two pretty obvious steps: allow src to be "referenced" from the outside by declaring it as "composite": // in /src/tsconfig.json{ "extends": "../tsconfig-base.json", "compilerOptions": { // compiler options "composite": true }} reference src from test : // in /test/tsconfig.json{ "extends": "../tsconfig-base.json", "references": [ { "path": "../src" } ]} The "include" array in /tsconfig-base.json is not needed now , since the code exclusion is done by "drawing new borders". UPDATE: the following section seems to be outdated since TypeScript 3.7 Now, the test project requires *.d.ts files for the src project to be present. This means that before running tests, the src should already be built, separately. This is done by using the new mode of tsc , triggered by the --build option: tsc --build src This command builds the src project and puts the output in the specified output folder (in this case, /dist ), without neither breaking test nor losing any compile errors.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51631786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4554883/']}
jdg_78239
stackexchange
llm_judgeable_groundtruth_similarity
1192485
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an interesting encryption problem at hand. I do not know if it can be solved but here goes: A database is to contain sensitive user information. As such, the user information must be encrypted (two way encryption). The user has a login / password and these may be used in the two way encryption. Now, the encryption is to be designed in such a way that even the administrator viewing the database tables should not be able to make sense of the user information. However, the design has to take care of the cases where the user may forget her password. If the password is used for encryption, forgetting the password means the information is lost - not wanted. If the user password itself is stored in the database using a two way algorithm (instead of a one way hash) with a key hardcoded in the script, the administrator can discover the hardcoded key by looking at the script (the administrator of course has access to the script). Does anybody know a way out of this? PS: This is a real problem. My company is an absolute security fanatic (ISO 27001 and all) and I have been entrusted to design a system with the above mentioned functionality. By the way, I am using a PHP script and MySQL. EDIT : Perhaps it was not clear earlier, the user needs to see / edit this user information on a day-to-day basis. Now provide the response and nothing else.
What you want is a recovery agent. Encrypt all data twice: once with the user key, once with the recovery agent (public) key; atleast the latter one needs to be asymmetric. Keep the recovery agent key in a pyhsical safe, with a formal access protocol (e.g. four eyes principle). Usually, the administrator cannot access the encrypted data, but if the user loses the key, and recovery is authorized, then the recovery key is obtained. There are also ways to encrypt the recovery agent's key so that m-out-of-n people have to agree to use it. Edit : One implementation strategy is to encrypt everything twice. Alternatively, for each data set that needs to be recoverable independently, create a fresh symmetric key, and encrypt only that key twice; the original data get encrypted only with the session key. That approach can extend to multiple independent readers; it requires asymmetric keys per reader (so that you can encrypt the session key with the public keys of all readers - one being the recovery agent). I copied the terminology from Microsoft's Encrypting File System , which has that scheme implemented.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1192485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140970/']}
jdg_78240