Why do people call their characters "toons"?

Question: I've seen that in games like MMORPGs and the Diablo series, where the player has an "arsenal" of several characters, people refer to their characters as "toons".
What is the origin of this term?
Comment: @Zoredache while the timing is right for Ender's Game (1985), the meaning is totally different.  "Toon" in MMO games refers to a singular character, not a group or organization.
Comment: I'd guess the thought process was something like `character -> cartoon character -> cartoon -> toon`.
Comment: I suggested that the term was popularized by [Toontown Online](http://en.wikipedia.org/wiki/Toontown_Online) but others noted that the earliest usage of the term predated this MMO.
Comment: @agent86 Yeah, I've heard reference to this in Everquest.
Comment: I haven't seen this before but it sounds like a term from Enders Game.  Toon is battle school slang that means something like squad or **platoon**. http://ansible.wikia.com/wiki/Toon
Comment: @MatthewRead and what a thought process it was!
Answer: Much of this is my opinion and recollection, but as a gamer for 25 years (MMO-gamer since Everquest) maybe I know a thing or two.
Character vs Toon
"Character" is the word old RPG players have used to describe their avatar.  MOO's, MUD's, D&D, Champions, and many other pen-and-paper systems.  Role-playing has an important concept of separation of "player knowledge" and "character knowledge" - what you know vs what your character should know.
Many RPG players cringe when the word "Toon" is used to mean "character".  "My character" implies a connection with my identity (or at least something my identity participates in), while "my toon" is something possessed, disconnected from me.  More on that later.
Pre-MMO History of Toon

Toon (1984, pen and paper rpg)
Who Framed Roger Rabbit (1988, movie)
Tiny Toon Adventures (1990, cartoon show) - note, different spelling than "Looney Tunes"

While these examples don't authoritatively show the origin of the word Toon, they do establish that the word was in use prior to the existence of MMORPGs.
The Question:
How did Toon come to be used to describe characters?

The Realm Online (1996)
Diablo  (1996)
Ultima Online (1997)
Everquest (1999)
Diablo 2 (2000)
Runescape (2001)
ToonTown (2003)

While ToonTown's characters are, in fact, toons, the term has been used in earlier games.  My recollection is that the term mainly was used in out-of-game character/account real-money trades.  The word "Toon" provides a solid disconnection between the player and what he made, allowing him to sell it without regret.
Also, consider the character systems of Diablo 1 and 2.  You pick your class and then the character's appearance and gender are determined from that.  If you are a male gamer playing an Amazon or a Sorceress, calling that character a "Toon" can be a signal to others that you don't identify as that gender.  Once again, there is a separation from identity.
Still, these games all pre-date the rise of the term around 2006.  I attribute the rise of the term "Toon" during this period as not belonging to a single game or experience, but instead to the increasing disconnection between player and character identity.  This can be due to many MMO players playing second or third games - how many character connections can a player create or sustain?
This can be due to games becoming more action-oriented (vs role-play centred),  there is more focus on what actions this mechanism or "Toon" is capable of, instead of what the character would do/say/feel.
The Realm Online
This game was released by Sierra in 1996.  It features animated cartoon-like characters.  The oldest usage of "Toon" I have identified so far comes from this game (see reference below).  Because the game lacked a two-way trade system, scamming was a common occurrence.  It seems reasonable to me that the characters created for the sole purpose of scamming would not be called "character", but would instead be labeled "toon".

References (more to come as I have time):

neologasm (2006): "Playing a toon instead of an avatar implies detachment".
Diablo 2 (2004): "gotten this toon killed 5 times"
Anarchy Online forums (2003) : "roll a new toon" - this is a fascinating mixture of words:  "Roll" is from pen-and-paper games where dice are rolled to determine stats, while "toon" is opposed to pen-and-paper - nothing is animated there.
Anarchy Online forums (2002) "I have a few toons"
The Realm Online (2000) "Hacker + Cheater Toons are buried here."
Comment: Those are a lot of assumptions that in my opinion don't really give a definitive answer to the question. Could you add some sources?
Comment: While I've played these games and have observed the change in player's use of the term, I don't use it myself.  My gf does and she says: "It means cartoon, I say it because it's shorter than character."  I guess that's more definitive but less fun than my answer.
Comment: @Shinrai WoW was released in late 2004.  Toon was in use before that.
Comment: I feel like there is a lot of assumptions with this answer, mostly related about players *trying* to have some sort of disconnect from their character by using the word 'toon'.
Comment: I always just thought it was because of the visual style of WoW, personally...that game seemed to really be the first to use it extensively.  To this day I've never heard an MMO player who didn't spend a lot of time on WoW use the term (although to be fair, a large percentage of MMO players today *have* spent a lot of time on WoW).  I've also *never* heard it used on a game of around the same age or older.
Comment: Toon has never been used in the RuneScape community to describe another character. Usually, they're a challenge or otherwise devoted character described in terms of their purpose, for example 'staking pure' or 'barrows pure'.
Comment: @AmyB That doesn't really make sense. There isn't very much use in creating new characters in RS. Every character can do everything, so it isn't like on wow where you have to roll a warrior to do melee and a mage to do magic. On RS, you just put on your melee gear and start training your melee stats. Only thing is you can't lose stats, so if you don't want your melee to count against your combat level, you'd make a pure character. I assure you, the kids next door are in the extreme minority.
Answer: "Toon" for your game characters absolutely started in The Realm Online.  It was one of the earliest graphical MMORPGs out, the characters actually looked like cartoons and people there called them "toons" because of that.  Sadly it carried on to other games out of habit.
I was a text MUD player from 1990 (the entire Internet at the time was all text) and on through as the graphical games started to come out.  I never once heard the word "toon" used to describe ones character until The Realm Online came out.  They looked like Cartoons, people started calling them toons, and unfortunately it stuck and was carried along by various people.
Answer: The first use of the word Toon that I know of is from Orson Scott Card's short story Ender's Game (not to be confused with his 1985 book of the same title), published in Analog Magazine in August of 1977.
In Ender's Game, Toon was actually [I believe] short for Platoon, and was used to identify the various Battle Groups and their leaders.
https://en.m.wikipedia.org/wiki/Ender%27s_Game_(short_story)
I first heard it used in MMO's circa 2006 in Fiesta Online, a MMORPG published by Outspark. The game was very cartoony, so at the time I made the assumption that the term Toon stood for Cartoon.
https://en.m.wikipedia.org/wiki/Fiesta_Online
I have never played WoW, so can't say if it originated there, but to this day I use the term universally as an identifier for any given character in any non Pen and Paper RPG I play. As for Pen and Paper RPG's, I still use the term Character.
Answer: The "origin" of the name isn't paramount in this instance. What makes the usage of the name important is the game that made it so popular.
None of the games mentioned so far have come close to being the real reason people use the term "toon" to this day.
I have been in this industry for many years. I am generation-X, the generation that invented the internet. I WROTE Multi-User Dungeons. I have been playing multiplayer, with focus on as massive as technologically possible, since they were conceived. That said..
The term "toon" was made popular by a game called "ToonTown Online". The game was developed and marketed starting in 2003, primarily by Disney, and every commercial included multiple usages of the term "toon". I remember the gravely commercial announcer saying things like "Create your very toon", "play with hundreds of other toons", "your toon your story".
The "origin" of the term "absolutely" came from the "carTOON" industry and decades of generations of people calling the characters in WB and Disney cartoons "toons". But, the regular USAGE of the term as a replacement for the term "character" or "avatar" in gaming started with the game "ToonTown".
It was actually a pretty popular game, lasting for ten years. What made the term popular was the commercialized marketing tactics used regularly by the Disney machine. The commercials were designed to make you "remember" simple terms that were "familiar" but not exactly the same. This gives the customer a feeling of getting something.. you guessed it.. both familiar AND new.
NO ONE used the term before this outside a very minuscule subset of gamers in niche games that no one cared about then and no one remembers now.

"Toon" for your game characters absolutely started in The Realm
  Online. It was one of the earliest graphical MMORPGs out, the
  characters actually looked like cartoons and people there called them
  "toons" because of that. Sadly it carried on to other games out of
  habit.

No one today uses the term "toon" because of the game "The Realm Online". That's like people saying they call all colas "coke" because it historically had cocaine in it at one time. Malarkey.
Comment: Ok Gen-Xer.

I didn't attribute The Realm Online as "the cause", only as the oldest usage that I could find.
I take umbrage with your description of Anarchy Online, Ultima Online and Diablo 2 as "niche games that no one cared about and no one remembers now". Diablo 2 is so fondly remembered it was rereleased on the Switch.

There can be more than one cause of the usage. Here's two.
Increasing disconnection between player and character.
Ease of typing.
Answer: Because your characters are on your computer screen much like a cartoon character is on the television. Chartoon character to Cartoon to Toon
Answer: It goes back to the movie "Who Framed Roger Rabbit", released in 1988.  Check the IMDB listing first sentence: http://www.imdb.com/title/tt0096438/?ref_=fn_al_tt_1
Comment: The accepted answer makes mention of the same movie, to a better extent.
Comment: Cartoon is different than the characters you control.


How to concatenate files found by the find command in bash

Question: Searching for files using the bash find command, I would like to concatenate the resulting files into a new file. For example, if the find command yields:
find . -name "configuration_dev.txt"

./tmp/configuration1/configuration_dev.txt
./tmp/configuration2/configuration_dev.txt

I would like to concatenate the contents of the two files into a new file directly as a bash command.
Comment: I don't know really know how to do it, but you could try to use `cat` command which take `find` output, and do a redirect to a `.txt` file with `>` operand
Answer: One possible way to do this is by piping the output of find to xargs and concatenate the content of the files by cat, then you can redirect the output to a new file:
find . -name '*file*' | xargs -I{} cat "{}" > output

The above command will call cat for each file and then the entire output of the  xargs statement will be redirected to the output file. The more effective way is to use null delimiter - thanks to @pLumo for this update:
find . -name '*file*' -print0 | xargs -0 cat > output

Comment: Don't forget xarg's `-r` flag. Running a command when no files were found is often Not Good.
Comment: This will call `cat` for each file, you could just use `xargs -0 cat`.
Answer: The command to achieve the desired result is:
find . -name "configuration_dev.txt" -exec cat > testing.txt {} +

A good explanation of the above line is provided here: What is meaning of {} + in find's -exec command?
Comment: @danzel That's not a problem, it just looks like it would be, due to the confusing placement of `> cat testing.txt`. As pLumo says, it's clearer to put it at the beginning or end of the whole command. The key is, *`> cat testing.txt` is not actually part of any command run by `find`*. `find` never sees `> cat testing.txt`. The shell applies that redirection to the command `find . -name "configuration_dev.txt" -exec cat {} +`. No matter how many times `find` runs `cat`--as you say, with enough files this happens multiple times--`testing.txt` is opened only once, when the shell opens it.
Comment: The  `> cat testing.txt` part can be put anywhere in the command. I'd put it in the beginning or the end, feels more natural, but maybe it's just me... But anyways, this is the way to do it! +1
Comment: Add `-type f` to avoid error messages if your `find` includes directories.
Comment: This probably fails with a large number of files because `cat > testing.txt {}` will be called more than once, overriding the previous contents of the file each time.
Answer: You can also open multiple files in cat and redirect the output to a new file. Since the names of multiple files would be returned by find, you can use that inside cat using `(backtick):
cat `find . -name "configuration_dev.txt"` > testing.txt

Command between backticks would be executed and replaced by the output of the command removing the trailing new line character and inserting a whitespace.
You can confirm this by running
A=`find . -name "configuration_dev.txt"`
echo $A

As you'll find that the output would be something like:
./tmp/configuration/configuration_dev.txt ./tmp/configuration/configuration_dev.txt

Thus the actual cat command under the hood will be:
cat ./tmp/configuration/configuration_dev.txt ./tmp/configuration/configuration_dev.txt > testing.txt

Comment: This fails with spaces somewhere along the path  ...
Comment: @pLumo I understand. Thank you for the comment. As of now I have no idea to remove this limitation using the current approach. :)
Answer: The Rust tool fd, which is a user-friendly alternative to find, makes this quite easy.
fd -X cat \; "configuration_dev.txt" . > output

-X is a batch executation of a command on all search results at once. The nice thing about this (since v8.4.0) is that it will not fail with the error Argument list too long.


A complete orthonormal basis for every RKHS?

Question: If I understand correctly, the Mercer Theorem states that if $R$ is a continuous positive-type function, then there exists a sequence of eigenfunctions $\phi_n(.)$ and corresponding nonnegative eigenvalues $\lambda_n$ associated with $R$ as an operator on $L^2$, such that
$$R(s,t)=\sum_{n=1}^\infty \lambda_n\phi_n(s)\phi_n(t)$$
Let $\mathcal{H}$ be the reproducing-kernel Hilbert space (RKHS) corresponding to $R$ (cf Moore-Aroszajn Theorem). I am reading the section on RKHS in Elements of Statistical Learning and Inference by Hastie et al (2017 edition, https://hastie.su.domains/ElemStatLearn/, p.168), and after positing an above expansion for $R$, the authors state that
$$\forall f\in\mathcal{H}\hspace{0.6cm} f(x)=\sum_{i=1}^{\infty}c_i\phi_i(x)$$
where $\phi_i$ are the eigenvalues associated with $R$, and $c$ are suitable scalars.
Here's my problem. The latter statement implies that $\mathcal{H}$ has a countable orthonormal basis, which means that $\mathcal{H}$ is separable. However, not every RKHS is separable. Moreover, a complete countable basis is not implied by the Mercer Theorem, since there is no claim that the given sequence of eigenfunctions is complete, and the Hilbert basis formed by the eigenfunctions of the Hilbert-Schmidt operator $R$ need not be countable.
Are Hastie et al tacitly assuming $\mathcal{H}$ is separable?  I see no other way around their claim.
Answer: You are right that in general, there is no reason for a RKHS to be separable. However, if the kernel $K$ is continuous and the set $\mathcal X$ over which it is defined is separable, then the corresponding RKHS $\mathcal H $ will also be separable. Here's a proof sketch :
Recall that $\mathcal H$ is the completion of $H_0 :=\text{span}\lbrace K(x,\cdot)\mid x\in\mathcal X\rbrace$. Hence if we prove that $H_0$ is separable, separability of $\mathcal H$ will follow. If we denote by $\{x_n\}_{n=1}^\infty\subset \mathcal X$ a dense subset of $\mathcal X$, it is enough to check that
$$H_1:=\bigcup_{n=1}^\infty \left\{\sum_{i=1}^n \alpha_i K(x_i,\cdot)\mid \alpha_1,\ldots,\alpha_n\in\mathbb Q\right\} $$
Is dense in $H_0$, since it is clearly countable. But it is easy to check that any function in $H_0$ can indeed be approximated by elements of $H_1$ when $K$ is continuous : for $H_0\ni f = \sum_{k=1}^m \beta_kK(y_k,\cdot)$, approximate each $y_k$ by an $x_{n_k}$ such that $\|K(y_k,\cdot)- K(x_{n_k},\cdot)\|$ is sufficiently small, and approximate each $\beta_k$ by sufficiently close rationals $\tilde\beta_k$, and the result will follow (I let you fill in the details).
In Hastie's book, they consider $\mathcal X \equiv \mathbb R^p$, which is clearly separable, and all the kernels they work with are continuous, so in their setting $\mathcal H$ is indeed separable.
Comment: Thanks for that, and the edit. I'm going to be super-rigorous (oh no!) with my grammar from now on!
Comment: That seems pretty complete to me! That also reminded me that a proof exists in *Reproducing Kernel Hilbert Spaces in Probability and Statistics*, Berlinet & Thomas-Agnan, 2004 (Theorem 15 and corollaries), but yours more compactly addresses the question.  I think the omission of this in Hastie et al is what bothers me about the book as a whole: it's comprehensive, but you come away with doubts rather than certainty. Personal view.


memberInfo.GetValue() C#

Question: How to get an instance's member's values?
With propertyInfos there is a propertyInfo.GetValue(instance, index), but no such thing exists in memberInfo.
I searched the net, but it seems to stop at getting the member's name and type.
Answer: You have to downcast to FieldInfo or PropertyInfo:
switch (memberInfo)
{
  case FieldInfo fieldInfo:
    return fieldInfo.GetValue(obj);
  case PropertyInfo propertyInfo:
    return propertyInfo.GetValue(obj);
  default:
    throw new InvalidOperationException();
}

Answer: I think what you need is FieldInfo.

memberInfo.GetValue() C#


Is there a way to save Airi's Father?

Question: So I found Airi's father bleeding on the ground after he accidentally summoned some high level demons.  I wasn't sure exactly when the event was opened up but I did it at 1700.  My previous save was 5 hours ago (at 1200) and I'm wondering if I could have saved him if I made it on time.
Answer: I haven't played my copy of DS2, but this is the info my google-fu has yielded.
No, you can't save him by making it on time. He has fixed events in a fixed order with some at fixed times.
You can maybe save him by not following his events because he presumably doesn't try to summon Jikokuten.
You need him to die in order to save him. If you proceed through all his events, he can be seen alive during the Daichi+ ending. You essentially need to get your team to fate 4, follow the Dera Deka events and choose the restoration ending if I read correctly. You may need to recruit everyone as well when doing so or maybe that's just to see the complete ending for all characters.

Is there a way to save Airi's Father?


Ubuntu shifted theme and I am unable to change theme

Question: enter image description hereI have installed sweet-icon package. Icons and folders were colorful according to sweet style. Today, without inference (at least conscious), the theme changed. I have black-and-white theme and some mixture on the deck. (a printscreen included). Unable to change in tweaks. Tweeks icons fixed on sweet. Could anyone suggest me any solution?
Thanks in advance.
Comment: does this answer your question?: https://help.ubuntu.com/stable/ubuntu-help/a11y-contrast.html.en . it seems you have turned on high contrast.
Comment: Thanks my Friend...What else can I say...
Answer: This looks as if you turned on the "High contrast" accessibility setting.
Head to "Settings", "Accessibility", and turn "High Contrast" off.
Comment: thanks vanadium. that's what i'm also trying to say.


What is the easiest way to set the value of an entire array?

Question: My current project requires me to fill an array based upon some other values. I know there's the shortcut:
int arr[4][4] = { {0,0,0,0} , {0,0,0,0} , {0,0,0,0} , {0,0,0,0} };

But in this case, I need to fill the array after its declaration. I currently have my code formatted like this:
int arr[4][4];
if(someothervariable == 1){
    arr = { {1,1,1,1},
            {1,2,3,4},
            {2,,3,4,5},
            {3,4,5,6} };
}

But it won't compile. Is there a way to make use of the mentioned shortcut in my case? If not, whats the best fix available? I'd appreciate a way to set it without explicitly assigning each element? ie: arr[0][0] = ...
Comment: Is the extra comma there in the original?
Comment: In the first case the shortcut would be `int arr[4][4] = {}`. What you have above is certainly a "longcut" :))
Comment: C++1x with its unified initialization syntax to the rescue! Unfortunately, it's not yet widely available.
Answer: How about using std::copy() ?
int arr[4][4];
if(someothervariable == 1){
        const static int a2[4][4] = { {1,1,1,1},
                                      {1,2,3,4},
                                      {2,3,4,5},
                                      {3,4,5,6} };
        std::copy(&a2[0][0], &a2[0][0]+16, &arr[0][0]);
}

Comment: This will work in practice, but formally and pedantically speaking reinterpreting a 2D array as 1D array is illegal. More precisely, it is formally illegal to use pointer arithmetic on `&a2[0][0]` that steps more than 4 steps away from that pointer. Doing `&a2[0][0] + 16` is undefined behavior. Again, this *will* normally work in practice.
Comment: Thanks for making me re-read the standard! I went by remembering the words `the same array object` (5.7/6) and `arrays in C++ are stored row-wise` (8.3.4/9), but you're right, it is legal to implement a 2D array with padding bytes between each row (just as it is legal to have &arr (before array-to-pointer conversion) != &arr[0][0]), in which case this would fail.
Answer: No, array initialization syntax is for array initialization. Although, you can use memset if all the values are the same byte.
The boost.assign library adds some interesting syntax for modifying/filling collections, but AFAIK it doesn't support C style arrays (only C++ and Boost containers).
Answer: In the current version of C++ language the only way to do it is to copy it from some original
int arr[4][4];

if (someothervariable == 1)
{
  const int SOURCE[4][4] = // make it `static` if you prefer
  {
    {1, 1, 1, 1},
    {1, 2, 3, 4},
    {2, 3, 4, 5},
    {3, 4, 5, 6}
  };

  assert(sizeof arr == sizeof SOURCE); // static assert is more appropriate
  memcpy(&arr, &SOURCE, sizeof arr);
}

The source "constant" can be declared as static in order to avoid re-initialization, if the compiler is not smart enough to optimize it by itself.
In the future version of the language a feature similar to C's compound literals is planned, which will provide support for immediate initialization (basically what you tried to do in your original post).
Comment: This has a `C++` tag (not a `C` tag), so I'd prefer `std::copy()` (and expect it to fall back on `std::memcpy()` when appropriate). [Cubbi did that right](http://stackoverflow.com/questions/3010413/what-is-the-easiest-way-to-set-the-value-of-an-entire-array/3010462#3010462).
Comment: @sbi: Unfortunately array type is not assignable in C++, which is why there's no immediately legal `std::copy`-based solution. Cubbi did it wrong (formally speaking), because he reinterpreted a 2D array as an 1D array. This is formally illegal in C++ and a pedantic (debugging) implementation has all rights to crash on that code. There's no elegant solution with one `std::copy`. You have to do nested copying to copy a 2D array in a pedantically correct way.
Comment: You do have a point there. While I cannot imagine an implementation where 2-dimensional arrays aren't contiguous, if they are, using `std::memcpy()` will be just as good.
Comment: Ha! Except when you're not using built-ins! Then, using `std::copy()` would be causing "less UB" then using `std::memcpy()` does. `:)`
Answer: If you wish to fill the array with a single value:
#include<algorithm>
#include<vector>

// ...
std::vector<int> arr;
std::fill(arr.begin(), arr.end(), VALUE);  // VALUE is an integer

If you wish to calculate the value for each element:
struct get_value {
    int operator()() const { /* calculate and return value ... */ }
};

std::generate(arr.begin(), arr.end(), get_value());

Answer: If you are setting everything to the same value (such as zero), you may be able to get away with ...
memset (arr, 0, sizeof (arr));

Note that this is fraught with perils.  You have to know your type sizes and all that jazz.
However, it appears that that will not suffice for you.  If you want to fill the array with different values, I can only only think of two ways of doing this.
Method #1.  (Can be a pain the butt)
arr[0][0] = 1;
...
arr[0][3] = 1;
arr[1][0] = 1;
...
arr[1][3] = 4;
arr[2][0] = 2;
...
arr[2][3] = 5;
arr[3][0] = 3;
...
arr[3][3] = 6;

Method #2.
   Predefine a set of arrays and switch between them using a pointer;
int  arr1[4][4] = {
        {0,0,0,0},
        {0,0,0,0},
        {0,0,0,0},
        {0,0,0,0} };
int  arr2[4][4] = {
        {1,1,1,1},
        {1,2,3,4},
        {2,,3,4,5},
        {3,4,5,6} };

int *arr[4];

Now you only have the four (4) values of *arr[] to set instead of setting everything.  Of course, this really only works if your arrays will be filled with predetermined constants.
Hope this helps.
Comment: I think you meant `int (*arr)[4]`. In C++, might as well do: `int (&arr)[4] = (someothervariable == 1) ? arr2 : arr1`.
Answer: I'm not sure if I like this solution or not, but C/C++ will give you assignment convenience if you wrap the array inside a struct with the minor cost of then having to use the struct name to get at the array:
typedef struct {
    int data[4][4];
} info_t;

info_t arr;

if (someothervariable == 1){
    static const info_t newdata = {{  // since this is static const, there generally
                                      // won't be a copy - that data will be 'baked'
                                      // into the binary image (or at worst a
                                      // single copy will occur)
        {1,1,1,1},
        {1,2,3,4},
        {2,3,4,5},
        {3,4,5,6}
    }};
    arr = newdata;  // easy to assign new data to the array
}

int somethingelse = arr.data[1][2]; // a tiny bit less convenient to get
                                    //    to the array data

Comment: This is C++, so the `typedef` isn't necessary. (BTW, he inconvenience could be overcome by overloading `operator[]` for `info_t`.)
Answer: int arr[4][4];
if (someothervariable == 1) {
     int tmp[4][4] = { {1, 1, 1, 1}, {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6} };
     arr = tmp;
}

Comment: Arrays are not assignable. `arr = tmp` will not compile.


How to define the expected value of utilities in Bayesian Decision Analysis (poisson distribution)?

Question: Suppose a boy at a circus is given two options to catch balls in 5 minutes from a ball throwing machine, a sticky catcher and a net. The sticky catcher will always certainly catches 50 balls (p=1). The net usually catches 12 balls/per minute and follows a Poisson process. Which option should he use to catch the balls?
Utility of option 1 => 50 balls.
But I am confused in describing the utility of option 2,
should it be equal to => p(catching 0 balls in 5mins)*0 balls + p(1 ball)*1 + p(2)*2 + p(3)*3+........+p(huuuuge number (n) balls in 5 mins)*n?
please explain and let me know if I'm right...
Comment: Oh...yeah.... :D got it!
Comment: The net follows a Poisson process, or the ball-throwing machine does?
Comment: Ah, I understand, the net catches a number of balls $X$ which is distributed like a Poisson with rate $\lambda=12$ balls/minute. Then yes, you need to compare the expected value of the number of balls to be caught with the net with the expected (sure) value of the number of balls to he caught with the sticy catcher.
Comment: The net follows the poisson process...so am i doing it correct? am i calculating it correctly? i mean calculation of expected value for the net...is that how its supposed to be done?
Comment: Yes, but notice that a Poisson distribution with rate parameter $\lambda$ has expected value equal to $\lambda$ itself.
Answer: The Poisson process catches $12$ balls per minute on average, so over $5$ minutes that's $60$ balls on average. More exactly, the number of balls caught $N$ is Poisson-distributed with mean $60$ so we have $$ P(N=n) = e^{-60}\frac{60^n}{n!}.$$ From this you can calculate that the expected number of balls caught is $60$ and the standard deviation is $\sqrt{60}.$
So the net catches $10$ more balls on average but also experiences fluctuations. Which one has higher utility depends on how risk-averse you are (i.e. how your utility function penalizes risk). You haven't given any information as to how this is handled in your class so I can't tell if you're on the right track. You seem to be just computing the expected value which I suspect misses the point. (But if it is the case that you are just maximizing the expected number of balls, then the net is best.)
One way to quantify the risk/reward is that the net has a "Sharpe ratio" of $$\frac{10}{\sqrt{60}} \approx 1.3$$ relative to the risk-free sticky catcher.


using sleep method in gui, not working

Question: public void actionPerformed( ActionEvent evt)
{
  if( combo1==true && !evt.getActionCommand().equals("correct"))
  {
    combo2 = true;
    combo1 = false;
    combo3 = false;
    outText.setText("One more try!");
  }
  else if( combo2==true && !evt.getActionCommand().equals("correct"))
  {
    combo1 = false;
    combo2 = false;
    combo3 = true;

    **outText.setText("Wrong!!");**

      //sleep for 1 second
    try {
            Thread.currentThread();
          Thread.sleep(1000);
         }
    catch (Exception ex)
    {
    System.exit(0);
    }

    System.exit(0);
  }
  else if( !evt.getActionCommand().equals("correct"))
  {
    combo1=true;
    combo2=false;
    combo3=false;
    outText.setText("Two more tries!");
  }
  else
    outText.setText("Correct");
}

This is a part of my code for getting the right answer, but the line where it's marked with ** is not working with the sleep method in there. The program sleeps for a sec and closes, but wouldn't print out "Wrong!!" before it goes into sleep. If someone could help me that'd be much appreciated! Thanks in advance.
Comment: So what *is* it printing? Are you getting errors? Does `outText.setText("One more try!");` work at all?
Comment: It was just not printing "Wrong!!" all the other ones were working fine. But it's solved now, thanks anyways!
Answer: You're blocking the method from completing execution with Thread.sleep(). Use a javax.swing.Timer` instead.
outText.setText("Wrong!!");
new javax.swing.Timer(1000, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}).start();

