message
stringlengths
2
17.7k
message_type
stringclasses
2 values
message_id
int64
0
19
conversation_id
int64
0
1.03k
Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting. Will the Note increase my lifespan? In other words, will I still be alive by then?
instruction
0
200
No. There are some rules that prevent this. From the Rules of the Death Note wiki: 1. The 23-days rule How to use: XXVII * [...] * If you write, “die of disease” for the cause of death, but only write a specific time of death without the actual name of disease, the human will die from an adequate disease. But the Death Note can only operate within 23 days (in the human calendar). This is called the 23-day rule. 2. Situation/cause of death is impossible How to Use: LIV * [...] * In the occasion where the cause of death is possible but the situation is not, only the cause of death will take effect for that victim. If both the cause and the situation are impossible, that victim will die of heart attack. While an UFO falling on your head is technically unlikely, but not impossible, the fact that you'll be naturally alive by 2315 is impossible. You'll just shorten your life, not make it longer. 3. Setting death after original lifespan How to Use: LVII * In the Death Note, you cannot set the death date longer than the victim’s original life span. Even if the victim’s death is set in the Death Note beyond his/her original life span, the victim will die before the set time.
output
1
200
I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ... Who will take control of the creature at the end? This is taking into consideration that my aura spell was cast 5 turns ago. Meaning my aura spell is NOT on the stack.
instruction
0
201
It depends on whose turn it is. Both abilities trigger at the same time, and so will be put on the stack together. Abilities are put on the stack in APNAP (Active Player, Non-Active Player) order.* This means that the player whose turn it is puts their ability on the stack, then the other player does. That second player's ability will resolve first, returning the creature to the battlefield. When the other ability tries to resolve, it fails to find the creature in the graveyard and thus can't return it. Thus whoever's the active player won't end up with the creature. For multiplayer games where there are multiple NAPs they are put on the stack in turn order starting from the AP, so the last player in turn order with such an effect would take precedence. * From the rules on Triggered Abilities: > 603.3b If multiple abilities have triggered since the last time a player received priority, each player, in APNAP order, puts triggered abilities he or she controls on the stack in any order he or she chooses. [...] This works with any number of players, starting with the active player and passing around in turn order. In this case, the player furthest away from taking their turn (the last player to put their ability on the stack) would get the creature.
output
1
201
I've found that some people call JavaScript a "dynamically, weakly typed" language, but some even say "untyped"? Which is it really?
instruction
0
202
strong/weak can be thought of in relation to how the compiler, if applicable, handles typing. * Weakly typed means the compiler, if applicable, doesn't enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time. ```"12345" * 1 === 12345 // string * number => number ``` Strongly typed means there is a compiler, and it wants you an explicit cast from string to integer. ```(int) "12345" * 1 === 12345 ``` In either case, some compiler's features can implicitly alter the instruction during compile-time to do conversions for you, if it can determine that is the right thing to do. Thus far, JavaScript can be categorized as Not-Strongly-Typed. That either means it's weakly-typed or un-typed. dynamic/static can be thought of in relation to how the language instructions manipulate types. * Dynamically typed means the value's type is enforced, but the variable simply represents any value of any type. ```x = 12345; // number x = "string"; // string x = { key: "value" }; // object y = 123 + x; // error or implicit conversion must take place. ``` Statically typed means the variable type is strongly enforced, and the value type is less-so enforced. ```int x = 12345; // binds x to the type int x = "string"; // too late, x is an integer - error string y = 123; // error or implicit conversion must take place. ``` Thus far, JavaScript can be categorized as Not-Statically-Typed. Also, it appears to be Dynamically Typed, if typed at all. So we need to see what Typing means. Typed means that the language distinguishes between different types such as string, number, boolean, object, array, null, undefined and so on. Also each operation is bound to specific types. So you cannot divide an integer by a string. ``` 2 / "blah" // produces NaN ``` Untyped means the operation of dividing integer by string would result in treating the first four bytes of string as integer. This is because Untyped operations take place directly on bits, there are no types to observe. The outcome will be something quite unexpected: ``` 2 / "blah" // will be treated as 2 / 1500275048 ``` Since JavaScript behaves according to the definition of being Typed, it must be. And therefore it must be Dynamically Typed, and Weakly Typed. If anybody claims JavaScript is Untyped, it is merely for academic theory, not for practical application.
output
1
202
I was fixing my laptop, and as you may know, laptops have a lot of small screws to take out when you are fixing it. One of the screws fell into the floor (the floor has carpet on it), and I was unable to follow the screw with my sight. If I don't follow the screw with my sight when it falls, there is a high chance that I will not see that screw again. My question is: what kind of method, tool or hack can I use to find small screws that falls into the floor? I have tried using the tool with a magnet on the tip, that mechanics use to grab wrenches that falls in inaccessible areas, but had no luck finding the screw.
instruction
0
203
This is why you should always have spare screws on hand. Fortunately, there is a way: ## Light Method Most screws are silver. Shine a flashlight into the carpet and look for little silvery glints. This may take some time, but you'll probably find it. If your carpet is unnaturally thick... ## Magnet Method Take a powerful magnet (like a bar magnet, hardware stores - fridge magnets might work) and run it over the surface where you think the screw is. You should find it. If that still fails... ## Vacuum Method Take a good vacuum cleaner. Put a sock over the extending arm, and run it over where you think the screw is. The sock will prevent the screw from being vacuumed up, but it will be stuck to the sock. There will still be enough suction to pick up the screw, even with the sock. If not, get a new vacuum! If that fails... ## Organize your screws There are many useful tools to organize screws. Go to your local RadioShack and get one, or make one out of a magnet for that awesome lifehack feel. ## Stop using carpet! [Not a "find your screws" method - a tip about not frying your computer] Carpet can cause static discharge, which is very very very bad for a computer (personal experience). Work on a hard floor with an antistatic strap to reduce the chance of frying your PC.
output
1
203
What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives? I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such.... Thanks
instruction
0
204
From a theoretical perspective, a critical section is a piece of code that must not be run by multiple threads at once because the code accesses shared resources. * A mutex is an algorithm (and sometimes the name of a data structure) that is used to protect critical sections. * Semaphores and Monitors are common implementations of a mutex. In practice there are many mutex implementation availiable in windows. They mainly differ as consequence of their implementation by their level of locking, their scopes, their costs, and their performance under different levels of contention. Availiable synchronization primitives. * Monitor * Mutex * Semaphore * ReaderWriterLock * ReaderWriterLockSlim * Interlocked The ```lock(object)``` statement is implemented using a ```Monitor``` - see MSDN for reference. In the last years much research is done on non-blocking synchronization. The goal is to implement algorithms in a lock-free or wait-free way. In such algorithms a process helps other processes to finish their work so that the process can finally finish its work. In consequence a process can finish its work even when other processes, that tried to perform some work, hang. Usinig locks, they would not release their locks and prevent other processes from continuing.
output
1
204
What is the purpose of the single underscore "_" variable in Python? What is the meaning of ```_``` after ```for``` in this code? ```if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 ```
instruction
0
205
```_``` has 3 main conventional uses in Python: 1. To hold the result of the last executed expression in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit. 2. For translation lookup in i18n (see the gettext documentation for example), as in code like ```raise forms.ValidationError(_("Please enter a correct username")) ``` 3. As a general purpose "throwaway" variable name: * To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: ```label, has_label, _ = text.partition(':') ``` * As part of a function definition (using either ```def``` or ```lambda```), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like: ```def callback(_): return True ``` This use case can conflict with the translation lookup use case, so it is necessary to avoid using ```_``` as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, ```__```, as their throwaway variable for exactly this reason). Linters often recognize this use case. For example ```year, month, day = date()``` will raise a lint warning if ```day``` is not used later in the code. The fix, if ```day``` is truly not needed, is to write ```year, month, _ = date()```. Same with lambda functions, ```lambda arg: 1.0``` creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write ```lambda _: 1.0```. An unused variable is often hiding a bug/typo (e.g. set ```day``` but use ```dya``` in the next line). The pattern matching feature added in Python 3.10 elevated this usage from "convention" to "language syntax" where ```match``` statements are concerned: in match cases, ```_``` is a wildcard pattern, and the runtime doesn't even bind a value to the symbol in that case. For other use cases, remember that ```_``` is still a valid variable name, and hence will still keep objects alive. In cases where this is undesirable (e.g. to release memory or external resources) an explicit ```del name``` call will both satisfy linters that the name is being used, and promptly clear the reference to the object.
output
1
205
What is the difference between doing: ```ptr = malloc (MAXELEMS * sizeof(char *)); ``` or: ```ptr = calloc (MAXELEMS, sizeof(char*)); ``` When is it a good idea to use calloc over malloc or vice versa?
instruction
0
206
```calloc()``` gives you a zero-initialized buffer, while ```malloc()``` leaves the memory uninitialized. For large allocations, most ```calloc``` implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX ```mmap(MAP_ANONYMOUS)``` or Windows ```VirtualAlloc```) so it doesn't need to write them in user-space. This is how normal ```malloc``` gets more pages from the OS as well; ```calloc``` just takes advantage of the OS's guarantee. This means ```calloc``` memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.) The effects are visible with performance experiments on Linux, for example. Some compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory. (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.) If you aren't going to ever read memory before writing it, use ```malloc``` so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation). Embedded implementations of ```calloc``` may leave it up to ```calloc``` itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes. On embedded Linux, malloc could ```mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)```, which is only enabled for some embedded kernels because it's insecure on a multi-user system.
output
1
206
Why would I want to use Kotlin's coroutines? It seems that the RxKotlin library is much more versatile. Kotlin's coroutines look significantly less powerful and more cumbersome to use in comparison. I base my opinion on coroutines on this design talk by Andrey Breslav (JetBrains) Slideshow from the talk is accessible here.
instruction
0
207
Kotlin coroutines are different from Rx. It is hard to compare them apples-to-apples, because Kotlin coroutines are a thin language feature (with just a couple of basic concepts and a few basic functions to manipulate them), while Rx is a pretty heavy library with quite large variety of ready-to-use operators. Both are designed to address a problem of asynchronous programming, however their approach to solution is very different: * Rx comes with a particular functional style of programming that can be implemented in virtually any programming language without support from the language itself. It works well when the problem at hand easily decomposes into a sequence of standard operators and not so well otherwise. * Kotlin coroutines provide a language feature that let library writers implement various asynchronous programming styles, including, but not limited to functional reactive style (Rx). With Kotlin coroutines you can also write your asynchronous code in imperative style, in promise/futures-based style, in actor-style, etc. It is more appropriate to compare Rx with some specific libraries that are implemented based on Kotlin coroutines. Take kotlinx.coroutines library as one example. This library provides a set of primitives like ```async/await``` and channels that are typically baked into other programming languages. It also has support for light-weight future-less actors. You can read more in the Guide to kotlinx.coroutines by example. Channels provided by ```kotlinx.coroutines``` can replace or augment Rx in certain use-cases. There is a separate Guide to reactive streams with coroutines that goes deeper into similarities and differences with Rx.
output
1
207
How do I get a ```PriorityQueue``` to sort on what I want it to sort on? Also, is there a difference between the ```offer``` and ```add``` methods?
instruction
0
208
## Java 8 solution We can use ```lambda expression``` or ```method reference``` introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) : Using lambda expression ```PriorityQueue pq= new PriorityQueue(5,(a,b) -> a.length() - b.length()); ``` Using Method reference ```PriorityQueue pq= new PriorityQueue(5, Comparator.comparing(String::length)); ``` Then we can use any of them as: ```public static void main(String[] args) { PriorityQueue pq= new PriorityQueue(5, (a,b) -> a.length() - b.length()); // or pq = new PriorityQueue(5, Comparator.comparing(String::length)); pq.add("Apple"); pq.add("PineApple"); pq.add("Custard Apple"); while (pq.size() != 0) { System.out.println(pq.remove()); } } ``` This will print: ```Apple PineApple Custard Apple ``` To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use ```reversed``` as: ```PriorityQueue pq = new PriorityQueue(5, Comparator.comparing(String::length).reversed()); ``` We can also use ```Collections.reverseOrder```: ```PriorityQueue pqInt = new PriorityQueue(10, Collections.reverseOrder()); PriorityQueue pq = new PriorityQueue(5, Collections.reverseOrder(Comparator.comparing(String::length)) ``` So we can see that ```Collections.reverseOrder``` is overloaded to take comparator which can be useful for custom objects. The ```reversed``` actually uses ```Collections.reverseOrder```: ```default Comparator reversed() { return Collections.reverseOrder(this); } ``` offer() vs add() As per the doc > The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues. When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.
output
1
208
I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this: We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. I'm looking for something more in depth, such as end all Controllers with Controller and their tests with ControllerTest, etc. What is a good set of naming conventions to use when developing on the Force.com platofrm? It would be preferable if the answer has something that handles custom objects, classes, visualforce pages, and components and not just Apex classes.
instruction
0
209
Follow the CamelCase Java conventions, except for VF pages and components start with a lower case letter. Triggers: * <ObjectName>Trigger - The trigger itself. One per object. * <ObjectName>TriggerHandler - Class that handles all functionality of the trigger * <ObjectName>TriggerTest Controllers: * <ClassName>Controller * <ClassName>ControllerExt * <ClassName>ControllerTest * <ClassName>ControllerExtTest Classes: * <ClassName> * <ClassName>Test (These might be Util classes or Service classes or something else). Visualforce pages and components: * <ControllerClassName>[optionalDescription] (without the suffix Controller). There might be multiple views so could also have an extra description suffix. Object Names and custom Fields * Upper_Case_With_Underscores Variables/properties/methods in Apex * camelCaseLikeJava - more easily differentiated from fields Test methods in test classes * test<methodOrFunctionalityUnderTest><ShortTestCaseDesc> - For example, testSaveOpportunityRequiredFieldsMissing, testSaveOpportunityRequiredFieldsPresent, etc. Working on something that would be used as an app or in some cases just a project? If yes, then do the following: Prefix all custom objects, apex classes, Visualforce pages and components with an abbreviation so that they are easier to identify (e.g., easier for changesets). For example the WidgetFactory app would have the prefix wf on those. Additionally, when adding custom fields to a standard object they would also be prefixed to identify them as part of the app/package. The main reason for the Object and Fields Names using Upper_Case_With_Underscores is that when you type in the name field or object with spaces it automatically adds the underscores. Although Apex is case insensitive, always refer to the Objects and Custom Fields in the code as Upper_Case_With_Underscores as well for consistency all around and consistency with what is generated by the SOQL schema browser and other tools. Object and Field Labels (which are generally ignored by code but visible to users) should keep spaces, not underscores.
output
1
209
When learning some basic French, I was somewhat surprised to learn that phrases of the form "I have found the cat" generally translate almost word-for-word from English (J'ai trouvé le chat). To me, it's not immediately obvious that possession ("I have"/"J'ai") has a correspondence with past tense, although if I think about it a little more I suppose I can kind of see how it makes sense. This makes me wonder: Is this a common pattern in other languages? Especially ones not closely related to English.
instruction
0
210
This is what's called a "Sprachbund" feature: it's a trait shared by a bunch of languages in an area, even ones that aren't genetically related. In particular, this one is a feature of the "Standard Average European" Sprachbund, a group of languages centered in Western Europe, and it's one of the features that was originally used to define that Sprachbund in the first place! The construction seems to have arisen back in Latin. In Classical Latin, past aoristic verbs ("I loved") and present perfective verbs ("I have loved") look exactly the same: both of those would be written amāvī. But it's a pretty useful distinction to be able to make! So in Vulgar Latin, a new construction arose, using the verb habēre ("to have"). It's thought that a phrase like habeō litterās scriptās "I have (written letters)" got reanalyzed into "I (have written) letters", with habēre no longer indicating that you're actually holding anything in your hands, just that an action's been completed in the past. Vulgar Latin eventually evolved into French, Italian, Spanish, and all the other Romance languages, and brought this construction with it; habēre is the direct ancestor of French avoir, via a series of sound changes. And once various Romance languages and Germanic languages and others were all being spoken in the same area, this feature spread through the Sprachbund: people speaking Germanic languages started to use the same construction. English "have"/German haben/etc isn't actually at all related to Latin habēre, but they looked similar, so it was the obvious choice when adopting the construction into Germanic. Nowadays, this feature is called the "have-perfective", and it shows up in all sorts of languages within the Standard Average European (SAE) Sprachbund. It's not at all universal, but can be a good way to determine if a language has been influenced by SAE or not!
output
1
210
I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?
instruction
0
211
Python have already evolve to the ```__future__``` long time ago. So how about using the amazing ```pathlib``` coming with Python 3.4 to accomplish the task instead of struggling with ```os```, ```os.path```, ```glob ```, ```shutil```, etc. So we have 3 paths here (possibly duplicated): * ```mod_path```: which is the path of the simple helper script * ```src_path```: which contains a couple of template files waiting to be copied. * ```cwd```: current directory, the destination of those template files. and the problem is: we don't have the full path of ```src_path```, only know it's relative path to the ```mod_path```. Now let's solve this with the the amazing ```pathlib```: ```# Hope you don't be imprisoned by legacy Python code :) from pathlib import Path # `cwd`: current directory is straightforward cwd = Path.cwd() # `mod_path`: According to the accepted answer and combine with future power # if we are in the `helper_script.py` mod_path = Path(__file__).parent # OR if we are `import helper_script` mod_path = Path(helper_script.__file__).parent # `src_path`: with the future power, it's just so straightforward relative_path_1 = 'same/parent/with/helper/script/' relative_path_2 = '../../or/any/level/up/' src_path_1 = (mod_path / relative_path_1).resolve() src_path_2 = (mod_path / relative_path_2).resolve() ``` In the future, it's just that simple. Moreover, we can select and check and copy/move those template files with ```pathlib```: ```if src_path != cwd: # When we have different types of files in the `src_path` for template_path in src_path.glob('*.ini'): fname = template_path.name target = cwd / fname if not target.exists(): # This is the COPY action with target.open(mode='wb') as fd: fd.write(template_path.read_bytes()) # If we want MOVE action, we could use: # template_path.replace(target) ```
output
1
211
How to send HTML-formatted email in C#?
instruction
0
212
Setting isBodyHtml to true allows you to use HTML tags in the message body: ``` msg = new MailMessage("[email protected]", "[email protected]", "Message from PSSP System", "This email sent by the PSSP system<br />" + "<b>this is bold text!</b>"); msg.IsBodyHtml = true; ```
output
1
212
I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized? ```Map integers; integers.values().stream().mapToInt(i -> i).sum(); ```
instruction
0
213
This will work, but the `i -> i` is doing some automatic unboxing which is why it "feels" strange. `mapToInt` converts the stream to an `IntStream` "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax: ``` integers.values().stream().mapToInt(i -> i.intValue()).sum(); integers.values().stream().mapToInt(Integer::intValue).sum(); ``` The other simple option is `BigDecimal sum = numbers.stream().reduce(BigDecimal.ZERO, BigDecimal::add);`.
output
1
213
I am beginner of LaTeX. From many examples I found, I notice that it's very common to use command ```\leavevmode```. I can't find any information about this command. Could anyone tell me what's the function of it and how to use it?
instruction
0
214
The ```\leavevmode``` is defined by LaTeX and plainTeX and ensures that the vertical mode is ended and horizontal mode is entered. In vertical mode, TeX stacks horizontal boxes vertically, whereas in horizontal mode, they are taken as part of the text line. For example ```\mbox{..}``` is defined as ```\leavevmode\hbox{..}``` to ensure that horizontal mode is entered if it is used at the beginning of a paragraph. If you only use ```\hbox{ }``` it is stacked above the following paragraph instead. Compare: ```Text\par\hbox{Hello} World ``` Result: ``` Text Hello World ``` with: ```Text\par\mbox{Hello} World ``` Result: ``` Text Hello World ``` You see that in the first case the ```\hbox``` is stacked with the two paragraphs vertically (but without paragraph indention) because it is processed in vertical mode. In the second case horizontal mode is entered first and so ```Hello``` is processed as part of the second paragraph. Use ```\leavevmode``` for all macros which could be used at the begin of the paragraph and add horizontal boxes by themselves (e.g. in form of text). For further reading about ```\leavevmode``` please see "The TeXBook" by Donald E. Knuth, Appendix A, section 13.1, page 313 as well Appendix B, page 356.
output
1
214
In Python specifically, how do variables get shared between threads? Although I have used ```threading.Thread``` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. Thanks in advance!
instruction
0
215
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them. The `Thread` object for a particular thread is not a special object in this regard. If you store the `Thread` object somewhere all threads can access (like a global variable) then all threads can access that one Thread object. If you want to atomically modify anything that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective. If you want actual thread-local storage, that's where `threading.local` comes in. Attributes of `threading.local` are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in _threading_local.py in the standard library.
output
1
215
I grew up in a country where we were not allowed to leave/travel to an other country even when we were able to do so – we had the resources and dual nationality. After two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries? Could it be that a dictator is usually interested in looting the country he rules, and having a smaller population means more natural resources for him and fewer protesters?
instruction
0
216
People are resources, dictators (and oppressive regimes in general) don't want them to defect to other countries because they want them working for their regime. Some of them are going to be people that the regime has put their resources into, like scientists and doctors, but even laborers are valuable for actually gathering and assembling the resources the regime needs. Additionally, the regime especially does not want people with access to sensitive information to defect to their enemies. That isn't just spies and soldiers, there are plenty of "regular" government positions that require access to something the regime would not want falling into enemy hands, like economic data that could be used for propaganda. Obviously this is true of any country, and even in democracies with strong human rights records, people with access to classified information are usually required to submit to strict scrutiny of their international travel. Given that they aren't concerned with human rights, dictatorships can take the easier option of restricting travel to any citizens. However, defection is really a piece of a bigger issue - oppressive regimes maintain their rule in part by controlling information. Here's an interesting article that talks about how dictatorships keep power. Jerrold Post, director of the political psychology program at George Washington University, is referenced: Post said that in both Iraq and North Korea, dictators tightly controlled the flow of information. That control was upended in the past two years during the "Arab spring" revolts that swept away despots in Tunisia, Egypt, Libya and some of the Gulf states, revolts that were encouraged in large part by information spread by cell phones and social media. North Korea is probably the most extreme example of information control (according to Reporters without Borders, they are dead last in Press Freedom in the world), but this can be seen in other oppressive regimes - for example, China attempts to limit access to "wrong" information via its Great Firewall. This is thrown out the window if citizens go somewhere with free media and realize they are being lied to. Traveling can be the cause of their dissension, rather than a symptom. Known dissidents may also be restricted from traveling so that they can not coordinate with foreign countries or anti-dictatorship organizations, and to prevent them from smuggling contraband or evidence of the regime's misinformation back into the country. Regimes can control the information originating in their country, but once someone is outside their borders the regime cannot control who they speak with.
output
1
216
Why can't we kill ourselves by holding our breath?
instruction
0
217
## Short answer Healthy people cannot hold their breaths until unconsciousness sets in, let alone commit suicide. ## Background According to Parkes (2005), a normal person cannot even hold their breath to unconsciousness, let alone death. Parkes says: Breath‐holding is a voluntary act, but normal subjects appear unable to breath‐hold to unconsciousness. A powerful involuntary mechanism normally overrides voluntary breath‐holding and causes the breath that defines the breakpoint. Parkes explains that voluntary breath‐holding does not stop the central respiratory rhythm. Instead, breath holding merely suppresses its expression by voluntarily holding the chest at a certain volume. At the time of writing, no simple explanation for the break point existed. It is known to be caused by partial pressures of blood gases activating the carotid arterial chemoreceptors. They are peripheral sensory neurons that detect changes in chemical concentrations, including low oxygen (hypoxia) and high carbon dioxide (hypercapnia). Both hypoxia and hypercapnia are signs of breath holding and both are detected by the chemoreceptors. These receptors send nerve signals to the vasomotor center of the medulla which eventually overrides the conscious breath holding. The breaking point can be postponed by large lung inflations, hyperoxia and hypocapnia, and it is shortened by increased metabolic rates. Reference - Parkes, Exp Physiol (2006); 91(1): 1-15
output
1
217
Sometimes while driving in the traffic, I come across a car or two which would be dripping water-like drops from its exhaust steadily in 4-5 second intervals. I tried to ask a couple of people at the local workshops; they say, and I quote, &quot;The car is giving an amazing mileage&quot;. And I am like, what does that water dripping mean even then? Why does the water drip? What is the source of it? And what does it signify?
instruction
0
218
It signifies that the car is running absolutely correct. Here is the reason why: A gasoline (petrol) molecule is made up as such: C8H18 (or 8 Carbon atoms and 18 Hydrogen atoms) Energy is obtained from the combustion of it by the conversion of a hydrocarbon to carbon dioxide and water. The combustion of octane follows this reaction: 2 C8H18 + 25 O2 → 16 CO2 + 18 H2O Or better said, you have two of the hydrocarbon molecules along with 25 oxygen molecules, they swirl together into a mix, the spark plug ignites them, boom, and out the tail pipe comes 16 carbon dioxide molecules and 18 water molecules ... at least in a perfect world. Some cars don't put out exactly that ratio. There may be a little bit of carbon monoxide (CO), unburnt hydrocarbons (C8H18), and/or nitrogen oxide (NO2) coming out of the engine exhaust port along with the CO2 and H2O. In this case, the catalytic convertor's job is to help clean these up so you can get closer to the perfect ratio described above. As described, the water coming out of the tail pipe is a natural occurrence of the combustion process. You will usually see it coming out of the tail pipe when the engine and exhaust system of the vehicle is not completely warmed up. When it does become completely warmed up, you won't see it any more, because it comes out as steam (well, you'll see it in the winter time if it's cold enough, but you get the idea).
output
1
218
Why can't MX records point to an IP address?
instruction
0
219
The whole idea behind the mail exchange (MX) record is to specify a host or hosts which can accept mail for a domain. As specified in RFC 1035, the MX record contains a domain name. It must therefore point to a host which itself can be resolved in the DNS. An IP address could not be used as it would be interpreted as an unqualified domain name, which cannot be resolved. The reasons for this in the 1980s, when the specs were originally written, are almost the same as the reasons for it today: A host may be connected to multiple networks and use multiple protocols. Back in the 80s, it was not uncommon to have mail gateways which connected both to the (relatively new) Internet which used TCP/IP and to other legacy networks, which often used other protocols. Specifying MX in this way allowed for DNS records which could identify how to reach such a host on a network other than the Internet, such as Chaosnet. In practice, though, this almost never happened; virtually everyone re-engineered their networks to become part of the Internet instead. Today, the situation is that a host may be reached by multiple protocols (IPv4 and IPv6) and by multiple IP addresses in each protocol. A single MX record can't possibly list more than one address, so the only option is to point to a host, where all of that host's addresses can then be looked up. (As a performance optimization, the DNS server will send along the address records for the host in the response additional section if it has authoritative records for them, saving a round trip.) There is also the situation that arises when your mail exchangers are provided by a third party (e.g. Google Apps or Office 365). You point your MX records to their hostnames, but it may occur that the service provider needs to change the mail servers' IP addresses. Since you have pointed to a host, the service provider can do this transparently and you don't have to make any changes to your records.
output
1
219
Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted? I understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column?
instruction
0
220
The asterisk character, "*", in the SELECT statement is shorthand for all the columns in the table(s) involved in the query. Performance The ```*``` shorthand can be slower because: * Not all the fields are indexed, forcing a full table scan - less efficient * What you save to send ```SELECT *``` over the wire risks a full table scan * Returning more data than is needed * Returning trailing columns using variable length data type can result in search overhead Maintenance When using ```SELECT *```: * Someone unfamiliar with the codebase would be forced to consult documentation to know what columns are being returned before being able to make competent changes. Making code more readable, minimizing the ambiguity and work necessary for people unfamiliar with the code saves more time and effort in the long run. * If code depends on column order, ```SELECT *``` will hide an error waiting to happen if a table had its column order changed. * Even if you need every column at the time the query is written, that might not be the case in the future * the usage complicates profiling Design ```SELECT *``` is an anti-pattern: * The purpose of the query is less obvious; the columns used by the application is opaque * It breaks the modularity rule about using strict typing whenever possible. Explicit is almost universally better. When Should "SELECT *" Be Used? It's acceptable to use ```SELECT *``` when there's the explicit need for every column in the table(s) involved, as opposed to every column that existed when the query was written. The database will internally expand the * into the complete list of columns - there's no performance difference. Otherwise, explicitly list every column that is to be used in the query - preferably while using a table alias.
output
1
220
I did my training around the Seattle area, and was told that landing at SeaTac Airport (the region's major International/Commercial airport), while not strictly forbidden, was definitely frowned upon because it can slow down and interfere with the big planes on schedules. To discourage GA aircraft from using the big airport, they have a variety of landing fees, ramp fees, and prior-approval requirements. But later, I moved near MCI, and was told that landing at the big airport was no big deal. That they're actually happy to have little planes there. If you fly small GA planes, do you land at the major airports in your area? What advanced preparations can you make to minimize your impact on the "big boys", and remain a good airspace citizen?
instruction
0
221
Can you? Absolutely, and air traffic control will treat you (almost) like any other airplane. You are supposedly handled on a first-come-first-serve basis (reality is slightly different with different aircraft speeds, etc.). Do the airlines like it if you slow them down? No, but it's part of the system and the way that it works. Very often, there are multiple runways at bigger airports, and sometimes there are even shorter runways that are dedicated for airplanes that don't need to land on the same one as the "big boys". Even if not, they will work you in. Now, that being said, very often there is a better option. As you said, there are usually high fees at the big airports, so landing at a smaller satellite airport can often save you money and save you time because you won't have to taxi as far or sit and wait in line to get out. An extra 15 minutes by car can be better than an extra 30 minutes while taxiing. As far as being prepared, it isn't really much different than smaller airports other than the fact that ATC is much busier. They don't have the time/tolerance to keep repeating instructions to you, and expect you to be "on your game". When they rattle off taxi instructions like "Cessna N1234, taxi to the ramp via Alpha, Tango, Echo, and Xray. Hold short of runway 23." they expect a quick readback and for you to follow instructions exactly because they need to move on to the next guy. It will also help everyone out if you don't fly your final approach the way that most people are taught for an entire 10 mile final: very close to your actual landing speed. In fact, you are usually landing on a runway that is 4X+ the distance that you need and you can slow down fairly quickly (especially compared to a jet), so if you can fly an extra 20 (or 80) knots as long as possible, it will be greatly appreciated and keep traffic moving. Make sure that you leave yourself enough time to slow down at the end and above all else, ***be safe***.
output
1
221
I need a way to compare multiple strings to a test string and return the string that closely resembles it: ```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW CHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN CHOICE B : THE RED COW JUMPED OVER THE RED COW CHOICE C : THE RED FOX JUMPED OVER THE BROWN COW ``` (If I did this correctly) The closest string to the "TEST STRING" should be "CHOICE C". What is the easiest way to do this? I plan on implementing this into multiple languages including VB.net, Lua, and JavaScript. At this point, pseudo code is acceptable. If you can provide an example for a specific language, this is appreciated too!
instruction
0
222
Fuzzy String Matching is the process of performing a human-like estimation of the similarity of two words or phrases. In many cases, it involves implementing the Levenshtein distance algorithm, which determines how many changes must be made to a string or phrase to turn it into another string or phrase. The following implementation in VBA involves a weighted comparison of the length of the two phrases, the number of changes between each phrase, and whether each word could be found in the target entry. ``` 'Calculate the Levenshtein Distance between two strings (the number of insertions, 'deletions, and substitutions needed to transform the first string into the second) Public Function LevenshteinDistance(ByRef S1 As String, ByVal S2 As String) As Long Dim L1 As Long, L2 As Long, D() As Long 'Length of input strings and distance matrix Dim i As Long, j As Long, cost As Long 'loop counters and cost of substitution for current letter Dim cI As Long, cD As Long, cS As Long 'cost of next Insertion, Deletion and Substitution L1 = Len(S1): L2 = Len(S2) ReDim D(0 To L1, 0 To L2) For i = 0 To L1: D(i, 0) = i: Next i For j = 0 To L2: D(0, j) = j: Next j For j = 1 To L2 For i = 1 To L1 cost = Abs(StrComp(Mid$(S1, i, 1), Mid$(S2, j, 1), vbTextCompare)) cI = D(i - 1, j) + 1 cD = D(i, j - 1) + 1 cS = D(i - 1, j - 1) + cost If cI <= cD Then 'Insertion or Substitution If cI <= cS Then D(i, j) = cI Else D(i, j) = cS Else 'Deletion or Substitution If cD <= cS Then D(i, j) = cD Else D(i, j) = cS End If Next i Next j LevenshteinDistance = D(L1, L2) End Function ``` We can creat two separate metrics for evaluating the similarity of two strings. One is "valuePhrase" and the other is "valueWords". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you'd like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one 'phrase' is really contained in another, just as a word-wise permutation. valueWords, valuePhrase, and Split function: ``` Public Function valuePhrase#(ByRef S1$, ByRef S2$) valuePhrase = LevenshteinDistance(S1, S2) End Function Public Function valueWords#(ByRef S1$, ByRef S2$) Dim wordsS1$(), wordsS2$() wordsS1 = SplitMultiDelims(S1, " _-") wordsS2 = SplitMultiDelims(S2, " _-") Dim word1%, word2%, thisD#, wordbest# Dim wordsTotal# For word1 = LBound(wordsS1) To UBound(wordsS1) wordbest = Len(S2) For word2 = LBound(wordsS2) To UBound(wordsS2) thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2)) If thisD < wordbest Then wordbest = thisD If thisD = 0 Then GoTo foundbest Next word2 foundbest: wordsTotal = wordsTotal + wordbest Next word1 valueWords = wordsTotal End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' SplitMultiDelims ' This function splits Text into an array of substrings, each substring ' delimited by any character in DelimChars. Only a single character ' may be a delimiter between two substrings, but DelimChars may ' contain any number of delimiter characters. It returns a single element ' array containing all of text if DelimChars is empty, or a 1 or greater ' element array if the Text is successfully split into substrings. ' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur. ' If Limit greater than 0, the function will only split Text into 'Limit' ' array elements or less. The last element will contain the rest of Text. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _ Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _ Optional ByVal Limit As Long = -1) As String() Dim ElemStart As Long, N As Long, M As Long, Elements As Long Dim lDelims As Long, lText As Long Dim Arr() As String lText = Len(Text) lDelims = Len(DelimChars) If lDelims = 0 Or lText = 0 Or Limit = 1 Then ReDim Arr(0 To 0) Arr(0) = Text SplitMultiDelims = Arr Exit Function End If ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit)) Elements = 0: ElemStart = 1 For N = 1 To lText If InStr(DelimChars, Mid(Text, N, 1)) Then Arr(Elements) = Mid(Text, ElemStart, N - ElemStart) If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) > 0 Then Elements = Elements + 1 Else Elements = Elements + 1 End If ElemStart = N + 1 If Elements + 1 = Limit Then Exit For End If Next N 'Get the last token terminated by the end of the string into the array If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart) 'Since the end of string counts as the terminating delimiter, if the last character 'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1 ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements SplitMultiDelims = Arr End Function ``` Using these two metrics, and a third which simply computes the distance between two strings, we have a series of variables which we can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results. To allow the optimization of fuzzy matching, we can weight each metric. The formula that defines the final score is a simply combination of the metrics and their weights: ``` value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight + Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue ``` For your specific context, you have to come up with a set of weights for any metrics you come up with to determine similarity. With the appropriate set of heuristics and weights, you'll have your comparison program quickly making the decisions that you would have made.
output
1
222
Given the following code: ```var arr = [1,2,3,4,5]; var results: number[] = await arr.map(async (item): Promise => { await callAsynchronousOperation(item); return item + 1; }); ``` which produces the following error: TS2322: Type 'Promise[]' is not assignable to type 'number[]'. Type 'Promise is not assignable to type 'number'. How can I fix it? How can I make ```async await``` and ```Array.map``` work together?
instruction
0
223
The problem here is that you are trying to ```await``` an array of promises rather than a Promise. This doesn't do what you expect. When the object passed to ```await``` is not a Promise, ```await``` simply returns the value as-is immediately instead of trying to resolve it. So since you passed ```await``` an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type ```Promise[]```. What you probably want to do is call ```Promise.all``` on the array returned by ```map``` in order to convert it to a single Promise before ```await```ing it. According to the MDN docs for ```Promise.all```: The ```Promise.all(iterable)``` method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects. So in your case: ```var arr = [1, 2, 3, 4, 5]; var results: number[] = await Promise.all(arr.map(async (item): Promise => { await callAsynchronousOperation(item); return item + 1; })); ``` This will resolve the specific error you are encountering here. Depending on exactly what it is you're trying to do you may also consider using ```Promise.allSettled```, ```Promise.any```, or ```Promise.race``` instead of ```Promise.all```, though in most situations (almost certainly including this one) ```Promise.all``` will be the one you want.
output
1
223
Why don't helicopters use reaction wheels to counter the main rotor?
instruction
0
224
You're talking about a device (in helicopters the tail fan imparting horizontal thrust) that counteracts the torque imparted on the main rotor (and therefore on the helicopter) by the surrounding air as the main rotor is dragged through the air. You propose instead to impart an opposite torque through a reaction wheel. That would indeed impart an opposite torque for short lengths of time. However, you don't get a torque from spinning a reaction wheel at constant angular velocity but by changing and accelerating that angular velocity. Now the torque imparted on the helicopter by the air through the main rotor is steady - or at least its of roughly constant direction. Therefore, to counter that torque, the reaction wheel would have to accelerated uniformly and indefinitely. Clearly this is impossible from an engineering standpoint. You can also think of this from a conservation of angular momentum, without thinking about the origin of the torques. The air imparts a steady angular impulse to the helicopter. Therefore, the helicopter system's angular momentum must increase steadily (unless there's a countering torque from the tailfan). So either that angular momentum is the spinning of the helicopter's body (which is what we're trying to avoid) or that of the reaction wheel, whose angular momentum must be steadily increasing under the action of the angular impulse to the system.
output
1
224
When configuring cron to run a command every other day using the "Day of Month" field, like so: ```1 22 */2 * * COMMAND ``` it runs every time the day of month is odd: 1,3,5,7,9 and so on. How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is problematic as every month has a different number of days in the month)?
instruction
0
225
The syntax you tried is actually ambiguous. Depending on how many days are in the month, some months it will run on odd days and some on even. This is because the way it is calculated takes the total number of possibilities and divides them up. You can override this strage-ish behavior by manually specifying the day range and using either an odd or even number of days. Since even day scripts would never run on the 31st day of longer months, you don't lose anything using 30 days as the base for even-days, and by specifying specifically to divide it up as if there were 31 days you can force odd-day execution. The syntax would look like this: ```# Will only run on odd days: 0 0 1-31/2 * * command # Will only run on even days: 0 0 2-30/2 * * command ``` Your concern about months not having the same number of days is not important here because no months have MORE days than this, and for poor February, the date range just won't ever match the last day or two, but it will do no harm having it listed. The only 'gotcha' for this approach is that if you are on an odd day cycle, following months with 31 days your command will also run on the first of the month. Likewise if you are forcing an even cycle, each leap year will cause one three-day cycle at the end of February. You cannot really get around the fact that any regular pattern of "every other day" is not always going to fall on even or odd days in every month and any way you force this you will either have an extra run or be missing a run between months with mismatched day counts.
output
1
225
Is there a way to have a private setter for a property in TypeScript? ```class Test { private _prop: string; public get prop() : string { return this._prop; } private set prop(val: string) { //can put breakpoints here this._prop = val; } } ``` Compiler complains that visibility for getter and setter don't match. I know I can just set the backing field, but but then I can't set breakpoints when the value is set. I though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter. Am I missing something here? There doesn't seem to be any reason to not allow private setters, the resulting JS doesn't enforce visibility anyway, and seems better that the current alternatives. Am I missing something? If not is there a good reason for no private setters?
instruction
0
226
The TypeScript specification (8.4.3) says" Accessors for the same member name must specify the same accessibility So you have to choose a suitable alternative. Here are two options for you: You can just not have a setter, which means only the ```Test``` class is able to set the property. You can place a breakpoint on the line ```this._prop =...```. ```class Test { private _prop: string; public get prop() : string { return this._prop; } doSomething() { this._prop = 'I can set it!'; } } var test = new Test(); test._prop = 'I cannot!'; ``` Probably the ideal way to ensure private access results in something akin to a "notify property changed" pattern can be implemented is to have a pair of private get/set property accessors, and a separate public get property accessor. You still need to be cautious about someone later adding a direct call to the backing field. You could get creative in that area to try and make it less likely. ```class Test { private _nameBackingField: string; private get _name() : string { return this._nameBackingField; } private set _name(val: string) { this._nameBackingField = val; // other actions... notify the property has changed etc } public get name(): string { return this._name; } doSomething() { this._name += 'Additional Stuff'; } } ```
output
1
226
When learning vocabulary, especially with the use of SRS (Spaced Repetition System), it is interesting to use flashcards. A commonly encountered problem is how to formulate those for maximum efficiency. How does learning vocabulary through sentences, thus giving context to the used words, compare to learning to recognize words alone? For example, the context may give away the meaning of the problematic vocabulary. Are there studies or expert opinions on one approach being preferable to the other at different stages of language learning? Or is it recommended that they be mixed for best results?
instruction
0
227
It's usually best to avoid dichotomies like "Is strategy X better or strategy Y better?". In most cases, strategies are not mutually exclusive but complementary. With vocabulary learning, using just one strategy is probably the least efficient. This is because every strategy has certain strengths (certain skills it builds well) and certain weaknesses (skills it doesn't cover well)- and if you keep using one strategy, you'll be only focusing on the strengths (but with diminishing returns), and not addressing the weaknesses. Using flashcards helps you establish word-to-meaning equivalences quickly, but it usually does so with a shallow meaning, ignoring the breadth of meaning that words usually have. It also ignores the contextual subtleties of the word, and the knowledge is not always retained long-term. It's best to combine flashcards with other strategies that will help you see how the word is used in context, show you the variety of meanings it can have (and doesn't have), see what collocations the word has, etc. One way of doing this is by reading examples of the word and writing your own sample sentences. Another important thing is to be exposed to the word in natural settings - so it's important to read a lot so that you'll encounter the words you've learnt naturally.
output
1
227
Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life? The backstory From the end of January, I'm starting my studies in a suburb of Stockholm. I've decided to, if it turns out plausible, not rent an apartment, but live in a tent. (This is not out of frugality, but out of a will to try something new.) I do have friends who I could visit once a week or so to prepare food and wash my clothes, so I think I can solve the practical problems, or at least those that I've come to think of. I'd camp in one of the forests, maybe 1 km from "civilisation". I'd have access to showers etc at university every day. However: I don't want to freeze to death in my sleep! That's very important to me. I've read that the nights can get as cold as -20°C (-4°F). With the proper preparations, would this be a plausible way of living, at least for a month or so? I do have camping experience, and have been hiking for three weeks, but only in summer.
instruction
0
228
Yes, it is definitely doable. -20&deg;C is only -4&deg;F. The real question is whether it is doable by you at the level of discomfort and hassle you are willing to put up with. Only you can answer that. At best we can point out what the hassles and discomforts will be. First, your fear of dying of cold in your sleep is silly. You'd have to do something pretty stupid to die of hypothermia, and even that's not going to happen when you're inside the sleeping bag. The main danger will be from frostbite, but that again would largely need stupidity to help it along, although that's easier to do than outright death from hypothermia. Your tent will be a long term fixed installation you set up once at a time and conditions of your choosing. You can therefore afford a larger and heavier tent with more stuff you bring in once. Definitely get a tent you can stand upright in. That will make changing clothes much quicker and more comfortable. Since you should be able to keep water out of the tent, get a nice down sleeping bag and a few light blankets. The down bag should be rated for most nights, then put the blankets on top for the few unusually cold nights. Since again weight is not really a issue, get a full sleeping bag, not a mummy bag. They are simply more comfortable. Get a good insulating pad, and another two as backup. Get a tent large enough to fit your sleeping bag and something to sit on next to it, like a folding chair. Put something under the legs to spread out the weight to that they don't hurt the tent floor. Get one of those rubber-backed mats people sometimes put just inside their doors and put it just inside your tent. That allows a place to step with boots still on, then you can sit down on the chair with boots still on the mat to take them off. The crud stays on the mat, which you can shake clean by reaching outside after having put on your down hut booties. Some things are going to be a hassle. At -4&deg;F you want to keep your gloves on whenever possible, but some tasks will be difficult that way. You end up taking your gloves on and off a lot, trading off efficiency with cold fingers. Get a pair of polypro glove liners. They are thin and still allow many tasks to be done, but provide at least a little insulation. Their main advantage is that any metal you touch won't immediately conduct the heet from your hand away. Touching bare metal at -4&deg;F is a good way to get frostbite. Be prepared for some discomfort no matter what equipment you have. The toughest part will be getting yourself out of the sleeping bag in the morning. You'll really have to will yourself to leave the warm comfort of the bag and get into the air at probably the coldest part of the day. At some point you'll have to change your clothes and get undressed in the process. That's going to be cold. It won't be cold long enough to be any real danger, so it's really a mindset issue to get over. Whether you can or not and are willing to push yourself in that way only you can say. You say you have access to heated buildings during the day, so it would make things a lot simpler for you if you don't have to deal with cooking and eating at your camp. Perparing food outside in the cold takes a lot longer than in a heated kitchen, severly limits what you can do, and may also risk predator encounters depending on what is around your area in the winter.
output
1
228
Why is the volt not identical to the full name Volta, unlike the other electrical units ohm, ampere, coulomb, tesla, weber and henry? Is there a historical explanation, was the volt introduced at a different time?
instruction
0
229
The volt, ohm and farad were introduced by the same person, Latimer Clark, a cable engineer, in a paper in 1861. He started the tradition of naming units after scientists. He initially distorted all names: the unit names ohma, volt, galvat (from Galvani), and farad (from Faraday). In his words, he "neglected etymological rules". In that same year, a committee of the British Association for the Advancement of Science began developing a coherent system of electrical units, the cgs system. Varley, a committee member, liked Clark's proposal, but he advocated adding a French name such as Ampere, to facilitate the international acceptance of the new units ("I should like to introduce a French name into the list. We have Germany, England and Italy represented"). For the same reason he may have pleaded for not distorting the French and German names. In addition, Varley objected to the galvat "because Galvani discovered next to nothing". Latimer Clark adapted the unit names in his 'Elementary treatise on electrical measurement' (1868). He changed ohma to ohm, and dropped the galvat. Maxwell acknowledged Clark's practical units and their names in his 'Treatise on electricity and magnetism' (1873). In 1881, at the International Electrical Congress in Paris), two French names, ampere and coulomb, were added. The diplomacy worked, and the new system of electrical units was adopted by all countries. The only units that kept the initial name distortion were the volt and the farad.
output
1
229
We can define cross products mathematically like if we take two vectors, we can find another vector with certain properties but why do we use it in physics, if we consider a hypothetical physical quantity like force which is equal to cross product of certain vectors? For example, the force exerted on a charge in motion in an uniform magnetic field. Why is it so? Why does that force have to be a cross product of two vectors? Is it possible to come up with them when what we do is just observe the nature?
instruction
0
230
This is a great question. The dot and cross products seem very mysterious when they are first introduced to a new student. For example, why does the scalar (dot) product have a cosine in it and the vector (cross) product have a sine, rather than vice versa? And why do these same two very non-obvious ways of "multiplying" vectors together arise in so many different contexts? The fundamental answer (which unfortunately may not be very accessible if you're a new student) is that there are only two algebraically independent tensors that are invariant under arbitrary rotations in $n$ dimensions (we say that they are "$\mathrm{SO}(n)$ invariant"). These are the Kronecker delta $\delta_{ij}$ and the Levi-Civita symbol $\epsilon_{ijk \cdots}$. Contracting two vectors with these symbols yields the dot and cross products, respectively (the latter only works in three dimensions). Since the laws of physics appear to be isotropic (i.e. rotationally invariant), it makes sense that any physically useful method for combining physical quantities like vectors together should be isotropic as well. The dot and cross products turn out to be the only two possible multilinear options. Why multilinear maps are so useful in physics is an even deeper and more fundamental question, but which answers to that question are satisfying is probably inherently a matter of opinion.
output
1
230
I have a web project in my solution file that is "unavailable" when I open the solution. When I right-click on the web project and reload the project, I get the following error: ``` The Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be found. ``` I have not manually set up virtual directories for this web application. Per colleagues, Visual Studio should prompt me to create virtual directories but I am not getting prompted. I installed VS2010 before installing IIS on my dev machine. Here is my development machine setup: * Windows 7 Enterprise * Service Pack 1 * 64 bit OS * Visual Studio 2010 Enterprise Service pack 1 * IIS version 7.5
instruction
0
231
When this happens the easiest solution is to make the virtual directory manually. First of all, you need to make sure you have the right version of ASP.Net installed and that you have installed the IIS extensions. To do this, go to the relevant .net version's folder in C:\(Windows)\Microsoft.NET\Framework\(dotnetver)\ (substituting the bracketed folders for the right folders on your PC) and run this command ```aspnet_regiis.exe -i ``` Next once that's run and finished, sometimes running ```iisreset ``` from the command line helps, sometimes you don't need to. Next, go to your IIS Manager and find you localhost website and choose add a folder. Browse to the folder in your project that contains the actual ASP.Net project and add that. Finally, right click on the folder you added and you should have an option that says 'convert to application' or 'create virtual directory' or something similar. Please make sure the Virtual directory has the name 'MyWebApp'!! Reload your solution and it should work. Good luck!
output
1
231
Why is it hard to draw people running in animes?
instruction
0
232
The walk cycle is considered to be one of the most basic aspects of animation. American animators and animation enthusiasts often times scorn the Japanese styles and methods of animation as lazy, while Japanese anime enthusiasts deride the American style as clunky or too comical. Why is that you ask? The answer lies in how these countries distribute their budget and time. While American animation often times may seem lacking in it's attention to detail, it makes up for it the quality of their animation. American animation often times meticulous and original in how they animate motion, though sometimes content is reused cyclically, the animation is painstakingly frame by frame. In contrast, Japanese anime uses a lot of shortcuts (to save budget and meet deadlines). Typically long scenes feature only the mouth of a character (and maybe other minor features like a waving hair or glittering eyes) moving during delivery of key information/dialog, or the short burst of motion of some character in some an action pose against an animated, cyclic, and stylized background (I'm looking at you transformation scenes). Often times these uses of dramatic still-shots are done against patterned (or static illustrated) backgrounds, sometimes a few moving emotive icons (sweat drops, question marks, small chibi animated heads) will accompany a some sort of monologue. Admittedly both styles of animation reuse shots and sequences, but it's more noticeable in Japanese anime for various reason (e.g., not enough budget and/or manpower). This is why Japanese anime is typically labeled as "lazy" by American animators and enthusiasts. A typical walk cycle in animation consists of 8 keyframes typically: The smoothness of an animation is typically determined by the framerate and amount of key frames in the animation. In American animation, the animation is captured by shooting two frames of film per drawing at a rate of 24 frames per second (fps) to achieve the smooth motion of American animation. Japanese anime, while it also runs at an average 24 fps, typically captures their animation at a rate of three or four frames per drawing in order to save money and manpower. Though it varies depending on the studio and tools used (e.g 3DCG) with main objects in the foreground (typically characters) are animated at 8 to 12 fps, while background objects can be animated at as low as 6 to 8 fps. Lets compare the difference between one walk cycle that is 8 frame to one that is 16 frames, both at 60 fps: Notice the 16 frame one is smoother, but slower while the 8 frame is faster, but choppier. This is because it takes the 16 frame animation twice as long, covering more frames, to go through one cycle than the 8 frame one. The varying of frame rates can also be be used to depict the expansion and compression of time (think bullet time from The Matrix). However generally choppy animation is the result of not enough keyframes in your animation. More frames mean more and manpower and/or time, which ultimately means more money is required. Japanese anime production don't typically have as big of a budget compared to American productions (but there are exceptions), so they must make do with what they have and cut corners where they can (like Shaft did with the certain Bakemonogatari TV episodes).
output
1
232
Malachi 4:5: I will send you the prophet Elijah. He will come before the day of the Lord arrives. It will be a great and terrifying day Jesus says in Matthew 11:14 "and if you are willing to believe their message, John is Elijah, whose coming was predicted" Jesus says in Mathew 17:12 But I tell you, Elijah has already come, and they did not recognize him, but have done to him everything they wished. In the same way the Son of Man is going to suffer at their hands.” It's pretty clear from the above verses that John was Elijah reincarnated. Wouldn't the above verses imply that reincarnation is true?
instruction
0
233
Faulty Premise #1: John the Baptist was a reincarnation of Elijah When Jesus asked Peter who people said he was, he answered that some people thought that Jesus was Elijah come back. Peter knew better and said Jesus was the Christ. In any event, John the Baptist himself directly denied the claim (see John 1:19-21). What Jesus more likely was saying in Matthew 11 is that John the Baptist was a prophet in the tradition of Elijah. Elijah was the greatest of the prophets (even if his disciple Elisha inherited a double portion of his spirit). All of the prophets that followed came in the name and spirit of Elijah, in the same way that some of Paul's letters apparently were created after his death. They were in the spirit and tradition even if not the actual man. Note also Elijah never died - he was taken up into heaven, and people thought he would return. As such, no Elijah was not being thought to have reincarnated- only returned. Elijah's return was long a part of Jewish custom. Even today, during a Passover sedar, a chair is left empty for Elijah. But again, since he did not die, Jews look for his return, not his reincarnation. Faulty Premise #2: The Jewish world view has any concept of reincarnation at all The most basic rule of hermeneutics suggests that a text cannot mean what it could not mean to the original audience. If the Jews had no concept of reincarnation, then any interpretation that says it does has a very, very high bar to clear. In his book The Gift of the Jews, Thomas Cahill advances the thesis that the primary distinctive philosophy of the Jews was precisely that history was not circular. Their linear idea of a human life was a departure from others and was an explicit rejection of reincarnation. As such, a text would need to be exceedingly explicit to a culture that rejected circular life patterns, and the obscure interpretation above (especially in light of the more obvious intepretation) simply doesn't hold water. Furthermore, the book of Hebrews - written to the people into which both Jesus and John the Baptist were born - explicitly reject reincarnation. As the writer points out in 9:27, It is appointed unto a man once to die and then the judgement. Here we do have an explicit rejection of reincarnation by the followers of Jesus. There is one death. There is one judgement. Hence, in any Christian worldview, you don't come back.
output
1
233
I see hugely varied performance depending on how many newlines there are in the file I'm visiting. Here's an example. I have two JSON files: ```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json $ python -m json.tool pretty_printed.json ``` These are two JSON files with the same content. ```one_line.json``` is 18MiB of JSON without any newlines. ```pretty_printed.json``` has newlines and whitespace added, making it 41MiB. However, the bigger file split over many lines is much faster to open in Emacs, both in Javascript mode and Fundamental mode. Why does Emacs have such poor performance with long lines, since it's actually fewer bytes? Is there anything I can do to improve performance without reformatting the data outside of Emacs?
instruction
0
234
Emacs' handling of long lines is not very well optimized. For a number of operations, Emacs has to scan the whole line repeatedly. For example, to display a line, Emacs has to figure out the height of the line, which requires scanning the whole line to find the tallest glyph. Additionally, scanning for bidirectional display eats up a lot of time. You can get some additional information in, for example, the docstring of ```cache-long-line-scans``` (renamed ```cache-long-scans``` in 24.4). You can try and see if setting ```bidi-paragraph-direction``` to ```left-to-right``` and setting ```bidi-inhibit-bpa``` (new in Emacs 27, see footnote 1) to ```t``` improves the speed for you (see footnote 2). This removes some significant contributors to line scans, but sadly not the only ones. The best option is to add newlines. You can pipe a JSON file through e.g. ```python -c 'import json, sys ; json.dump(json.load(sys.stdin), sys.stdout, indent=2)'``` to add newlines and improve readability in general. Footnote 1: ```bidi-inhibit-bpa``` is new in Emacs 27. Setting it to ```t``` can have a noticeable (sometimes dramatic) effect in cases where (a) a physical line is very long, and (b) the line includes many parentheses and/or braces, especially if they are nested. Footnote 2: There is also ```bidi-display-reordering```, but this is only for internal/debugging purposes. Setting it to ```nil``` may improve performance, however that is an unsupported setting which may cause other problems, so it is not recommended. In Emacs 27, the combination of setting ```bidi-paragraph-direction``` and ```bidi-inhibit-bpa``` is a supported configuration which provides approximately the same performance boost.
output
1
234
Sooner or later we come across a task in our project, with which we are totally unfamiliar ('we' as in PM, but also possibly the staff assigned to do this particular task). How can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume?
instruction
0
235
Don't place too much confidence on your first guess just because you've used a sophisticated formula to derive your estimate. Do your best, move on, plan to revise your estimate, don't let bad estimates linger and destroy the discipline of your project schedule ... errors in time estimates are likely to be lognormally distributed... use a method that incorporates an optimistic guess, a pessimistic guess and heavily weights your best guess. Estimate, test, check, then revise and update your project schedule. The third or fourth revision of the estimates is usually about as accurate as you can hope for; your second estimate is far better than your first guess ... if possible, try to get a measure from an early trial of a similar or analogous task ... revise the estimate and revise your plan as soon as better data becomes available. If your first estimate was too conservative, don't allow slack time to corrupt completion of succeeding tasks. If your first estimate was overly optimistic, make your adjustments EARLY and let your stakeholders and customers know. It's more important to be good at following up, to check your estimates and to competently communicate updates than it is to be a develop skill as an estimator of unfamiliar tasks.
output
1
235
Why is Nazi-Germany commonly referred to as "The Third Reich" in English? Why is reich not translated when Dritten ("third") is? And what is the English synonym of reich? Realm? Austria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish corresponding etymology related word) in their name and they all have English translations of their name.
instruction
0
236
Although English historians have defined Reich as being a strictly German concept of sovereign rule, in the German language itself it means "Empire". In English, we speak of the Holy Roman Empire; in German, it is the HRR or "Heiliges Römisches Reich Deutscher Nation". Wiktionary quotes Busching, who in 1762 explained Reich as a German understanding of "Eminence", from the Latin Regnum, rather than an Empire or a Realm as other cultures would understand it. One could see it as a word used in English, Russian, Portuguese and many other languages as a designation for any kind of German kingdom, empire or absolutism, similar to how one would address a foreigner according to their origin, e.g. Senor Martinez, Monsieur Aragon. Compare it to how many cultures, including the Germans, also use the word "Commonwealth" or "Soviet Union", despite the fact that Bavaria had formed its own Union of Soviets, the Räterepublik, during the Weimar Republic. If you're interested in knowing when the word "Third Reich" came into usage, it is worth noting that during Fascist Germany, the country's official name was Das Deutsche Reich, and in the USA and UK it was usually referred to as Germany, Hitler's Germany, Berlin, Reich or, the most popular term, Nazi Germany. (Sources: Neville Chamberlain's declaration of war against Germany, headlines about Germany in newspapers like the NY Times or the Times, the Daily Mail's Lord Rothermere) In Germany itself, the idea of a third Reich stemmed from the 19th century, where it was a popular philosophical theme in literature and theology. Writers like Johannes Schlaf, who wrote "Das Dritte Reich" in 1899, or the German translator of Ibsen's "The Emperor and the Galilean", popularized the idea of the imminent arrival of a thousand years of Christianity (a kind of positive apocalypse), which would follow a third "Reich". And they would quote Paul the Apostle and various saints, to make it clear that the third Reich would follow the heretic lex naturalis and the lex mosaica. Nazi propagandists exploited this in their articles, making it sound as if the saints had had some sort of epiphany about Hitler and the Nazis. In other words, the Third Reich began as an abstract idea of a Christian revolution, but was assumed by Nazi writers in order to bolster Hitler's popularity and justify the drastic and bloody decisions that the Fascist government was making. In one of the earliest examples of the Third Reich being mentioned outside of Germany, Major Strasser in the film Casablanca talks about the Third Reich as if it was just the beginning to a kind of paradisaical future or of a fourth Reich. After 1945, the term was used exclusively to associate only to the unsuccessful reign of Fascism in Germany, and it ceased as a philosophical or theological idea in German literary circles.
output
1
236
If we fold a paper and then apply pressure on the newly formed crease, it seems that the paper's surface gets a permanent deformation but what exactly has happened to the paper at a molecular scale?
instruction
0
237
Basically, a fold or crease in paper will remain because the structure of the fibers in the paper have become irreversibly damaged. This happens because the paper is bent/compressed beyond its elastic limit. Chemically, paper is mainly composed of cellulose from plant fibers. Cellulose is an organic polymer, which has D-glucose units connected through hydrogen bonds. These bonds form between the oxygen atom of the one-hydroxyl group belonging to the glucose and the hydrogen atom of the next glucose unit. These are microscopic properties of paper, but to understand what happens when we fold paper or do Origami, it is sufficient to learn what is happening macroscopically. All materials have what is called an elastic limit and a plastic region. The elastic limit is the point at which a material will bend but still return to its original position without any permanent change or damage to its structure. Further deforming the material beyond this limit takes it to its plastic region. At this point any structural or physical changes become permanent and the paper will not return to its original form. Every material has a different elastic limit or yield, and plastic region. Imagine holding a piece of paper slightly bent but not folding or creasing it. The plant fibers that make up the paper will not have exceeded their elastic limit. So as soon as you let go of the paper sheet it will quickly return to its noncreased original flat state. However, if you were to roll that piece of paper into a cylinder and hold it for a few minutes, some of these fibers will be pushed beyond the elastic limit which is evident since it will not lie flat anymore since slight deformations have occurred in this sheet. Now, when you properly fold a piece of paper as you would during Origami, the plant fibers along the crease are pushed into the plastic region of the paper, causing a fracture point at the actual line of the fold. A practical example of this is if you were to fold a piece of paper, you will note that if you stretch the paper evenly on both sides of the fold, the paper will tear right on the fold (a quick way to &quot;cut&quot; paper if you have no scissors). The fold then becomes an irreversible structural failure and the fibers in the paper will never regain their original state. Because of this damage to its structure, the paper will from then on have this fold. And no matter how hard you try to flatten out the fold it will never return to its original state. This is why Origami models continually retain their shape.
output
1
237
In general, there are two types of syntax of defining functions - Something like C, C++, C#, or Java (```int functionName(char arg)```) vs the ML (and others) tradition of defining the return type after the function (and using something like a ```fun``` keyword to define a function - like ```fun functionName(char arg): int```). One of the advantages (for the parser, at least) for a ```fun``` keyword is that it lets the parser be context-free (it doesn't have to guess if ```int``` defines a variable or if it defines a function). When C was invented, computers had very little memory and speed (so little, that the reason C requires one to define all the variables in the beginning of the function was because it had to be a one-pass parser). Why didn't they choose the simple way out and use function defining keyword?
instruction
0
238
Dennis Ritchie’s paper on The Development of the C Language gives some idea of the reasoning behind this: namely, the fundamental rule in C that declaration syntax should match expression syntax" For each object of such a composed type, there was already a way to mention the underlying object: index the array, call the function, use the indirection operator on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus, ```int i, *pi, **ppi; ``` declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that ```i```, ```*pi```, and ```**ppi``` all yield an ```int``` type when used in an expression. Similarly, ```int f(), *f(), (*f)(); ``` declare a function returning an integer, a function returning a pointer to an integer, a pointer to a function returning an integer; ```int *api[10], (*pai)[10]; ``` declare an array of pointers to integers, and a pointer to an array of integers. In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration. It appears this rule trumped parser considerations. Its immediate consequence is that function declarations can’t use specific keywords, or impose a different ordering of declaration components. It’s worth noting that parsing was somewhat different in early C, since function declarations didn’t specify their arguments, and function definitions separated the argument list from the argument declarations (which weren’t necessary for ```int``` arguments): ```sum(); ``` declares a ```sum``` function, which would then be defined as ```sum(a, b) { return a + b; } ``` (no types needed here, the default is ```int```). So the parser didn’t deal with types inside argument lists.
output
1
238
I am new to TeX, working on it for about 2 months. Have not yet figured out how to script the 'curvy L' for Lagrangian and/or for Laplace Transforms. As of now I am using the 'L' - which is not good! :-( Any help? UPDATE The 2 best solutions are; ```\usepackage{ amssymb } \mathcal{L} ``` and ```\usepackage{ mathrsfs } \mathscr{L} ``` I got my answers at, http://detexify.kirelabs.org/classify.html
instruction
0
239
You have been told how to get a curved L. But here's some more general advice, which also applies in this situation: In cases such as this, always create your own shortcut macro, say ```\newcommand{\Lagr}{\mathcal{L}} ``` This way, if you ever decide that that curly L is not quite the one you like, it is easy to switch. Also, even before you knew the answer to this question, you could have written ```\newcommand{\Lagr}{L} ``` in your preamble. Then you could start/continue writing the document, use ordinary capital Ls where you want, and ```\Lagr``` wherever you actually mean a Lagrangian, and then later changing the definition of ```\Lagr``` to something appropriate. This way, you wouldn't have to manually search for each occurence of a capital L and decide if it's a Lagrangian or not. Clearly ```\Lagr``` (or whatever you want to call this macro) is also easier to type than ```\mathcal{L}```, and it makes the source code much more readable. Another advantage, which is probably more subtle, since you're new to LaTeX, is that we can make the curvy L exactly the type of math we want. TeX distinguishes between ordinary letters, binary operators, binary relations, opening and closing parenthesis and so on; the spacing between two ordinary letters is not the same as the spacing between the ```a```, ```+```, and ```b``` in ```$a+b$```. So since the Lagrangian is a kind of operator, we could say ```\newcommand{\Lagr}{\mathop{\mathcal{L}}} ``` But in the case of operators, the package amsmath (which you are most likely using; if not, you should) provides a somewhat better mechanism: ```\DeclareMathOperator{\Lagr}{\mathcal{L}} ``` Another (related) tip: Even if you are using the same notation for two different things, it is best to make a separate macro for each. In this case you might have ```\DeclareMathOperator{\Lagr}{\mathcal{L}} \DeclareMathOperator{\Lapl}{\mathcal{L}} ``` The reason is the same as in the ```L``` vs. ```\Lagr``` case above: If you at some point decide that using ```\mathcal{L}``` for both is a bad idea, you would have to find each occurence of ```\Lagr``` and figure out if it is really a Laplacian. Using macro names carrying semantic meaning is one of the great powers of TeX.
output
1
239
My son doesn't want to share anything with other kids, and if some kid even so much as touches his toy, he pushes the kid. He shouts and cries at the same time, and tries to express his anger by pushing and hitting the kid. I feel so embarrassed in front of other parents. And when he is at home with me and doing something wrong, I try to stop him, he tries to repeat my words and shouts at me. He is copying the behavior of others, whether it's a good act or bad... Please help me how to stop him from being a bully.
instruction
0
240
Welcome to the "Terrible Two's"! Your son behaves typically for his age. At 2 he starts to assert himself and express his demands. It's likely that he has also learned that he gets his way when he throws a tantrum. For a 2-year old screaming, hitting or even biting is a normal way to express his anger - at least he will try and every success reinforces this. He also comes across more limitations: The more he is able to do, the more often he is stopped. The solution? It's already in your question: He will copy what others do. So by all means, stay calm. No yelling, no fussing and - please! - no hitting. He has some learning (accepted behaviour like sharing) and some unlearning (no hitting or pushing) to do and needs your help. * When he throws a tantrum, either ignore him, or quietly remove him from the scene. Do not worry about others! Most likely they have had the same trouble with their kids or will some time ;-) * When he doesn't want to share yet - fine, he will learn. This can be practiced. Don't make him share, or he will resent it. Rather, teach him the benefits of sharing. Start with food, for example. Have a plate of cookies (or other favorite food), that's yours. He will likely demand some, but demanding doesn't get him a cookie. Asking nicely will! Explain, repeat. Then, switch roles. If he has cookies, ask him to share. If he does, praise him. Else - remind him next time when he wants your cookies that he didn't share. Share whenever possible: Having a bite from your plate, getting a piece off his. Repeat, repeat, repeat.... Same goes for objects. Ask him to "please" share a toy, "play" with it for a short moment, then return. Say "Thank you". He learns, that he gets the toy back. Share some of your things. (Monitor the behaviour of other children, that want his toys - make sure they ask first and give toys back, at least during this learning stage.) You have some serious work to do, but it will be sooooo worth it!
output
1
240
What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms?
instruction
0
241
The difference simply lies in that they solve different problems: * The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas * the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm. The constructs for achieving these different goals are however very similar; both patterns are examples of composition with delegation. Some observations on their advantages: * By using the State pattern the state-holding (context) class is relieved from knowledge of what state or type it is and what states or types that are available. This means that the class adheres to the open-closed design principle (OCP): the class is closed for changes in what states/types there are, but the states/types are open to extensions. * By using the Strategy pattern the algorithm-using (context) class is relieved from knowledge of how to perform a certain task (-- the "algorithm"). This case also creates an adherence to the OCP; the class is closed for changes regarding how to perform this task, but the design is very open to additions of other algorithms for solving this task. This likely also improves the context class' adherence to the single responsibility principle (SRP). Further the algorithm becomes easily available for reuse by other classes.
output
1
241
Why don't Tour de France riders always ride their TT bikes?
instruction
0
242
There are 2 good reasons for this. First, a TT bike is the most efficient machine for flat, fast course racing, where there are a minimum of hills. It is not the most efficient machine when it comes to climbing. The body position is far too aggressive for even professional athletes to use in a non-TT style event. A bike with more a more upright body position, a more stable weight distribution, a lighter frame, and far, far lighter wheels, is a more efficient choice for that style of ride. Secondly, a TT bike sacrifices bike handling for that extreme power and aero efficiency. The TT stages are controlled events, where there are either one rider, or one team on the course at a time, and so limitations on stability and handling are acceptable. Take the same bike in a 150 rider peloton, where riders constantly jockey for position, and where even on a stable bike losing focus for 1 second can cause a major crash, and all of a sudden, those same sacrifices in bike handling and stability are no longer a benefit for the rider or the team. They become a hazard to the team's chances of winning. And not just for the stage or the day, since a bad crash can take a rider out for the season. Or God forbid, permanently. For these reasons, the UCI has seen fit to ban the bikes in non-TT events, in order to ensure rider safety. And for once, their decision makes sense.
output
1
242
I remember when the Muslim holy book was the Koran when I was in middle school, but now it's the Quran. But it's always been Qatar and Iraq (but still Kuwait.) Who decided that 'Q' was going to be represent that sound instead of 'K', and why?
instruction
0
243
In Arabic, in fact, they've always been separate sounds! The sound we write "K" is spelled with the letter ك in Arabic, and is pronounced a little bit further forward in the mouth; the sound we write "Q" is spelled with the letter ق and pronounced a little bit farther back. In phonetic terms, "K" is a velar sound, and "Q" is a uvular sound. English doesn't distinguish between these two different sounds. But since we've got a spare letter lying around—the English letter "Q" is actually related to the Arabic letter ق, if you go back far enough!—it's become conventional to separate them in writing. "Kuwait" is spelled with a ك, so it gets a "K"; "Qatar" is spelled with a ق, so it gets a "Q". The "Qur'an", similarly, has a ق in it. Nowadays, by the way, the letter "Q" has started to be associated with Arabic in particular, since it shows up significantly more there than in English. So in pop culture, you'll sometimes see names like "Hakeem" respelled to "Haqim"—even though the original Arabic has a ك in it! Linguistically, this is called hypercorrection, and it's the same reason you'll see words like "forté" with an é: English-speakers associate the acute accent with Romance loans (café, fiancé, résumé), but it has no special meaning in English, so it sometimes gets inserted where it doesn't actually belong (the original Italian word is simply forte).
output
1
243
How do you add Boost libraries in CMakeLists.txt?
instruction
0
244
Put this in your `CMakeLists.txt` file (change any options from OFF to ON if you want): ``` set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost VERSION COMPONENTS *boost libraries here*) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) add_executable(progname file1.cxx file2.cxx) target_link_libraries(progname ${Boost_LIBRARIES}) endif() ``` Obviously you need to put the libraries you want where I put `*boost libraries here*`. For example, if you're using the `filesystem` and `regex` library you'd write: ``` find_package(Boost VERSION COMPONENTS filesystem regex) ```
output
1
244
Quando devo fazer essa gravação direto no banco? Quais as situações? Eu sei que posso gravar no banco o caminho da imagem.
instruction
0
245
Além do custo ser mais alto como mencionado, deve-se levar em conta vários fatores: * Volume de dados: para um baixo volume de dados pode não haver problema. Por outro lado, para armazenamento de grande massa de dados o banco de dados é praticamente inviável. Pergunte ao Facebook ou ao Google se eles usariam banco. O Facebook, por exemplo, usa um sistema de arquivos personalizado para tornar o acesso mais rápido ainda e diminuir a o overhead por arquivo exigido pelos sistemas de arquivos tradicionais. * Clusterização: uma vantagem do banco de dados é no caso do seu sistema rodar em vários servidores, todos terão acesso uniforme aos arquivos. Porém, usar uma unidade na rede para armazenar os arquivos. * Disponibilidade: seu sistema vai ter muitos acessos? Isso pode sobrecarregar um banco de dados tradicional. Por outro lado, seu servidor HTTP pode usar as rotinas de acesso de baixo nível ao sistema de arquivos para enviar o stream de dados ao cliente. * Escalabilidade: se a demanda de volume ou disponibilidade aumentarem, será possível adicionar mais capacidade ao sistema? É muito mais fácil dividir arquivos entre servidores diferentes do que distribuir registros de uma tabela em mais servidores. * Flexibilidade: fazer cópias de segurança, mover arquivos de um servidor para outro, fazer algum processamento nos arquivos armazenados, tudo isso fica mais fácil se os arquivos estiverem num diretório. Se você faz o deploy em ambiente de cliente, os arquivos no disco não inviabilizam você de receber cópias do banco de dados para testes. Tente pedir para o seu cliente enviar terabytes de dados para você analisar se der algum problema no banco. * Overhead de leitura e gravação: o custo computacional para gravar e ler dados do banco de dados é maior do que para ler e gravar diretamente em um arquivo. Existem várias estratégias para escalar um sistema tanto em termos de disponibilidade quanto em volume. Basicamente essas estratégias consistem em distribui-los em vários vários servidores e redirecionar o usuário para cada um deles conforme algum critério. Os detalhes variam de implementação, tais como: estratégia de atualização dos dados, redundância, critérios de distribuição, etc. Uma das grandes dificuldades em gerenciar arquivos fora do BD é que temos agora duas fontes de dados distintas e que precisam estar sempre em sincronia. Do ponto de vista de segurança, efetivamente há pouca diferença. Se um hacker pode comprometer um servidor, ele poderá ler tanto os arquivos gravados em disco do seu sistema quanto os arquivos do sistema de banco de dados. Se essa questão for crítica, uma alternativa é armazenar os dados criptografados. Porém, sempre que fiz a análise do melhor tipo de solução, o uso do sistema de arquivos sempre esteve em grande vantagem.
output
1
245
I need a regular expression that validates a number, but doesn't require a digit after the decimal. ie. ```123 123. 123.4 ``` would all be valid ```123.. ``` would be invalid
instruction
0
246
Here is the regular expression you can use: ``` /^\d*\.?\d*$/ ``` * `^` - Beginning of the line; * `\d*` - 0 or more digits; * `\.?` - An optional dot (escaped, because in regex, . is a special character); * `\d*` - 0 or more digits (the decimal part); * `$` - End of the line. This allows for .5 decimal rather than requiring the leading zero, such as 0.5
output
1
246
The year is 2109 C.E my friends and I were caught in a space disaster when the spacecraft we're in broke apart during a daring escape from a patrolling spacecraft. We stole an antique cellphone (from 1999, in good working condition) from a space museum but our escape was interrupted and fortunately we managed to get into the escape pod and didn't get caught up in the explosion. The only emergency transponder in the escape pod isn't working probably due to the destruction of the spacecraft. Given the technology of 1999, is it possible for us to sent out a distress signal to alert the leaving patrol spacecraft? Note: the cellphone was the most innovative product of 1999 money can buy. The escape pod is not a Faraday cage we're talking about the future and the patrol spacecraft don't necessary be on a lookout for distress signal; please use these clues to your advantage. If there is absolutely no way to transmit any man-made signal out, please state a valid reason why it can't be done.
instruction
0
247
Assets * 1 obsolete piece of short range comms kit requiring a battery you probably can't charge * 1 slightly malfunctioning escape pod with up to date comms that isn't working but you're still alive Current standards say the Mayday should be broadcast on VHF channel 16 (156.8 MHz). A 1999 phone, probably on 2g would likely use 900MHz (UHF). The slightly broken comms unit in the pod is probably using channel 16 or equivalent*. This is your first problem. The patrol ship will be listening in for signals broadcast on the mayday frequency. That's the frequency you need to hit, so first up is rebuilding your phone to that frequency. Or you could look at the pod comms system and see what's wrong. Your next problem is that your mobile phone's range is laughable in interstellar space. What's going to be even more laughable is when you try to use it in the radiation shielded environment of your escape pod. The signal, which is line of sight at the best of times, most likely won't even penetrate the hull. So now you need to hook it up to the external antenna used by the pod's own comms system. Or you could look at the pod comms system and see what's wrong. Now you need to make sure you're using the right broadcast method: are you on AM or FM? (There's no reason to think that 100 years from now they'd be able to pick up an analog signal) I'm sure you can see where I'm going with this. Fix the pod. Ultimately all you're going to do is rebuild a copy of the pod's own comms system with a batch of obsolete components. If you're good enough to do that you're good enough to fix the pod's own system which will be much easier. *I mention channel 16 as an example to show that there are standards for distress signals and they're very different from the standards for mobiles, if you want someone to pick it up then you need to be broadcasting on a frequency they're listening on. ## Distress frequencies 2182 kHz forms an essential part of the Global Maritime Distress Safety System (GMDSS). It has an associated DSC frequency at 2187.5 kHz. Other international distress frequencies, in use as of 2008, include: ```121.5 MHz - civil aircraft emergency frequency 243 MHz - military aircraft emergency frequency 156.8 MHz - Marine VHF radio channel 16, short range maritime use 406 MHz / 406.1 MHz - Cospas-Sarsat international satellite-based search and rescue (SAR) distress alert detection and information distribution system ``` Discontinued frequencies ```500 kHz Morse code is no longer monitored. 121.5 or 243 MHz locators. (No longer automatically monitored by satellite, though still used for aircraft communication and short-range direction finding.) Effective 1 August 2013, the U. S. Coast Guard terminated its radio guard of the international voice distress, safety and calling frequency 2182 kHz and the international digital selective calling (DSC) distress and safety frequency 2187.5 kHz. Additionally, marine information and weather broadcasts transmitted on 2670 kHz terminated concurrently. ```
output
1
247
Often I want to just point the camera to an object or a specific area in my scene to get an idea of how it'll look in the render. What's the most painless hassle-free way to do this in blender? A quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result. This question could probably be broken down into these two main questions: * How do I point a selected camera to the current 3d-cursor location in the scene? * How do I point the selected camera to the currently selected object(s) in the scene?
instruction
0
248
Situation 1: You're not looking through the camera yet * Fly Mode: Shift + F or the standard Viewport Navigation * Set Camera to View: Ctrl + Alt + Numpad 0 Situation 2: You're already looking through the camera via Numpad 0 * Select the camera: Right Mouse Button * Grab: G & optionally... * Lock the grab to a local axis: XX or YY or ZZ (my favorite) * Rotate: * Tilt: R * Look around: R R * Orbit around the 3D cursor: .R followed by R, or Z. (Press , afterwards) Tips & Notes (some go beyond this question): 1. In earlier versions of Blender, Fly Mode would to make the camera slowly flatten with the horizon line. It doesn't anymore, but you can reset the camera's rotation Alt + R to make the horizon flat and then use fly mode to reorient the camera while maintaining that flat horizon. 2. If you decide to use another object as a target for the camera to look at, you can use the Object Constraints. To do this: * Select the camera. * Shift-select the target. * Press Ctrl T and select Track To or Damped Track To. You can modify the new constraint in the camera's Constraints panel, for example, to animate the influence.
output
1
248
What are the general tactics of Krav Maga as opposed to Systema? For instance, the tactics of Silat are to hurt the other person so badly they can't hurt back. Another example would be that the tactics of boxing would be to knock out the other person first using only punches. So, as far as I know, the goal of Systema and Krav Maga are both to do anything you can to defeat your attacker because they are serious about self defense. Does that mean that Krav Maga and Systema are strategical identical? Does Krav use strategies that Systema doesn't? Does Systema use any strategies that Krav doesn't? Is there a difference or do they generally work the same way?
instruction
0
249
At first glance Krav Maga and Systema seem to be very similar in that they are both very unconventional, no-rules, practical self-defence, martial arts (although Krav isn't technically a martial art) which are no holds barred and generally formless. However... Krav Maga is basically a very raw, dangerous situation survival system (including avoidance and escape) which builds upon your natural instincts and taught in a very short space of time. Therefore it is highly stress tested. It relies on the fact that fear will set in in order to use your natural responses and turn them into functional movements to your advantage. It relies heavily on shock and awe in that defence and attack should be simultaneous where possible to capitalise on the opponent's shock value. Systema is - in many ways - the exact opposite, it is a system which teaches over a much longer period of time how to control your fear/anger/pity and teaches relaxation (through breathing/stretching) in stressful situations so that attacks on your person are less effective, better recovered from and the pressure points, levers and momentum of attackers can be manipulated to your advantage using the clarity of mind gained from your training. In Summary So in effect Krav Maga is taught fast and turns your weaknesses into strengths so your defence/attack becomes like a reflex just when you need it, while Systema is a methodology that needs to be learned and seeks to remove those weaknesses so that your defense/attacks can be more effective. Also, another martial art, similar and somewhere between these is the Keysi Fighting Method (KFM) - developed for street fighting - but that has some actual forms that have to be learned such as the very distinctive 'Pensador' that the Christian Bale Batman uses/ KFM is a lot more like Krav Maga but it makes heavy use of the 'Pensador' guard (much like the 'Rhino' Krav pose) and concentrates a much larger chunk of its time to dealing with multiple opponents and ground based fighting, as it was developed for street fighting and this is where they tend to end up. It doesn't deal with survival (avoidance and get away) as much as Krav however. There are also no weapons.
output
1
249