message
stringlengths
2
17.7k
message_type
stringclasses
2 values
message_id
int64
0
19
conversation_id
int64
0
1.03k
So, students in Gryffindor are supposed to represent bravery. How does Neville represent bravery, to the point in being accepted into the house. I've always thought of his strongest traits being things like loyalty, willingness to work hard, etc, and these things would tend to put him in Hufflepuff.
instruction
0
50
First of all, in the first 4 years, it isn't really shown that Neville is NOT brave - the only thing he's really afraid of is his Grandmother and maybe Snape during Potions. With good reason. :) You may be confusing a lack of confidence/assertiveness with not being brave, but they are not the same (for a good in-universe illustration of the opposite, think Prof. Lockhart). First four books, he's clumsy, and is not yet showing any magical talent. Starting with the fifth year, Neville is shown to have been changed, and repeatedly proves his bravery and willingness to fight. NOTE: He first shows bravery in the First Year (see System's great answer for details), but the real Gryffindor-y Neville emerges in the Fifth year. There's another instance of him showing a Gryffindor quality - more specifically, integrity. He argued with the Hat to sort him into Hufflepuff (src: Pottermore), because he felt he wasn't brave enough to be a Gryffindor. Fifth year * He joins DA * He shows marked and significant improvement in his magical abilities while in DA * He voluntarily joins the DA members who accompany Harry to Ministry of Magic battle in the end of OoP, even arguing with Harry about it: Neville: "We were all in the D.A. together. It was all supposed to be about fighting You-Know-Who, wasn't it? And this is the first chance we've had to do something real — or was that all just a game or something?" Harry: "No — of course it wasn't —" Neville: "Then we should come too. We want to help." * During the battle at the Ministry, he refused to leave as per Harry's suggestion after Dolohov broke Neville's nose and wand. * When being threatened and tortured by Death Eaters, he told Harry not to give them the Prophecy Sixth year * participated in the Battle of the Astronomy Tower. Along with Luna Lovegood, he was the only member of Dumbledore's Army to reply to the summons via the coins. Seventh year * Neville got in trouble with the Carrows for refusing to practise the Cruciatus Curse on other students as a method of punishment, as well as for standing up against their bigotry and cruelty. * along with Ginny and Luna, restarted Dumbledore's Army. * attempted to steal Godric Gryffindor's Sword from Snape's office * Neville was eventually left alone to lead the rebellion efforts (Luna and Ginny were not in Hogwarts anymore). When avoiding the Death Eaters at one point, Neville stumbled into the Room of Requirement, which he was able to turn into a hiding place for the D.A., and to connect to the Hog's Head in order to get food from Aberforth Dumbledore. By May, most of the D.A. had taken to living there. * During the first round of battle, Neville used various plants to attack Death Eaters, and helped transport the injured and dead when a temporary cease-fire was called. * When the Death Eaters approached with a "dead" Harry, Neville stood up in defiance of Voldemort. He was subsequently forced to wear the Sorting Hat as it burned because he refused to join Voldemort. Fortunately, due to Harry's sacrifice, Neville was able to shrug off the Full Body-Bind Curse. * Because of his tremendous bravery shown on the battlefield, Neville was able to pull Godric Gryffindor's Sword from the burning hat, in the process proving himself a true Gryffindor, something that was doubted constantly throughout due to his apparently weak-willed, shy, and bumbling nature. In a single stroke, he killed Nagini, destroying Voldemort's last remaining Horcrux. * Neville subsequently teamed up with Ron Weasley as the defenders of Hogwarts and Death Eaters were forced into the Great Hall and defeated Fenrir Greyback. All in all, pretty convincing evidence of someone's bravery.
output
1
50
This claim was made popular by being said in the movie The Social Network. It exactly says: > Did you know there are more people with genius IQs living in China than there are people of any kind living in the United States?
instruction
0
51
This claim can actually be tested very easily. Others have done it, e.g. Brian Dickerson: The perils of repeating political nonsense and came to the conclusion that the claim was wrong. You just need the chance a random person from a large group has a genius level IQ, then multiply it with the number of people in China and compare the result with the number of people in the USA. The IQ follows a Gaussian distribution where 100 is the mean by definition and a standard deviation (SD) of 15 (after Wechsler) or 16 (after Stanford-Binet). The rarity of a particular IQ can be calculated easily and are listed by the IQ Comparison Site. These numbers give the percentage of people with an IQ equal or lower than the given IQ and the rarity of this occurring. The main question actually is what an genius level IQ is. There is no definite answer. According to the IQ Comparison Site, it is 140 or higher ("Genius or near genius") while another source states it as at least 160. The rarity of such an IQ is 1/261 (with a SD of 15) or 1/161 (SD=16) for an IQ of 140 and 1/31,560 (SD=15) or 1/11,307 (SD=16) for an IQ of 160 according to Wikipedia. The population of USA for 2012 is about 313,221,000 according to the U.S. Census Bureau. The population of China for 2011 is about 1,370,537,000. Taking the lowest rarity of 1/161 from above then there are about 1,370,537,000/161 = about 8,513,000 geniuses in China, which is significantly less then the 313,221,000 Americans. If you take the 15 SD value of 1/261 then you get only about 5,251,000 Chinese geniuses. With the 160 IQ points, which are more realistic to indicate a real genius, the numbers are even smaller (about 43,400 or 12,100). Note that 1,370,537,000/313,221,000 = 4.375, so in order for this claim to be true actually one of every four (or say five) Chinese would need to be a Genius. Even without the numbers above, it can be easily understood that this is not the case. Conclusion: This claim is wrong according to the definition and probabilities of the IQ. Supplement: It has been pointed out, that there are published research results showing that China and other Asian countries have a higher average IQ of about 106 (or even as high as 115) as the normed average of 100. This would increase the number of geniuses in China: The above factor of 1/161 would drop to about 1/60 or, for a Chinese average of 115, even to about 1/17. These numbers can be easily calculated using the standard deviation, e.g. using MS Excel's function ```NORM.DIST(140, 106, 16, TRUE)```. However, both these factors are not in any way close to the US/Chinese population ratio of about 1/4.375, so the original conclusion still holds.
output
1
51
I am trying to get my program to print out ```"banana"``` from the dictionary. What would be the simplest way to do this? This is my dictionary: ```prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } ```
instruction
0
52
As of Python 3.7, insertion order is maintained, so you don't need an ```OrderedDict``` here. You can use the below approaches with a normal ```dict``` Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6. source Python 3.6 and earlier* If you are talking about a regular ```dict```, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your ```dict``` you will likely not get ```"banana"``` as the first thing you see. If you need to keep things in order, then you have to use an ```OrderedDict``` and not just a plain dictionary. ```import collections prices = collections.OrderedDict([ ("banana", 4), ("apple", 2), ("orange", 1.5), ("pear", 3), ]) ``` If you then wanted to see all the keys in order you could do so by iterating through it ```for k in prices: print(k) ``` You could, alternatively put all of the keys into a list and then work with that ```keys = list(prices) print(keys[0]) # will print "banana" ``` A faster way to get the first element without creating a list would be to call ```next``` on the iterator. This doesn't generalize nicely when trying to get the ```nth``` element though ```>>> next(iter(prices)) 'banana' ``` * CPython had guaranteed insertion order as an implementation detail in 3.6.
output
1
52
Different coffee packets advertise different amounts of 'Robusta' and 'Arabica'? What do these terms refer to, and how does it affect the taste of the coffee?
instruction
0
53
* One reason that the taste isn't as good for Robusta is that it has more caffeine compared to Arabica. Which may sound like a positive thing but caffeine carries a bitter taste which makes it an unpleasant drink. In fact the Robusta bean has 2.7% caffeine content, almost double the 1.5% of Arabica. * Arabica contains almost 60% more lipids and almost twice the concentration of sugar than Robusta. This factor also probably has a big impact on why we prefer the taste of Arabica. * From a price perspective, green beans of Robusta is about half the price of Arabica green beans on the commodity market. * Robusta is easier to tend to on the farm, has a higher yield and is less sensitive to insects - the extra caffeine is a chemical defense for the coffee seed as the quantity in the Robusta is toxic to bugs. All of these factors help bring up the supply and lower the input costs for farmers to produce. With this more attractive price point, a lot of roasters back in the day would add Robusta to their blend in an attempt to reduce their costs and increase their profits. When coffee was initially sold in the 1900s the quality of coffee slowly and slowly deteriorated in an effort for companies to squeeze the most profit. Where you’ll find it: Nowadays, it’s not often you’ll find Robusta in a coffee blends or in coffee shop. If you’re drinking instant coffee? Well, that’s probably all Robusta… but you probably don’t care very much about taste. In your espresso blend? That’s a mixed bag. Literally. Oddly enough, Robusta is still widely used as part of espresso blends – specifically Italian style blends. It is said to help improve the crema. One thing to note is despite the association with Arabica of being higher quality, and Robusta as being lower quality, it’s not always the case. Top notch specialty Robusta coffee will usually taste as good as or better than low end Arabica. However, high end Robusta isn’t widely used or available. Rather, Robusta is usually used as a filler or cost reducer. * Robusta beans are much more circular, whereas Arabica are more oval. * Chlorogenic acid is a significant antioxidant and an insect deterrent. Robusta is 7-10% CGA and Arabica has 5.5-8% CGA.
output
1
53
So whenever we want to shoot our flash before taking a photo. we have to charge it first. What is the point of the charging our flashes? Aren't their power directly supplied by the battery of our camera? Please answer for the built in flash on the 2000D and the traditional hot shoe Xenon flashes. Perhaps these hot shoe xenon flashes have their own batteries charged by the slow hot shoe port. Who knows?
instruction
0
54
The peak power at work when a flash is being discharged is extreme. Example: a classic Metz 45CT (a large but still handheld unit) on full manual power delivers around 90 watt-seconds of electrical output to the flash tube in 1/300s. That means there are 27000 watts at work for a short time. A 27000 watt lightbulb (BTW, your flash is much brighter than that - more efficient!) would need the ampacity of around eight european household sockets (230V, fused at 13 or 16 amps) to operate, since it would draw around 120 ampere from them. At the voltage levels xenon flash tubes typically operate at, around 80 amperes will flow; if you wanted to pull that energy "live" from a 5-6V battery, you'd need to pull around 5000 amperes AND instantaneously convert them to around 80 amperes at high voltage. Batteries that could deliver 5000 amps - while not wasting most of the power as heat generated across their internal resistance - for a short duration and live certainly exist - you are looking at starter batteries for big lorries, which are rather inconvenient to lug around. Also, a 5000 ampere current pulse is quite a magnetic nuisance if there is anything either ferromagnetic or intended as an electrical conductor near the conductors used. Your average "big" speedlite, btw, will be around half the power described here (but might in some cases reach the same or higher peak currents in order to discharge even faster), an in-camera flash will be a fraction of these numbers - but still inconvenient to build any other way. If you need a short, massive current pulse, the best energy source available in engineering is a previously charged capacitor (metal-paper or electrolytic type, not dual-layer "supercap"). This energy storage device is large for its storage capacity if you compare it to a battery - but able to respond far quicker to high current demand, since a) there is no chemical energy conversion involved in its operation, b) the relevant current path only involves metallic, very conductive parts instead of ionic conductors (aka electrolytes. An electrolytic capacitor, btw, does use its electrolyte for chemical self-upkeep, not for chemical energy storage or electrical connectivity). Also, since the charge in a a capacitor is limited, it allows portioning total energy to what the flashlamp can safely take. This allows a flash in manual mode to just completely discharge the capacitor until it is nearly empty (when the remaining charge can only deliver voltage below the quench voltage of the flashlamp) without complex control circuitry - and at the same time gives you a safety fallback when working with dynamically controlled power levels (telecomputer or TTL mode), leaving no way for catastrophic circuit failure in combination with several kilowatts of constant power available turning into a massive safety hazard. A handheld-sized efficient electrical near point light source with 27000W input, driven constantly, would first severely damage your eyes and then self destroy violently (think of a welding arc - dangerously bright, and it melts metal).
output
1
54
What are some strategies to maintain morale and productivity after massive layoffs? I am not in a managerial role, just a lead role, and am asking for myself and my fellow employees.
instruction
0
55
The situation you're describing is tough. Layoffs have a very real impact on both the individuals that are let go and those that remain. I'm sorry you're experiencing this. Here are some things to consider that may help you and your colleagues cope with the added stress and emotions following a layoff: * Acknowledge the layoff and the feelings of your colleagues. Avoiding the topic can extend negative feelings and disenfranchise those most impacted. You should find an opportunity to connect with your colleagues for an honest conversation about your feelings following the layoff. Perhaps reach out to hold a number of 1-on-1 conversations, or gather your team for an off-site lunch and prompt the discussion. * Acknowledge that everyone will be impacted differently. Some of your colleagues will feel totally okay and ready to get back to work. Others will feel anxious and worried in a way that prevents them from performing the same way they did before the layoff. There is no right or "professional" reaction to a layoff. Be open to the feelings and reactions of all of your colleagues equally. * Create practical solutions to new processes and responsibilities. If your team now has a greater workload, be a generator of solutions. Try out ideas for making processes in your team more efficient and predictable. * Create transparency about the state of the business and potential future staff changes. Layoffs are a clear indication of business trouble. Facilitate sharing facts about the state of the business and actively work to eliminate rumors. Additionally, layoffs will likely cause shifts in responsibility as roles are consolidated or reorganized. Make clear who has specific responsibilities both inside and outside of your team. Actively eliminate any sources of uncertainty and anxiety that you can. * Be a role model. Don't participate in gossip or complaining about the layoff. Don't disparage management or other colleagues in casual conversation. Be a model for professionalism and caring. * Maintain work standards and a caring meritocracy. A layoff isn't an excuse for allowing work quality to decline. Additionally, differences in productivity and quality between team members should be consistently and fairly addressed. If a team member is underperforming following the layoff, provide direct feedback and ask what you can do to help.
output
1
55
Could you please clearly explain what is the difference between correlation and convolution that is done by a filter on an image? I mean in terms of signal processing definition I know that convolution describes the output of an LTI system, that is if an LTI system produces an output due to convolution with an input system then the output signal can be described as the result of convolution of the input signal and the impulse response of the LTI system. As for the correlation, it describes the similarities between to signals. But how does convolution and correlation effect on a image and how different are they in terms of effects? Thanks
instruction
0
56
Convolution is correlation with the filter rotated 180 degrees. This makes no difference, if the filter is symmetric, like a Gaussian, or a Laplacian. But it makes a whole lot of difference, when the filter is not symmetric, like a derivative. The reason we need convolution is that it is associative, while correlation, in general, is not. To see why this is true, remember that convolution is multiplication in the frequency domain, which is obviously associative. On the other hand, correlation in the frequency domain is multiplication by the complex conjugate, which is not associative. The associativity of convolution is what allows you to "pre-convolve" the filters, so that you only need to convolve the image with a single filter. For example, let's say you have an image $f$, which you need to convolve with $g$ and then with $h$. $f * g * h = f * (g * h)$. That means you can convolve $g$ and $h$ first into a single filter, and then convolve $f$ with it. This is useful, if you need to convolve many images with $g$ and $h$. You can pre-compute $k = g * h$, and then reuse $k$ multple times. So if you are doing template matching, i. e. looking for a single template, correlation is sufficient. But if you need to use multiple filters in succession, and you need to perform this operation on multiple images, it makes sense to convolve the multiple filters into a single filter ahead of time.
output
1
56
24601 has developed into being an iconic part of both the Les Miserables book and musical. Was that number special to him, or was it simply a random number he chose (I doubt it)?
instruction
0
57
Yes: it corresponds to the date of Hugo's conception. This is part of a pattern of similarities between the character of Jean Valjean and the author himself: both are of similar age, have similar habits and similarly austere lifestyles, and even share the same dreams. This is according to David Bellos's The Novel of the Century: The Extraordinary Adventure of Les Misérables, which concludes Part Three with: But Hugo put in a secret sign to remind himself and maybe those who knew him well that there were deep links of identity between the dutiful and persistent ex-convict and himself. Hugo was born on 26 February 1802, but because he was a slightly premature baby, he always believed he had been conceived on 24 June 1801. Valjean's prison number on his first incarceration at Toulon is 24601. -- p. 162 (emphasis mine) As a bonus, Valjean's second prisoner number was apparently also chosen for its special significance to Hugo: it refers to the month of his daughter Léopoldine's death. From footnote 46 in Kathryn Grossman's Figuring Transcendence in Les Miserables: Hugo's Romantic Sublime: Gaudon demonstrates that this image, which represents genius in one of the poet's earliest carnets (8 July 1820), is a sign of his "deep identification" with Valjean (Temps 547). As further evidence that the hero is an alter ego, Gohin cites the two numbers assigned to him in prison. The first, 24601, refers to the supposed date of Hugo's conception (24 June 1801), while the second, 9430, alludes to Léopoldine's death in September 1843 ("Une histoire" 47; see also 52). -- p. 165 (emphasis mine)
output
1
57
Why does Michael Crichton use US Customary measurements in hard sci-fi?
instruction
0
58
Crichton used both imperial and metric, depending on the context. In the course of one paragraph in The Sphere, he managed to use both! > "Pacific coral grows two-and-a-half centimeters a year, and the object-- whatever it is-- is covered in about five meters of coral. That's a lot of coral. Of course, coral doesn't grow at a depth of a thousand feet, which means that the present shelf collapsed to a lower depth at some point in the past." When the character (Barnes, a Navy captain) is talking about precise measurements, he uses metric. When he's being more general, he uses imperial. The main character Norman (a psychologist, not exactly the most mathematically intensive field) uses imperial when thinking to himself. > He climbed up through the submarine and into a round steel cylinder approximately eight feet in diameter. But later, when the astrophysicist Ted is giving officialish measurements the titular sphere, he uses metric: > "This object is a burnished sphere approximately ten meters in a diameter, no solid, and composed of a dense metal alloy." So the short answer is that Crichton is an American writing American characters for a predominantly American audience. He uses imperial units for clarity, but metric when it would realistically be used.
output
1
58
How can horns, most of which have only three buttons, play all their notes?
instruction
0
59
Put as simply as possible, horns are tubes. Blowing in special ways makes certain notes sound from those tubes. By changing one's embouchure, those notes start at a fundamental, then gradually go up in harmonics. The first notes (in key C) would be C, G, C, E, G.Those notes are the ones we hear when a bugle is played - Reveille, Last Post, etc. Bugles only play the harmonic series of notes, and can't play the ones in between. Read on. On a trumpet, for starters, there are three valves. One drops any open note played by one semitone, another by two semitones, and the other by three semitones. So using a combination of valves, you can lower any open note by up to six semitones. Let's take the first G note. To get F♯, press the semitone valve. To get F, press the tone valve. To get E, press two valves to drop a tone and a half. (there's one valve alone that can do this). To play E♭, press the two valves that drop two tones. To get D, press the two valves to drop two and a half tones. And to get C♯, press all three. That's the more complicated bit, as between the open notes, there's more semitones than anywhere else further up in pitch. Notice that between G and the next C, there are only two tones. So at this point, not so many notes are needed, so the valve pressing is more simple. Next, between that C and the E, there's even fewer, so again, not so many valve changes are needed. Now, onto trombone. There are actually valve trombones, which work the same as trumpets, etc., but for the standard trombone, imagine those extra lengths of tube brought into play by pressing valves are now a single continuum of tubing, operated by the slide. At various places along that slide, there are all the notes found similarly to pressing valves. There's also loads of extra notes that are going to be out of tune!
output
1
59
I am a big fan of worldbuilding. A common sight in science fiction is that aliens pretend to be human (For example in Third Rock from the Sun). Obviously if the aliens are advanced enough to disguise themselves as another species, there are much easier, simpler and less expensive methods to destroy humanity, so why else would an advanced alien civilization waste time, energy and resources to disguise themselves as humans? What possible scientific, cultural or commercial use could such an expensive procedure have?
instruction
0
60
Aliens are alien, without a common background their motives may be incomprehensible. If we assume that these aliens are Hollywood aliens (ie humans with odd-looking rubber bits stuck on their faces) then there are all of the reasons that humans from one culture spend time in another culture and try and learn to fit in: * Anthropology; studying how a different culture has developed to better understand the developmental processes that influenced your own. Iain M. Banks wrote Inversions (two anthropologists from the Culture investigating a Renaissance-era world) and The State of the Art (a Culture Contact team on Earth ca 1970) in this vein. * Tourism; experiencing a culture that is vastly different from your previous experiences. * Reality TV; Bear Grylls. * Method Acting; preparing for a role in their own entertainment channels that involves playing the part of a member of an Information Age society. * Challenge; because they can. * Hermitage; there are people here on Earth who prefer to step away from the rat race and all the newfangled gadgets and live as their ancestors did, but usually not all the way back to stone tools. Selecting a developing world and fitting in gives them access to a level of technology between their home culture and being trapped on a desert island. * Camouflage; they are being sought by members of their home culture and it's easier to hide and survive amongst us than in their own milieu. There are a lot of examples of this in fiction already: For Richer or Poorer, Men in Black II and it's analogous to fleeing the law and retiring to a country without an extradition treaty. * Crash Landing, or a failure that prevents them from going home; if they came on an FTL ship that doesn't have FTL communications they may be waiting a long time for spare parts or updated navigational maps, or if they brought Gilligan who proceeded to ruin all of their plans to return home, or they may have arrived on a slower-than-light colony ship and would prefer to stay here and fit in amongst us rather than try and find another prospective colony. * Uplift; meddling to steer us onto the "right" path of development and prevent us from immolating ourselves (or vice versa if your species doesn't like the competition).
output
1
60
I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
instruction
0
61
The following is an explanation of the uses of the underscore is Scala _ [underscore] magic. Examples: ``` def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "anything other than one and two" } expr match { case List(1,_,_) => " a list with three element and the first element is 1" case List(_*) => " a list with zero or more elements " case Map[_,_] => " matches a map with any key type and any value type " case _ => } List(1,2,3,4,5).foreach(print(_)) // Doing the same without underscore: List(1,2,3,4,5).foreach( a => print(a)) ``` In Scala, ```_``` acts similar to ```*``` in Java while importing packages. ```// Imports all the classes in the package matching import scala.util.matching._ // Imports all the members of the object Fun (static import in Java). import com.test.Fun._ // Imports all the members of the object Fun but renames Foo to Bar import com.test.Fun.{ Foo => Bar , _ } // Imports all the members except Foo. To exclude a member rename it to _ import com.test.Fun.{ Foo => _ , _ } ``` In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and ```_=``` is added for the setter name. ```class Test { private var a = 0 def age = a def age_=(n:Int) = { require(n>0) a = n } } ``` Usage: ```val t = new Test t.age = 5 println(t.age) ``` If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable. ```class Test { def fun = { // Some code } val funLike = fun _ } ```
output
1
61
My university usually asks that we book a flight via a travel agent, but the prices he gives me are about $50 higher than the prices I can get by online booking in the flight company's website. Why would a company want me to book a flight via a travel agent if it is more expensive?
instruction
0
62
There are several reasons why such internal policies exist: * Your institution may get a discount on certain services of the travel agent if it buys enough from the agent * By having a contract with a reasonably-priced travel agent, they make sure that no employee books the flight with a very pricey agent or with a travel agent that happens to be a relative of the traveller * The travel agency offers easy methods to verify expense information and thus may lower the workload of your local administrative personnel. This especially holds if the payment is routed directly from the institution to the travel agent, which also makes sure that the flyer does not get credit card bonus points for the booking. * Your institution may have an agreement with the travel agent that they manually check if members of your institution are not unnecessarily booking expensive booking classes (in order to get more airline bonus miles) * Some insurances that your institution bought may only work if the ticket is bought directly from the institution and not by the flyer, and they elected the agent to handle such bookings. Which of these reasons is the one why this policy exists can only be answered by the responsible employees of your institution.
output
1
62
Layman's explanation of encryption backdoors
instruction
0
63
There are two somewhat orthogonal concepts in backdooring encryption algorithms: * The backdoor can be explicit or implicit. An explicit backdoor is one that everybody knows it is there. An implicit backdoor strives at remaining undetected by the algorithm owners. Of course, when there is an explicit backdoor, people tend to avoid the algorithm altogether, so explicit backdoors may hope to work only in the presence of a legal framework that forces implementers to use the backdoored system. An example of an explicit backdoor is the Clipper chip (which was ultimately abandoned). The backdoor is not really in the algorithm, more in the assembly of algorithms into a protocol, and technically it was an automatic key escrowing method. For an implicit backdoor, see the Dual EC DRBG as a famous example: it worked only as long as nobody was aware that it was backdoored. * The backdoor's security may be quantifiable, or not. In the case of Dual EC DRBG, the mechanism uses well-trodden mathematical paths: the NSA knew that exploiting the backdoor required knowledge of an internal secret key, based on discrete logarithm (on elliptic curves). A non-quantifiable security is what happens when you try to push, for instance, a voluntarily flawed algorithm, or one for which you know of a cryptanalytic method that you did not publish. This is a very dangerous game for a spy agency, because you cannot really know whether third parties could find the flaw or not. Such backdooring tends to backfire in the long term. Interestingly, the NSA tends not to use non-quantifiable backdoors. A good example is DES. At the time it was designed, the NSA believed that it could tackle an upfront 256 exhaustive search, and that nobody else (in particular the Soviets) had the technology and budget for that. The NSA also knew of a novel cryptanalytic method (differential cryptanalysis). So when the NSA intervened in the design of DES, it insisted on shortening the key from 64 to 56 bits (that's addition of a quantifiable backdoor, and it was rather obvious, so quasi-explicit), and also on strengthening the design against differential cryptanalysis. This is a good example about how NSA consciously refrained from a non-quantifiable backdoor. There is only one thing that spy agencies fear more than not being able to spy: it is the idea that other competing spy agencies may also spy. So a real, good backdoor is one that uses maths to offer quantifiable security against unauthorized usage of the backdoor. It is extremely difficult to have quantifiable security without making the backdoor explicit. The "best in class" in that area is Dual EC DRBG, and even before the Snowden business, cryptographers were already finding it weird and strongly suspected foul play (see the analyses back in 2007, 6 years before Snowden).
output
1
63
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player. When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar. I am using this code to make it move the selected option to the top of the div: ```var pathArray = window.location.pathname.split( '/' ); var el = document.getElementById(pathArray[5]); el.scrollIntoView(true); ``` It moves it to the top of the div but about 10 pixels too far up. how to fix that?
instruction
0
64
CSS ```scroll-margin``` and ```scroll-padding``` You might want to have a look at new CSS properties ```scroll-padding``` and ```scroll-margin```. You can use ```scroll-padding``` for the scrolling container (```html``` in this case), and ```scroll-margin``` for the element within the container. For your example, you would want to add ```scroll-margin-top``` for the element that you want to scroll into view, like this: ```.example { scroll-margin-top: 10px; } ``` This affects ```scrollIntoView``` code, like this code: ```const el = document.querySelector(".example"); el.scrollIntoView({block: "start", behavior: "smooth"}); ``` This will cause the viewport to scroll to align the top border of the viewport with the top border of the element, but with 10px of additional space. In other words, these properties of the element are taken into account: * ```padding-top``` * ```border-top``` * ```scroll-margin-top``` * (and not ```margin-top```) In addition, if the ```html``` element has ```scroll-padding-top``` set, then that is taken into account too. If you're using a framework like Vue, you might want to make sure that all changes to the DOM are finished before running `scrollIntoView` by using something like `Vue.nextTick(() => el.scrollIntoView())`
output
1
64
Suppose I have the geographic coordinates of "Saratoga, California, USA" as ```Latitude: 37°15.8298′ N Longitude: 122° 1.3806′ W ``` I know from here that in the case of latitude ```1° ≈ 69 miles``` and that longitude varies: ```1° longitude = cosine (latitude) * length of degree (miles) at Equator. ``` How many miles is 1° longitude at ```longitude: 122°1.3806′ W```?
instruction
0
65
It doesn't matter at what longitude you are. What matters is what latitude you are. Length of ```1 degree of Longitude``` = ```cosine (latitude in radians) * length of degree (miles) at equator```. Convert your latitude into decimal degrees ~ 37.26383 Convert your decimal degrees into radians ~ 0.65038 Take the cosine of the value in radians ~ 0.79585 1 degree of Longitude = ~0.79585 * 69.172 = ~ 55.051 miles More useful information from the about.com website: Degrees of latitude are parallel so the distance between each degree remains almost constant but since degrees of longitude are farthest apart at the equator and converge at the poles, their distance varies greatly. Each degree of latitude is approximately 69 miles (111 kilometers) apart. The range varies (due to the earth's slightly ellipsoid shape) from 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km) at the poles. This is convenient because each minute (1/60th of a degree) is approximately one [nautical] mile. A degree of longitude is widest at the equator at 69.172 miles (111.321) and gradually shrinks to zero at the poles. At 40° north or south the distance between a degree of longitude is 53 miles (85 km) Note that the original site (about.com) erroneously omitted the "nautical" qualifier.
output
1
65
I have read numerous times that some Norse warriors, upon death, would go in Fólkvangr, while some others would go to Valhalla. How was it decided which warrior would go to which place? Why did the need to have many "paradises" (whatever you many call it) exist? Citing Wikipedia: > In Norse mythology, Fólkvangr (Old Norse "field of the host" or "people-field" or "army-field") is a meadow or field ruled over by the goddess Freyja where half of those that die in combat go upon death, while the other half go to the god Odin in Valhalla.
instruction
0
66
The Norse mythological texts record three primary places where the dead were perceived to go: Helheim (Old Norse Helheimr, “the home of the goddess Hel“), Valhalla (Old Norse Valhöll, “the hall of the fallen”), and Folkvang (Old Norse Fólkvangr, “the field of the people” or “the field of warriors”). But they're indistinguishable and don't have any major differences between them. Valhalla is presided over by Odin, and to gain entrance to it, one must be chosen by him and his valkyries, the “choosers of the fallen.” Similarily, entrance to Folkvang is dependent upon being selected by Freya. Valhalla is often depicted as a realm where distinguished warriors engage in a continuous battle, and just such a place is described, in important early sources, as being located beneath the ground – and, intriguingly, without the name “Valhalla” or a cognate anywhere in the account. source: Ellis, Hilda Roderick. 1968. The Road to Hel: A Study of the Conception of the Dead in Old Norse Literature. p. 85-86. * Folkvang is the ninth, and there Freyia arranges the choice of seats in the hall; half the slain she chooses every day, and half Odin owns. source: 1996 Carolyne Larrington in The Poetic Edda “Grimnir’s Sayings” The only difference that is pointed out, is in the way that the dead are chosen to stay. Odin chooses for Valhalla, while Freya chooses for Folkvang. Coming to the second part of the question: And why did the need to have many "paradises" (whatever you many call it) exist? Hel is a place where all humans have to go after their death: “For there is a time when every man shall journey hence to Hel." Fáfnismál 10 So before the dead finally reach Hel, Odin and Freyja select the ones who are worthy of living in Valhalla and Folkvang. Therefore, * Valhalla receives distinguished warriors. * Folkvangr receives the rest of the warriors. * Hel receives the rest of the dead. source: Norse-Mythology.org
output
1
66
I noticed that there is a binary executable ```/bin/echo``` on my Ubuntu MATE 17.04 system. I thought, that's odd, because ```$ type echo echo is a shell builtin``` Cursory testing suggests that ```/bin/echo``` does the same sort of thing as the Bash builtin ```echo```: ```$ /bin/echo foo foo $ /bin/echo $USER zanna ``` So, why is there another version of ```echo``` separate from the Bash program, and why or when would I want to use it?
instruction
0
67
If you open up a ```bash``` prompt and type in an ```echo``` command, that uses a shell builtin rather than running ```/bin/echo```. The reasons it is still important for ```/bin/echo``` to exist are: * You're not always using a shell. Under a variety of circumstances, you run an executable directly and not through a shell. * At least in theory, some shells don't have an ```echo``` builtin. This is not actually required. To expand on #1, suppose you wanted to move all the regular files whose names started with ```abc``` anywhere in ```src``` to ```dest```. There are several ways to do that but one of them is: ```find src -name 'abc*' -type f -exec mv -nv {} dest/ \; ``` But suppose, rather than just running that, you want to see every command that will be run first. Well, then you can prepend ```echo``` to the command, just as you might in other contexts: ```find src -name 'abc*' -type f -exec echo mv -nv {} dest/ \; ``` But ```find``` doesn't use a shell. That runs ```/bin/echo```. Besides ```find``` with ```-exec``` or ```-execdir```, the ```/bin/echo``` executable will be called by other programs that themselves run programs but not through a shell. This happens with the ```xargs``` command (which is related to ```find```), as well as in a number of other contexts, such as the ```Exec=``` line of a ```.desktop``` file. Another example is when you run ```sudo echo```, which can be handy for testing if ```sudo``` is working. Similarly, some shells have a ```printf``` builtin but ```/usr/bin/printf``` also exists. A less common possible reason you might deliberately use ```/bin/echo``` is if you were relying on the differences between it and the ```echo``` command provided by your shell. ```man echo``` documents ```/bin/echo```; ```help echo``` in ```bash``` documents the ```bash``` builtin. ```echo``` is not very portable, because different implementations--both across operating systems and across shells on the same operating system--support different options (e.g., ```-e```) and differ in their treatment of backslashes. Of course, it's better to avoid relying on such details, and use ```printf``` instead, which is far more portable. In ```bash```, you can make the ```type``` builtin show ```/bin/echo``` as well--assuming ```/bin``` is in your ```$PATH``` as it always should be--by passing it the ```-a``` flag: ```$ type -a echo echo is a shell builtin echo is /bin/echo ```
output
1
67
what's the difference between JavaScript objects, classes and functions?
instruction
0
68
As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the ```new``` keyword. This is known as the constructor pattern. In JavaScript everything is an object except for the primitive data types (boolean, number and string), and ```undefined```. On the other hand ```null``` is actually an object reference even though you may at first believe otherwise. This is the reason ```typeof null``` returns ```"object"```. Functions in JavaScript are similar to functables in Lua (i.e. they are callable objects). Hence a function can be used in place of an object. Similarly arrays are also objects in JavaScript. On the other hand objects can be thought of as associative arrays. The most important point however is that there are no classes in JavaScript because JavaScript is a prototypal object oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes. All we need is a way to create and extend objects.
output
1
68
In most introductory algorithm classes, notations like $O$ (Big O) and $\Theta$ are introduced, and a student would typically learn to use one of these to find the time complexity. However, there are other notations, such as $o$, $\Omega$ and $\omega$. Are there any specific scenarios where one notation would be preferable to another?
instruction
0
69
You are referring to the Landau notation. They are not different symbols for the same thing but have entirely different meanings. Which one is "preferable" depends entirely on the desired statement. $f \in \cal{O}(g)$ means that $f$ grows at most as fast as $g$, asymptotically and up to a constant factor; think of it as a $\leq$. $f \in o(g)$ is the stricter form, i.e. $ $f \in \Omega(g)$ has the symmetric meaning: $f$ grows at least as fast as $g$. $\omega$ is its stricter cousin. You can see that $f \in \Omega(g)$ is equivalent to $g \in \cal{O}(f)$. $f \in \Theta(g)$ means that $f$ grows about as fast as $g$; formally $f \in \cal{O}(g) \cap \Omega(g)$. $f \sim g$ (asymptotic equality) is its stronger form. We often mean $\Theta$ when we use $\cal{O}$. Note how $\cal{O}(g)$ and its siblings are function classes. It is important to be very aware of this and their precise definitions -- which can differ depending on who is talking -- when doing "arithmetics" with them. When proving things, take care to work with your precise definition. There are many definitions for Landau symbols around (all with the same basic intuition), some of which are equivalent on some sets on functions but not on others. If you are interested in using Landau notation in a rigorous and sound manner, you may be interested in a work by Rutanen et al.. They formulate necessary and sufficient criteria for asymptotic notation as we use them in algorithmics, show that the common definition fails to meet them and provide a (the, in fact) workable definition. * A general definition of the O-notation for algorithm analysis by K. Rutanen et al. (2015)
output
1
69
Why is Gaia operating around Earth orbit? Why not send it to Neptune's orbit?
instruction
0
70
Well, you thought about the spatial aspect of a parallax measurement, but not about the temporal one. Gaia's intention is to measure 3D positions as well as 3D velocities. For the distance, you need accurate parallactic measurement, which come in with your orbital period. For a typical Gaia-star with several measurement per year, you'll get 5 values of the parallax after 5 years of time, which you then average. If you'd send Gaia towards Neptune (besides the fact that no one has ever sent an orbiter, to say nothing of a L2 mission that far out) that has a period of 168 years, then after 5 years you'd get... 5/168 th of one paralactic measurement. It simply couldn't achieve its science goals if put around the L2 behind Neptune. Also no one on this planet has any experience in putting something into a outer system L2 point. This is different than putting it into Earth's L2, because reaching the L2 around one of the giants has vast and very precise $\Delta v$ requirements. This would be a massive technological leap, and things don't work that way in space. Small, incremental technological steps are required in an anyways unfriendly environment, to make sure everything works properly and no millions of dollars have been wasted. Compare that to Gaia's predecessor, the Hipparcos satellite, which was parked in geostationary orbit. Now you could still say, why not use Jupiter hypothetically anyways. Well, the orbital period there is still 11 years, and Jupiter's L2 still suffers from the intense radiation environment that is provided by Jupiter's magnetosphere. This would lead to rapid degradation of the CCDs used for scanning across the sky.
output
1
70
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use ```time.strftime```, I get a ```TypeError```: ```>>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "", line 1, in TypeError: argument must be 9-item sequence, not str ```
instruction
0
71
There are two parts here: * Convert the unix timestamp ("seconds since epoch") to the local time * Display the local time in the desired format. A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a ```pytz``` timezone: ```#!/usr/bin/env python from datetime import datetime import tzlocal # $ pip install tzlocal unix_timestamp = float("1284101485") local_timezone = tzlocal.get_localzone() # get pytz timezone local_time = datetime.fromtimestamp(unix_timestamp, local_timezone) ``` To display it, you could use any time format that is supported by your system e.g.: ```print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)")) print(local_time.strftime("%B %d %Y")) # print date in your format ``` If you do not need a local time, to get a readable UTC time instead: ```utc_time = datetime.utcfromtimestamp(unix_timestamp) print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)")) ``` If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system: ```local_time = datetime.fromtimestamp(unix_timestamp) print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f")) ``` On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows): ```#!/usr/bin/env python3 from datetime import datetime, timezone utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc) local_time = utc_time.astimezone() print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)")) ``` Functions from the ```time``` module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding ```datetime``` methods otherwise you could use them too: ```#!/usr/bin/env python import time unix_timestamp = int("1284101485") utc_time = time.gmtime(unix_timestamp) local_time = time.localtime(unix_timestamp) print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time)) ```
output
1
71
In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this: ```mysite/ manage.py mysite/ --> (settings.py, etc) myapp/ --> (models.py, views.py, etc) static/ ``` In ```mysite/settings.py``` I have: ```STATIC_ROOT = 'staticfiles' ``` So when I run the command: ```python manage.py collectstatic ``` It creates a folder called ```staticfiles``` at the root level (so same directory as ```myapp/```) What's the point of this? Isn't it just creating a copy of all my static files?
instruction
0
72
## Collect static files from multiple apps into a single path A single Django project may use several apps, so while there you only have one ```myapp```, it may actually be ```myapp1```, ```myapp2```, etc By copying them from inside the individual apps into a single folder, you can point your frontend web server (e.g. nginx) to that single folder ```STATIC_ROOT``` and serve static files from a single location, rather than configure your web server to serve static files from multiple paths. ## Persistent URLs with ManifestStaticFilesStorage A note about the MD5 hash being appended to the filename for versioning: It's not part of the default behavior of ```collectstatic```, as ```settings.STATICFILES_STORAGE``` defaults to ```StaticFilesStorage``` (which doesn't do that) The MD5 hash will kick in e.g. if you set it to use ```ManifestStaticFilesStorage```, which adds that behavior. > The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.
output
1
72
I am used to thinking of finite-differences as a special case of finite-elements, on a very constrained grid. What are criteria to choose between finite-differences and finite-elements
instruction
0
73
It is possible to write most specific finite difference methods as Petrov-Galerkin finite element methods with some choice of local reconstruction and quadrature, and most finite element methods can also be shown to be algebraically equivalent to some finite difference method. Therefore, we should choose a method based on which analysis framework we want to use, which terminology we like, which system for extensibility we like, and how we would like to structure software. The following generalizations hold true in the vast majority of variations in practical use, but many points can be circumvented. Finite Difference Pros * efficient quadrature-free implementation * aspect ratio independence and local conservation for certain schemes (e.g. MAC for incompressible flow) * robust nonlinear methods for transport (e.g. ENO/WENO) * M-matrix for some problems * discrete maximum principle for some problems (e.g. mimetic finite differences) * diagonal (usually identity) mass matrix * inexpensive nodal residual permits efficient nonlinear multigrid (FAS) * cell-wise Vanka smoothers give efficient matrix-free smoothers for incompressible flow Cons * more difficult to implement "physics" * staggered grids are sometimes quite technical * higher than second order on unstructured grids is difficult * no Galerkin orthogonality, so convergence may be more difficult to prove * not a Galerkin method, so discretization and adjoints do not commute (relevant to optimization and inverse problems) * self-adjoint continuum problems often yield non-symmetric matrices * solution is only defined pointwise, so reconstruction at arbitrary locations is not uniquely defined * boundary conditions tend to be complicated to implement * discontinuous coefficients usually make the methods first order * stencil grows if physics includes "cross terms" Finite Element Pros * Galerkin orthogonality (discrete solution to coercive problems is within a constant of the best solution in the space) * simple geometric flexibility * discontinuous Galerkin offers robust transport algorithm, arbitrary order on unstructured grids * cellwise entropy inequality guaranteeing $L^2$ stability holds independent of mesh, dimension, order of accuracy, and presence of discontinuous solutions, without needing nonlinear limiters * easy of implementing boundary conditions * can choose conservation statement by choosing test space * discretization and adjoints commute (for Galerkin methods) * elegant foundation in functional analysis * at high order, local kernels can exploit tensor product structure that is missing with FD * Lobatto quadrature can make methods energy-conserving (assuming a symplectic time integrator) * high order accuracy even with discontinuous coefficients, as long as you can align to boundaries * discontinuous coefficients inside elements can be accommodated with XFEM * easy to handle multiple inf-sup conditions Cons * many elements have trouble at high aspect ratio * continuous FEM has trouble with transport (SUPG is diffusive and oscillatory) * DG usually has more degrees of freedom for same accuracy (though HDG is much better) * continuous FEM does not provide cheap nodal problems, so nonlinear smoothers have much poorer constants * usually more nonzeros in assembled matrices * have to choose between consistent mass matrix (some nice properties, but has full inverse, thus requiring an implicit solve per time step) and lumped mass matrix.
output
1
73
How important is multithreading in the current software industry?
instruction
0
74
It is extremely important. What is more important though is to understand that multithreading is just one way to solve the asynchrony problem. The technical environment in which many people are now writing software differs from the historical software development environment (of monolithic applications performing batch computations) in two key ways: * Many-core machines are now common. We can no longer expect clock speeds or transistor densities to increase by orders of magnitude. The price of computation will continue to fall, but it will fall because of lots of parallelism. We're going to have to find a way to take advantage of that power. * Computers are now heavily networked and modern applications rely upon being able to fetch rich information from a variety of sources. From a computational standpoint, these two factors essentially boil down to the same core idea: information increasingly will be available in an asynchronous fashion. Whether the information you need is being computed on another chip in your machine or on a chip halfway around the world doesn't really matter. Either way, your processor is sitting there burning billions of cycles a second waiting for information when it could be doing useful work. So what matters now, and what will matter even more in the future, is not multithreading per se, but rather, dealing with asynchrony. Multithreading is just one way to do that -- a complicated, error-prone way that is only going to get more complicated and more error-prone as weak-memory-model chips become more widely used. The challenge for tools vendors is to come up with some way better than multithreading for our customers to deal with the asynchronous infrastructure they'll be using in the future.
output
1
74
Is it true that the price of diamonds is based on a monopoly? And who actually runs/owns this supposed monopoly? Is this likely to affect diamond prices if I am interested in purchasing?
instruction
0
75
Yes, the De Beers Group of Companies is a diamond cartel that had complete control of the diamond market for most of the 20th century. They still control a sizable portion of the market and their effort at marketing (particularly with the slogan "A Diamond is Forever") has done much to inflate the market for diamonds in our society. The intrinsic value of diamonds is much lower than the market prices currently reflect, but with the caveat that there is a rarity factor which does drive up the price of larger diamonds. The larger the diamond, the more likely it is to have flaws, so when it comes to diamonds that are 5 carats or greater, you are not as likely to see a new supply of diamonds disrupt the prices of those larger stones. Some other ways that high end jewelers and suppliers are differentiating themselves is by patenting a specific cut that they design. This is another barrier to entry that works to create some artificial price inflation. One common example is the Lucida cut sometimes referred to as the Tiffany cut. Diamonds can also be manufactured. The same carbon structure can be grown in a lab. These stones have the same carbon structure as natural diamonds but without the flaws and visible impurities. Most manufactured diamonds are used industrially, but processes have improved sufficiently to allow for gemstone quality synthetic diamonds. They sell at a decent discount, so that might be an option to consider if you want a substitute. In the years to come, you can expect prices for synthetic diamonds to continue to decrease which will probably put some further downward pressure on jewelers' prices.
output
1
75
Normal filesystem images can be easily mounted: ```mount system.img /mnt ``` Examined, and modified. But when I try this with a Raspberry Pi system image (e.g. raspbian), I get: ```mount: unknown filesystem type '(null)' ``` And no matter what I try with ```-t```, it won't work. How can I mount this image?
instruction
0
76
You can't mount the image as a whole because it actually contains two partitions and a boot sector. However, you can mount the individual partitions in the image if you know their offset inside the file. To find them, examine the image as a block device with ```fdisk -l whatever.img```. The output should include a table like this: ```Device Boot Start End Blocks Id System whatever.img1 8192 122879 57344 c W95 FAT32 (LBA) whatever.img2 122880 5785599 2831360 83 Linux ``` These are the two partitions. The first one is labelled "FAT32", and the other one "Linux". Above this table, there's some other information about the device as a whole, including: ```Units: sectors of 1 * 512 = 512 bytes ``` We can find the offset in bytes by multiplying this unit size by the ```Start``` block of the partition: * 1st partition 512 * 8192 = 4194304 * 2nd partition 512 * 122880 = 62914560 These can be used with the ```offset``` option of the ```mount``` command. We also have a clue about the type of each partition from ```fdisk```. So, presuming we have directories ```/mnt/img/one``` and ```/mnt/img/two``` available as mount points: ```mount -v -o offset=4194304 -t vfat whatever.img /mnt/img/one mount -v -o offset=62914560 -t ext4 whatever.img /mnt/img/two ``` If you get an "overlapping loop" error here, your version of ```mount``` requires you to specify the size as well as the offset of the first partition. Unmount that, and use the number of blocks (57344) * 512 (= 29360128): ```mount -v -o offset=4194304,sizelimit=29360128 \ -t vfat whatever.img /mnt/img/one ``` The second partition doesn't need a sizelimit since there's nothing after it in the image. You can now access the two partitions. If you do not intend to change anything in them, use the ```-r``` (read-only) switch too. If you do change anything, those changes will be included in the ```.img``` file. Note that the first partition is probably mounted on ```/boot``` in the second partition when the system is running.
output
1
76
How does immersion passively help with learning a language?
instruction
0
77
There are a few reasons why immersion helps you learn a language without you actively trying: * You encounter the language more often. When you are immersed in a language, you don't go to class and do homework for a few hours a week, but rather use the language the entire day. You depend on the language to survive—to buy groceries, to talk to employers and customers, to ask for directions, etc. Being forced to use the language means you learn it even when you're not actively trying to. It becomes a way of life. * You learn the language in more than one way. Classroom learning focuses on specific activities at a time and generally is oriented around learning vocabulary and grammar. Immersion implicitly forces you to learn vocabulary (if you don't know a word, you simply can't communicate) and grammar (people will probably correct you if you say something incorrectly). You will learn these things whether you're trying to or not. In addition you will learn how to carry on a conversation, both by listening and participating in your own. This is something that simple exercises can very rarely accomplish. * You begin to think in the language. If you use the language enough you'll start to get good enough at it that you won't have time to think in your native language and translate. Immersion spurs this on because native speakers talk relatively quickly, signs you read may pass by in a moment, and you may quickly need to say "excuse me" or ask for help. Because you can't afford long delays, you'll begin to skip the translation step. This helps you use the language as a native speaker would. * Culture reinforces language learning. When you are immersed in a language, you often encounter the culture and traditions associated with speakers of that language. Your brain will retain the new knowledge and experiences you acquire better because it is different than what you are used to, and if the language is part of that cultural experience, you will remember it better. For example, you might remember an idiom or a joke that only exists in the language you are learning. This will expand your ability to communicate in that language.
output
1
77
I have a script, that does not exit when I want it to. An example script with the same error is: ```#!/bin/bash function bla() { return 1 } bla || ( echo '1' ; exit 1 ) echo '2' ``` I would assume to see the output: ```:~$ ./test.sh 1 :~$ ``` But I actually see: ```:~$ ./test.sh 1 2 :~$ ``` Does the ```()``` command chaining somehow create a scope? What is ```exit``` exiting out of, if not the script?
instruction
0
78
```()``` runs commands in the subshell, so by ```exit``` you are exiting from subshell and returning to the parent shell. Use braces ```{}``` if you want to run commands in the current shell. From bash manual: (list) list is executed in a subshell environment. Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter. It's worth mentioning that the shell syntax is quite consistent and the subshell participates also in the other ```()``` constructs like command substitution (also with the old-style ````..```` syntax) or process substitution, so the following won't exit from the current shell either: ```echo $(exit) cat <(exit) ``` While it may be obvious that subshells are involved when commands are placed explicitly inside ```()```, the less visible fact is that they are also spawned in these other structures: * command started in the background ```exit & ``` doesn't exit the current shell because (after ```man bash```) If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. * the pipeline ```exit | echo foo ``` still exits only from the subshell. However different shells behave differently in this regard. For example ```bash``` puts all components of the pipeline into separate subshells (unless you use the ```lastpipe``` option in invocations where job control is not enabled), but AT&T ```ksh``` and ```zsh``` run the last part inside the current shell (both behaviours are allowed by POSIX). Thus ```exit | exit | exit ``` does basically nothing in bash, but exits from the zsh because of the last ```exit```. * ```coproc exit``` also runs ```exit``` in a subshell.
output
1
78
Adding a new swap file. How to edit fstab to enable swap after reboot?
instruction
0
79
These ares the steps to create a swap on a file: 1. Create a large file e.g. with ```sudo mkdir -p /var/cache/swap/ # create a directory that holds the swap file sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096 # for 4 GByte ``` Of course any other method of creating a file of defined size would do. 2. Announce swap to the system ```sudo chmod 0600 /var/cache/swap/myswap # only root should have access sudo mkswap /var/cache/swap/myswap # format as swap sudo swapon /var/cache/swap/myswap # announce to system ``` Insert the following line in ```/etc/fstab``` for swap from the next boot: ```/var/cache/swap/myswap none swap sw 0 0 ``` Note: 1. In case you have your system files on a SSD you may want to consider to hold your swap file on a hard disk location. 2. You can not use a swap file for hibernation (see Ubuntu SwapFaq) 3. Additional note for Ubuntu >= 17.04: A swap on file ```/swapfile``` is created by default in a new installation (when no swap partition was present). We can manually create a swap partition later if we prefer. In case we want to replace an existing swap (e.g. partition) with another swap (e.g. on file) we need to remove the old swap with ```sudo swapoff -a # for all ``` Then remove the swap entry from ```/etc/fstab``` or replace it with the new swap respectively.
output
1
79
How do I add a validation to make sure the date string being passed to the method is in the ffg. format: ```'YYYY-MM-DD' ``` if it's not, method should raise some sort of error
instruction
0
80
The Python ```dateutil``` library is designed for this (and more). It will automatically convert this to a ```datetime``` object for you and raise a ```ValueError``` if it can't. As an example: ```>>> from dateutil.parser import parse >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, 0) ``` This raises a ```ValueError``` if the date is not formatted correctly: ``` ValueError: day is out of range for month ``` ```dateutil``` is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: ```dateutil``` parsing examples. It also handles timezones if you need that. Update based on comments: ```parse``` also accepts the keyword argument ```dayfirst``` which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g. ```>>> parse('11/12/2001') >>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12 >>> parse('11/12/2001', dayfirst=True) >>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11 ```
output
1
80
When to use UICollectionView instead of UITableView?
instruction
0
81
That depends on the requirements. How the application flows determines which type of UI to integrate into the application. People mainly use the ```UICollectionview``` for creating types of UIs with multiple images shown in a grid. This would have complex logic using ```UITableView```, but with ```UICollectionview```, it would be easy. When using ```UICollectionview```, you don't need to set buttons with tags or other things by getting selected items values. You can simply get ```-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath``` and in ```UITableViewDelegate```: ````-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath` ``` You get the selected row instead of the item, so for creating grid or modified items, using ```UICollectionview``` is best. For the listing details of each item, people use ```UITableView``` because it shows more info on each item. Apple Docs: UICollectionView Class Reference The UICollectionView class manages an ordered collection of data items and presents them using customizable layouts. Collection views provide the same general function as table views except that a collection view is able to support more than just single-column layouts. Collection views support customizable layouts that can be used to implement multi-column grids, tiled layouts, circular layouts, and many more. You can even change the layout of a collection view dynamically if you want. UITableView Class Reference A table view displays a list of items in a single column. UITableView is a subclass of UIScrollView, which allows users to scroll through the table, although UITableView allows vertical scrolling only. The cells comprising the individual items of the table are UITableViewCell objects; UITableView uses these objects to draw the visible rows of the table. Cells have content—titles and images—and can have, near the right edge, accessory views. Standard accessory views are disclosure indicators or detail disclosure buttons; the former leads to the next level in a data hierarchy and the latter leads to a detailed view of a selected item. Accessory views can also be framework controls, such as switches and sliders, or can be custom views. Table views can enter an editing mode where users can insert, delete, and reorder rows of the table.
output
1
81
On my branch I had some files in .gitignore On a different branch those files are not. I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not. Unfortunately I get this: The following untracked working tree files would be overwritten by merge How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?
instruction
0
82
Safely remove/overwrite only bothersome files When you want to ```merge```: ```git checkout -f donor-branch # replace bothersome files with tracked versions git checkout receiving-branch # tracked bothersome files disappear git merge donor-branch # merge works ``` When you want to ```pull```: ```git fetch git checkout -f origin/mybranch # replace bothersome files with tracked versions git checkout mybranch # tracked bothersome files disappear git pull origin/mybranch # pull works ``` That's all you need to know to use this. Below is an explanation. Detailed explanation The Bothersome Files that we are going to remove: * exist in the donor branch (for ```git pull```: the upstream branch), * do not exist in the receiving branch, * and are blocking the merge because they are present and untracked in your working directory. ```git merge -f``` and ```git pull -f``` do not exist, but ```git checkout -f``` does. We will use ```git checkout -f``` + ```git checkout``` to track + remove the Bothersome Files, and then your merge can proceed normally. Step 1. This step forcibly replaces untracked Bothersome Files with tracked versions of the donor branch (it also checks out the donor branch, and updates the rest of the working dir). ```git checkout -f donor-branch ``` Step 2. This step removes the Bothersome Files because they they are tracked in our current (donor) branch, and absent in the ```receiving-branch``` we switch to. ```git checkout receiving-branch ``` Step 3. Now that the Bothersome Files are absent, merging in the donor branch will not overwrite any untracked files, so we get no errors. ```git merge donor-branch ```
output
1
82
Since long time ago I have been thinking in two problems that I have not been able to solve. It seems that one of them was recently solved. I have been thinking a lot about the motivation and its consequences. Mostly because people used to motivate one of them with some very interesting implications. My conclusion however, is that there is a mistake in the motivation of the problem, and that, while being a really interesting result, it does not make any sense in the setting in which is formulated. As my opinion is not relevant compared to one of the experts in the area, I do not say anything. My question is if you can provide me some examples of conjectures that were believed to be interesting in the mathematical community because of a specific reason, but that once having the proof, people realized that the reason to motivate the problem was not truly related to its solution. Or in other words, the solution of the problem gives no clues about the original motivation.
instruction
0
83
The three-body problem is one of the most famous problems in the history of mathematics, which also has an important application in science: it was supposed to explain the Moon's motion, among other things. Enormous effort was spent on this problem by many famous mathematicians of the 18th and 19th centuries. Since Newton's time it was clear that there was no simple closed form solution. (The problem also had an important practical application in 18th century, namely to navigation. If you can predict the motion of the Moon for few years ahead with sufficient accuracy, you can determine longitude at sea without a chronometer, just by observing Moon's position with respect to the stars). In the middle of the 19th century, an exact mathematical formulation of what was desired was achieved: to express the motions of the bodies in the form of convergent series of functions of time, valid for all times. Few people remember nowadays that in this precise form the problem was actually solved (by Sundman, at the very end of the 19th century). This solution can be found in Siegel's book on celestial mechanics. But by that time it was already understood that this solution was useless for practical purposes, namely for prediction of the Moon's motion over long time periods. It was also useless for understanding the qualitative features of the motion.
output
1
83
How do GPS receivers communicate with satellites?
instruction
0
84
The first thing to know is the communication is one-way. There's a satellite-to-receiver transmission, nothing going in the opposite direction. So your cell phone doesn't have to find the radio power to send a signal all the way to space! (exceptions: The decommissioned Chinese BeiDou-1 system - and any products where the GPS receiver chip is used alongside a satellite transmitter, like a Cospas-Sarsat emergency locator beacon) The signal from GPS satellites is very faint - each satellite has to broadcast a signal to about half the planet, powered only by some solar panels! So the broadcast signal is modulated using a 'Gold Code' (in the case of the oldest public GPS signal) where part of the signal transmitted by the satellite is already known by the receiver - the GPS receiver can pick out the signal despite how faint it is, by tracking the cross-correlation between the received and expected signals. This also means multiple satellites can transmit their signals at the same frequency - so long as they use different gold codes, the receiver can track both signals independently. Newer GNSS signals replace gold codes with newer techniques - like 'multiplexed binary offset carriers' - which perform better, but do basically the same thing.
output
1
84
Why is iceberg lettuce bad for rabbits?
instruction
0
85
In short, iceberg lettuce is mostly water with little to no nutrient value. A rabbit can fill up on it (because of the bulk), but still need food because they didn't get enough calories, vitamins, minerals, etc. If you look at the USDA's webpage on iceberg lettuce. You'll notice that water makes up just about 95% of the nutrients, leaving 5% to be divided up between every other nutrient. Protein is a little less than 1%, Carbohydrates less than 3%, and sugars less than 2%. Most importantly, you want to pay attention to the vitamin and calorie content. Iceberg lettuce has only 14 calories per 100 grams (2 calories or less in each leaf), and 18mg of calcium. Other effects to consider, is when fed straight from the fridge, lettuce will be cold and wet, both are conditions that can upset a pet's stomach. In addition, since most rabbit breeders do not feed lettuce to their baby rabbits, it is an unfamiliar food and if the rabbit owner does not add lettuce to the diet gradually, it will cause stomach upset. Finally, it is often believed amoung rabbit breeders that Rabbits should not eat some lettuces (such as iceberg) as they contain a substance called laudanum which can be harmful in large quantities. RSPCA: Rabbit Diet Myths But this is disputed because Lettuce does not contain laudanum. Edible lettuce does contain a chemical called lactucin which is a component of lactucarian. Lactucarian is the milky fluid found in some species of lettuce and occurs in much larger amounts in wild lettuce, Lactuca virosa. Lactucarium has sedative and analgesic effects. It creates a sense of mild euphoria. The milky exudate resembles that of opium and it can also be reduced to a thick substance which can be smoked in the same way as opium. As a result of which it acquired the name ‘lettuce opium’. Edible lettuce, Lactuca sativa, does not even contain lactucarium although it does contain lactucin which is in lactucarium. Lettuce for Rabbits and Guinea Pigs (note that rabbits and guinea pigs have different digestive systems, this link is included for the information on lettuce composition). It is not known if lactucin turns into lactucarium during the digestive process in the rabbit, there are some accounts of rabbits appearing sedated after ingesting large quantities of lettuce. Regardless of the laudanum/lactucin status, there's no reason to feed iceberg because of the low nutrient value. The House Rabbit Society's website has even more details on what foods are good for rabbits and why.
output
1
85
How do I open the JavaScript console in different browsers?
instruction
0
86
Chrome Opening the “Console” panel of Chrome’s DevTools: * Windows and Linux: Ctrl + Shift + J * Mac OS: Cmd + Opt + J Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Firefox Opening the “Console” panel in Firefox’s Developer Tools: * Windows: Ctrl + Shift + K * Mac OS: Cmd + Opt + K Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Internet Explorer Opening the “Console” panel in Internet Explorer’s F12 Developer Tools: * F12, then click on the “Console” tab Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Ctrl + ` while any of the other panels is active. Safari Note: In order to view the console in Safari, you have to enable the “Show Develop menu in menu bar” setting in the “Advanced” pane of Safari’s preferences (screenshot). Opening the “Console” panel in Safari’s Web Inspector: * Cmd + Opt + C Note: In addition to the “Console” panel, there also exists a smaller slide-up console which can be toggled via Esc while any of the other panels is active. Opera * Windows and Linux: Ctrl + Shift + I * Mac : ⌘+⌥+I
output
1
86
I have Ubuntu 10 as the guest OS on a Windows 7 machine. I have been trying to setup shares through VirtualBox, but nothing is working. First, I create the share in VirtualBox and point it to a Windows folder. Then I try to mount the drive in Linux, but I keep getting ```/sbin/mount.vboxsf: mounting failed with the error: Protocol error ``` I have read so many solutions to this, but none seem to work. I have tried: * Using the mount.vboxsf syntax * Reinstalling VBox additions * Rebooting * Enabling and trying as root account I made a share called &quot;Test&quot; in VBox Shared folders. Then I made a directory in ubuntu named &quot;test2&quot;. Then I tried to execute this command: ```sudo mount -t vboxsf Test /mnt/test2 ``` Any other ideas?
instruction
0
87
In order to use shared folder functionality few prerequisites need to be met: * Make sure that Guest Additions are properly installed on the guest OS. * Users in a guest Ubuntu must be in the group ```vboxsf``` to be able to access shares. * Define a directory on the host that will be used in the virtual machine using the settings dialogue of Virtual Box. Depending on host or guest OS the following may also be needed: * Do not share personal folders like ```/home/username``` or ```My Documents``` * Avoid special characters or empty spaces in the path to the shared folder, especially if the host or VM is a Windows machine * Use different names for share and mountpoint * Create a mountpoint on the guest OS (best in your HOME directory). Testing shared folders functionality can be done by creating a shared directory on the host (e.g. ```C:\myshare```), define this as a shared folder for your guest system in Virtual Box settings (e.g. ```share```), create a mount point in your guest os (e.g. ```mkdir /home/username/host```) and mount this in the guest OS with the command: ```sudo mount -t vboxsf -o uid=1000,gid=1000 share /home/username/host ``` where the option -o makes sure that you will have access to the mount (that will otherwise be owned by root). For further information on shared folders see also the Virtual Box User Manual. Files or directories can also be shared over the network by using Samba on the host and the guest.
output
1
87
What does %~dp0 mean, and how does it work? I'd also like to know if it is a documented feature, or something prone to be deprecated.
instruction
0
88
Calling `for /?` in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found). > In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax: ```%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string ``` The modifiers can be combined to get compound results: ```%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only %~dp$PATH:I - searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found. %~ftzaI - expands %I to a DIR like output line ``` In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive. There are different letters you can use like ```f``` for "full path name", ```d``` for drive letter, ```p``` for path, and they can be combined. ```%~``` is the beginning for each of those sequences and a number ```I``` denotes it works on the parameter ```%I``` (where ```%0``` is the complete name of the batch file, just like you assumed).
output
1
88
Should a tester feel bad about finding too many defects/bugs in the product?
instruction
0
89
If this is a medical application you are talking about it is serious stuff. What if the bugs affected real users? Developers would be much less happy if they put in life threat someone or if management has to retire a product or make public excuses. Nowadays it is pretty standard for software having minor bugs, but a medical application should be as much as bug-free as possible. A good developer should not be angry about bugs, but rather be happy, and a good manager already know how software development work so should not put under too much pressure its team unless really necessary: * It has been caught before product release * It is pretty standard for a programmer fixing bugs daily * If you have to focus on programming it is hard also to focus on testing * A tester Always reports bugs * A regular user usually not (unless particularly angry or determined) * If the user is your client, he will report bugs and he will not be happy if the project already cost him much money or required a good amount of time. Literally a project for which bugs are not reported at least on a weekly basis: * Too simple project: no value every other company could easily create a better clone * Not much-used project: maybe there are bugs but no one incurred in them * Bad management: if there are no bugs it's time to move on further work (extra features or different projects). * Bug fixes should drive development, they give a correct idea of what should work and is not working, this allows to manage priorities between fixes and features * In important projects it makes sense adding automated testing so that every fix and feature comes with new tests that avoid breaking pre-existing functionality
output
1
89
Millions of colors in the visible spectrum can be generated by mixing red, green and blue - the RGB color system. Is there a basic set of smells that, when mixed, can yield all, or nearly all detectable smells ?
instruction
0
90
There are about 100 (Purves, 2001) to 400 (Zozulya et al., 2001) functional olfactory receptors in man. While the total tally of olfactory receptor genes exceeds 1000, more than half of them are inactive pseudogenes. The combined activity of the expressed functional receptors accounts for the number of distinct odors that can be discriminated by the human olfactory system, which is estimated to be about 10,000 (Purves, 2001). Different receptors are sensitive to subsets of chemicals that define a “tuning curve.” Depending on the particular olfactory receptor molecules they contain, some olfactory receptor neurons exhibit marked selectivity to particular chemical stimuli, whereas others are activated by a number of different odorant molecules. In addition, olfactory receptor neurons can exhibit different thresholds for a particular odorant. How these olfactory responses encode a specific odorant is a complex issue that is unlikely to be explained at the level of the primary neurons (Purves, 2001). So in a way, the answer to your question is yes, as there are approximately 100 to 400 olfactory receptors. Just like the photoreceptors in the visual system, each sensory neuron in the olfactory epithelium in the nose expresses only a single receptor gene (Kimball). In the visual system for color vision there are just three (red, green and blue cones - RGB) types of sensory neurons, so it's a bit more complicated in olfaction. References - Purves et al, Neuroscience, 2nd ed. Sunderland (MA): Sinauer Associates; 2001 - Zozulya et al., Genome Biol (2001); 2(6): research0018.1–0018.12 Sources - Kimball's Biology Pages
output
1
90
Do you bleed to death after your penis is cut off?
instruction
0
91
Assuming the person is not taking anticoagulants, it's actually quite difficult to bleed to death from dismemberment of small members (hands, feet, penis, ears, nose, etc). Even large members such as arms and legs are often survivable because the body is very good at protecting itself from blood loss. For example, transected arteries will spasm and clamp off blood flow, and loss of blood will cause the body to divert blood flow away from the extremities and to the vital organs, thereby slowing the bleeding and allowing it to clot. In fact, the whole shock process can be viewed as a set of defensive measures by the body to ensure survival in the face of serious injury. This was a bitter lesson learned by emergency medicine only fairly recently. The standard practice used to be to infuse hypovolemic patients with fluids to maintain normal blood pressure. The trouble is, a normal blood pressure prevents the body from realizing it has inadequate blood volume and turns off its defensive measures, thus allowing the bleeding to continue unabated. Left to fend for himself, a healthy adult would almost certainly survive having his penis removed. With modern medical care, that becomes a certainty. Could he still urinate? Sure, as long as the urethra wasn't blocked. It could become blocked by clotted blood, but eventually the pressure of a full bladder would overcome the blockage. Downvoter, care to comment?
output
1
91
In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with ```filter```, ```map``` or ```reduce```?
instruction
0
92
With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem. #1. Using ```subscript(_:)``` subscript ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array[..<5] //let arraySlice = array[0..<5] // also works //let arraySlice = array[0...4] // also works //let arraySlice = array[...4] // also works let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` #2. Using ```prefix(_:)``` method Complexity: O(1) if the collection conforms to ```RandomAccessCollection```; otherwise, O(k), where k is the number of elements to select from the beginning of the collection. ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` Apple states for ```prefix(_:)```: If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection. #3. Using ```prefix(upTo:)``` method Complexity: O(1) ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(upTo: 5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` Apple states for ```prefix(upTo:)```: Using the ```prefix(upTo:)``` method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over ```prefix(upTo:)```. #4. Using ```prefix(through:)``` method ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(through: 4) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ``` #5. Using ```removeSubrange(_:)``` method Complexity: O(n), where n is the length of the collection. ```var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] array.removeSubrange(5...) print(array) // prints: ["A", "B", "C", "D", "E"] ``` #6. Using ```dropLast(_:)``` method Complexity: O(1) if the collection conforms to ```RandomAccessCollection```; otherwise, O(k), where k is the number of elements to drop. ```let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let distance = array.distance(from: 5, to: array.endIndex) let arraySlice = array.dropLast(distance) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] ```
output
1
92
What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile? For instance, an environment variable that has been set through some ```docker exec container /bin/bash``` session? I can do ```docker exec container env | grep ENV_VAR```, but I would prefer something that just returns the value. I've tried using ```docker exec container echo "$ENV_VAR"```, but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer. Thanks.
instruction
0
93
The downside of using ```docker exec``` is that it requires a running container, so ```docker inspect -f``` might be handy if you're unsure a container is running. Example #1. Output a list of space-separated environment variables in the specified container: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name ``` the output will look like this: ```ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3 ``` Example #2. Output each env var on new line and ```grep``` the needed items, for example, the mysql container's settings could be retrieved like this: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \ container_name | grep MYSQL_ ``` will output: ```MYSQL_PASSWORD=secret MYSQL_ROOT_PASSWORD=supersecret MYSQL_USER=demo MYSQL_DATABASE=demodb MYSQL_MAJOR=5.5 MYSQL_VERSION=5.5.52 ``` Example #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts: ```docker inspect -f \ '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \ container_name | grep MYSQL ``` will output: ```export MYSQL_PASSWORD=secret export MYSQL_ROOT_PASSWORD=supersecret export MYSQL_USER=demo export MYSQL_DATABASE=demodb export MYSQL_MAJOR=5.5 export MYSQL_VERSION=5.5.52 ``` If you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format.
output
1
93
I am confused about the use cases for both ```InputStream``` and ```OutputStream```. Please include a snippet of code to go along with your explanation.
instruction
0
94
InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources. For example, you can write primitive data to a file: ```File file = new File("C:/text.bin"); file.createNewFile(); DataOutputStream stream = new DataOutputStream(new FileOutputStream(file)); stream.writeBoolean(true); stream.writeInt(1234); stream.close(); ``` To read the written contents: ```File file = new File("C:/text.bin"); DataInputStream stream = new DataInputStream(new FileInputStream(file)); boolean isTrue = stream.readBoolean(); int value = stream.readInt(); stream.close(); System.out.printlin(isTrue + " " + value); ``` You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency: ```DataInputStream stream = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); ``` You can write other data such as objects: ```MyClass myObject = new MyClass(); // MyClass have to implement Serializable ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream("C:/text.obj")); stream.writeObject(myObject); stream.close(); ``` You can read from other different input sources: ```byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9}; DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test)); int value0 = stream.readInt(); int value1 = stream.readInt(); byte value2 = stream.readByte(); byte value3 = stream.readByte(); stream.close(); System.out.println(value0 + " " + value1 + " " + value2 + " " + value3); ``` For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).
output
1
94
What is the difference between: ```npm install [package_name] ``` and: ```npm install [package_name] --save ``` and: ```npm install [package_name] --save-dev ``` What does this mean? And what is really the effect of ```--save``` and ```-dev``` keywords?
instruction
0
95
The difference between ```--save``` and ```--save-dev``` may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples... Let's say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use ```npm install moment --save ``` This would create a new value in your package.json ```&quot;dependencies&quot;: { ... &quot;moment&quot;: &quot;^2.17.1&quot; } ``` When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use ```npm install jasmine-core --save-dev npm install karma --save-dev ``` This would also create a new value in your package.json ```&quot;devDependencies&quot;: { ... &quot;jasmine-core&quot;: &quot;^2.5.2&quot;, &quot;karma&quot;: &quot;^1.4.1&quot;, } ``` You do not need the test suite to run the app in its normal state, so it is a ```--save-dev``` type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine. Taken directly from NPM docs docs#dependencies > Dependencies > Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string that has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL. Please do not put test harnesses or transpilers in your dependencies object. See devDependencies, below. Even in the docs, it asks you to use ```--save-dev``` for modules such as test harnesses.
output
1
95
pod install -bash: pod: command not found
instruction
0
96
Please follow the following steps to install Pod: 1. Open terminal and type: ```sudo gem install cocoapods ``` Gem will get installed in Ruby inside the System library. Or try on 10.11 Mac OSX El Capitan, type: ```sudo gem install -n /usr/local/bin cocoapods ``` If there is an error &quot;activesupport requires Ruby version >= 2.xx&quot;, then install the latest active support first by typing in the terminal. ```sudo gem install activesupport -v 4.2.6 ``` 2. After installation, there will be a lot of messages, read them and if no error found, it means cocoa pod installation is done. Next, you need to set up the cocoa pod master repo. Type in terminal: ```pod setup ``` And wait it will download the master repo. The size is very big (370.0MB in Dec 2016). So it can be a while. You can track the download by opening Activity and go to the Network tab and search for git-remote-https. Alternatively, you can try adding verbose to the command like so: ```pod setup --verbose ``` 3. Once done it will output &quot;Setup Complete&quot;, and you can create your XCode project and save it. 4. Then in a terminal cd to &quot;your XCode project root directory&quot; (where your .xcodeproj file resides) and type: ```pod init ``` 5. Then open your project's podfile by typing in terminal: ```open -a Xcode Podfile ``` 6. Your Podfile will get open in text mode. Initially, there will be some default commands in there. Here is where you add your project's dependencies. For example, in the podfile, type ```/****** These are Third party pods names ******/ pod 'OpenSSL-Universal' pod 'IQKeyboardManager' pod 'FTPopOverMenu' pod 'TYMActivityIndicatorView' pod 'SCSkypeActivityIndicatorView' pod 'Google/SignIn' pod 'UPStackMenu' ``` (this is For example of adding library to your project). When you are done editing the podfile, save it and close XCode. 7. Then install pods into your project by typing in terminal: ```pod install ``` Depending on how many libraries you added to your podfile for your project, the time to complete this varies. Once completed, there will be a message that says &quot;Pod installation complete! There are X dependencies from the Podfile and X total pods installed.&quot;
output
1
96
I read in the Essential C# 3.0 and .NET 3.5 book that: GetHashCode()’s returns over the life of a particular object should be constant (the same value), even if the object’s data changes. In many cases, you should cache the method return to enforce this. Is this a valid guideline? I have tried a couple built-in types in .NET and they didn't behave like this.
instruction
0
97
The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story. The point being made is that for mutable types, you cannot base the hash code on the mutable data because two equal objects must return the same hash code and the hash code has to be valid for the lifetime of the object. If the hash code changes, you end up with an object that gets lost in a hashed collection because it no longer lives in the correct hash bin. For example, object A returns hash of 1. So, it goes in bin 1 of the hash table. Then you change object A such that it returns a hash of 2. When a hash table goes looking for it, it looks in bin 2 and can't find it - the object is orphaned in bin 1. This is why the hash code must not change for the lifetime of the object, and just one reason why writing GetHashCode implementations is a pain in the butt. A guideline is just a guide, not a rule. In reality, ```GetHashCode``` only has to follow these guidelines when things expect the object to follow the guidelines, such as when it is being stored in a hash table. If you never intend to use your objects in hash tables (or anything else that relies on the rules of ```GetHashCode```), your implementation doesn't need to follow the guidelines. When you see "for the lifetime of the object", you should read "for the time the object needs to co-operate with hash tables" or similar. Like most things, ```GetHashCode``` is about knowing when to break the rules.
output
1
97
Especially in blitz or bullet games, it is possible that a player makes an illegal move, for example castles through check. * If the opponent does notice the illegal move, then as far as I know the first player is obliged to make a legal move with the same piece, if one exists. What if there are no legal moves? * What if the opponent, being in time pressure, doesn't notice the illegal move and makes a move. What happens after they realize that? Does the person who made the illegal move forfeit? Or is the whole game cancelled? Are there any standard rules for these kinds of situations?
instruction
0
98
This only really applies to over the board games (since online chess servers prevent illegal moves). In a standard time control game, under USCF rules, when the illegal move is noticed by one of the players, a few things happen. First, the illegal move must have been made within the last 10 moves. If not, then the current position stands, and play continues. Assuming that the move is recent, the position is restored to the position immediately before the illegal move. Then, the player that made the illegal move now must make a legal move with the same piece (if one exists). If there are no legal moves, then the player is free to make any move. This is due to the touch move rule. Finally, if the offending player has pressed the clock, a two minute &quot;bonus&quot; is added to the opponent's clock to compensate them for any time lost and to penalize the offending player. Here is the relevant passage from the USCF rulebook: 11A. Illegal move during last ten moves. If, during a game, it is found that one of either player's last ten moves was illegal, the position shall be reinstated to what it was before the illegal move. The game shall then continue by applying Rule 10, The Touched Piece, to the move replacing the illegal move. If the position cannot be reinstated, then the illegal move shall stand. Move counters on clocks that have them may by readjusted. 11D. Illegal move. If, a player completes an illegal move by pressing the clock, in addition to the usual obligation to make a legal move with the touched piece if possible, the standard penalty specified in rule 1C2a applies (i.e. two minutes added to the opponent's clock). In blitz chess, the rules are different. According to the WBCA (World Blitz Chess Association) rules, a player who makes an illegal move loses the game instantly. This rule is frequently enforced in casual games too. The most common way that this occurs is that one player doesn't notice that they are in check and makes a move that doesn't get out of check. Then the checking player simply captures the king and claims a victory. Because blitz is a much faster pace game, the illegal move must be noticed within two moves. If it is not, then the current position stands and play continues. At no point is the game cancelled due to an illegal move. Pretty much once a game starts and both players make a move, a result of win, loss, or draw will be recorded.
output
1
98
How to set button click effect in Android?
instruction
0
99
It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button. Kotlin Version: ```fun buttonEffect(button: View) { button.setOnTouchListener { v, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP) v.invalidate() } MotionEvent.ACTION_UP -> { v.background.clearColorFilter() v.invalidate() } } false } } ``` Java Version: ```public static void buttonEffect(View button){ button.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP); v.invalidate(); break; } case MotionEvent.ACTION_UP: { v.getBackground().clearColorFilter(); v.invalidate(); break; } } return false; } }); } ```
output
1
99