// get rid of Thread.sleep()

See more at How to Use Swing Timers

using sleep method in gui, not working


Setting glutBitmapCharacter color?

Question: Just wondering if someone can help me track down my issue with the following code where the text color is not being set correctly (its just rendering whatever color is in the background)
void RenderText(int x, int y, const char *string)
{
int i, len;

glUseProgram(0);

glLoadIdentity();
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(0.0f, 0.0f, -5.0f);
glRasterPos2i(x, y);

glDisable(GL_TEXTURE_2D);
for (i = 0, len = strlen(string); i < len; i++)
{
    glutBitmapCharacter(GLUT_BITMAP_8_BY_13, (int)string[i]);
}
glEnable(GL_TEXTURE_2D);
}

I've checked all the usual things (I think), disabling texturing, setting color before rasterPos'ing, etc Ive disabled shaders but Im still having issues
Comment: Please post a picture of what you observe.
Comment: When you say that it's "rendering whatever color is in the background", do you mean the color set with `glClearColor`, or something different?
Answer: Looks like you've forgotten to glDisable(GL_LIGHTING) before drawing your string.
Comment: this comment really was a life saver, was not able to figure out why my text kept appearing in black. Can you please explain as to why do we have to turn off lighting before writing to the screen ?
Comment: The lighting in OpenGL only specifies, how the colours at a specific point in the scene are calculated. If youre not using lighting, all that OpenGL has to calculate the colour of a point is your GLColor command (and maybe some shading interpolation, but the colour is coming from glColor). if you turn glLighting on, there are several circumstances that influence the color of a point: the position and colour of the light source, the material of the point, the material colour of the point, and the texture. so turn it off to tell openGL to draw the next thing with your glColor, nothing more.
Comment: You could also have specified all lighting arguments correctly before drawing the characters so they would have been illuminated by a light source. that would have been much more extensive though.
Answer: No color is stored with any OpenGL bitmap (which is what glutBitmapCharacter created.  The bitmap is monochrome and stores only shape.
When the bitmap is drawn (e.g. glBitmap or maybe glDrawLists), the current raster color is used.  The raster color is not always the same as the active color, see http://www.opengl.org/wiki/Coloring_a_bitmap.
Answer: Color is usually controlled with the glColor3f function, thus if the text is white and shouldn't be then the following change should help:
glLoadIdentity();
glColor3f(0.5f, 0.5f, 0.5f);     //<-- this line controls the color (now text is gray)
glTranslatef(0.0f, 0.0f, -5.0f);
glRasterPos2i(x, y);

Also, calling glDisable(GL_TEXTURE_2D) and glEnable(GL_TEXTURE_2D) is unnecessary. Instead you can just call glBindTexture(GL_TEXTURE_2D,0) to disable textures and then use the same function to set the active texture. Just make sure to call glEnable(GL_TEXTURE_2D) in your initialization function.

Setting glutBitmapCharacter color?


Combine multiple column values into new column(s) if it's a duplicate

Question: I'm even sure if this can be done or not, but I'm hopeful. Currently using mysql 5.7
I want to show all columns if they're duplicate entries based on the phone value. Then I want to select all the data from the higher id number into multiple new columns.
I have no idea how to create a view that will correctly show all duplicates, otherwise this would be easier to figure out. I used the following query to get the data.
Original table
id  customer_name   customer_email   customer_phone   comments
1   Jack            firstname.lastname@example.com    111-111-1111
2   Jill            firstname.lastname@example.com    111-111-1111
3   Tim             firstname.lastname@example.com      222-222-2222
4   Tonya           firstname.lastname@example.com  222-222-2222

Expected results
id  customer_name   customer_email   customer_phone   spouse_name   spouse_email    comments
1   Jack            firstname.lastname@example.com    111-111-1111     Jill          firstname.lastname@example.com   Jill firstname.lastname@example.com
3   Tim             firstname.lastname@example.com      222-222-2222     Tonya         email@example.com Tonya email@example.com

Ideally, all 3 columns would be populated, but spouse_name and spouse_email are more important since I can always combine them and insert into comments.
Comment: This seems stunningly presumptuous. What century are you using?
Comment: @Strawberry Do you have a better recommendation or just want to be rude?
Answer: If you are running MysQL 8.0, you can do this with window functions and conditional aggregation:
select
    max(case when rn = 1 then customer_name end) as customer_name_1,
    max(case when rn = 1 then customer_email end) as customer_email_1,
    customer_phone,
    max(case when rn = 2 then customer_name end) as customer_name_2,
    max(case when rn = 2 then customer_email end) as customer_email_2
from (
    select t.*,
        row_number() over(partition by customer_phone order by id) rn
    from mytable t
) t
group by customer_phone

When two rows have the same customer_phone, this puts the name and email of the row that has the smallest id in the first two columns, then those of the other row.
Notes:

if there are more than two rows, rows after the second one are ignored

if there is just one row, the last two columns are empty

nothing in your data allows distinguishing the customer from the "spouse", so I used numeric prefixes for the column names instead
Comment: I should have said I'm using 5.7 Is there anyway to accomplish it using that version?
Comment: @J.R.: implementing such logic in MySQL < 8.0 will be challenging.
Comment: I just ran it locally and it works perfectly using 8.0 Is there anyway to combine customer_name_2 and customer_email_2 into a notes column or is that gonna require a separate query?


Make any app run full-screen

Question: Is there any systemwide command to make any app run full screen? It seems some apps have this feature, and some don't. Is there any way to force any app to go full screen?
Answer: Depending on your security with ubuntu you may or may not need sudo you can always force in terminal.
sudo application-fullscreen
Comment: What is `application-fullscreen` supposed to be?
Comment: That's a bad answer.
Comment: This doesn't work. Did you misformat your question? Maybe it's supposed to be an argument to a certain app which supports it?

Make any app run full-screen


Replacing bath fan light heater - Existing Wire is (3) /2 cable

Question: Old fan light heater was on a triple switch where each function had its own switch. I am a amateur DIYer, have tried each and every way possible to wire it. I either get nothing or the switch is bypassed causing the fan to run continuously. Please Help!
Comment: @Harper  brain fart on my part.... momentarily  thinking fan and light on same switch. But never neutral on bare one.  Happy Halloween Harper.
Comment: @JACK no sorry, YOU were right.  3 cables with the power at the fan is wrong.  3 cables with power at the switch is the situation I endorse.
Comment: Can you include a picture of your switch box?
Comment: I'm thinking your not supposed to run three separate cables like that.
Comment: Can you live with fan and light coming on together?
Comment: I agree with 3 cables + power at the switch being correct. The last few of these I have done with smurf tube and just ran THHN  easier than the larger horribly expensive 12/2/2 & ground.
Answer: If you have 4 cables going into the switch box and the white wires are pigtailed together and there is a hot, black, connected to the common post,  then  connect your three white wires from the switch box to the three white wires from the fan unit. Then connect each switch wire to one of the wires from the fan unit. You can rearrange the switch locations in the switch box for your preference. Remember to shut off the power at the main panel before doing any work.
In the future, don't just try all different combinations to see what works. Sometimes things will work but can still kill you..... Take pictures and come back to this site for help before you start. There are some really smart people (not me) that will help you out.
Answer: Are you saying you have the hot at the fan and then 2 more cables going to the switch? If so this was a code violation but I have seen it done before.
First,   Identify the feeder cable and mark it, next tie the neutral / white wire of the feeder to the fan, light and heater.
Now you have 2 cables going to the switch box you have to figure out which is which mark them 1 & 2 or identify them so you know the difference.
Next at the fan tie the hot supply to one of the switch cable's whites and mark that white wire with black at each end (actually any color other than green, white or gray is ok). The white you just marked in the switch box goes to all 3 switches.
Now you have 2 black and 1 white left, Mark the white again I like red in this case because it will be a switched hot but black works, tie it to one of your switches and the other end to the light , fan or heat black
repeat for the other 2 black wires each to a switch then to the fan / heat. Last if you have grounds tie them together in the fan box and ground the switch to it's green screw,
now you should be able to power it up and everything will work.
Again separate cables is not to code but I have seen this done and with the feeder in the ceiling this would work, if you have 4 cables at your switch box and no others we will need to start over.
Comment: 4 wires at the switch box would be ok 1 feed and each device has its own cable but I have seen 3 wires in the ceiling many times mostly in 50's & 60's era homes, I always thought it was strange to have the exhaust fan pulling all the heat out. But that was the only heat source in many of that eras homes.
Comment: Since the folly of separate cables is proportional to current, strive to have supply and heater-switched in the same cable.
Comment: That would make sense it would be helpful if the op came back and let us know where the power comes in at.


Product of disjoint cycle example

Question: $(123)(45)(15)(24) = (14)(235)$, according to my lecture notes, yet I keep getting $(143)(25)$. By doing
$$1 \to 4\\
4 \to 3\\
3 \to 1\\
2 \to 5\\
5 \to 2$$
Where am I going wrong?
Comment: You get one answer (lecture notes) by evaluating left to right; and the other answer (your answer) by evaluating right to left.
Comment: And actually AFAIK right to left (yours) is more standard as in consistent with usual composition.
Answer: After $(123)$ we have $31245$.
After $(45)$ we have $31254$.
After $(15)$ we have $41253$.
After $(24)$ we have $45213$.
which gives $(14)(235)$.

Product of disjoint cycle example


Sending an HTTP GET request xcode

Question: I'm trying to send the content of a contact form to my webservice.
My code is based on a StackOverFlow topic named : Sending get method in Xcode .
I think i follow the rules but it still doesn't work. I don't want u to lose your time, but i'm starting to get mad.
<code>- (IBAction)send:(id)sender{

NSString *get = [[NSString alloc] initWithFormat:@"&Contact%%5BFirstName%%5D=%@+First&Contact%%5BLastName%%5D=%@+Last&Contact%%5BMail%%5D=%@&Contact%%5BPhone%%5D=%@&Contact%%5BMotivations%%5D=%@&Contact%%5BCommentaires%%5D=%@",prenomtxtfield.text,nomtxtfield.text,emailtxtfield.text,teltxtfield.text,pvController.mail.motiv,questiontxtview.text];

NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *getLength = [NSString stringWithFormat:@"%d", [getData length] ];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://xxx.zfort.net/index.php?r=site/contactAdd"]];
[request setHTTPMethod:@"GET"];
[request setValue:getLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:getData];
</code>
My fields are : Last Name , First Name , Mail, Phone , Motiv, Question .
My webservice addr is : http://xxx.zfort.net/index.php?
Thank you all (even you're not responding... you've all already helped me in the past with your comments)
PS: it may be an issue of encoding values ?
Comment: What happens when you run this code?
Comment: Nothing.. the webservice shows no add contact, and when i tried to get a response with this :

    NSURLResponse *response = [[NSURLResponse alloc] init];
    NSError *error = [[NSError alloc] init];

    NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSString *replyString = [[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding];
    NSLog(@"reply string is :%@",replyString);

replyString is empty
Comment: Have you tried to track the request and response with something like charlesproxy.com? That way you could check, how far your request gets or what the response exacly look like. If you then don't get any response at all, your request or the server is not working.
Answer: Try this:
<code>NSString * sendstring=[NSString StringWithFormat:@"http://xxx.zfort.net/index.php?r=site/contactAdd&Contact%%5BFirstName%%5D=%@+First&Contact%%5BLastName%%5D=%@+Last&Contact%%5BMail%%5D=%@&Contact%%5BPhone%%5D=%@&Contact%%5BMotivations%%5D=%@&Contact%%5BCommentaires%%5D=%@",prenomtxtfield.text,nomtxtfield.text,emailtxtfield.text,teltxtfield.text,pvController.mail.motiv,questiontxtview.text];

[NSURLConnection initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:sendstring]] delegate:self];
</code>
Then you haven to implement
<code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
</code>
and
<code>- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
</code>
from
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
Answer: You should either change the method to "POST" or

append your get arguments to the url parameter
set content-length to 0 and set http body to nil
Comment: Hmmm i let the GET method, (because the webservice is that way) plus

    NSString *get = [[NSString alloc] initWithFormat:@"http://imassa.zfort.net/index.php?r=site/contactAdd&Contact%%5BFirstName%%5D=%@+First&Contact%%5BLastName%%5D=%@+Last&Contact%%5BMail%%5D=%@&Contact%%5BPhone%%5D=%@&Contact%%5BMotivations%%5D=%@&Contact%%5BCommentaires%%5D=%@",prenomtxtfield.text,nomtxtfield.text,emailtxtfield.text,teltxtfield.text,pvController.mail.motiv,questiontxtview.text];

and did 1. and 2.
Still nothing .
PS : how am i not getting any response ?
Thank you vm.

Sending an HTTP GET request xcode


how to apply for loop inside in select query inside the configured datalist?

Question: I have created a datalist with
GridLines="Both" RepeatDirection="Horizontal" BorderColor="Black"
                    BorderStyle="None" CellPadding="5" CellSpacing="1" RepeatColumns="6">

I also have created database where their is column with productid which is the primary key of my table
so in this as i insert the items they get insert in the datalist in the the horizontal columns,( incrementing the value of productid) and  as its limit exceed 6 a new row got created.But I want only 12 item each time i.e. only 2 rows.
I have added two Linkbuttons in the footer template of the page. I want as i click on the next button the items display count from product id =13 to 24 and  so on upto count(n).
I have configured my datalist with SqlDataSource1 and want to use the query statement like this
 SelectCommand="SELECT * FROM Products where ProductId>=n and ProductId<=m order by [Sports Name]"

i declared the m=1 and n=12 at the page load
 but when i run my page the following error occured
Invalid column name 'n'.
Invalid column name 'm'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'n'.
Invalid column name 'm'.

now please help me to do this type of coding in my project.
Answer: Try string.Format
SelectCommand = string.Format("SELECT * FROM Products where ProductId={0} and ProductId={1} order by [Sports Name]", n, m);

Comment: this statement iss generating parse error Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Comment: The SelectCommand is set in the .ASPX file, therefore you can't use VB code like `String.Format()`.


Is there a way to play KSP without having studied rocket science?

Question: A couple of years ago I bought KSP and struggled to even get through the tutorial getting the "basics".
I didn't get anywhere, got frustrated and just stopped playing the game. However this morning I felt like I should give the game another chance.
Now it's currently 5pm and after about 10 hours of playing I still didn't even get successfully through 1 of the tutorials and I'm just getting as frustrated as before.
So my question is: Is there any preknowledge expected for this game, or is there anything I can get a tutorial about how to play successfully the tutorial?
currently I'm just faced failing all some minutes in the same situation with not explained instructions I dont know how to execute and without any help from the internet.
Is it just me who has this trouble or am I simply missing some other people's help?
Comment: Ah, I thought you meant rocket science as in the in-game technology, and I was like, "It's gonna be hard to land on Duna with just the weakest SRBs".
Comment: You don't need to be a rocket scientist to start playing KSP, [but you will likely become one when you play it enough](https://xkcd.com/1356/). In my opinon the point of the game is to teach yourself rocket science just like the space pioneers in the 50s and 60s. Reading real-world material about space exploration is surprisingly helpful. I fully understand that this kind of game experience is not for everyone.
Comment: I haven't played in a while, but what helped me the most were [a few video tutorials by Scott Manley](https://www.youtube.com/user/szyzyg).
Comment: I have no clou... Its more like I spent now (counted by steam) like 12 hours playing the game at all, and haven't had any success.... But I guessit is really just me...
Comment: A warning, if you continue with the tutorials: "To the Mun, Part 2" is broken in the current version of KSP (220.127.116.11).  You're supposed to land on Kerbin, but the parachute is configured to open too late, and you'll crash.  You'll need to change the parachute altitude from 500m to 1000m by right-clicking the parachute on the top of your actual rocket (not the parachute icon in the staging panel), which you can do before flight.  You don't need to do this in the main game; parachutes are set to open at 1000m by default.
Comment: The KSP Wiki has some [campaigns](http://wiki.kerbalspaceprogram.com/wiki/Campaigns) that are very good for learning the game. You basically play out the history of rocketry/space travel through the game. The wiki also has good tutorials. The in-game tutorial isn't too great.
Comment: Mad Scientist is right. Watch Scott Manley's video tutorials. As a veteran player, I *still* learn oodles from his videos.
Comment: As @MadScientist mentioned, a great way to get started is just watching some Scott Manley tutorials on YouTube.  There are other tutorials for sure, but I find his to be among the best, he keeps it simple yet entertaining...and he really knows his stuff.
Comment: @Philipp Your comment seriously just sealed the deal on wether or not I'm going to purchase this. (You convinced me yes, btw.)
Answer: You don't need to have previously studied rocket science to play Kerbal Space Program.
I've had a brief look at the tutorial and it covers stuff that you don't really need to know to get started, like radial decouplers. You can practically get into orbit by just using the starting pod, chucking a parachute on top, sticking some fuel tanks in the middle, and a rocket on the bottom (getting out of orbit again needs a little more ;p). And you start with SRBs (solid rocket boosters) so you won't even really need that, just chuck a bunch of SRBs on the bottom.
The second tutorial starts off with introducing the controls in the bottom left, which I think that I have literally never ever used. RCS which you won't need until you're trying to dock ships in orbit. The ship holder thingies that are only useful for the biggest, heaviest rockets. Then there's a bunch about asteroid redirects, which are pretty late-game stuff.
Actually playing KSP is a lot easier than the tutorial makes it seem. All of those things (well most of them) are useful, but you are introduced to them a lot more gradually.
However, you will need the ability to discover and grasp new concepts for yourself. For example, orbital mechanics- the first time I tried to fly to the Mun, I literally just tried to go straight up. You need to have somewhere you can ask questions when you get stuck, but the answers are usually quite simple. You won't succeed at Kerbal Space Program without outside help from time to time.
I also forgot to mention MechJeb, which is fucking awesome and IMO the game is unplayable without. But that's in the somewhat longer term.
Comment: Yep. You can start with only the stuff you actually need.
Comment: So your advice is screw on the tutorial and jsut start a game?
Comment: While this is totally subjective, I would recommend checking out _Scott Manley_ on YouTube. I learnt most of the basics from watching his beginner's guides and tutorials.
Comment: I was barely able to get a rocket in orbit, and one thing that jumpstarted my progress was learning about maneuver points (been a while, don't remember the exact name). Then landing and orbiting got much simpler
Comment: IIRC one of the in-game tutorials demonstrates orbital mechanics and the map view.
Comment: @IlmariKaronen: Thanks I will have a look into it next weekend when I have time for playing again. I'm looking forward to play the game again since all the hints here feel like it is worth trying it one more time. It would be nice if someone (you?) could summarize the in some comments named tutorials into an answer, as comments aren't neccesarly available for ever, and the OP also asks for 3rd party tutorials. So It wpould be at least worth an upvote of me.
Comment: "ship holder thingies". I'm assuming that's the technical term? ;)
Comment: Scott Manley's videos are funny but quite outdated now as far as I can tell.
Comment: To be fair, you *can* get to the Mun by going straight up.  It's just very difficult since you have to launch at exactly the right time and you can't use maneuver nodes to plan the route.  It'd be crazy to try, but it's possible.
Comment: You forgot to attach https://xkcd.com/1356/ to answer ;)
Answer: As other answers have noted, the built-in tutorials in Kerbal Space Program are not something you need to complete before starting the actual game.  It's much easier to just dive right in and start playing, learning as you go.
The three game modes in KSP each have their advantages for beginners:

In Sandbox mode, you have access to everything from the start, and don't have to worry about money or science or reputation or anything else but building big rockets and seeing if they explode or not. ;-)  The main drawback of Sandbox mode is that the sheer number of parts and features available may be overwhelming.  Pick this mode if you just like to stick a bunch of crazy stuff together and see if it'll fly. :-)
Science mode is kind of a compromise between Sandbox and Career modes: you still don't need to worry about money or reputation, but you only start with a few simple rocket parts, and have to work your way up the tech tree to acquire more options.  I'd suggest this as the most beginner friendly mode in general, although the other modes have their advantages too.
Finally, in Career mode, you've got a limited amount of funds to play with, and have to worry about things like blowing up too many pilots and ruining your reputation.  The nice thing about Career mode for beginners is that you get contracts, which give you specific goals to meet and can sort of act as an in-game quasi-tutorial.  If that's something you think you'd like, or if you just feel the Sandbox and Science modes feel too aimless, go ahead and start a Career mode game.  You can always adjust the difficulty, or just restart the game if your first space program crashes and burns.

Also, there are several third-party tutorials for KSP that you might find useful.  Since it was requested in the comments that these should be mentioned in an answer, here's a brief, non-exhaustive list:

Kerbal Space Program - Career Mode Guide For Beginners by Scott Manley (for KSP v1.0)
An older tutorial series, also by Scott Manley; this is for KSP v0.23 "Career mode", which is more or less the same as Science mode in KSP v1.0
List of tutorials on the KSP wiki

Note that, due to the rapid development of KSP, some older tutorials may be somewhat out of date.  In particular, what's now called Science mode used to be called Career mode, before the new Career mode was introduced in KSP v0.24, so the naming of some older tutorials may be a bit confusing from a modern perspective.
Also, I've made this a Community Wiki answer so that it's easier to edit; feel free to improve and update the third-party tutorials list above.
Comment: I can't recommend Scott Manley's tutorials enough.
Comment: `The main drawback of Sandbox mode is that the sheer number of parts and features available may be overwhelming.` this was the problem I had when I picked it up in EA and career mode wasn't really a thing yet. Just too many pieces to worry about at once.
Comment: I second the "Science Mode" suggestion for the first playthrough. A friend of mine was overly ambitious and started with Career mode. He got stuck with his "rendezvous in orbit" contract and failed the docking tutorial several times - it is a bit picky, I have to admit. Science mode on the other hand let's you advance using your own pace and doesn't punish failures. You can always enjoy some fancy explosions instead of worrying about the lost funds and additional contract penalty.
Answer: The first versions of KSP were hard, because there was no help at all. Figuring out trajectories indeed was a major pain, and I can imagine why you bailed out.
The current version is much more accessible, in sandbox mode. That's because you get all the components. Some of them are rather critical to get to other planets and are entirely, totally overkill just to get in orbit. In career mode, however, you'll only get a few components to start with. That's hard in a different way: there's only so much you can do, and it will be quite a while before you can get to Mun.
So, if you get frustrated, ignore the tutorial and grab some big, BIG rocket components. Use a big orange Jumobo tank, a big Mainsail engine, a sturdy Mk1-2 command pod, a decoupler between  tank and engine, and an XL parachute. I don't think you need fins.
There are two core fundamentals in space flight: the most efficient acceleration is forward and backwards, which are the lime indicators on the navball. Secondly, your orbit has a high point (apoapsis) and low point(periapsis). To increase the height of one, accelerate in the opposite point.
Finally, the quick tip to get to the Mun is to get in a low circular orbit, starting eastward from the base, and wait for the Mun to rise above the horizon. Then accelerate until your apoapsis touches Mun orbit.
Personally, I use MechJeb. This is a smart calculator which gives many important figures. For instance, it can show orbital information. So that Munshot becomes a lot easier: you can see the predicted apoapsis and you just accelerate until it hits 11400 km. (Don't try to be too precise, you'll just hit the Mun if you go for 11400 km exactly.)
Comment: The limited amount of components you start with in career is an advatange, IMO - no need to scroll through hundreds of components you have no idea about; all you need is right there - just the 10 components or so.
Comment: @mbx True, `For Science!!!` mode is much better :))
Comment: @Luaan How can you enjoy the explosions? How can you embrace failure? How can you do it *the Kerbal Way*  when constantly thinking about money?
Answer: The other answers, especially "Community Wiki" answer above with the lists of tutorials is great.
My recommendation is (like others) to skip the tutorials and do your first play-through in science mode.  I'd set your first goal to be making orbit.
One other thing to add: I've seen a lot of posts above recommending MechJeb (MJ).  Instead, I'd recommend Kerbal Engineer (KER).  It give the same data, and doesn't do anything more.  From what I understand, MJ gives the data, and then has a bunch of autopilot features, which can be confusing if you don't understand what they're doing.
Watch some tutorials, and if you're having trouble making orbit after several attempts, come on back and we'll try to help step by step as best we can.
Best of luck and clear skies.


