message
stringlengths 2
17.7k
| message_type
stringclasses 2
values | message_id
int64 0
19
| conversation_id
int64 0
1.03k
|
---|---|---|---|
PHP is writing this error in the logs: "Notice: Use of undefined constant".
Error in logs:
```PHP Notice: Use of undefined constant department - assumed 'department' (line 5)
PHP Notice: Use of undefined constant name - assumed 'name' (line 6)
PHP Notice: Use of undefined constant email - assumed 'email' (line 7)
PHP Notice: Use of undefined constant message - assumed 'message' (line 8)
```
Relevant lines of code:
```$department = mysql_real_escape_string($_POST[department]);
$name = mysql_real_escape_string($_POST[name]);
$email = mysql_real_escape_string($_POST[email]);
$message = mysql_real_escape_string($_POST[message]);
```
What does it mean and why am I seeing it?
|
instruction
| 0 | 150 |
The error message is due to the unfortunate fact that PHP will implicitly declare an unknown token as a constant string of the same name.
That is, it's trying to interpret this (note the missing quote marks):
```$_POST[department]
```
The only valid way this would be valid syntax in PHP is if there was previously a constant ```department``` defined. So sadly, rather than dying with a Fatal error at this point, it issues this Notice and acts as though a constant had been defined with the same name and value:
```// Implicit declaration of constant called department with value 'department'
define('department', 'department');
```
There are various ways you can get this error message, but they all have the same root cause - a token that could be a constant.
Strings missing quotes: ```$my_array[bad_key]```
This is what the problem is in your case, and it's because you've got string array keys that haven't been quoted. Fixing the string keys will fix the bug:
Change:
```$department = mysql_real_escape_string($_POST[department]);
...(etc)...
```
To:
```$department = mysql_real_escape_string($_POST['department']);
...(etc)...
```
Variable missing dollar sign: ```var_without_dollar```
Another reason you might see this error message is if you leave off the ```$``` from a variable, or ```$this->``` from a member. Eg, either of the following would cause a similar error message:
```my_local; // should be $my_local
my_member; // should be $this->my_member
```
Invalid character in variable name: ```$bad-variable-name```
A similar but more subtle issue can result if you try to use a disallowed character in a variable name - a hyphen (```-```) instead of an underscore ```_``` would be a common case.
For example, this is OK, since underscores are allowed in variable names:
```if (123 === $my_var) {
do_something();
}
```
But this isn't:
```if (123 === $my-var) {
do_something();
}
```
It'll be interpreted the same as this:
```if (123 === $my - var) { // variable $my minus constant 'var'
do_something();
}
```
Referring to a class constant without specifying the class scope
In order to refer to a class constant you need to specify the class scope with ```::```, if you miss this off PHP will think you're talking about a global ```define()```.
Eg:
```class MyClass {
const MY_CONST = 123;
public function my_method() {
return self::MY_CONST; // This is fine
}
public function my_method() {
return MyClass::MY_CONST; // This is fine
}
public function my_bad_method() {
return MY_CONST; // BUG - need to specify class scope
}
}
```
Using a constant that's not defined in this version of PHP, or is defined in an extension that's not installed
There are some system-defined constants that only exist in newer versions of PHP, for example the mode option constants for ```round()``` such as ```PHP_ROUND_HALF_DOWN``` only exist in PHP 5.3 or later.
So if you tried to use this feature in PHP 5.2, say:
```$rounded = round($my_var, 0, PHP_ROUND_HALF_DOWN);
```
You'd get this error message:
Use of undefined constant PHP_ROUND_HALF_DOWN - assumed
'PHP_ROUND_HALF_DOWN' Warning (2): Wrong parameter count for round()
|
output
| 1 | 150 |
I'm from a very rural area and love to garden, however, for work I just moved into an apartment in the city. I miss being able to grow vegetables and so I attempted to start some leaf lettuce indoors, however, almost every plant died quickly. I'm just curious, does anyone have experience growing vegetables indoors? What are the best ones for this? What sort of planter do you use? Do they need to be directly next to a window? How often should they be watered? I'm not used to not having Mother Nature help me out with my plants Any tips that can be provided would be much appreciated, thanks!
|
instruction
| 0 | 151 |
Indoor gardening is a bit more difficult then the regular outdoor gardening, there are several factors but in most cases it boils down to: Temperature, Humidity, Light, The air in your apartment.
You didn't mention exactly where your dying plants are being placed. Do you have a fan within the apartment? Plants need air whether it is natural or even if it is coming from a fan. What type of lighting is inside the apartment? Are you only using natural light? These are important factors to aide the growth of the plant as well. How is the temperature within the apartment? If you notice a lot of temp ups / downs in the area you are gardening than it is probably worth moving the garden or choosing another spot. With apartments that becomes all the more difficult.
Your plant also probably came from some nice greenhouse, an english gardens, a ray weigands, etc etc...They have plenty of light, they also have plenty of means of water and the temperature well most of this is all outside, so they have the advantage of using mother nature. Your plant needs to adjust to these conditions. You should try to begin to place your plants in a very lit area with as much natural wind / fan as possible, these plants need to breath. If your plants are not conditioned for this type of environment you run the risk that they give up and die.
When potting the plant ensure the actual pot is cleaned up to remove any unnecessary plant diseases from prior plants. Look on the bottom of the actual pot, are you getting drainage? If not drill a hole in the bottom of the pot if you can, if not toss that pot out and get you a pot that has a good amount of drainage. Overwatering plants will destroy them, and without nature (wind, temperature, etc) the water sitting there takes all the longer to dry out.
When it comes to veggies Tomatoes need a ton of sunlight and humidity is great for them as well. Herbs are probably the simpliest to get going but I'm not sure if this is what you are after. Cucumbers and squash don't need as much sunlight as tomatoes.
|
output
| 1 | 151 |
What are the advantages of studying words by their frequency?
|
instruction
| 0 | 152 |
The main advantage is that by learning higher frequency words, you get a greater "bang for your buck" - that is, if you know the most frequent words of the language, you'll be able to understand more of the words you encounter, and therefore you gain the greatest benefit by studying those frequent words first.
According to Nation & Waring (1997), text coverage in the Brown corpus is as follows:
* Most frequent 1000 words: 72.0%
* Most frequent 2000 words: 79.7%
* Most frequent 3000 words: 84.0%
* Most frequent 4000 words: 86.8%.
So by learning the top 1000 words, you'll know 72% of the words in the average text you read. But after that, there are diminishing returns: the next 1000 words gives you another 7.7% of a typical text, and the next 1000 words allows you to understand just 4.3% more. After that, the returns on memorizing by frequency decrease even more, so learning from frequency lists becomes less useful.
Note that text coverage (the percentage of words that you know in an average text) is important. We don't need to understand every single word in a text in order to understand the general meaning. Some research has investigated what percentage of words we do need to understand. Laufer and Sim (1985) suggested 65-70% should be understood as an absolute minimum for comprehension, but Laufer (1989) (as described in Hu and Nation (2000)) suggests 95% should be known for solid comprehension. Hu and Nation (2000) suggest that 98% of words should be known for unaided comprehension.
Although learning high-frequency words is a good idea, especially when you first start learning a language, frequency is not the only consideration when choosing words to learn. Barker (2007) suggests that "cost" and "benefit" be the primary considerations when choosing words to learn; benefit is partially defined by frequency, but also on personal needs.
So it's good to learn the "technical" vocabulary of your major or field, and it's also useful to learn words related to your interest. It's also beneficial to learn words with a lower "cost" - words that are familiar, that you've encountered a lot recently, or that just seem easy.
Also, although memorizing words has benefits, it is best to combine this with real exposure to words, so that you learn them naturally in real contexts.
|
output
| 1 | 152 |
I have heard many people saying, βHah! I beat Stockfish,β and one saying, βI am the best chess player ever! I beat Stockfish.β So I wonder if it is possible, just to know whether I should try to beat it. I tried to play it once; I barely played 25 moves.
|
instruction
| 0 | 153 |
The answer is that they either played it on some very handicapped mode, they took back A LOT of moves, or they are probably lying.
Stockfish 11 is currently rated about 3607, and that is in standard chess. Computer programs are typically even HARDER to beat for humans at even faster controls.
There is a reason elite humans have not played matches against computers for a long time: even the Carlsens of the world cannot beat them any more. According to the ELO winning expectancy calculator, there is currently a 745 point difference between Stockfish 11 and Carlsen, and per the chart, that gives the computer a 99.5439696% chance of winning.
Note: The ratings used above are from different rating pools, and thus, are not truly directly comparable, but used as a rough estimate of what would happen between the computer and Carlsen.
|
output
| 1 | 153 |
How to decrypt Jenkins passwords from credentials.xml?
|
instruction
| 0 | 154 |
There is a `hudson.util.Secret.decrypt()` function which can be used for this, so:
1. In Jenkins, go to: `/script` page.
2. Run the following command:
```println(hudson.util.Secret.decrypt("{XXX=}"))
```
or
```
println(hudson.util.Secret.fromString("{XXX=}").getPlainText())
```
where `{XXX=}` is your encrypted password. This will print the plain password.
To do the opposite, you can run:
```
println(hudson.util.Secret.fromString("some_text").getEncryptedValue())
```
Alternatively check the following scripts: `tweksteen/jenkins-decrypt`, `menski/jenkins-decrypt.py`.
|
output
| 1 | 154 |
I'm pretty disappointed with my horse. He wasn't cheap -- 1000g -- but he just doesn't seem that fast. To make things worse, he's a bit of a wolf magnet and every time I get attacked I have to tediously dismount, blast the wolf, and then remount.
Is the speed of a horse actually significantly faster than normal running speed? If so, how much faster?
|
instruction
| 0 | 155 |
Don't forget that you can sprint with a horse. It might be that you know that you can sprint on your character, but not on your horse. Please note that your horse is also able to sprint using stamina. You can do this using the default Alt key.
Horses are indeed faster, transportation was simplified.
Since Oblivion, they took Acrobatics and Athletics skills away, thus you can't improve your speed in such way anymore that it would be faster than a horse. The speed improvements by not being Fatigued and not being overweight are not enough to be significant.
All horses in Skyrim have the same speed and hardiness, they are all draft types that resemble a Clydesdale, and all cost 1000 septims.
β Wikia - Elder Scrolls V: Skyrim - Horse
All horses in Skyrim are the same, seems that they wanted to simplify the whole transportation idea.
Restrictions apply on both your character and horse.
Without mods, a horse can't be used inside a city. If you do a lot of role-playing within cities having a horse might not be useful. At the same time, characters are limited in Skyrim as Raven Dreamer noted; while you can get over some mountains by jumping left and right trying to get over a rock, a horse will be more superior in performing this task as it is less restricted by physics. You can however be smart enough to choose your path right, rather than trying to work against the physics...
|
output
| 1 | 155 |
Other than rust, corrosion, and other reactions with air that would make the use of a metal unfavorable, how do different metals affect the performance?
Let's give Yagi an example:
Let's say I use 4 different metals for the directors
, reflector, and driven element.
One antenna made out of copper, one made out of aluminum, and one made out of a higher resistance conductor, let's say graphite (I know it would snap, I'm just talking theoretical), and iron
Other then the metal variations, the antennas are identical.
So, do different metals with different conductivity and permiability affect the performance of an antenna including gain, efficiency, impedance, elevation, or any other characteristic other then mechanical strength, and chemical reliability in open air.
|
instruction
| 0 | 156 |
Considering just electrical properties, the most significant parameter for your selection of antenna conductor is resistance. You want to keep the resistance to a minimum, because when current flows through a resistance, the electrical power is converted to heat, according to Joule heating:
$$ P = I^2 R $$
Any energy you use to make heat is energy you aren't using to make electromagnetic waves.
So first, you should consider the resistivity ($\rho$) of various metals. A lower resistivity means you will need less of a metal to reduce the resistance to an acceptable target. Here's a selection, ordered from lowest to highest resistivity in nano-ohm-meters (nΞ©m), of some metals you might consider using in an antenna:
* Silver: 15.9
* Copper: 16.8
* Gold: 24.4
* Aluminium: 26.2
* Zinc: 59.0
* Nickel: 69.9
* Iron: 100
* Tin: 109
I'm not going to list stainless steel because there are so many kinds, but generally stainless steels are not great conductors, being over 100 on this scale.
A high resistivity isn't bad in itself, because you can compensate by making the conductor thicker, and end up with the same resistance. Thus, you might think copper is the best choice (ruling out silver due to high cost), but when you start making mechanical and cost considerations, you may find aluminium is better. This is because for a sample of copper and another of aluminium of equal resistance, the aluminium sample will be bigger, but stiffer, lighter, and cheaper.
There's another effect to consider here: with increasing frequency, currents like to flow on the surfaces of conductors. This is called the skin effect. The current flowing only on the skin of a conductor effectively reduces the cross-sectional area, and thus the conductance.
Since most of the RF current is only on the surface, it often makes sense to build antennas from tubing for antennas requiring rigid elements (a 440 MHz Yagi), or copper-clad steel for wire antennas requiring tensile strength (a 40 meter dipole). This saves weight and cost for a negligible increase in loss.
Magnetic permeability is a factor in skin depth. With increasing permeability, the skin depth decreases, increasing loss. Of the metals listed above, only iron and nickel have significantly higher permeability. Iron by a factor of about 5000, and nickel by 100 to 600. You could compensate for the reduced skin depth by increasing the surface area of the conductor, but when you consider cost and mechanics, it usually makes more sense to simply avoid iron and nickel and alloys containing them.
|
output
| 1 | 156 |
Windows in its earliest days was simply a shell that ran on top of MS-DOS, which means that Windows 3.1 itself was actually just a standard MS-DOS application like any other.
Yet, MS-DOS is not a multitasking operating system, and at the same time, Windows applications were compiled native-code binaries that ran without any form of managed environment. So, how exactly was multitasking of Windows binaries achieved if Windows 3.1 was simply a regular old MS-DOS program itself? Are there any old technical documents still floating around that describe the early Windows architecture internally?
|
instruction
| 0 | 157 |
For Win16 programs, Windows implemented co-operative multitasking. Its implementation was based upon the "message loop" architecture of every Windows program.
The duty of every program was to endlessly run in a loop in which a call to the ```GetMessage``` function was performed. This function call looks whether a message to this process is in the queue. If there is one, it is retrieved (```GetMessage```), optionally translated (```TranslateMessage```, done to convert keyboard shortcuts into menu actions) and finally, passed to the window procedure (```DispatchMessage```).
If there is no message available in the queue, Windows suspends the current task and gives the CPU to another task. This task will try to retrieve a message from its queue as well, yielding the CPU to another task if no message is present and so on.
If a program needed to perform background tasks while there were no pending messages in its queue, it would call ```PeekMessage``` instead of ```GetMessage```. This didn't make the task relinquish the CPU, as ```PeekMessage``` would immediately return to the caller task to inform it whether a message is available or not. This was used to time-multiplex message processing with another time-consuming task (think of a 3D program rendering but letting the user cancel that render by pressing a "Cancel" button).
If this time-consuming task was actually very time-consuming, a well-behaved program should call the ```Yield``` function from time to time, to relinquish the CPU and let other tasks run. A badly-behaved program could easily hog the CPU by not retrieving messages too often or by spending too much time in a window procedure function.
The situation was quite different for MS-DOS boxes. They ran using the V8086 mode of the 80386 (if Windows was running in enhanced mode). Windows-aware programs ran in the so-called System VM (Virtual Machine 1). DOS boxes ran from VM 2 upwards. DOS programs usually were badly-behaved programs, so Windows assigned each DOS box a different virtual machine. Virtual machines used pre-emptive multitasking in Windows 3.1, so each DOS box could run concurrently to others and to any Windows-aware program.
|
output
| 1 | 157 |
I'm working on 2 different branches: release and development.
I noticed I still need to integrate some changes that were committed to the release branch back into the development branch.
The problem is I don't need all of the commit, only some hunks in certain files, so a simple
```git cherry-pick bc66559
```
does not do the trick.
When I do a
```git show bc66559
```
I can see the diff but don't really know a good way of applying that partially to my current working tree.
|
instruction
| 0 | 158 |
The core thing you're going to want here is ```git add -p``` (```-p``` is a synonym for ```--patch```). This provides an interactive way to add in content, letting you decide whether each hunk should go in or not, and even letting you manually edit the patch if necessary.
To use it in combination with cherry-pick:
```git cherry-pick -n # get your patch, but don't commit (-n = --no-commit)
git reset # unstage the changes from the cherry-picked commit
git add -p # make all your choices (add the changes you do want)
git commit # make the commit!
```
``git-cherry-pick``` has a ```--no-commit``` option, and you need to do ```git reset```. If you only want to leave a few things out of the commit, you could use ```git reset ...``` to unstage just those files.)
You can provide specific paths to ```add -p``` if necessary. If you're starting with a patch you could replace the ```cherry-pick``` with ```apply```.
If you really want to ```git cherry-pick -p ``` (that option does not exist), you can use
```git checkout -p
```
That will diff the current commit against the commit you specify, and allow you to apply hunks from that diff individually. This option may be more useful if the commit you're pulling in has merge conflicts in part of the commit you're not interested in. (Note, however, that ```checkout``` differs from ```cherry-pick```: ```checkout``` tries to apply ``````'s contents entirely, while ```cherry-pick``` applies the diff of the specified commit from it's parent. This means that ```checkout``` can apply more than just that commit, which might be more than you want.)
|
output
| 1 | 158 |
In Civilization V, you attain a cultural victory by accumulating enough culture to purchase at least 36 social policies, and then building a wonder. The catch is that the more cities you build, the more culture you need to generate before you hit the next "plateau" of culture.
What is the ideal number of cities for a cultural victory? Does it change over time?
|
instruction
| 0 | 159 |
The question you're really asking is "When does the combined culture / turn of an additional city outstrip the increase in social policy cost incurred by founding that city?"
The short answer is...
We know that adding another city increases the culture costs by approximately 30% of the base cost (that of 1 city). Therefore:
If your maximum potential culture / turn won't increase by at least 30% due to the new city, you are hurting, not helping, the time till your next social policy.
(This may be slightly hard to calculate, and if you take too long to reach your "maximum potential culture / turn" you're actually wasting turns.)
The long answer is...
It depends
To begin with, we need to make some assumptions:
* When you found a new city, you can get its culture / turn maximized within a single turn by buying the necessary building improvements (monument, etc).
* Ignore city-states, leader specific abilities, +culture social policies, and wonders. These all help produce culture, and will shift the "ideal city count" down, but do so inconsistently. To produce an "ideal" city count, we limit ourselves by era and improvements alone.
* This list of social policy costs is accurate for the given parameters: medium map and normal speed.
And now, some math.
The 1st social policy costs 25 points with a single city. In the ancient era, your cities can generate 2 culture / turn due to the monument. (Remember, we're ignoring the palace for now)
This means that it will take 13 turns (Ceiling(25/2) to enact the policy, or 9 turns (ceiling (45/4) with two cities. We can continue this extrapolation -- 8 turns with 3 cities, 7 turns with 4 cities, 6 turns with 5 cities, and we finally reach diminishing returns at city 6 (also 6 turns).
For the second social policy, the ramifications of the # of cities gets magnified due to a larger starting value: One city takes 23 turns, two cities take 15 turns, three cities take 13 turns, four cities take 12, five cities take 10, and again, we run into diminishing returns cap out at at six cities (10 turns).
It is not until the 4th social policy that this trend is broken and diminishing returns end at the NINTH! city.
Remember -- this assumes that each city has a monument the minute it is founded.
Now let's say we've reached the classical age, and have temples in addition to monuments. Each city is now generating 5 culture.
The first policy takes 5 turns with a single city, 4 turns with two, and 3 with three.
What (hopefully) becomes clear is that we reached diminishing returns (4 cities as opposed to 6 cities) much faster when each individual city's contribution is higher. The more culture any one city is capable of producing, the more incentive there is to produce more cities. Even if you don't manage to build every +culture improvement immediately, you're still likely to come out ahead (as long as you're pre-diminishing returns).
So while the optimal number of cities changes due to any number of factors, you can probably safely not shoot yourself in the foot if you stay between three and six cities, with six being on the high end.
|
output
| 1 | 159 |
How to find if a customer is logged in or not in Magento 2.
If the customer is logged in then how to get customer data from a session?
|
instruction
| 0 | 160 |
It is possible via ```Magento\Framework\App\Http\Context``` or via ```Magento\Customer\Model\Session```. However, the result may be different:
* HTTP context is initialized earlier than the customer session (but it does not matter since both are initialized in action controllers)
* When the ```PageCache``` module is on (probably always on production), keep in mind that as soon as layout generation started, the customer session will be cleared by ```\Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml``` on all cacheable pages. It means that if you now check if the customer is logged in via the HTTP context, it will still say 'yes, but customer data will not be available in customer sessions anymore. So double-check is necessary before trying to access data in customer sessions. This can easily happen in the block, while is unlikely in action controller since you are not expected to generate layout manually there, it will be generated after-action controller returns an instance of ```ResultInterface```
To eliminate any risk of described inconsistencies when PageCache is on, consider using customer session if it is already initialized (true for action controllers). Else use the HTTP context.
|
output
| 1 | 160 |
I have a 9 year old daughter that has expressed some interest in manga, but I'm having trouble locating series that are appropriate for her age. No one at our local bookstore could offer any advice. Is there a kid-friendly imprint or other resource I could use to help her find something appropriate? My preference is for physical books but I'm willing to explore digital options.
|
instruction
| 0 | 161 |
The content deemed acceptable for Japanese children generally differs from the concept in other countries; manga contains all genres of stories, so one cannot responsibly presume that just because a title was marketed at Japanese kids, that you would likewise consider it appropriate for your kid of the same age.
As one example:
The popular girl's series Sailor Moon was published in the manga magazine Nakayoshi, which was marketed toward elementary school-age girls (1st through 6th grade). This series includes strong language, bullying, violence, death, war, genocide, refugees, lovers' suicide (more than once), non-consensual kisses (forced while awake, while asleep, while drunk), a father fondling his adult daughter while brainwashed, human/animal romance, demonic-style alien possession of human bodies, nudity, cross-dressing, a non-monogamous lesbian couple, and non-graphic sex resulting in teen pregnancy (the 90s anime version, also marketed toward children, also added wrist/ankle restraints for a rape-like, pain-inducing entering of victims).
There are many manga reviews on the web, including those that specifically for parents and teen/preteen/kid readers on what sort of possibly objectionable content is included in the title (such as strong language, violence, nudity, gender-bending, innuendo, sexual content, etc.) and what sort of general content you can expect (for example: horror, potty humor, serious themes like depression/body image/sexual orientation/prostitution/parental abandonment/bullying/suicide) and let you as the parent or the reader use your own judgment about whether a title fits what you deem appropriate at what age. Browsing reviews also allows you to seek out titles that reinforce and contribute to your family's values (such as traits of selflessness, generosity, celebration of uniqueness, etc.).
Some good starting places are:
* A Parent's Guide to Anime
* Good Manga for Kids at Manga Bookshelf
* Good Comics for Kids at School Library Journal
* Kids Manga at No Flying No Tights
Since you have a daughter, she may be especially interested in shoujo manga, which was written with the target audience of Japanese girls. Within shoujo, nearly all genres of stories are included; some titles are very cheerful and innocuous and teach a moral-of-the-day, others are dark and heavy. Good starting places to get informed are:
* What is Shoujo Manga?, What Shoujo Manga Are and Are Not, and Recommended Shoujo Manga by Matt Thorn, a professor in the Faculty of Manga at Kyoto Seika University (one of the world's experts on shoujo manga)
* What is Shoujo? at Energetic Heartbeats
Some shoujo manga review sites are:
* The Classics at Shoujo Corner
* Emily's Random Shoujo Manga Page (despite its unassuming name, contains many detailed reviews)
* Heart of Manga
* Shoujo Savvy
* Shoujo Manga Recommendations
* Romance Manga Reviews
* Shoujo Manga Reviews
* Shoujo Manga with Anime at Anime Manga Reviews
More general review websites include MangaBlog and Kuriousity, and a Google search will find you many more.
|
output
| 1 | 161 |
I'm looking for a precise piece of information in a database which I have no knowledge about. The database is on a separate machine, but I can log into it, and launch a ```psql``` command line, with administrator rights.
It's a third-party product, and they are slow to answer questions. I know the data is inside that database, so I want to do a little bit of reverse-engineering.
Given a table name, is it possible to get a list of the names of the columns in that table?
For example, in SQL Server, it's possible to dump a table into a reusable ```CREATE``` statement, which textually lists all the columns the table is composed of.
|
instruction
| 0 | 162 |
The information schema is the slow and sure way: it is standardized and largely portable to other databases that support it. And it will keep working across major versions.
However, views in the information schema often join many tables from the system catalogs to meet a strictly standardized format - many of which are just dead freight most of the time. This makes them slow.
The Postgres developers aren't making promises, but basics (like what is needed here) aren't going to change across major versions.
More detailed assessment:
* Query to output names and data types of a query, table or view
```psql``` (the native command-line interface) takes the fast lane, of course, and queries the source directly. If you start ```psql``` with the parameter ```-E```, the SQL behind backslash commands like ```\d``` is displayed. Or ```\set ECHO_HIDDEN on``` from the psql command line. Starting from there you can build an answer to your question.
Given one table, is it possible to have a list of the names of the columns for this table.
```SELECT attrelid::regclass AS tbl
, attname AS col
, atttypid::regtype AS datatype
-- more attributes?
FROM pg_attribute
WHERE attrelid = 'myschema.mytable'::regclass -- table name optionally schema-qualified
AND attnum > 0
AND NOT attisdropped
ORDER BY attnum;
```
Faster than querying ```information_schema.columns```. Try ```EXPLAIN ANALYZE``` to see for yourself. Still hardly matters for a one-time look-up. But might make a difference if used in a query / function that's repeated many times.
There are also subtle differences in visibility. The following artical has detailed comparison:
* How to check if a table exists in a given schema
|
output
| 1 | 162 |
I am using Visual Studio Code and have a fairly common project structure:
```βββ client/
β βββ tsconfig.json
βββ shared/
βββ server/
β βββ tsconfig.json
βββ project.json
```
The two tsconfig files have different settings (e.g. the one under ```client/``` targets ES5, the one under ```server/``` targets ES6). Note that there is no tsconfig in the root directory.
The problem is that I want the shared directory to be included in both projects. I can't do this using tsconfig because the ```exclude``` option won't let me include a folder that is in a higher directory than the tsconfig.json, and using ```files``` I have to constantly keep the list of files up to date as it doesn't support globs.
Note that I can compile fine by adding the shared folder into tsc, what I want is for the Visual Studio Code IDE to recognise the shared code for intellisense etc.
Is the only option to wait for filesGlob?
|
instruction
| 0 | 163 |
These days it is much easier as vscode has better support for this.
You can use this directory structure so all the code is independent:
```βββ frontend/
β βββ src/
β β βββ
β βββ package.json
β βββ tsconfig.json
βββ shared/
β βββ package.json
βββ backend/
β βββ src/
β β βββ
β βββ package.json
β βββ tsconfig.json
```
Then in both the backend and frontend ```tsconfig.json```:
```{
"compilerOptions": {
"paths": {
"~shared/*": ["../shared/*"]
},
"rootDirs": [
"./src",
"../shared"
]
}
}
```
To allow access to the shared code e.g.:
```import { Foo } from '~shared/foo';
```
|
output
| 1 | 163 |
I have the following method to save an Object to a file:
```// Save an object out to the disk
public static void SerializeObject(this T toSerialize, String filename)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
TextWriter textWriter = new StreamWriter(filename);
xmlSerializer.Serialize(textWriter, toSerialize);
textWriter.Close();
}
```
I confess I did not write it (I only converted it to a extension method that took a type parameter).
Now I need it to give the xml back to me as a string (rather than save it to a file).
|
instruction
| 0 | 164 |
Use a `StringWriter` instead of a `StreamWriter`:
```
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
```
Note, it is important to use `toSerialize.GetType()` instead of `typeof(T)` in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of `T` (which are valid for the method), while using the latter one will fail when passing a type derived from `T`. There is some example code on Ideone that motivates this statement, with XmlSerializer throwing an `Exception` when `typeof(T)` is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class.
Also, Ideone uses Mono to execute code; the actual `Exception` you would get using the Microsoft .NET runtime has a different `Message` than the one shown on Ideone, but it fails just the same.
|
output
| 1 | 164 |
I have a problem with the embedded bitcode term.
What is embedded bitcode?
When to enable, ```ENABLE_BITCODE``` in new Xcode?
What happens to the binary when enabled, ```ENABLE_BITCODE``` in Xcode 7?
|
instruction
| 0 | 165 |
> What is embedded bitcode?
According to docs:
> Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
This phrase in "New Features in Xcode 7" made me to think for a long time that Bitcode is needed for Slicing to reduce app size:
When you archive for submission to the App Store, Xcode will compile your app into an intermediate representation. The App Store will then compile the bitcode down into the 64 or 32 bit executables as necessary.
However that's not true, Bitcode and Slicing work independently: Slicing is about reducing app size and generating app bundle variants, and Bitcode is about certain binary optimizations. I've verified this by checking included architectures in executables of non-bitcode apps and founding that they only include necessary ones.
Bitcode allows other App Thinning component called Slicing to generate app bundle variants with particular executables for particular architectures, e.g. iPhone 5S variant will include only arm64 executable, iPad Mini armv7 and so on.
> When to enable ENABLE_BITCODE in new Xcode?
For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS and tvOS apps, bitcode is required.
> What happens to the binary when ENABLE_BITCODE is enabled in the new Xcode?
From Xcode 7 reference:
> Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode.
|
output
| 1 | 165 |
In Dupire's local volatility model, the volatility is is a deterministic function of the underlying price and time, chosen to match observed European option prices.
To be more specific, given a smooth surface $(K,T)\mapsto C(K,T)$ where K is the strike and T is time to maturity. Dupire equation implies that there exits an unique continuous function $\sigma_{loc}$ defined by
$$\sigma_{loc}^{2}(K,T)=\frac{\partial_{T}C(K,T)+rK\partial_{K}C(K,T)}{\frac{1}{2}K^{2}\partial_{KK}C(K,T)}$$ for all $(K,T)\in(0,\infty)\times(0,\infty)$ such that the solution to the stochastic differential equation $dS_{t}/S_{t}=rdt+\sigma(t,S_{t})dW_{t}$ exactly generates the European call option prices.
What do the dynamics of the local volatility mean? Are dynamics equivalent to the volatility surface? Why the dynamics of local volatility model is highly unrealistic?
|
instruction
| 0 | 166 |
A general model (with continuous paths) can be written
$$
\frac{dS_t}{S_t} = r_t dt + \sigma_t dW_t^S
$$
where the short rate $r_t$ and spot volatility $\sigma_t$ are stochastic processes.
In the Black-Scholes model both $r$ and $\sigma$ are deterministic functions of time (even constant in the original model). This produces a flat smile for any expiry $T$. And we have the closed form formula for option prices
$$
C(t,S;T,K) = BS(S,T-t,K;\Sigma(T,K))
$$
where $BS$ is the BS formula and $\Sigma(T,K) = \sqrt{\frac{1}{T-t}\int_t^T \sigma(s)^2 ds}$. This is not consistent with the smile observed on the market. In order to match market prices, one needs to use a different volatility for each expiry and strike. This is the implied volatility surface $(T,K) \mapsto \Sigma(T,K)$.
In the local volatility model, rates are deterministic, instant volatility is stochastic but there is only one source of randomness
$$
\frac{dS_t}{S_t} = r(t) dt + \sigma_{Dup}(t,S_t) dW_t^S
$$
this is a special case of the general model with
$$
d\sigma_t = (\partial_t \sigma_{Dup}(t,S_t) + r(t)S_t\partial_S\sigma_{Dup}(t,S_t) + \frac{1}{2}S_t^2\partial_S^2\sigma_{Dup}(t,S_t)) dt + \frac{1}{2}S_t\partial_S\sigma_{Dup}(t,S_t)^2 dW_t^S
$$
What is appealing with this model is that the function $\sigma_{Dup}$ can be perfectly calibrated to match all market vanilla prices (and quite easily too).
The problem is that while correlated to the spot, statistical study show that the volatility also has its own source of randomness independent of that of the spot. Mathematically, this means the instant correlation between the spot and vol is not 1 contrary to what happens in the local volatility model.
This can be seen in several ways:
1. The forward smile. Forward implied volatility is implied from prices of forward start options: ignoring interest rates,
$$
C(t,S;T\to T+\theta,K) := E^Q[(\frac{S_{T+\theta}}{S_{T}}-K)_+] =: C_{BS}(S=1,\theta,K;\Sigma(t,S;T\to T+\theta,K))
$$
Alternatively, it is sometimes defined as the expectation of implied volatility at a forward date. In a LV model, as the maturity $T$ increases but $\theta$ is kept constant, the forward smile gets flatter and higher. This is not what we observe in the markets where the forward smile tends to be similar to the current smile.
This is because the initial smile you calibrate the model too has decreasing skew:
$$
\partial_K \Sigma(0,S;T,K) \xrightarrow[T\to +\infty]{} 0
$$
2. Smile rolling. In a LV model, smile tends to move in the opposite direction of the spot and get higher independently of the direction of the spot.
This is not consistent with what is observed on markets. See Hagan and al. Managing Smile Risk for the derivation. This means that
$\partial_S \Sigma_{LV}(t,S;T,K)$ often has the wrong sign so your Delta will be wrong which can lead to a higher hedging error than using BS.
3. Barrier options. In FX markets, barrier options like Double No Touch are liquid but a LV model calibrated to vanilla prices does not reproduce these prices. This is a consequence of the previous point.
The LV model is a static model. Its whole dynamic comes from the volatility surface at time 0. But the vol surface has a dynamic that is richer than that.
There are alternatives using multiple factors like SV models, LSV models (parametric local vol like SABR or fully non parametric local vol), models of the joint dynamic of the spot and vol surface etc... but the LV model remains the default model in many cases due to its simplicity, its ability to calibrate the initial smile perfectly and its numerical efficiency.
|
output
| 1 | 166 |
Can you explain why we need a large number of trees in random forest when the number of predictors is large? How can we determine the optimal number of trees?
|
instruction
| 0 | 167 |
Random forest uses bagging (picking a sample of observations rather than all of them) and random subspace method (picking a sample of features rather than all of them, in other words - attribute bagging) to grow a tree. If the number of observations is large, but the number of trees is too small, then some observations will be predicted only once or even not at all. If the number of predictors is large but the number of trees is too small, then some features can (theoretically) be missed in all subspaces used. Both cases results in the decrease of random forest predictive power. But the last is a rather extreme case, since the selection of subspace is performed at each node.
During classification the subspace dimensionality is $\sqrt{p}$ (rather small, $p$ is the total number of predictors) by default, but a tree contains many nodes. During regression the subspace dimensionality is $p/3$ (large enough) by default, though a tree contains fewer nodes. So the optimal number of trees in a random forest depends on the number of predictors only in extreme cases.
The official page of the algorithm states that random forest does not overfit, and you can use as much trees as you want. But Mark R. Segal (April 14 2004. "Machine Learning Benchmarks and Random Forest Regression." Center for Bioinformatics & Molecular Biostatistics) has found that it overfits for some noisy datasets. So to obtain optimal number you can try training random forest at a grid of ```ntree``` parameter (simple, but more CPU-consuming) or build one random forest with many trees with ```keep.inbag```, calculate out-of-bag (OOB) error rates for first $n$ trees (where $n$ changes from $1$ to ```ntree```) and plot OOB error rate vs. number of trees (more complex, but less CPU-consuming).
|
output
| 1 | 167 |
I believe artificial intelligence (AI) term is overused nowadays. For example, people see that something is self-moving and they call it AI, even if it's on autopilot (like cars or planes) or there is some simple algorithm behind it.
What are the minimum general requirements so that we can say something is AI?
|
instruction
| 0 | 168 |
It's true that the term has become a buzzword, and is now widely used to a point of confusion - however if you look at the definition provided by Stuart Russell and Peter Norvig, they write it as follows:
> We define AI as the study of agents that receive percepts from the environment and perform actions. Each such agent implements a function that maps percept sequences to actions, and we cover different ways to represent these functions, such as reactive agents, real-time planners, and decision-theoretic systems. We explain the role of learning as extending the reach of the designer into unknown environments, and we show how that role constrains agent design, favoring explicit knowledge representation and reasoning.
Artificial Intelligence: A Modern Approach - Stuart Russell and Peter Norvig
So the example you cite, "autopilot for cars/planes", is actually a (famous) form of AI as it has to use a form of knowledge representation to deal with unknown environments and circumstances. Ultimately, these systems also collect data so that the knowledge representation can be updated to deal with the new inputs that they have found. They do this with autopilot for cars all the time
To answer your question, for something to be considered as "having AI", it needs to be able to deal with unknown environments/circumstances in order to achieve its objective/goal, and render knowledge in a manner that provides for new learning/information to be added easily. There are many different types of well defined knowledge representation methods, ranging from the popular neural net, through to probabilistic models like bayesian networks (belief networks) - but fundamentally actions by the system must be derived from whichever representation of knowledge you choose for it to be considered as AI.
|
output
| 1 | 168 |
I have some questions regarding the usage and significance of the ```synchronized``` keyword.
* What is the significance of the ```synchronized``` keyword?
* When should methods be ```synchronized```?
* What does it mean programmatically and logically?
|
instruction
| 0 | 169 |
The ```synchronized``` keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:
> ```synchronized``` methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named ```foo```, you need to ensure that these threads access the variable in an atomic way. Without the ```synchronized``` keyword, your thread 1 may not see the change thread 2 made to ```foo```, or worse, it may only be half changed. This would not be what you logically expect.
Again, this is a non-trivial topic in Java. To learn more, explore topics about:
* Concurrency
* Java Memory Model
Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.
|
output
| 1 | 169 |
I am using the ```$http``` service of AngularJS to make an Ajax request.
How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?
|
instruction
| 0 | 170 |
This really depends on your specific use case, but a simple way would follow a pattern like this:
```
.controller('MainCtrl', function ( $scope, myService ) {
$scope.loading = true;
myService.get().then( function ( response ) {
$scope.items = response.data;
}, function ( response ) {
// TODO: handle the error somehow
}).finally(function() {
// called no matter success or failure
$scope.loading = false;
});
});
```
And then react to it in your template:
```
<div class="spinner" ng-show="loading"></div>
<div ng-repeat="item in items>{{item.name}}</div>
```
|
output
| 1 | 170 |
Let's say that we have a gaseous or liquidus compound (I don't know if elements or compounds make a difference, take this as a thought experiment), and we have a tungsten or steel block that's 5cm (or less, you choose) thick. Is there any physical method for that gas or liquid to pass through that thick heavy metal block (not by drilling etc.)?
|
instruction
| 0 | 171 |
Yes, some gases can diffuse into and through metal. It is the bane of the high-vacuum engineer's life. Hydrogen is the worst because it tends to dissociate into atoms at the surface and the nucleus, a single proton, can then leave its electron behind and wander through the metal lattice until it picks up another electron when it leaves.
For example Mu-metal, favoured for some applications, typically has to be annealed in hydrogen at high temperature. Once that is over, it can take weeks or months for the residual hydrogen to diffuse out of the metal before a high enough vacuum can be achieved and the work proceed.
A "virtual leak" occurs where a small bubble of gas is embedded in the material inside a vacuum chamber. The leak usually happens because a tiny hole exists for the gas to diffuse out through, but sometimes the "hole" is no more than an ultra-thin skin of metal (invisible to the frustrated technician) and the gas diffuses through it. These little horrors can keep going for months or even years and generally mean replacing suspected parts and pumping down over and over again until the dodgy one is finally stumbled on.
Helium is both monatomic and the physically smallest atom. It can diffuse more easily than any other neutral atom or molecule, making certain metal foils unsuitable as say gas-tight liners for airships. As noted in another answer, in quantity it can also affect the bulk properties of the metal.
On a more energetic scale, hydrogen and helium nuclei (protons and alpha particles) can pass through thin metal foils if fired with sufficient energy, and this has been used to establish the crystalline structures of some metals and alloys (where, for whatever reason, electrons were unsuitable).
Other gases have much larger atoms (neon and other noble gases) or molecules (nitrogen and other diatomic molecules, water and other hydrides), but they can still diffuse extremely slowly through some metals. This can limit the lifetime of some microchips. A related phenomenon occurs where there is a defect in the lattice at the surface, such as a grain boundary, and a gas atom attaches to it. Defects are sometimes quite mobile and can migrate through the lattice; the gas atom will stabilise the defect and may be able to hitch a ride.
Quantum processes such as tunnelling are not really relevant, as they work over distances smaller than the atomic wavelength, which in turn is typically far smaller than the thickness of any metal atom or foil. The probability of a gas atom tunnelling across is so infinitesimal as to be effectively zero.
|
output
| 1 | 171 |
Once, I boarded a plane, went to my designated seat and tried to put my bag in the overhead bin. However, it was full, and other adjacent overhead bins were full too. Because I had a seat next to the emergency exit, which I paid for, I had to hand over my bag to someone else in order to take off.
Do I have any rights over the overhead bin above my seat?
Could I ask the flight attendant to remove some of the bags to make room for me?
I cannot imagine that the bins were full because there was not enough space. I think this happened because some people were ignorant enough to bring more bags than is allowed inside the airplane instead of sending them to cargo. If this is the case why doesn't the airline enforce the bag limit inside the airplane?
|
instruction
| 0 | 172 |
You have no right to the bin above your seat. For those exit rows where you cannot put anything beneath the seat in front of you, flight attendants will generally try to help find some space somewhere for at least your small personal item, but any passenger may be required to check their bags rather than put them in the overhead bin.
It is entirely possible that the airline didn't enforce the bag limit, but the overhead bins can easily fill up even when the limit is strictly enforced. If every passenger, or even most passengers, brings a regulation sized carry-on on a full flight, it is obvious that many of the bags will not fit in the bins and will have to be checked.
In some cases, overhead bins may be marked as reserved for first class or premium economy passengers (or safety equipment, or pillows and blankets). Even in such cases, cabin crew may fill these bins with other bags in an attempt to accommodate as many passengers as possible, and a late-boarding passenger may be caught out with no space.
It is hard to imagine that they are likely to remove and check someone's bag so you may have that space. Overhead bin space is typically first-come first served, and at some point, they will declare the bins full and start checking bags (sometimes even before the bins are actually full). Note that if your bag must be checked, you should ensure you remove any essential items (medication, passports, keys, etc...) and any valuables, along with any hazardous material that cannot be checked, namely spare (uninstalled) lithium batteries including external power packs.
Boarding as early as possible (which, on some airlines, could require frequent flyer status or paying an extra fee) will help secure you overhead bin space.
|
output
| 1 | 172 |
The Canon EF 40mm f/2.8 has a designation of STM on the lens. What does this mean? What are the advantages of having it and does it replace an older technology?
|
instruction
| 0 | 173 |
STM stands for Stepper Motor and is a applied to a new range of Canon lenses which feature a new design of focus motors which, along with a new iris mechanism are designed to eliminate (auditory) noise during video recording.
Canon haven't revealed any information about how the new design works but it's probably the same type of motor used in mirrorless camera lenses. It's a more precise version of a regular DC motor but still has the same direct connection to the lens focus group, which means manual focus has to be implemented using a focus-by-wire arrangement whereby moving the focus ring by hand sends a signal to the motor to move the focus group.
In comparison an ultrasonic motor (like Canon's USM) consists of a pair of concentric rings which vibrate at high frequency to rotate back and forth, an arrangement which permits the user to move the focus ring to directly move the lens element, achieving full time manual focus without damaging the motor.
Stepper motors are better at producing smooth, precise incremental movements, such as those required by contrast detect AF, and AF during video. Ultrasonic motors are better at jumping to the right focus point as part of a phase detection system.
|
output
| 1 | 173 |
I'm trying to set get id of all elements in an ```HTMLCollectionOf```. I wrote the following code:
```var list = document.getElementsByClassName("events");
console.log(list[0].id);
for (key in list) {
console.log(key.id);
}
```
But I got the following output in console:
```event1
undefined
```
which is not what I expected. Why is the second console output ```undefined``` but the first console output is ```event1```?
|
instruction
| 0 | 174 |
You can't use ```for```/```in``` on ```NodeList```s or ```HTMLCollection```s. However, you can use some ```Array.prototype``` methods, as long as you ```.call()``` them and pass in the ```NodeList``` or ```HTMLCollection``` as ```this```.
So consider the following as an alternative to jfriend00's ```for``` loop:
```var list= document.getElementsByClassName("events");
[].forEach.call(list, function(el) {
console.log(el.id);
});
```
There's a good article on MDN that covers this technique. Note their warning about browser compatibility though:
[...] passing a host object (like a ```NodeList```) as
```this``` to a native method (such as ```forEach```) is not guaranteed to work in
all browsers and is known to fail in some.
So while this approach is convenient, a ```for``` loop may be the most browser-compatible solution.
Update (Aug 30, 2014): Eventually you'll be able to use ES6 ```for```/```of```!
```var list = document.getElementsByClassName("events");
for (const el of list)
console.log(el.id);
```
It's already supported in recent versions of Chrome and Firefox.
|
output
| 1 | 174 |
I am 21 years old and living in a large city in Germany where smalltalk in local markets is not a common thing.
A new cashier joined my local food shop. Sheβs always at the checkout and never doing stuff like sorting products or cleaning the floor where I could actually ask her out. I am quite new to relationships, but the signs she gave me are promising.
My question is how I can ask for her number, or ask her out for coffee while she is only sitting at the checkout? I mean there are always like 5 people before and after me, and I think it would be awkward if we are changing numbers while customers are waiting behind us. Or even worse if I read the signs wrong and she rejects me? Since the store is just 5 min away from my place I visit regularly and don't want to leave a bad impression there.
|
instruction
| 0 | 175 |
Asking her out directly seems like a bad idea.
Instead, in these situations, I've found something that works much better for both of you. During your conversation with her, mention some place you're planning to be in the future so she can find you there if she chooses.
For example: "I like to grab lunch here before going to [Public Event You Enjoy]"
This could be almost anything, but here are some examples:
* A place your band plays
* A public dance
* A painting/pottery class
* A wine tasting
This should be something you actually enjoy, so be sure to let your excitement about your hobby be apparent when you mention it. Ex: "I enjoy that they let you try lots of different wines from all around the world!"
If she expresses interest in the activity as well, tell her more about it so she can attend: "Yeah, it's really fun. They do it every Tuesday and Thursday at 7pm - the admission fee is 5 Euro. You should check it out sometime!"
If she is interested in you and has time, she will probably arrange to come to the event some time and you will see her there. This is preferable because she is not under obligation to behave professionally for her work and you can spend some time chatting as equals.
And if that goes well, then you have created a good opportunity to ask her on a real date. And if she doesn't come, well, you were planning to go there anyways so it's not a real loss on your part - you just spent an afternoon/evening doing something you already enjoy.
|
output
| 1 | 175 |
You start with the number 1536. Your mission is to get to 1 in as few steps as possible. At each step, you may either multiply or divide the number you have, by either 2 or 3; but, only if the result is a whole number whose first digit is 1, 3, 4, or 9. That is all.
|
instruction
| 0 | 176 |
As Jo has already shown, this can be accomplished in
28 steps. This is minimal, and it can be proven.
To help visualize this problem, we can imagine:
A two-dimensional grid/chart where each point is a number of the form $3^x2^y$, with $(x,y)$ as the relevant co-ordinates. We want to find a path from $(1,9)$ to $(0,0)$ while making only one step up/down/left/right at a time, and ensuring that the numbers we step on have their most significant digit in the set {1,3,4,9}.
Here is what the chart looks like for the range $(0,0)$ to $(10,10)$. The dashes represent numbers that do not begin with {1,3,4,9}, and so are unusable in our path.
```1024 3072 9216 ---- ---- ---- ---- ---- ---- ---- ---- .```
```---- 1536 4608 13824 41472 124416 373248 1119744 3359232 10077696 30233088 .```
```---- ---- ---- ---- ---- ---- 186624 ---- 1679616 ---- 15116544 .```
```128 384 1152 3456 10368 31104 93312 ---- ---- ---- ---- .```
```---- 192 ---- 1728 ---- 15552 46656 139968 419904 1259712 3779136 .```
```32 96 ---- ---- ---- ---- ---- ---- ---- ---- 1889568 .```
```16 48 144 432 1296 3888 11664 34992 104976 314928 944784 .```
```---- ---- ---- ---- ---- 1944 ---- 17496 ---- 157464 472392 .```
```4 12 36 108 324 972 ---- ---- ---- ---- ---- .```
```---- ---- 18 ---- 162 486 1458 4374 13122 39366 118098 .```
```1 3 9 ---- ---- ---- ---- ---- ---- 19683 ---- .```
From here, we can see two different routes of 28 steps each: (1536->373248->93312->384->48->3888->972->36->9->1) and (1536->373248->46656->3779136->944784->3888->972->36->9->1).
Proving minimality:
Since a path of length 28 exists (we've found two), we can rule out anything that's too far away to be used in a shortest path.
Moving from (1,9) to (0,0) must take at least ten steps on its own, so we can move at most nine steps completely out of the way (and nine steps back) in a shortest route. That limits us to only considering x-coordinates up to 10; any further would require making at least ten '*3' steps, eleven 'Γ·3' steps, and at least nine 'Γ·2' steps, putting the route definitely longer than 28.
With our x-coordinate limited to [0,10], we now look at the bottlenecks.
It should be clear that any shortest route must start by going from 1536 to 93312 in seven steps, and must end by going from 3888 to 1 in nine steps. These are both forced by unique bottlenecks; there is only one way to step from $(x,7)$ to $(x,6)$ and only one way to step from $(x,3)$ to $(x,2)$ in this range.
This leaves at most twelve steps to go from 93312 to 3888. Either by observation or by pointing out that there are only two ways to go from $(x,6)$ to $(x,5)$, we can see that there are exactly two shortest routes from 93312 to 3888, and both require all twelve steps.
Therefore, the shortest route is 28 steps, and there are exactly two ways to do so, both of which are described in Jo's solution and below the chart.
|
output
| 1 | 176 |
I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 = ```var oImg = document.createElement("img"); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); ``` Is this the simplest but most robust (error free) way to do it?
|
instruction
| 0 | 177 |
```oImg.setAttribute('width', '1px');
```
```px``` is for CSS only. Use either:
```oImg.width = '1';
```
to set a width through HTML, or:
```oImg.style.width = '1px';
```
to set it through CSS.
Note that old versions of IE don't create a proper image with ```document.createElement()```, and old versions of KHTML don't create a proper DOM Node with ```new Image()```, so if you want to be fully backwards compatible use something like:
```// IEWIN boolean previously sniffed through eg. conditional comments
function img_create(src, alt, title) {
var img = IEWIN ? new Image() : document.createElement('img');
img.src = src;
if ( alt != null ) img.alt = alt;
if ( title != null ) img.title = title;
return img;
}
```
Also be slightly wary of ```document.body.appendChild``` if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the `````` element has started), you could try inserting it at the start of the body using ```body.insertBefore(body.firstChild)```.
To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page `````` as the body's first child and put any tracking/preload images you don't want to be visible in there.
|
output
| 1 | 177 |
Why is %s better than + for concatenation in python?
|
instruction
| 0 | 178 |
There are several benefits of using ```%s``` over ```+``` for string concatenation in Python:
* Readability. The format string syntax is more readable, as it separates style from the data. Also, in Python, ```%s``` syntax will automatically coerce any non ```str``` types to ```str```; while concatenation only works with ```str```, and you can't concatenate ```str``` with ```int```.
* Performance. In Python ```str``` is immutable, so the left and right string have to be copied into the new string for every pair of concatenation. If you concatenate four strings of length 10, you will be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters, instead of just 40 characters. And things gets quadratically worse as the number and size of the string increases. Java optimizes this case some of the times by transforming the series of concatenation to use ```StringBuilder```, but CPython doesn't.
* For some use cases, the logging library provide an API that uses format string to create the log entry string lazily (```logging.info("blah: %s", 4)```). This is great for improved performance if the logging library decided that the current log entry will be discarded by a log filter, so it doesn't need to format the string.
|
output
| 1 | 178 |
I had an interview with an employer working on a software-based vehicle solution.
Before going further in the interview process, he gave me a task to find out if a potential customer (automotive OEMs) is interested.
My question is, how can I approach a potential customer and arrange some time together to present to them the solution?. I'm intending to use Linkedin, but I'm not sure how to proceed.
* Who to contact (I mean the person position in the company)
* How to formulate the request?
|
instruction
| 0 | 179 |
Run (and run fast) - here are just a few points to consider:
* That's a very unorthodox task for somebody still in the interviewing stage.
* How you going to present a solution you aren't familiar with?
* Since you aren't an employee of said company yet you have no grounds to represent them or even hustle their products.
* You aren't on their payroll yet so why should you waste your time looking for customers?
* There are a bunch of legal issues arising from such a 'task' (think NDA etc..).
* How will your potential employer determine if your task has been carried out successfully?
* Any CEO/CTO or even higher management of any automotive company will NOT engage in such a conversation with a random stranger.
* Such an unprofessional approach is extremely disrespectful of the prospective customer's time.
These are all major red flags and should lead any mentally sane person to the conclusion that the person asked for such tasks is unreasonable and has no clue about business in general.
Additionally - what kind of impression do you think they will have of you or your potential, future employer considering the above mentioned points?
Thank them for their time and continue applying elsewhere because this company is a nut-house.
|
output
| 1 | 179 |
When an expendable booster rocket stage nears the end of its burn, does the guidance computer shut the engine(s) off at a certain velocity/altitude for the mission, or does the stage completely exhaust its propellants?
|
instruction
| 0 | 180 |
First stages are generally run to depletion (though not complete depletion). First stage ascents often use a preprogrammed, open loop guidance system to get out of the atmosphere with a good chunk of downrange velocity. Because winds aloft and other factors may vary, first stage performance also varies somewhat.
Upper stage guidance is almost always closed loop, targeting a specific position and velocity combination. As a result, upper stages of boosters are shut down when that target is reached, with some amount of reserve propellants left to cover dispersions during ascent and a disposal burn.
Liquid fueled first stages are not run dry. Cutoff is triggered with some amount left in the tank. This is because the turbopumps operate at ridiculous velocities and need something to pump, at a specific inlet pressure. The heat source (gas generator, expander, or preburner) that drives the pump is downstream of the inlet in the flow path, so cutoff has to happen by cutting off the drive force to the pump before the inlet loses pressure or runs dry.
If that pressure drops below minimum specifications or if the inlet goes dry, you will get cavitation and/or overspeed conditions, both of which would result in a violent reconfiguration of the hardware.
Solid lower stages are much simpler in this regard. At some point, the thrust will tail off until the booster no longer supports its own weight. At that point, it is jettisoned.
|
output
| 1 | 180 |
Is "ima" an informal spelling of "I must"?
MegaCharizardZord Replying to @nytimes about COVID-19 vaccine:
i just hope when i take it don't die lol. i trust the government in Canada, but if I do get something ima sue the shit out of em lol.
Source: Twitter
|
instruction
| 0 | 181 |
Ima is an informal contraction of I'm going to when it's used in going-to future construction - not in sentences like I'm going to London etc. It's also written i'ma or imma in informal conversations.
How did I'm going to come to be pronounced/spelt that way?
In casual speech, we tend to drop consonants that require more effort to articulate, assimilate nearby consonants, drop weak vowels etc., for the ease of articulation. Grammatical words that don't have any meaning on their own (function words?) like have to, going to (not present continuous), has, is, was, will etc., are highly susceptible to these sound changes. For instance, have to is often pronounced hafta, trying to is pronounced tryna, want to is wanna etc etc. The same thing happened to the phrase I'm going to.
There are a few processes involved in the reduction of I'm going to to ima.
* I'm going to β I'm gonna: the consonant t is often dropped in many other clusters and grammatical constructions as well (as in tryna, wanna etc). Here it's dropped and the vowel of toβwhich is usually a schwa [Ι]βis linked with the preceding word; going to β gonna: [ΛΙ‘ΙΚΙͺΜΕtΙ] β [ΛgΙΜnΙ]
* Deletion of the /g/: plosives (/g t d k/ etc) require great effort to articulate (the air is completely blocked and then released), so people dropped the plosive /g/ to make its articulation easier: [aΙͺΜm gΙΜnΙ] β [aΙͺΜm ΙΜnΙ] (i'm ana)
* linking I'm and gonna: In causal and connected speech, consonants and vowels are often linked by a process called liaison, so both I'm and gonna join together and become [aΙͺΜmΙΜnΙ] (i'mana).
* Syncope of the vowel in the second syllable: Unstressed schwas are often lost through syncope (for example, 'chocolate' is choc.late for most speakers). If we removed the schwa from the second syllable, we'd get [aΙͺmnΙ] (i'mna).
* Deletion of /n/: It's simple cluster reduction. In English, two nasals that are next to each other are often reduced to a single nasal (as in damn), so the /n/ is deleted, yielding in this case [aΙͺΜmΙ] (i'ma). Or people dropped the /n/ for the sake of ease.
Some people further reduce the diphthong [aΙͺ] it to something like [a], which results in [aΜmΙ] (ama)
That's why people spell it that way. It's highly informal and as TypeIA pointed out in a comment, it's mostly a verbal thing and is not usually found in written form. It's commonly found in chatspeak or lolspeak. You shouldn't write it in any kind of writing.
|
output
| 1 | 181 |
How to prevent "Delhi Belly" from eating/drinking locally?
|
instruction
| 0 | 182 |
Basically, you can't.
The world is full of gastrointestinal (GI) diseases, even in developed, First World nations. There are some decent steps to trying to minimize your exposure:
* Properly cooked foods. Everything heated to a proper internal temperature (depends on the dish, check the USDA's site for guidelines), no sampling the raw chicken dish, etc.
* For fruits and veg, if you can't peel it, don't eat it. A tremendous number of GI outbreaks are due to fruit and veg, rather than meat. This includes things like salads - since you can't really peel lettuce, avoid it.
* Check if the local water is safe. When in doubt, assume it isn't. You can stick to bottled water, though there's always the distinct chance its being bottled from a contaminated source. Coke/Pepsi etc., and beer are good alternatives. Little known fact, the Coca-Cola company is hugely involved in clean water programs worldwide, because they need it for their product.
* Ice. Ice is bad. Its probably made using the local tap-water, and there are many beasties that can survive an encounter with an ice machine.
But when it comes down to it, nearly every traveller makes some sort of safe-eating "mistake" fairly frequently, whether they realize it or not. At the end of the day, your best bet is to talk to your travel physician, and see if you can get a prescription for an antibiotic. Using that in combination with something like Imodium will probably keep your trip mostly on track - shutting down the problem long enough for the antibiotics to treat the source. Unless of course its viral - norovirus, rotavirus etc. In that event, best of luck.
And if it does happen? Stay hydrated. You're losing salts and water, they need to be replaced.
|
output
| 1 | 182 |
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.
What can I do to impress him?
Thank you.
|
instruction
| 0 | 183 |
Remember the scene in Aladdin where Aladdin wants to impress Jasmine, and the genie tells him he'd do better to just focus on being himself? Same principle here.
If the boss is that much better than you and you know it, he probably knows it too. He isn't expecting any great feats of programming rock-stardom out of you. Since this is your first job, he most likely hired you because he saw the potential to become a good coder in you. So if you really want to impress him, learn. Learn the language, learn the system you're working on, learn the ins and outs and dark corners. Focus on learning correct principles, learning them well and learning them quickly, in that order.
And remember that part of learning is copying knowledge that other people already have. Don't be afraid to ask questions, either of your coworkers or on StackOverflow, or research things on Google. Whatever you do, don't pretend you know something when you really don't, in an effort to avoid seeming dumb. Any good developer will notice quickly, and that will make you look even stupider in their eyes. Humility tends to still be considered a virtue among engineers.
Do a good job at that and it'll impress the boss.
|
output
| 1 | 183 |
Can I pass variables to a GNU Makefile as command line arguments? In other words, I want to pass some arguments which will eventually become variables in the Makefile.
|
instruction
| 0 | 184 |
You have several options to set up variables from outside your makefile:
* From environment - each environment variable is transformed into a makefile variable with the same name and value.
You may also want to set ```-e``` option (aka ```--environments-override```) on, and your environment variables will override assignments made into makefile (unless these assignments themselves use the ```override``` directive . However, it's not recommended, and it's much better and flexible to use ```?=``` assignment (the conditional variable assignment operator, it only has an effect if the variable is not yet defined):
```FOO?=default_value_if_not_set_in_environment
```
Note that certain variables are not inherited from environment:
* ```MAKE``` is gotten from name of the script
* ```SHELL``` is either set within a makefile, or defaults to ```/bin/sh``` (rationale: commands are specified within the makefile, and they're shell-specific).
* From command line - ```make``` can take variable assignments as part of his command line, mingled with targets:
```make target FOO=bar
```
But then all assignments to ```FOO``` variable within the makefile will be ignored unless you use the ```override``` directive in assignment. (The effect is the same as with ```-e``` option for environment variables).
* Exporting from the parent Make - if you call Make from a Makefile, you usually shouldn't explicitly write variable assignments like this:
```# Don't do this!
target:
$(MAKE) -C target CC=$(CC) CFLAGS=$(CFLAGS)
```
Instead, better solution might be to export these variables. Exporting a variable makes it into the environment of every shell invocation, and Make calls from these commands pick these environment variable as specified above.
```# Do like this
CFLAGS=-g
export CFLAGS
target:
$(MAKE) -C target
```
You can also export all variables by using ```export``` without arguments.
|
output
| 1 | 184 |
I have noticed that some games quote the requirement for "pixel shader 3.0 or better".
What is a pixel shader and is it some software requirements or hardware requirements?
|
instruction
| 0 | 185 |
Simple answer
Pixel shaders are tiny programs that can do operations on a single pixel on the screen, as opposed to geometry shaders and vertex shaders which work on the geometrical primitives (triangles) that make up everything you see on the screen. The most common use for pixel shaders is 'shading', approximation to real world lighting. Commonly used shading model is Phong.
Pixel shaders are executed on your video card, so your video card needs to support them. Each new version provides more capabilities, so an older video card will not run newer shaders. A new version of the pixel shader specification (e.g. Pixel Shader 3.0) is usually released for each new version of DirectX (more accurately, Direct3D).
Software Requirements
You need to have the correct version of Direct3D (or OpenGL) installed in order to use the shaders. For example, Pixel Shader 4.0 requires at least Direct3D 10. Normally you don't have to worry about this, every game that uses Direct3D will install the correct version for you when you install the game. The only exceptions are Direct3D 10 and later, which will not run on Windows XP or earlier. You will need at least Windows Vista in order to play a game that uses Direct3D 10 or 11.
Wikipedia provides a nice list of Pixel Shader versions, the version of Direct3D you need, and the types of graphics cards that work with them.
Technical answer
The 'standard' stages of a 3D rendering pipeline are as follows (somewhat simplified):
* Transformation (Moving, rotating and scaling all the objects in the scene)
* Lighting
* Projection ('Squashing' the 3D world into a 2D plane)
* Clipping (Removing anything outside the field of view)
* Rasterising (Converting the vector graphics (triangles, etc) into raster graphics (pixels))
* Texturing
* Display
Pixel Shaders are used as an alternative to the standard texturing phase. During rasterisation, each triangle is converted into pixels. These pixels do not have their final colour yet, but the do have a bunch of parameters associated with them. These include base colour, texture coordinates, lighting information, etc. The Pixel Shader is a small program that takes these parameters and uses them to calculate the final colour as it is displayed on the screen. The Pixel Shader has access to all texture data, and can use them to do interesting things such as blending two textures (to create a 'dirty' look), using a texture as a bump map (to simulate a relief), or to simulate reflections.
Hardware
On the hardware side, Pixel Shaders are executed on 'Shader Units', small processors on your GPU. Each Shader Unit is basically a very simple CPU, but a modern video card may contain thousands of these things (an AMD Radeon HD6990 contains over 3000). Older GPUs had different Shader Units for different tasks: Pixel Shaders were executed on different parts of the system than Vertex Shaders. Modern GPUs have so called 'unified shader units' which can perform all of these operations.
|
output
| 1 | 185 |
Red light facing forwards? It was nighttime in Manhattan. Isn't more always better when it comes to being seen?
|
instruction
| 0 | 186 |
No. You should always ride with a white light facing forward and a red light facing backwards. If you want additional illumination, you can add multiple white/red lights in the appropriate direction. Amber/yellow lights can be used facing any direction for additional visibility.
The first reason is that it's the law:
(a) Every bicycle when in use during the period from one-half hour after sunset to one-half hour before sunrise shall be equipped with a lamp on the front which shall emit a white light visible during hours of darkness from a distance of at least five hundred feet to the front and with a red or amber light visible to the rear for three hundred feet. Effective July first, nineteen hundred seventy-six, at least one of these lights shall be visible for two hundred feet from each side.
More importantly for your safety though, the color of a light conveys a certain meaning. Drivers, pedestrians, and other cyclists associate the color red with a taillight and the color white with a headlight. If you put the wrong color facing the wrong direction, people may think you are traveling the opposite direction. Imagine a car is pulling out of a driveway and sees a red bike light flashing to their left. They may assume that means a bike is moving away from them on the left. If they then pull out of the driveway and you're really moving towards them, you could get hit.
|
output
| 1 | 186 |
If water is not a good conductor, why are we advised to avoid water near electricity (no wet hands near circuits etc.)?
|
instruction
| 0 | 187 |
"Pure" water is a very poor conductor (resistivity is actually used as a measure of purity).
"Real" water is not pure - it contains electrolytes and is quite conductive. Also - when your skin is wet, its resistivity is significantly lower.
For example - "pure" water has a resistivity of (about) 18.2 M$\Omega\cdot\rm{cm}$. With 10 ppm of dissolved NaCl ("very good quality tap water" would have less than 50 ppm), the resistivity drops to about $43~\rm{k\Omega\cdot cm}$
A lot of detail can be found in "Conduction of Electrical Current to and Through the Human Body: A Review" (Fish and Geddes, ePlasty 2009, 9, e44).
> Why immersion in water can be fatal with very low voltages
* Immersion wets the skin very effectively and great lowers skin resistance per unit area
* Contact area is a large percentage of the entire body surface area
* Electric current may also enter the body through mucous membranes, such as the mouth and throat
* The human body is very sensitive to electricity. Very small amounts of current can cause loss of ability to swim, respiratory arrest and cardiac arrest
|
output
| 1 | 187 |
What is the difference between cohesion and coupling?
How can coupling and cohesion lead to either good or poor software design?
What are some examples that outline the difference between the two, and their impact on overall code quality?
|
instruction
| 0 | 188 |
Cohesion refers to what the class (or module) can do. Low cohesion would mean that the class does a great variety of actions - it is broad, unfocused on what it should do. High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.
Example of Low Cohesion:
```-------------------
| Staff |
-------------------
| checkEmail() |
| sendEmail() |
| emailValidate() |
| PrintLetter() |
-------------------
```
Example of High Cohesion:
```----------------------------
| Staff |
----------------------------
| -salary |
| -emailAddr |
----------------------------
| setSalary(newSalary) |
| getSalary() |
| setEmailAddr(newEmail) |
| getEmailAddr() |
----------------------------
```
As for coupling, it refers to how related or dependent two classes/modules are toward each other. For low coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.
Good software design has ***high cohesion*** and ***low coupling***.
|
output
| 1 | 188 |
Can Romex (NM-B) cable be run through conduit?
|
instruction
| 0 | 189 |
Yes, NM (Romex) cable can be in conduit. In fact, National Electrical Code (NEC() calls for it to be in conduit, when protection from physical damage is required. But it really isn't worth it.
## It's a nightmare to pull
NM (Romex) is already solid wire except in the large sizes, and now you have 3-4 wires bound together. You are trying to pull this around maybe 14" radius elbows, and if the NM gets twists in it (it always does), it really drags in those places. It's just a stiff, miserable pull - enough to "put you off conduit forever" - which is a shame, because conduit is wonderful when using easy-to-pull stranded wire.
Pulling this stiff cable increases the risk of damaging the cable. What's more, "cable in conduit" is often a newbie who chooses cable simply because he is unaware that wire comes in any other forms. Which leads to more risk of damage still.
## It requires ridiculously large conduit
You still have to calculate and respect conduit fill rules, and those are very punishing toward cable. Most cable is oblong, and the rules say you use the largest dimension and treat it as a circular wire of that dimension.
* For a single "wire", you are allowed 53% conduit fill. That means the conduit ID must be at least 137% of the large cross-section of the cable. That's not so bad, but...
* For two "wires", you're only allowed 31% fill. That's to protect the wires from binding. That means the conduit ID must be at least 2.54 times the cable large dimension.
* For three "wires", you're allowed 40% fill. That means the conduit must be at least 2.74 times the cable width (at 3 wires), larger for more wires.
For instance, someone wanted to squeeze three #6 cables through a 1" conduit. Now this is "easy peasy" with 6 individual #6 THHN wires and 3 bare #10 grounds. However, with three #6 UF cables, the conduit size needed to be 3" instead of 1". Whoa.
You are certainly allowed to do it, but you will be using rather enormous conduit, and you will have a hard time pulling.
|
output
| 1 | 189 |
Let's say I have a function which takes an ```std::function```:
```void callFunction(std::function x)
{
x();
}
```
Should I pass ```x``` by const-reference instead?:
```void callFunction(const std::function& x)
{
x();
}
```
Does the answer to this question change depending on what the function does with it? For example if it is a class member function or constructor which stores or initializes the ```std::function``` into a member variable.
|
instruction
| 0 | 190 |
If you want performance, pass by value if you are storing it.
Suppose you have a function called "run this in the UI thread".
```std::future run_in_ui_thread( std::function )
```
which runs some code in the "ui" thread, then signals the ```future``` when done. (Useful in UI frameworks where the UI thread is where you are supposed to mess with UI elements)
We have two signatures we are considering:
```std::future run_in_ui_thread( std::function ) // (A)
std::future run_in_ui_thread( std::function const& ) // (B)
```
Now, we are likely to use these as follows:
```run_in_ui_thread( [=]{
// code goes here
} ).wait();
```
which will create an anonymous closure (a lambda), construct a ```std::function``` out of it, pass it to the ```run_in_ui_thread``` function, then wait for it to finish running in the main thread.
In case (A), the ```std::function``` is directly constructed from our lambda, which is then used within the ```run_in_ui_thread```. The lambda is ```move```d into the ```std::function```, so any movable state is efficiently carried into it.
In the second case, a temporary ```std::function``` is created, the lambda is ```move```d into it, then that temporary ```std::function``` is used by reference within the ```run_in_ui_thread```.
So far, so good -- the two of them perform identically. Except the ```run_in_ui_thread``` is going to make a copy of its function argument to send to the ui thread to execute! (it will return before it is done with it, so it cannot just use a reference to it). For case (A), we simply ```move``` the ```std::function``` into its long-term storage. In case (B), we are forced to copy the ```std::function```.
That store makes passing by value more optimal. If there is any possibility you are storing a copy of the ```std::function```, pass by value. Otherwise, either way is roughly equivalent: the only downside to by-value is if you are taking the same bulky ```std::function``` and having one sub method after another use it. Barring that, a ```move``` will be as efficient as a ```const&```.
Now, there are some other differences between the two that mostly kick in if we have persistent state within the ```std::function```.
Assume that the ```std::function``` stores some object with a ```operator() const```, but it also has some ```mutable``` data members which it modifies (how rude!).
In the ```std::function const&``` case, the ```mutable``` data members modified will propagate out of the function call. In the ```std::function``` case, they won't.
This is a relatively strange corner case.
You want to treat ```std::function``` like you would any other possibly heavy-weight, cheaply movable type. Moving is cheap, copying can be expensive.
|
output
| 1 | 190 |
I have an Eloquent model which has a related model:
```public function option() {
return $this->hasOne('RepairOption', 'repair_item_id');
}
public function setOptionArrayAttribute($values)
{
$this->option->update($values);
}
```
When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not.
So I need to check if the related model exists, to either update it, or create it, respectively:
```$model = RepairItem::find($id);
if (Input::has('option')) {
if () {
$option = new RepairOption(Input::get('option'));
$option->repairItem()->associate($model);
$option->save();
$model->fill(Input::except('option');
} else {
$model->update(Input::all());
}
};
```
Where `````` is the code I am looking for.
|
instruction
| 0 | 191 |
A Relation object passes unknown method calls through to an Eloquent query Builder, which is set up to only select the related objects. That Builder in turn passes unknown method calls through to its underlying query Builder.
This means you can use the ```exists()``` or ```count()``` methods directly from a relation object:
```$model->relation()->exists(); // bool: true if there is at least one row
$model->relation()->count(); // int: number of related rows
```
Note the parentheses after ```relation```: ```->relation()``` is a function call (getting the relation object), as opposed to ```->relation``` which a magic property getter set up for you by Laravel (getting the related object/objects).
Using the ```count``` method on the relation object (that is, using the parentheses) will be much faster than doing ```$model->relation->count()``` or ```count($model->relation)``` (unless the relation has already been eager-loaded) since it runs a count query rather than pulling all of the data for any related objects from the database, just to count them. Likewise, using ```exists``` doesn't need to pull model data either.
Both ```exists()``` and ```count()``` work on all relation types I've tried, so at least ```belongsTo```, ```hasOne```, ```hasMany```, and ```belongsToMany```.
|
output
| 1 | 191 |
NASA is hiring a new 'planetary protection officer' to defend Earth from alien matter, and the pay is a six-figure salary: as much as $187,000 a year.
When we are not sure whether aliens exist, why are we still hiring staff for protecting Earth? I do understand we have to take precautions. But when we don't have any proof why spend $187,000 a year?
Source: Nasa [sic] hiring new 'planetary protection officer' to defend Earth from alien matter - Times of India, Aug 3, 2017
|
instruction
| 0 | 192 |
You're observing shamefully bad journalism. The "protect Earth from aliens" bullet point in the "Highlights" section of the article was put there by an editor who either ignorantly or willfully distorted the actual role of the Planetary Protection Officer.
The first paragraph of the story gets a little closer:
The full-time role of "planetary protection officer" will involve ensuring that humans in space do not contaminate planets and moons, as well as ensuring that alien matter does not infect Earth.
"Planetary Protection Officer" isn't a new position; the current one is retiring. The primary focus of the planetary protection office is sterilizing probes that are going to other planets and moons. This is done both to preserve any existing life elsewhere in the solar system from Terran competition, and so that if and when we find life on other bodies, we will know we didn't bring it ourselves.
Preventing microbes from other worlds reaching Earth is also a concern, for similar reasons.
Developing and implementing the policies of the planetary protection office is a complex job requiring a broad array of both technical and human skills, and so a $187K salary is not remarkable for it:
Candidates will be required to travel frequently β but like any job, there will be a significant amount of emails, proposals and other reading.
Candidates must have at least one year's experience as a top-level civilian government employee, and an advanced degree in physical science, engineering or mathematics. They must also have "advanced knowledge" of planetary protection.
The position also requires "demonstrated skills in diplomacy that resulted in win-win solutions during extremely difficult and complex multilateral discussions". The new hire will also receive "secret" security clearance. Only US citizens and US nationals can apply.
|
output
| 1 | 192 |
Traditional advice for making megadungeons in older versions of D&D is in addition to any rooms with Monsters, Treasure, Traps, or "Tricks", there should also be at least 50 to 60 percent "Empty" rooms, which contain nothing overtly threatening or valuable. Now, there's several arguments for including these empty rooms that I buy, so I'm not going to accept any answer which primarily says, "Don't include empty rooms". The main issue I run into with empty rooms, however, is that they're boring in the way that I've been including them. They don't do their job of increasing tension, and the set dressing included around them hasn't been sufficiently interesting to my players either. My question is this: How can I make empty rooms interesting, by increasing tension or simply being interesting in and of themselves?
|
instruction
| 0 | 193 |
By definition, nothing's going to happen in an empty room (though see below). There are no hidden doors to find, no puzzles to solve, no enemies to fight. So what's their purpose?
## Bringing the dungeon to life
While all the orcs may sit around in a guard room waiting for PCs to show up, where do they sleep, what do they eat, what happens to their trash? Think of a dungeon not just as a place to have fights in, but as an actual place that serves a purpose. Once you do, the dungeon will start making sense. "Empty" rooms will increase immersion for the players, and force you to consider things you may not have otherwise. Should there be a pet otyugh that eats the trash? Are the orcs demanding cows from the local farmers for "protection"? Do they keep a famed halfling cook enslaved, to make them rare steaks?
## Foreshadowing
Once the dungeon makes sense, you can use that to place clues for things that dwell deeper within. Has a horde of zombies marched through to guard the necromancer's abode within, and left a few rotten body parts here and there? Has a malevolent force been summoned and spoiled all the meat and milk in the dungeon? Is there a golem maintenance station, with oil to grease them, rags to polish them, and a mad goblin mechanic? These may be vital clues PCs need to prepare for a tough fight, or they can simply let them form theories and feel smart about being right once they do come upon a golem or three.
#Currently empty
These rooms are empty now, but they don't have to stay that way. PCs may choose to fortify a room and bring the enemy to them - such tactical choices could be an important part of dungeoncrawling. Orcs may chase PCs through the dungeon, or randomly come across them in a kitchen because they were feeling peckish.
Note that some of these ideas would introduce creatures or things into rooms that PCs may choose to interact with, which would make them non-empty. In a way that's fine: you started with an empty room but found something interesting to put inside after all. If that's not your intention, well, don't put goblins or halflings or otyughs in. Stick to body parts and greasy pots and shadowy portraits and bloodstains and scent of brimstone and fresh flowers and broken mirrors and...
Tell a story with your empty rooms, or offer tactical choices. Preferably both.
|
output
| 1 | 193 |
Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? explain in the context of an example
|
instruction
| 0 | 194 |
With
```with()``` is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
```User > hasMany > Post```
```$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
```
Has
```has()``` is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use ```has('relation')``` that means you only want to get the models that have at least one related model in this relation.
Example:
```User > hasMany > Post```
```$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
```
WhereHas
```whereHas()``` works basically the same as ```has()``` but allows you to specify additional filters for the related model to check.
Example:
```User > hasMany > Post```
```$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
```
|
output
| 1 | 194 |
What are some of the advantages of using one over the other?
|
instruction
| 0 | 195 |
ASP.NET Web Forms and MVC are two web frameworks developed by Microsoft - they are both good choices. Neither of the web frameworks are to be replaced by the other nor are there plans to have them 'merged' into a single framework. Continued support and development are done in parallel by Microsoft and neither will be 'going away'.
Each of these web frameworks offers advantages/disadvantages - some of which need to be considered when developing a web application. A web application can be developed using either technology - it might make development for a particular application easier selecting one technology versus the other and vice versa.
ASP.NET Web Forms:
* Development supports state
β’ Gives the illusion that a web application is aware of what the user has been doing, similar to Windows applications. I.e. Makes 'wizard' functionality a little bit easier to implement. Web forms does a great job at hiding a lot of that complexity from the developer.
* Rapid Application Development (RAD)
β’ The ability to just 'jump in' and start delivering web forms. This is disputed by some of the MVC community, but pushed by Microsoft. In the end, it comes down to the level of expertise of the developer and what they are comfortable with. The web forms model probably has less of a learning curve to less experienced developers.
* Larger control toolbox
β’ ASP.NET Web Forms offers a much greater and more robust toolbox (web controls) whereas MVC offers a more primitive control set relying more on rich client-side controls via jQuery (Javascript).
* Mature
β’ It's been around since 2002 and there is an abundance of information with regards to questions, problems, etc. Offers more third-party control - need to consider your existing toolkits.
ASP.NET MVC:
* Separation of concerns (SoC)
β’ From a technical standpoint, the organization of code within MVC is very clean, organized and granular, making it easier (hopefully) for a web application to scale in terms of functionality. Promotes great design from a development standpoint.
* Easier integration with client side tools (rich user interface tools)
β’ More than ever, web applications are increasingly becoming as rich as the applications you see on your desktops. With MVC, it gives you the ability to integrate with such toolkits (such as jQuery) with greater ease and more seamless than in Web Forms.
* Search Engine Optimization (SEO) Friendly / Stateless
β’ URL's are more friendly to search engines (i.e. mywebapplication.com/users/ 1 - retrieve user with an ID of 1 vs mywebapplication/users/getuser.aspx (id passed in session)). Similarly, since MVC is stateless, this removes the headache of users who spawn multiple web browsers from the same window (session collisions). Along those same lines, MVC adheres to the stateless web protocol rather than 'battling' against it.
* Works well with developers who need high degree of control
β’ Many controls in ASP.NET web forms automatically generate much of the raw HTML you see when an page is rendered. This can cause headaches for developers. With MVC, it lends itself better towards having complete control with what is rendered and there are no surprises. Even more important, is that the HTML forms typically are much smaller than the Web forms which can equate to a performance boost - something to seriously consider.
* Test Driven Development (TDD)
β’ With MVC, you can more easily create tests for the web side of things. An additional layer of testing will provide yet another layer of defense against unexpected behavior.
Authentication, authorization, configuration, compilation and deployment are all features that are shared between the two web frameworks.
|
output
| 1 | 195 |
What factors determine the maximum altitude for a plane?
Is it limited by wing design, engine thrust, and so on?
Is there a formula by which one can calculate the maximum altitude a plane can reach?
|
instruction
| 0 | 196 |
The higher you get, the lower the density of the air becomes. This lower density results in a lower lift being generated for the same airspeed and angle of attack. Effectively, the higher you fly the higher your minimum speed becomes. So while climbing, your speed needs to increase to compensate for the lower air density. As long a you can fly faster, the lower density at altitude can be compensated for.
Basically there are two things that limit your maximum speed: thrust and speed of sound and with that your maximum altitude.
First is thrust; the higher you get, the lower the thrust your engines deliver. You might note that drag goes down with the air density as well but since you are flying faster and faster during the climb the drag doesn't decrease at all. If your maximum altitude is limited by thrust then at some point during the climb the thrust and drag are getting close to equal and that is where the climb stops. When you can no longer climb with more than 100ft per minute (for propeller aircraft) or 500ft per minute (for jet / turbofan aircraft) you have reached your service ceiling. If the aircraft maximum altitude is determined by thrust, the absolute ceiling will take very long to reach.
At high altitudes air breathing engines will get difficulties eventually. Due to the lower air density the mass flow through the engine is reduced up to a point where it causes a flame out.
The other limitation is the speed of sound, at least for subsonic aircraft. In the process of generating lift, air flowing over the top of the wing is accelerated. At one point, when the aircraft is still flying below the speed of sound, shock waves will start to form over the wing. This results in increase of drag and reduces the lift. So provided you have enough engine power at your disposal you can climb to an altitude where your minimum speed is also your maximum speed. This is called the coffin corner. In the coffin corner:
* if you fly any faster, you will exceed the maximum Mach number ($M_{mo}$) of your aircraft, resulting in high speed buffet, vibrations and possible loss of control.
* if you fly any slower, the maximum lift that the wing can provide will be insufficient to maintain altitude. Descent or the aircraft will stall.
* if you fly any higher and you will be too fast and too slow at the same time.
* if you turn, you increase the wing loading, thereby increasing the minimum speed needed to create the required lift. Also the outer wing will easily exceed the maximum speed while at the same time the inner wing is below stall speed. This can quickly develop into a spin.
Since accurate knowledge of engine performance, drag and wing characteristics of the aircraft is needed, there is not a simple formula to derive the maximum altitude for an aircraft.
Apart from the aircraft performance related limitations above there is a certified maximum operating altitude for the pressurized cabin. This takes into account the structural properties of the hull (pressure difference between inside and outside) and the achievable emergency descent rate in case of a depressurization event.
|
output
| 1 | 196 |
Why did the Typescript folks create the ```infer``` keyword?
According to the documents, this is an example of how you would use it:
```type ReturnType = T extends (...args: any[]) => infer R ? R : any;
```
I don't understand why this is needed. Why can't it just be:
```type ReturnType = T extends (...args: any[]) => R ? R : any;
```
Why doesn't this work? Why is the ```infer``` keyword necessary ?
|
instruction
| 0 | 197 |
With ```infer```, the compiler ensures that you have declared all type variables explicitly:
```type MyType = T extends infer R ? R : never;
type T1 = MyType // T1 is { b: string; }
```
Here we declare a new type variable ```R``` in ```MyType```, which gets inferred from ```T```.
(Note, that ```infer``` is always used within the ```extends``` clause of a conditional type.)
Usage of undeclared type parameters now can result in a compile error:
```type MyType2 = T extends R2 ? R2 : never; // error, R2 undeclared
```
Without ```infer```, the compiler wouldn't know, if you wanted to introduce an additional type variable ```R2``` that is to be inferred (see first case), or if ```R2``` is just an accidental typing error/typo. ```infer``` exists to remove this ambiguity.
More precisely the compiler checks, if ```T``` is assignable to ```R``` , when ```infer``` is omitted:
```type R = { a: number }
type MyType3 = T extends R ? R : never; // compare T with type R
type T3 = MyType3 // T3 is never
```
Note, that ```infer R``` shadows type references of an equally-named type declaration ```R```:
```type R = { a: number }
type MyType4 = T extends infer R ? R : never;
type T4 = MyType4 // { b: string; }
```
|
output
| 1 | 197 |
Which is more widely supported: ```window.onload``` or ```document.onload```?
|
instruction
| 0 | 198 |
When do they fire?
```window.onload```
* By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).
In some browsers it now takes over the role of ```document.onload``` and fires when the DOM is ready as well.
```document.onload```
* It is called when the DOM is ready which can be prior to images and other external content is loaded.
How well are they supported?
```window.onload``` appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced ```document.onload``` with ```window.onload```.
Browser support issues are most likely the reason why many people are starting to use libraries such as jQuery to handle the checking for the document being ready, like so:
```$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });
```
For the purpose of history. ```window.onload``` vs ```body.onload```:
A similar question was asked on codingforums a while
back regarding the usage of ```window.onload``` over ```body.onload```. The
result seemed to be that you should use ```window.onload``` because it is
good to separate your structure from the action.
|
output
| 1 | 198 |
I was surprised to learn that Puerto Ricans, despite living in a US territory, were not entitled to vote in the presidential elections.
I was even more surprised to learn that US citizens are allowed to vote for president from anywhere in the world - EXCEPT if they happen to live in Puerto Rico.
What is the legal/political rationale behind this? What is it about Puerto Rico that magically removes one's right to vote? Has anyone ever challenged this?
|
instruction
| 0 | 199 |
This is a peculiarity as a result of the federal nature of the USA and the exceptional position of Puerto Rico as a territory but not a state. Within the States and Territories of the USA, your voting rights depend on residence. If you leave the States and Territories your voting rights depend on former residence or inheritance.
In general most citizens of the USA are also citizens of a state of the USA. Since states don't issue their own passports, your citizenship of a state is determined by residence. If a New Yorker moves to Florida, they become Floridians, and so can vote in state elections in Florida, but can't now vote in elections in New York.
Now if our New Yorker moves to Timbuktu, this is treated slightly differently. They remain a US citizen and a citizen of New York, and so retain the right to vote in New York elections. Their children could also claim New York citizenship.
But Puerto Rico is both part of the USA but not a State or part of a State of the USA. When our New Yorker moves to Puerto Rico, they can vote in Puerto Rican elections but not elections in New York.
Now the nature of elections in the US is that there are no national elections There are statewide elections of Senators, Governors and Presidential electors. There are district elections of Representatives and there are local elections of many kinds. Our New Yorker has lost the right to vote in New York elections (just as they would have done if they had moved to Florida) but not gained the right to vote in Puerto Rican elections for Presidential electors (because there are none).
This is odd, but something similar is true if the New Yorker moves to DC. They cease to have the right to vote in elections to the Senate.
|
output
| 1 | 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.