Differentiation constant times a function

Question: The volume of a right circular cylinder of radius $r$ and height $h$ is given by the formula $V=\pi r^2h$. Find the rate of variation of volume with the radius when $r=5.5 \text{in.}$ and $h=20 \text{in}$. If $r=h$, find the dimensions of the cylinder so that a change of $1$ inch in radius causes a change of $400$ cubic inches in the volume.
 The rate of variation of $V$ with regard to $r$ is $$\frac{dV}{dr}=2\pi rh$$
If $r= 5.5\text{in}$. and $h= 20\text{in}$. this becomes $691.2$. A change of radius of $1\text{in}$. will cause a change of volume of $691.2$ cubic inches.
 Also, if $h=r$, and $h$ remains constant, $$\frac{dV}{dr}=2\pi r^2=400$$ and $$r=h=\sqrt{\frac{400}{2\pi}}=7.98\text{in}.$$
If, however, $h=r$ and varies with $r$, then $$\frac{dV}{dr}=3\pi r^2=400$$ and $$r=h=\sqrt{\frac{400}{3\pi}}=6.51\text{in}.$$
I'm having trouble understanding the last part, when $h=r$ and varies with $r$. Since both $r$ and $h$ are varying, do I use the product rule? I follow the differentiation of $V$ with respect to $r$ when only $r$ was varying, now that they're both varying I'm stumped. Thanks in advance for any assistance and apologies if this turns out horrendous it's my first question.
Comment: In the first case you took the partial derivative with respect to r and **then** set h= r.  The partial derivative with respect to r assumes that h is a constant.  That is not possible with r= h.  You have to replace r with h **first**, then differentiate.
Comment: If one of the answers is posted, please mark it as the answer with the check mark right beneath the vote ticker in the answers list.
Answer: So, what you're looking at is a problem of "when is $h$ dependent on $r$?" To solve this, we can simply rewrite it as $h(r)$ and differentiate when necessary.
Given $V(r) = \pi r^2h(r)$, we can differentiate with the product rule.
$$\begin{align*}
\frac{dV}{dr} &=\pi \frac{d}{dr}\left(r^2\right)h(r)+\pi r^2\cdot \frac{d}{dr}\left(h(r)\right) \\ \frac{dV}{dr}&= 2\pi rh(r) + \pi r^2h'(r)
\end{align*}$$
Now, if $h(r)$ is a constant, then $h(r) = h$ and $h'(r)=0$. Simply plugging in will yield your resultant formula, $dV/dr = 2\pi rh$.
However, if $h(r)$ is not a constant, then simply plug in for $h(r)$ and $h'(r)$.
Hope this helps!
Comment: Thank you big time @Drew Christensen, great help
Comment: If this is the answer to your question, then please mark it as the answer using the check button right beneath the vote ticker.
Answer: It looks like you have the first two in hand.  But don't convert to decimals unless you have been told to do so.
3) $h$ varies with $r.$
You can apply the product rule, but it is not really necessary.
$v = \pi r^2 h\\
\frac {dv}{dr} = (2\pi r)h + (2\pi r^2) \frac {dh}{dr}$
Now you can substitute $r=h$ and $\frac {dh}{dr} = 1$ and $r = h$
However, if $r = h$ and $r$ varies with $h,$ you can merely say $V = \pi r^3$
And differentiating you will get the same result.


CDF of mins and max's of Random Variables

Question: Suppose $X$ is a uniform random variable on $[0, 2]$. I just wanted to check some basic problems regarding CDFs.
(i) What is the CDF of $Y = max\{1, X\}$ and (ii) What is the CDF of $Z = min\{X, X^2\}$?
For (i) I want to say that $F_Y(t) = 0$ if $t \leq 1$, and then for $t \in [1, 2)$, $F_Y(t) = (t-1)/2$ since the relevant part is $X$ being between $1$ and $t$ only. And then at $t = 2$ we have a discontinuous jump up to $F_Y(2) = 1$ at which point it is constant. Does this sound right?
(ii) is a bit more complicated I guess. $F_Z(t) = 0$ for $t \leq 0$ obviously. But for $t \in [0, 1]$, $X^2 \leq X$ always holds, so $\mathbb{P}(Z \leq t) = \mathbb{P}(X^2 \leq t) = \mathbb{P}(X \leq \sqrt{t}) = \sqrt{t}/2$, so $F_Z(t) = \sqrt{t}/2$ on $t \in [0, 1]$. Then from $t \in [1, 2]$ onwards, we always have that $X \leq X^2$, so that $\mathbb{P}(Z \leq t) = 1/2 + \mathbb{P}(1 \leq X \leq t)  = 1/2 + (t-1)/2 = t/2$, and so $F_Z(t) = t/2$ for $t \in [1, 2]$ and is a constant $1$ from that point onwards. I'm less sure about this since it is continuous which seems unlikely to me, and my logic feels sketchy.
Answer:
For (i) I want to say that $F_Y(t) = 0$ if $t \leq 1$, and then for $t \in [1, 2)$, $F_Y(t) = (t-1)/2$ since the relevant part is $X$ being between $1$ and $t$ only. And then at $t = 2$ we have a discontinuous jump up to $F_Y(2) = 1$ at which point it is constant. Does this sound right?

Not quite.  That is not at all correct on the discontinuity issue, but you are correct in other aspects.
There is no step discontinuity at $t=2$, that is just where the CDF stops increasing (when it reaches $1$).   The function is not smooth there, but it is continuous.   $$\lim_{t\nearrow 2}F_Y(t)=1\\\lim_{t\searrow 2}F_Y(t)=1$$
The step discontinuity occurs at $t=1$, because there all the mass of $\{X\leqslant 1\}$ is concentrated. That is to say $\mathsf P(\max\{1,X\}<1)=0$ and $\mathsf P(\max\{1,X\}=1)=\mathsf P(X\leqslant 1)$.
$$\lim_{t\nearrow 1} F_Y(t)=0\\\lim_{t\searrow 1} F_Y(t)=1/2$$
For all $t$ at and above $1$ (and below $2$), then the CDF for $Y$ equals the CDF for $X$.  So your evaluation in the parts is correct.
$$F_Y(t) =\begin{cases} 0 & : & t<1 \\ t/2 &:& 1\leqslant t < 2\\1 &:& 2\leqslant t\end{cases}$$

(ii) is a bit more complicated I guess.

Just a bit, but not that much.  You are correct that the function partitions at $X=1$, and about the evaluation in each part, but the function is continuous at that point.
$$F_Z(t) = \begin{cases}0&:& t<0\\ \sqrt{t~} / 2&:& 0\leqslant t<1\\ t / 2&:& 1\leqslant t< 2\\1&:& 2\leqslant t\end{cases}$$

Long story short.  Don't confuse continuity of the function with continuity of the gradient.


Import modules in a angular Worker?

Question: we are developing a ionic application. I created a service(.ts) and imported a geo-json-pathfinder. Initializing this pathfinder takes 10-20 seconds, so im supposed to outsource it into a Worker(.js).
import PathFinder from 'geojson-path-finder';

at the top of my worker.js returns an error:

SyntaxError: import declarations may only appear at top level of a
  module

How i can deal with it? And am i able to send this pathfinder to my ui thread like this?
let pathfinder : Pathfinder = new Pathfinder(geojson);
self.postMessage({obj: pathfinder})

Answer: There are two issues.

Most likely, you cannot just pass the path finder like that. Read the documentation more carefully. You'll see that you should only pass the result of graph preprocessing. Check the sourcecode of the project, you can see how they're obtained.
const preprocessedGraph = preprocess(graph, options);

You will need to mess around with this a little to make it do what you need.
To import ES6 modules into web worker, use the second parameter:
const myWorker = new Worker("worker.js", "module");

Import modules in a angular Worker?


What advantages does bending copper pipes have over joining many parts without brazing?

Question: These questions are in context of a DIY solar water heater I am planning (another separate question). The copper pipes in question, are supposed to carry around hot water using thermo-siphon mechanism.
Are there some specific reasons why people recommend bending long copper pipes, instead of cutting them into sections and joining them using U-joints, elbow-joints etc. ?
Also, can such joints be made reliable (as in leak-proof, while withstanding water pressure) without brazing them ?
Comment: Just a side note:  Questions about Braising belong on cooking.stackexchange.com.  Questions about brazing belong here. (I fixed it)
Comment: Thanks Chris. Looks like this is a common mistake. Even wikipedia has clarifications to this effect.
Answer: Fewer points of failure
Bending results in fewer high risk failure points.
A continuously bent pipe has 2 high risk failure points. Whereas a similar length of pipe made with a bunch of fittings, has 2 high risk failure points per fitting.
Quieter
Bending a radius will provide less resistance within the pipe, so water will flow smoother. In a pressurized system, this means water flow is quieter.
Thanks @kavisiegel
Comment: This, along with the fact that bending a radius will provide less resistance within the pipe. Water will flow smoother. In a pressurized system, this means water flow is quieter as well.
Answer: Bending copper has to be done with annealed copper.  Rigid copper is too brittle can be done with either drawn or annealed copper.  This table from copper.org does suggest slightly larger minimum radii for drawn pipe. thanks to @UNECS for prompting further research.
You can make rigid copper easier to bend successfully by heating the area of the bend with a torch and letting the pipe air cool slowly, thus annealing that area.

The mandrel bender will make very uniform bends.

The spring bender will make more freeform bends.
Once bent, compression connection joints can be made with ferrules or flared ends.  Note, you cannot mix ferrules with flares without a intervening adapter.

Note the tubing extending out past the joint.  Make sure the copper tube bottoms in the fitting THEN tighten the overcap firmly.

Flare connections mate with flare nuts (be sure to put flare nut on BEFORE making flare.
Comment: Hard drawn copper can and is quite regularly bent without annealing (as I do it nearly every day)
Comment: In which case @UNECS, would annealing help bend copper tubing more easily, and with more rudimentary tools ?
Comment: @UNECS based on your coments, I did more research and I agree concerning drawn copper.  I've updated my answer to reflect this.
Answer:
Are there some specific reasons why people recommend bending long copper pipes, instead of cutting them into sections and joining them using U-joints, elbow-joints etc. ?

Pipe fittings add resistance to the flow of the fluid in the pipe. This is usually expressed in terms of an equivalent pipe length for the different fittings (eg, elbows, tees, etc). For example an elbow bend is approximately equivalent to an additional 300mm of straight pipe. The total equivalent legnth of pipe in a system can then be used to determine the size of pump required, as pipe of a given diameter will have a known pressure loss (due to friction) per unit length.
A 90 degree swept bend in a pipe will have lower resistance than an elbow fitting (albeit with a much larger radius). It will be a little higher resistance than the same length of straight pipe, but not significantly so when compared to the approximately 300mm of additional equivalent length the elbow would introduce.


Is there a way in Google Sheets to combine JOINs and FILTERs in a dynamic way and with one single formula?

Question:
I have a situation like the one depicted in the screenshot.

In column E:E there's a list of words that I want to join.
In column F:F there's a sequence of increasing integers.
In cell G5 theres an integer (1999) that divides the previous increasing list of integers in several groups (1, 2, 3 ,4 etc). The groups show up below 1999, in range G6:G.
In colum H:H I have the desired results, which by now I am able to achieve via a series of JOINS and FILTERS placed manually in each cell under H6. In the first row (cell H6), we find words joined that belong to the group 1, in the cell below words belonging to group 2 and so on.
I would like to achieve the same results but with one single formula, located in cell H6, a formula that would work independently of how long the list of words is, or how large the interger divider is, or how many resulting groups are.
Thank you so much.
Spreadsheet example
Answer: Use MAP, like this:
=MAP(I6:I,LAMBDA(i,iferror(if(i="",,join(", ",filter( E:E,G:G=i))),)))

Comment: Thanks for your answer. However, the intention was not to use the column I:I for the purpose of the excercise
Answer: Calculating everything directly from your lists of words and integers, and the divisor value (so avoiding the need for columns G & I):
=arrayformula(let(
integers,tocol(F6:F,1),
words,tocol(E6:E,1),
divisor,$G$5,
groups,ceiling(integers/divisor,1),
map(unique(groups),lambda(each,join(", ",filter(words,groups=each))))))


Minimize Portal 2 diskusage

Question: Portal 2 uses 12 GB on my disk if I install it via Steam.
I only have a 60GB SSD in my laptop.
If I only want to play Multiplayer, which files can I safely delete, so the game will still run?
the .vpk files are the largest part of the game, and I tested to move some files and found out, that the game starts, if I remove these files in \SteamApps\common\Portal 2\portal2\: pak01_009.vpk   pak01_013.vpk   pak01_014.vpk, pak01_015.vpk,   pak01_017.vpk,   pak01_018.vpk,   pak01_019.vpk,   pak01_020.vpk and pak01_022.vpk
(That frees up already 2GB)
Which other files are not needed to play Multiplayer?
Comment: What's your HD situation? I've never been in a position where "what files can I delete from this game and it still work" is a question I ask before "what files on my HD can I backup and delete" or "what games can I uninstall to make room for new games".
Comment: I only have a 60GB SSD in my laptop, and I don have any other large games on it that I could delete
Comment: Then I'm sorry to say the right answer may be "your laptop won't support that game due to your [small SSD size]", just as I wouldn't be surprised to replace the text in brackets with "underpowered video card" or "older processor" or "small RAM amount" for other games.
Comment: It runs fine on my laptop with high resolution and effects, It is just, that I don't need all the single-player part of the game
Comment: My point is not that those other parts aren't up to snuff when you're gaming; I'm saying that for any game and any PC, there's usually (at least) one piece of hardware that's the limiting factor. For this game and for your laptop, it's your SSD. If you had a desktop PC and you didn't have 12 GB to spare, the answer would be "go get a bigger HD/SSD", not "hack the game files".
Comment: What is so bad about asking? sure, if I had the money I could buy a bigger ssd. I still have 2GB left now after installing portal and it works fine. I just would like to free some unneeded stuff. I think it is a good goal to circumvent the costs of a bigger SSD.
Comment: The reason it's a bad question is that any solution would be an unsupported hack. It's one thing if, like Microsoft Word (for example), the Portal 2 installer allowed you to uninstall or turn off features you didn't want to use. It's another if there's no supported way to remove parts of the installation. (Mods, feel free to delete/move my comments to chat.)
Comment: Maybe expensive, but I use Ceedo and run all my steam, including portal 2, off an external harddrive. I use a 500gb non-ssd drive. My main drive is 120gb ssd. I also have a second drive internal 1tb, I never install anything to main drive.  And I moved all my user folders off main drive as well. So only OS runs there, and I have backup should OS fail.
Answer: You won't be able to delete any of the data and play it.
Steam will force you to re-download all of the content before you can launch the game.
Comment: I'm fairly certain that replacing them with dummy files will not work. Steam performs an integrity check on core files regularly.
Comment: Also you might get some VAC warns if it's a multiplayer game.
Comment: maybe I can replace some video-files with some small dummy files?
Comment: @rubo77 How much of the game were you able to play? Were there any glitches? Where you in offline mode? When you quit/reconnected to steam did steam re download all of the missing files?
Comment: @rubo77 Possible, but I don't really know. I have never had luck with replacing files on valve games. I have only had success with adding new video files and then changing the .ini files that reference them to play my custom vids.
Comment: This is not correct: I added to my Question some **files I could delete without Steam forcing me to re-download** and still play it
Comment: I played multiplayer the first level without problems. Logged out of the game and still Steam didn't try to re-download those files
Answer: Rather than deleting files, you should move them to another disk and link them from there (using symbolic Links). I do this myself to free space on my SSD without breaking programms. Link Shell Extension is a perfect tool if you don't want to use the console.
Answer: You can delete the all of the .bsp files in your "maps" directory which do not have names containing "coop" or are part of the main menu.
Answer: Since the .vpk files are the largest part of the game, you can remove these files in \SteamApps\common\Portal 2\portal2\: pak01_009.vpk   pak01_013.vpk   pak01_014.vpk, pak01_015.vpk,   pak01_017.vpk,   pak01_018.vpk,   pak01_019.vpk,   pak01_020.vpk and pak01_022.vpk
That frees up already 2GB of disk-space.
Maybe there are more files you can remove, some more testing woul be needed to find out.

Minimize Portal 2 diskusage


Nodejs redirect from POST method not working

Question: I have a logout button, which sends a POST request. After that it should redirect the user to the main page, but nothing happens. I also tried to set the status code to 302, 303...
Code:
//on click this is executed
function logout() {
  fetch('/logout', { method: 'POST' });
}

//this is called on POST request
const logout = (_req, res) => {
  res.clearCookie('token');
  res.locals.payload = undefined;
  res.redirect('/');                    //problem
};

//logged requests
POST /logout 302 23 - 0.865 ms
GET / 304 - - 6.058 ms

Comment: I don't see anything wrong with this specific snippet. Could you show how this is used in the context of your application?
Comment: Note if you are using an AJAX request to reach that endpoint it won't redirect the user's page, it will just redirect the AJAX request to that location and retrieve whatever data is returned.
Answer: If your /logout endpoint accepts GET requests, try redirecting the user there instead. For example:
function logout() {
    document.location = '/logout';
}

Otherwise, add a redirect in JavaScript once the cookies are cleared:
async function logout() {
  await fetch('/logout', { method: 'POST' });
  document.location = '/';
}


Concat first name and last name in where clause in laravel mongodb to search

Question: I am trying concat first name and last name in Laravel but it's not working. i am using mongo db
i was tried this sql query but its not working
<code>->orWhere(\DB::raw("CONCAT(`last_name`, ' ', `first_name`)"), 'LIKE', "%".$search."%");
</code>
can anyone find the alternate solution of concat in mongodb
Thank you in advance
Comment: what package are you using ?
Comment: https://stackoverflow.com/questions/24662413/select-records-matching-concat-value-of-two-fields-in-mongodb says it can't be done with a regular query. I don't know how to use that with Laravel's query builder, though
Comment: Hello @MoussabKbeisy We are using a mongo package for laravel jenssegers/mongodb
Answer: Can't you do something like:
<code>$full_name = explode(" ", $search);
$last_name  = $full_name[0];
$first_name = $full_name[1];
</code>
Then:
<code>->orWhere(function($query){
  $query->where('last_name', $last_name)->where('first_name', $first_name);
});
</code>
Comment: hi @kapitan thank you it's working
Comment: glad to know its working, though you might want to full proof this further by adding the `trim()` function. `trim(explode(" ", $search))`, `trim($full_name[0])` and `trim($full_name[1])`.


How can we approximate the integrand?

Question: How can we approximate the integrand of $$\int_0^\infty \exp\left({-(x-a)^2\over 2a}\right)$$ so that the integral is approximated by $$\sqrt{2\pi a}$$?
Thank you!
Comment: welcome to SE. You might want to give some more context to your question to get better answers. Feel free to look around the site to see how questions are formulated to achieve most useful answers.
Answer: Hint: Note that $a<0$ is necessary, otherwise the integral diverges. Now, $$u=\frac{x-a}{\sqrt{2(-a)}},$$ so that you have $du=\frac{dx}{\sqrt{2(-a)}}$. Now integrate $$\sqrt{2(-a)}\int_{\sqrt{-a/2}}^\infty \exp(-u^2)\,du.$$
Comment: Which equals $+\infty$.
Comment: @julien: You are correct. I've edited it now; thanks.
Comment: I think this is wrong.  What is the value of $u$ at the lower integration limit?  I don't think it is $0$.
Comment: @RossMillikan: You are correct. I think it's been edited (?) correctly now. I was actually in the process when you commented. Either way, it seems a poor answer to me.
Comment: Thank you, Clayton. I have stupidly left out a minus sign -- edited.
Answer: If $a$ is positive, the integral diverges.  If $a$ is negative, the peak is to the left of zero and the integral will be less than $\sqrt {\frac {\pi a}2}$, which is what it would be if the integrand were $\exp(\frac {x^2}a)$
Comment: Thank you, Ross. I have left out a minus sign :/ Does it work now?
Comment: Now it diverges is $a$ is negative.  If $a$ is large and positive, the integral will be close to $\sqrt 2 {\pi a}$ because the peak will shift to the left.  The standard deviation is $\sqrt {\frac a2}$, so the peak is $\sqrt {2a}$ standard deviations above zero.  The tail below $0$ will get small as $a$ gets large.  You can use the error function to integrate this, but that is just giving it a name.  You can look up approximations to it based on the number of standard deviations.
Answer: Following up on @Clayton's corrected answer, the integral is
$$\sqrt{\frac{\pi a}{2}} \mathrm{erfc}{\left (\sqrt{\frac{a}{2}} \right )}$$
where $\mathrm{erfc}$ is the complement of the error function.  For small values of $a$, this takes the value, roughly of $\sqrt{\frac{\pi a}{2}} - a$

How can we approximate the integrand?


Relative path not working in cron PHP script

Question: If a PHP script is run as a cron script, the includes often fail if relative paths are used. For example, if you have
require_once('foo.php');

the file foo.php will be found when run on the command line, but not when run from a cron script.
A typical workaround for this is to first chdir to the working directory, or use absolute paths. I would like to know, however, what is different between cron and shell that causes this behavior. Why does it fail when using relative paths in a cron script?
Comment: Don't change your PHP files just to make them work from a cron job, instead change the current directory on the cron job line. Check my answer [here](https://stackoverflow.com/a/55385788/5407848).
Comment: This is a great resource as well: http://stackoverflow.com/questions/2857712/enable-proper-relative-path-in-cron
Answer: Change the working directory to the running file path.  Just use
chdir(dirname(__FILE__));
include_once '../your_file_name.php'; //we can use relative path after changing directory

in the running file. Then you won't need to change all the relative paths to absolute paths in every page.
Comment: You can also use `chdir(__DIR__);` which is a bit more concise.
Comment: This was driving me mad. This sorted it out perfectly
Comment: this only works if you can execute `chdir()` in your environement. `include/require dirname( __FILE__ )` is much more reliable.
Comment: I don't like to change the PHP code, instead change the directory at the cron tab, check [my answer](https://stackoverflow.com/a/55385788/5407848)
Answer: The working directory of the script may be different when run from a cron. Additionaly, there was some confusion about PHPs require() and include(), which caused confusion about the working directory really being the problem:
include('foo.php') // searches for foo.php in the same directory as the current script
include('./foo.php') // searches for foo.php in the current working directory
include('foo/bar.php') // searches for foo/bar.php, relative to the directory of the current script
include('../bar.php') // searches for bar.php, in the parent directory of the current working directory

Answer: The only chance I got "require_once" to work with cron and apache at the same time was
require_once(dirname(__FILE__) . '/../setup.php');

Answer: Because the "current working directory" for cron jobs will be the directory where your crontab file exists -- so any relative paths with be relative to THAT directory.
The simplest way to handle that is with dirname() function and PHP __FILE__ constant. Otherwise, you will need to edit the file with new absolute paths whenever you move the file to a different directory or a server with a different file structure.
dirname( __FILE__ )

__FILE__ is a constant defined by PHP as the full path to the file from which it is called. Even if the file is included, __FILE__ will ALWAYS refer to the full path of the file itself -- not the file doing the including.
So dirname( __FILE__ ) returns the full directory path to the directory containing the file -- no matter where it is included from and basename( __FILE__ ) returns the file name itself.
example:
Let's pretend "/home/user/public_html/index.php" includes "/home/user/public_html/your_directory/your_php_file.php".
If you call dirname( __FILE__ ) in "your_php_file.php" you would get "/home/user/public_html/your_directory" returned even though the active script is in "/home/user/public_html" (note the absence of the trailing slash).
If you need the directory of the INCLUDING file use: dirname( $_SERVER['PHP_SELF'] ) which will return "/home/user/public_html" and is the same as calling dirname( __FILE__ ) in the "index.php" file since the relative paths are the same.
example usages:
@include dirname( __FILE__ ) . '/your_include_directory/your_include_file.php';

@require dirname( __FILE__ ) . '/../your_include_directory/your_include_file.php';

Answer: Another possibility is that the CLI version is using a different php.ini file. (By default, it'll use php-cli.ini and fallback to the standard php.ini)
Also, if you're using .htaccess files to set your library path, etc. this obviously won't work via the cli.
Answer: In addition to the accepted answer above, you can also use:
chdir(__DIR__);

Comment: only if you are allowed to execute `chdir()` in the environment you're in
Comment: is that common?  I've never worked in any environment where that function wasn't allowed.
Comment: i have experienced it related to PHP safe_mode. http://php.net/manual/en/features.safe-mode.functions.php, but this has been deprecated http://php.net/manual/en/features.safe-mode.php. -- that's deprecated not removed... meaning, it could still be encountered.
Answer: When executed trough a cron job your PHP script probably runs in different context than if you start it manually from the shell. So your relative paths are not pointing to the right path.
Comment: absolute path names are a nightmare to manage as you move files around... just use `dirname( __FILE__ )`
Comment: that's right. In fact, the script's working directory is the working directory of the shell. Should use absolute pathnames.
Answer: The DIR works although it will not work on my localhost as it has a different path than my  live site server. I used this to fix it.
    if(__DIR__ != '/home/absolute/path/to/current/directory'){ // path for your live server
        require_once '/relative/path/to/file';
    }else{
        require_once '/absolute/path/to/file';
    }

Comment: still using a conditional statement that can be replaced by `dirname( __FILE__ )`


Chaining rows in a SQL Server table in a distributed system

Question: Let's say that I have the following SQL table where each value has a reference to the previous one:
ChainedTable
<code>+------------------+--------------------------------------+------------+--------------------------------------+
| SequentialNumber | GUID                                 | CustomData | LastGUID                             |
+------------------+--------------------------------------+------------+--------------------------------------+
|                1 | 792c9583-12a1-4c95-93a4-3206855d284f | OtherData1 |                                    0 |
+------------------+--------------------------------------+------------+--------------------------------------+
|                2 | 1022ffd3-afda-4e20-9d45-eec884bc2a50 | OtherData2 | 792c9583-12a1-4c95-93a4-3206855d284f |
+------------------+--------------------------------------+------------+--------------------------------------+
|                3 | 83729ad4-2564-4146-b451-00d82585bd96 | OtherData3 | 1022ffd3-afda-4e20-9d45-eec884bc2a50 |
+------------------+--------------------------------------+------------+--------------------------------------+
|                4 | d7197e87-d7d6-4175-8172-12656043a69d | OtherData4 | 83729ad4-2564-4146-b451-00d82585bd96 |
+------------------+--------------------------------------+------------+--------------------------------------+
|                5 | c1d3d751-ef34-4079-a73c-8952f93d17db | OtherData5 | d7197e87-d7d6-4175-8172-12656043a69d |
+------------------+--------------------------------------+------------+--------------------------------------+
</code>
If I were to insert the sixth row, I would retrieve the data of the last row using a query like this:
<code>SELECT TOP 1 (SequentialNumber, GUID) FROM ChainedTable ORDER BY SequentialNumber DESC;
</code>
After that selection and before the insertion of the next row, an operation outside the database will take place.
That would suffice if it is ensured that only one entity is using the table every time. However, if more entities can do this same operation, there is a risk of a race condition. There is the possibility that one entity requests the information of the last row and before doing the insert on the second one.
At first, I thought of creating a new table with a value that indicates if the table is being used or not (the value can be null or the identifier of the process that has access to the table). In that solution, the entity won't start the request of the last operation if the value indicates that the table is being used by another process. However, one of the things that can happen in this scenario is that the process using the table can die without releasing the table, blocking the whole system.
I'm sure this is a "typical" computer science problem and that there are well known solutions to implement this. Can anyone point me in the right direction, please?
Comment: I don't understand: why are you selecting out the `SequentialNumber` at all? Just let the server increment the next ID (which it is perfectly capable of doing safely). Or are you trying to do something else?
Comment: Just search on the term [sql race condition](https://www.google.com/search?q=sql+race+condition&rlz=1C1CHBF_enUS727US727&oq=sql+race+condition&aqs=chrome.0.69i59j0i20i263j0i22i30l7j0i10i22i30.3729j0j7&sourceid=chrome&ie=UTF-8). And when a process dies (along with its connections to the database), any locks will automatically be released. That is a situation that you should anticipate and handle and test, but it should be rare.
Comment: To echo @Charlieface, why not use either an identity column or column whose default is `next value for dbo.SomeSequence`?
Answer: I think using Transaction in SQL may solve the problem For example, if you create a transaction that will add a new row, no one else will be able to do the same transaction until the first one is completed.


Have TFS 2010 Build server publish to the same folder and overwrite

Question: I've been looking for ages and I'm so exasperated because what I want to do is theoretically so simple!
I have a web project and when I tell my TFS to queue a new build I want my published files(or un-published files - I don't care) to end up in a static folder such as "C:\inetpub\myproj\webfiles".
I've checked out this post TFS 2010 Build Publish via file system which led me to this post Team Build: Publish locally using MSDeploy but I just don't get it and it doesn't seem to be working.
I have my build definition all set up and it builds successfully and will even build into a folder that I specifiy, but once it's built it ends up in a shed load of subfolders - one of which has a version number appended meaning IIS won't automatically pick up my latest version without some re-config. (I did remove the version bindings, but then it won't overwrite the last build with the latest build)
I'm currently messing around with these MSBuild Arguments to try and get it working:
<code>/p:DeployOnBuild=true;
DeployTarget=PipelinePreDeployCopyAllFilesToOneFolder;
_PackageTempDir="\\HomeServer\inetpub\SiteTest";
AutoParameterizationWebConfigConnectionStrings=false
</code>
But there's a couple of points:

The 'SiteTest' folder is never created and
It's being accessed via share location when it's meant to be the HomeServer's local file system I want to publish too.

I just need to automatically get my web files inside of a folder I can predetermine for IIS, please help!
Comment: You'd do better to stop fighting it, and instead ask a separate question on what you're trying to accomplish.
Comment: Did you find an answer to this?
Comment: I never did, there is a way to achieve it but I now rent a TFS server that doesn't have a build server anyway :( Sorry :(
Answer: I achieved this by customizing our build process template.  Make a copy of your DefaultTemplate.xaml (DefaultTemplateV2.xaml for example) and open it.
If you're new to working in the workflow xaml editor I find it helps to collapse all first.
Once it's open, click on the root Sequence and click Arguments.  Add three arguments:

DeployBuild (Boolean) defaulted to False
FromPath (String)
InstallPath (String)

Then, in your workflow open these sections:

Run on Agent
Try Compile, Test and...
Under Try open the Sequence

At the bottom of the Sequence after Get Impacted Tests,.. open your toolbox and drag in an "If" workflow item.  Set the Condition to DeployBuild.
In the Then section of the If drag in a CopyDirectory workflow item.  Set the Destination to InstallPath and the Source to
<code>String.Format("{0}\{1}", BinariesDirectory, FromPath).
</code>
Save it and check it in.  You'll need to open a previous build and note the build subfolder you want to deploy. It'll be something like _PublishedWebsites\mywebsite\
Edit your build definition (you might have to close and reopen VS first) and go to the Process tab.  Change the Build Process Template to your new version.
Set the FromPath to the path you just noted.  Set the InstallPath to the UNC path of the destination folder (you'll need to make sure that whatever service account your builds run under has access to that path) and set DeployBuild to True.
Save, queue a build and test your deploy.
You can also, in your workflow XAML, go to Arguments and edit the Metadata argument with each of your new arguments.  You can set where they can be viewed.  So you could, for example, set the FromPath and InstallPath to only be viewed when editing the definition but DeployBuild to be seen when queuing a build.  That way you could turn it on or off when queuing.
Good luck.
Comment: Thanks Paul, this is a much anticipated response - but we no longer have a build server >.< I'm going to mark your answer anyway as you seemed to have laid out the steps to customise the build output and put in a lot of research. Many thanks


Integral Calculus Fundamental Theorem of Calculus

Question: I am not sure where this question came from, its on my study sheet and hit me out of nowhere,
The question is
if $$f(x) = \int_0^{x^3} cos(t^2)\,dt$$
find $f'(x)$
Now, i am not sure if this is actually FTC, I just have never seen a question like this before
Comment: This is probably a typo, but this integral does not mean anything, and there is no $f$.
Answer: The first part of the fundamental theorem of calculus states:

If $f$ is continuous on $[a,b]$ and $x\in[a,b]$, then if $$g(x)=\int_a^x f(t)\,dt,$$ then $g'(x)=f(x)$.

To solve your problem, let $g(x)=\int_0^x\cos(t^2)\,dt$. You are looking for the derivative of $g(x^3)$. Use the chain rule to see that $$\frac{d}{dx}g(x^3)=3x^2g'(x^3).$$ Now use FTC to rewrite $g'(x^3)$.
Answer: Using fundamental theorem of calculus and derivative of composite function you'll have
$$
f'(x)=\cos(t^2)\big|_{t=x^3}(x^3)'=3x^2 \cos(x^6)
$$
Answer: Hint
Let $$g(s) = \int_0^{s} cos(t^2)\,dt$$
so $f(x)=g(x^3) $ than use the Chain-Role