Unhandled promise rejection typescript e node.js

Question: Boa a noite a todos!
estou desenvolvendo um app com react, node e typescript e estava programando uma rota com método post para inserção de dados usando banco de dados sqlite e testando no insomnia mas ao executar o arquivo ele me retorna um erro de Unhandled promise rejection e não sei tratar esse evento.
essa e a minha rota:
routes.post('/points', async(request, response)=>{

    const {
        name,
        email,
        whatsapp,
        latitude,
        longitude,
        city,
        uf,
        items
    }=request.body;

   await knex('points').insert({
        image: 'image_fake',
        name,
        email,
        whatsapp,
        latitude,
        longitude,
        city,
        uf,

    })
    return response.json({sucess: true});

});

no insomnia eu faço uma requisiçao do tipo post e o corpo em json da seguinte forma
{
    "name": "Mercado Livre",
    "email": "email@example.com",
    "whatsapp": "3198774664",
    "latitude": "-45.4892729",
    "longitude": "-35.4324233",
    "city": "BH",
    "uf": "MG",
    "items": [
        1,
        2,
        6
    ]
}

o esperado era que eu tivesse um "sucess: true;" como resposta de acordo com meu return response.json({sucess: true});
porem ele me retorna o seguinte:
(node:13488) UnhandledPromiseRejectionWarning: Error: insert into points (city, email, image, latitude, longitude, name, uf, whatsapp) values ('BH', 'email@example.com', 'image_fake', '-45.4892729', '-35.4324233', 'Mercado Livre', 'MG', '3198774664') - SQLITE_ERROR: table points has no column named whatsapp
    (node:13488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
    (node:13488) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
será que alguém poderia me ajudar?
Answer: O Express não possui um método para capturar rejeições de promessas nativamente. Portanto, como você está utilizando async/await, deve sempre garantir que nenhuma promessa rejeitada "saia" de dentro do roteador, já que não há outro mecanismo para tratá-la.
Você pode usar blocos try/catch:
routes.post('/points', async (request, response) => {
  try {
    const {
      name,
      email,
      // ...
    } = request.body;

    await knex('points').insert({
      name,
      email,
      // ...
    });

    return response.json({ sucess: true });
  } catch (error) {
    response.json({
      error: true,
      message: error.message
    });
  }
});

No seu caso específico, o erro está na tentativa de inserir um nojo registro em points. De acordo com a mensagem de erro, não há coluna whatsapp na tabela:

SQLITE_ERROR: table points has no column named whatsapp

Há outras maneiras de se resolver esse problema, como usar alguma função de ordem superior (higher order function), que fará um tratamento de erros mais genérico, ou encadear o catch diretamente no método que retorna a Promise.
Para saber mais sobre o aviso unhandledPromiseRejection, leia esta resposta.

Também coloquei ponto e vírgula no final de uma linha que faltava. Pode parecer "frescura", mas isso evita algumas situações bizarras que podem ocorrer se você não os usar (veja mais sobre isso aqui).
Comment: o try catch ajudou bastante a identificar o erro e com isso pude perceber que havia criado o nome da variavel whatsapp errado na tabela e com isso dava erro na inserção.


terminology: set of sets

Question: What is the proper name for "a set of sets"? Is it just a "higher-order set" in general or a "secondary set" in particular? A Wikipedia link would be great. I've been unable to find a special term for "set of sets" there.
Comment: In modern set theory, every set is a set of sets. Anyway, what's wrong with "set of sets"? That's a fine term.
Comment: Suppose that we make the usual set-theoretic definitions of natural number, then integer, then rational, then real. Then something as modest as $\sqrt{2}$ is a fantastically elaborate concoction of sets of sets of sets and so on.
Answer: As others have pointed out, technically, there is no distinction between a "set" and a "set of sets"; in fact, in most modern set-theoretic formalizations of mathematics, every object is a set, and so there is nothing a set can contain besides other sets.  A set such as $\{\{\{\emptyset\}, \emptyset\}, \emptyset \}$ contains two sets, one of which contains two sets, one of which contains a set.  In examples much more complicated than this, the notion of "second-order set" does not make much sense.  And in case you don't believe such sets come up, see Arturo's comment below.
However, for psychological reasons, other terms such as "family" and "collection" are often used.  (Royden's book Real Analysis describes a hierarchy for which terms he uses when; see the first paragraph of Chapter 1, Section 1 (p. 6 in my edition).)  This is similar to the psychological reasons that we choose to use different symbols (e.g., $\cdot$ or $+$) for group operations, depending on what sort of group we're looking at.
One last technical point: Logicians do sometimes work with "languages" in which every object is, say, a real number rather than a set.  In cases such as these, one needs second-order logic to talk about sets at all, and third-order logic to talk about sets of sets, etc.  However, most mathematicians work, more or less, in the "first-order language of set theory": every object is already a set, so there is no need for higher order sets.  (Although there are a few people who prefer second-order set theory as a formalization of mathematics, I think they are in a very small minority of the people who care about such things.)
Comment: The set you give in your first paragraph is not a natural number, because it is not transitive: $\{\emptyset, \{\emptyset\}\}$ is an element, but not a subset. Either $\{\emptyset,\{\emptyset\}\}$ (which corresponds to 2) or $\{\emptyset,\{\emptyset\},\{\emptyset,\{\emptyset\}\}\}$ (corresponding to 3) would be natural numbers, though.
Comment: @Arturo: Corrected (with a reference to your comment, so please don't delete it). Thanks!
Comment: There is one more technicality that you forget to mention. A family might not exist as an *object* in the universe, but still can be defined externally. The "collection of all sets" etc.
Comment: @Asaf: Good point, although I think the word "collection" or sometimes "class" is used for that more often than "family." Anyone who wants to know about this should check out the Wikipedia article on "proper class"; I'm not going to try to explain it here.
Answer: In set theory, it is just a set.  We do not distinguish between the levels, as the elements of a set are sets, but they could be sets of sets of sets of ....  In fact, the usual ordinals have one set at each level (up to that ordinal)
Answer: In some contexts, a "set of sets" is called a family. Some examples:

Extremal set theory: an intersecting family of sets.
Matroids: a family of independent sets (but: a set of bases).
Topology: a family of open sets.

This is semantic terminology. "Physically" (if you "believe" in ZFC) everything is considered a set, as mentioned by Ross and Qiaochu.
Comment: @Asaf: You have expressed a philosophical position that not all mathematicians hold. It's not a bad position, but it should not be stated as fact on a forum such as this one.
Comment: @Charles: I have a strongly negative view on anything which postulates any concrete and absolute answer. Be it in real life or in mathematics. That is not what is open for discussion here. I do not see the point to mention anything about ZFC when I sit down to work, and I am very much unworried by that issue. I still don't find any place for "belief" with regards to the consistency of ZFC or FOL or proposition calculus. Instead, I do my best to invest my time in mathematics, and the occasional pointless internet debate :-)
Comment: I dislike the phrase "believe". You do not "believe" the axioms. You assume them, you work within their context, etc. Whether or not ZFC is consistent, trying to come up with nontrivial proofs (i.e. not deduced from contradiction) is a serious mathematical challenge.
Comment: What I meant was rather that (1) there are other foundations possible (e.g. topos theory) and (2) we need not care about foundations (e.g. we're using type theory). Everything is a set only if you want to think of matters this way. Even within the framework of set theory, there may be atoms. When I'm programming, I'm certainly not thinking of my integer variables as Cantor (or Church) ordinals (plus sign).
Comment: @Charles: I think that mathematicians that "believe" in their axioms are adding a religious dogma into mathematics. This should not be. Mathematics is not about *belief* but rather about logical inference. Either way, writing "believe in ZFC" is as degrading as calling all finitists morons, in my eyes.
Comment: @Asaf: I'm sorry you have such a negative view of religion, that you consider it insulting if someone uses phrasing that suggests you might possibly believe in something.  [Especially since in this case, the phrasing was clearly intended to be metaphorical.]  But generally speaking, most mathematicians don't consider that such issues need to be addressed every time they come up.
Comment: @Yuval: But do you think about it as a **von Neumann** ordinal? :-)

terminology: set of sets


why the permission of the stack in process address space of linux is executive?

Question: The linux kernel sets the permission of statck of process to be executive. As we know, the stack contains data instead instructions gernerally, So I wonder the reason why the kenel does this.
Especially, the buffer overflow attacks store the malicious code into the stack generally and execute it when it successfully exploit the system. if the permission of stack is not executive, the attack should be avoided, is this right?
So in my opinion, to set the stack's permission to be executive is harmful, what's the real purpose of linux doing this even it's running a risk of buffer overflow attacking ?
Comment: I think the buffer overflow attacking is just overriding the return address to the malicious codes start address. Not writing codes to stack.
Comment: I think your question can be: why the data segment of one process has the executive permission?
Answer: The Linux kernel does support the NX bit on CPUs that have it. The support has been there since 2004.
Some distributions ship with kernels that don't enable the options required to use NX but that's more to do with the fact that setting those options (specifically, using PAE mode) will cause the OS to not boot on certain hardware.
That's why I tend to recompile my kernel rather than taking the default supplied in a distro. That way, I'm certain it's optimised for my hardware rather than just the general case.
Comment: @Florian, buffer overflows can still occur since the stack is writable. However, one particular vactor of attack is removed because, even if you get code on to the stack with a buffer overflow (massaging a return address so that it "returns" to that code), it won't run. That's still an attack but it's more just getting your app to crash rather than execute arbitrary code.
Comment: @Florian, you can't _run_ code on the stack if it's set no-execute. I'm saying you can use a buffer overflow to change the stack but the primary attack vector is to place both the code you want run and the modified return address on to the stack with a buffer overrun. Then, when some function returns, it does so to _your_ code. `NX` prevents this since you can still change the return address but you need a _different_ way to get your malicious code in, since it won't execute on the stack.
Comment: @Florian, that's answered in the second paragraph. Not all hardware will even _boot_ if you try and use NX. So the default kernels don't do that. Only those kernels that know they'll be running on NX-capable hardware can assume it's okay.
Comment: If you use "pmap" command in the shell, you will find the stack's permission is "rwxp", this indicates that the stack can be excuted, that's why I am confused, I think the perssion should be "rwp" to avoid code running in stack, so why linux makes this decision ?
Comment: @Florian, it depends on the kernel entirely. For example, my `pmap -x $$` output has: `bf827000 84K rw--- [ stack ]` - no execute allowed. I suspect either your CPU doesn't support `NX` or your kernel hasn't got things set up for it.
Comment: If so, can I make a simple conclusion that your system can avoid buffer overflow attacking ?
Comment: I think the buffer overflow attacking is just overriding the return address to the malicious codes start address. Not writing codes to stack.
Comment: On a recently compiled 3.8.2 kernel on x86-64, `pmap $$` shows that the stack is e.g. `132K rw---    [ stack ]` which is *not* executable.
Comment: @tian_yufeng, yes, but the key "jump" binary was still stored in stack gernerally.
Comment: @paxdiablo, sorry for that I didn't get your idea. Can you explain more about how to run rw-stack code ?
Comment: @paxdiablo,Back to our original question:In what reason the kernel make the stack to be executive in the past kernel version?
Answer: Linux is a *nix. All *nix are based on early OSs written in assembler/machine code, where the concept of security was non-existent and also unnecessary. As more people started using computers, the OS evolved into something with contributions from tons of people around the world, and more importantly, computers gained more inputs from the outside world.
Machine code only exists as a way to change the machine's behavior without modifying the hardware, nothing more. People these days use C, whose purpose was to make porting assembly/machine code to other processor architectures easier.
The stack is just a means for implementing recursion.
There is simply no concept of security in machine code nor C. It's up to the user to choose his abstractions that map to machine code. C is not one of them. No amount of human beings and time will have or ever will validate a codebase sized reasonably enough to be useful (such as the Linux kernel + libc), as it requires validating arithmetic equations scattered across millions of lines of code, moreover which is changing all the time and so is the compiler, moreso that the language itself is not even well defined. A single arithmetic error anywhere in a C program is enough to compromise the entire address space of that program. No amount of SELinux, stack smashing protection, ASLR, App Armor, NX-bit, guard pages, etc will solve this.
Your question is like asking a barbaric primitive male why he doesn't do yoga.
If you disable execution of code on the stack (which most OSs support these days) there are still infinite other ways to own C code - for example, replacing the return address and words below it to setup a call to an arbitrary function with malicious parameters. Now someone will be like "oh that can be fixed, you just need a canary", but no, that doesn't fix the fact that the language being used is C, and is just distracting people from the real problem here, which is that if you want security you can't have C. PERIOD.
Comment: Thanks for explaining this.But you didn't make the original question clear.I wonder in what cases the kernel should execute the code int stack which causes the stack executive?
Comment: @Florian: It depends on the version of your kernel and linux distribution, it would be hard to enumerate them all. "what's the real purpose of linux doing this even it's running a risk of buffer overflow attacking ?" Executable isn't something you turn "on". It's something that's always existed until people devised ways to disable it.
Comment: I can't think of why this question is downvoted other than sheer ignorance or offended fanboys. If there is a reason state you reason. If not, all that can be assumed is fanboyism. I'd like to see someone explain why _any_ part of what I said is wrong.
Comment: You're being downvoted because your answer is largely composed of your (rather silly) opinions about C, and doesn't actually answer the question at all.
Comment: @duskwuff: What I say is backed by massive amounts of both theoretical and empirical evidence spanning decades. In theory, any undefined behaviour whatsoever in your C code is a vulnerability. In practice, it happens in every commonly used code base [OSVDB]. More importantly, it's simply obvious to any novice that C cannot be used to create secure systems. Remember how you messed up and didn't get 100% in math class? Well, probably then your C code has vulns in it too. Fortunately it's trivial to implement a PL that doesn't have this problem. for example, lisp, which has been around forever.
Comment: @duskwuff: The question is implying there's any reason to disable executable stack. But there is not. It's only a workaround to make it harder to exploit bugs in a fundamentally insecure system. Only fix is to A) Write perfect C code. B) Write in a language that isn't so hard.


memset an array of void pointers

Question: Consider the following initialization of an array of void pointers:
#include <string.h>

void foo()
{
    void * a[10];
    memset(a, 0, sizeof a);
    // ...
}

Is the array guaranteed to hold NULL pointers after the memset call?
Comment: (I found a dupe after answering).
Answer: No, it's not guaranteed. Converting 0 to a pointer type is defined to produce a null pointer [22.214.171.124.3], but here you're setting the object representation of the pointer to all zero bytes. The standard doesn't specify the object representation of pointers, so an all-zero-byte pointer or may not be a null pointer.
I don't think your question needs to mention arrays, as asking whether p is now a null pointer hinges on the same issue:
void *p;
memset(&p, 0, sizeof p);

Answer: No. As per C11 188.8.131.52 Pointers /3, an integral constant or expression of zero will translate to the null pointer. However, the underlying representation of types is specified by 6.2.6 where /1 states:

The representations of all types are unspecified except as stated in this subclause.

Given there's nothing in that section pertaining to pointers, you cannot then assume that a null pointer is all zero bits, which is what you'll get from your memset() call (neither signed char nor unsigned char are allowed to have padding bits and positive-zero is represented the same way in all possible encodings).
A safer way to do it is with:
void foo (void) {
    void *a[10];
    for (size_t s = 0; s < sizeof(a) / sizeof(*a); s++)
        a[s] = 0;
}

You can use memset if you know that all-zero-bits is the correct underlying representation of a null pointer in your implementation, but it won't be portable. That may not be an issue given the number of machines in active use that don't use that representation (very few if any). Just be aware of the possible ramifications.
Answer: If you put NULLs in it then yes, it will hold NULLs.
But you fill it with zeroes and 0 might happen to be the same as NULL but there is no guarantee. It depends on the hardware architecture + operating system + compiler.
The short answer to your question is: NO.

memset an array of void pointers


how to write a team scheduling program in Java

Question: I would like someone to give me some ideas how to to write this program in Java. I don't want people to write code for me, but guide me on how to start and what methods/design should be used to get this program done. I'm new in Java and this is a programming practice for me.
My idea for the program is a simple team scheduling program, which allows users to enter numerous teams and generate the schedule for each team. In the schedule, each team will play against each other once only.
e.g. 4 teams

Team 1 vs Team 2
  Team 3 vs Team 4
  ------------------------
  Team 1 vs Team 3
  Team 2 vs Team 4
  ------------------------
  Team 1 vs Team 4
  Team 2 vs Team 3

My question is should I use an Array to store all the teams? How should I generate the schedule (use the Random class)? How can I make sure that each team will play against each other once, and not multiple times?
Thanks a lot.
Comment: @ahment/Rob: I understand the sentiment. Another pov is that STO is a resource for anyone connected to the network.  OP may or may not be socially responsible (in the sense of the STO community's norms) but that should not prevent others from getting some possibly useful info.
Comment: First you should decide exactly what you want- how will input work, what should your output look like? Another tip- I would avoid using the Random class to generate matches, although you could do it that way. You didn't just pick random matches to generate your example did you? There's a systematic way you can code it, pretty much the same as the way you generated the example in your head. Maybe try drawing it out, maybe with more teams, and looking for a pattern.
Comment: And agreeing with ahmet, you've gotten some good answers to past questions- make sure you click the Accepted button on the best one, or people will be reluctant to help you any more!
Comment: Additionally SO (SE in general) isn't about getting as many points as possible. It's about helping each other, helping and sharing information in a managed way. Moreover, a question isn't private to the OT, anyone can have a similar/related problem/question. Even if the question doesn't get accepted, the votes hopefully should indicate that it's correct.
Comment: A more complex form of this problem is the [Traveling Tournament Problem](http://docs.jboss.org/drools/release/5.2.0.Final/drools-planner-docs/html_single/index.html#d0e529), where there are additional constraints, such as a team should play no more than 3 sequential away matches.
Answer: 1) implementation details: wait just yet.  You don't know how you are approaching the logical solution.
2) The fact that each team must play against every other team in the tournament is deterministic.  What is entirely up to you is how you distribute the games over a time period.  For example, how many consecutive games per day for a given team? Given a certain set of rules, naturally you may then opt for a random selection given n choices for a slot (or you may just pick the first item in .. [see answer #1]).
3) Read up on permutations and combinations if this material is new to you.
Answer: You should have a Team object which holds data about the team. One team object for each team. It may also be useful to have a Match object where you can pass in two Team objects so they can play against each other. You can write a method outside of the Team and Match objects to auto generate the teams competing in the matches.
I would use an ArrayList of Team objects and then if you want random matches just generate two random numbers that would be an index in the ArrayList. You can use Math.random() or the Random class, doesn't matter. The two numbers should not be the same otherwise a team would be playing itself which doesn't make sense. You should be able to work out the algorithm in code from this.
Hope this helps.
Answer: Here are a few basic ideas:
Of course you need a Team object. And you need a Schedule object. Then I would recommend a couple of implementation choices from the Design Patterns book. One would be to use the Builder pattern. You would have a ScheduleMaker and then you could have different concrete builders. For instance, in Football, there are rules about the schedule: each team is going to play 2 games against each peer in its division. Generally different concrete Builders are used to provide for different physical variances. For example, in the Go4 book, the example is of a MazeBuilder where simple and complex implementations contain different numbers of doors, halls, etc. In your case, you would want to have perhaps different rule-oriented ways of making the schedule. For the example I gave, you would push a method called 'setupDivisionalGames' into the interface, then you could fill the rest of the schedule with randomly selected rivals who are not from within the division. (Builder is generally buildA, buildB... getProduct().)
If this is starting to sound like another pattern, a simpler implementation would be to just have a Strategy pattern for picking opponents. If you don't have rules like the one above, then a simple random Strategy would be a good default implementation and if you wanted to get more fancy, you could just unit test a new implementation and change no other code and get new schedules.
Finally, think about the possibility of doing a score-based approach. That's how the NFL works. If you are the Detroit Lions, your schedule is going to be more cush than if you are the Packers this coming season. Either Builder or Strategy would let you do something like that pretty easily: the team's relative score must be close to the average score of all opponents, something like that.


Actual Image of a triangle in complex plane

Question: Let ABC be an acute-angled triangle. Let the altitudes from the vertices A, B, C meet the circumcircle at P, Q, R whose corresponding complex numbers are $z_1,z_2$ & $z_3$ respectively. If $\frac{z_3-z_1}{z_2-z_1}$  is purely imaginary, then angle A is
(A) $\frac{\pi}{2}$
(B) $\frac{\pi}{3}$
(C) $\frac{\pi}{4}$
(D) None of the above
I have already solved this problem and the answer is $\frac{\pi}{4}$
My solution is provided .
But some student asked me how the ACTUAL IMAGE looks in reality. Can some body helped me with the actual image which corresponds to this problem. My image is just a representative image
Comment: What's the problem with drawing a really accurate image? Just draw a circle, inscribe a triangle with a 45 degree angle, and draw the altitudes.
Comment: It is unclear what 'actual' mwans in this context. Can you provide an example?
Comment: Actually I wanted to show ABC, $x_1,z_2,z_3$ so that one can understand the concept of solving problem using clock wise and anti clockwise direction, hence an accurate image will helpful
Comment: Actual means any acute angled triangle which follows the above criteria
Answer: I would like to share a synthetic solution that utilizes some properties of orthocenters. Since you primarily asked for an accurate diagram, I will share that as well.

It is a well known orthocenter reflection property that $P,Q,R$ are the reflections of $X$ about the sides of the triangle. If $Q'$ is the reflection of $Q$ about $BC$, then we have
$$\angle XPQ=\angle PXQ'$$
Since $Q'$ is the reflection of $X$ about $AC$ and then about $BC$, another property about paired reflections about lines tells us that
$$\angle XCQ'=2\angle ACB$$
$$\angle XQ'C=\angle Q'XC=\frac{\pi}{2}-\angle ACB$$
Hence,
$$\angle PXC=\angle PXQ'+\angle Q'XC$$
$$\angle PXC=\angle XPQ+\frac{\pi}{2}-\angle ACB$$
Some angle chasing yields that
$$\angle ABC=\angle PXC$$
$$\angle ABC=\angle XPQ+\frac{\pi}{2}-\angle ACB$$
$$\angle XPQ=\angle ABC+\angle ACB-\frac{\pi}{2}$$
Using symmetrical reasoning, we also get that
$$\angle XPR=\angle ACB+\angle ABC-\frac{\pi}{2}$$
Adding these two equations gives
$$\angle QPR=2(\pi-\angle BAC)-\pi$$
$$\frac{\pi}{2}=\pi-2\angle BAC$$
$$2\angle BAC=\frac{\pi}{2}$$
$$\angle BAC=\boxed{\frac{\pi}{4}}$$
Comment: Actually, there is a much simpler solution that uses the property of inscribed angles to show that $\angle APQ=\angle ABQ=\frac{\pi}{2}-\angle BAC=\angle ACR=\angle APR$. Hence, $\angle QPR=\pi-2\angle BAC\implies \angle BAC=\frac{\pi}{4}$.
Answer:
Let $\text{ABC}$ be an acute-angled triangle. Let the altitudes from the vertices $\text{A}$, $\text{B}$, $\text{C}$ meet the circumcircle at $\text{P}$, $\text{Q}$, $\text{R}$ whose corresponding complex numbers are $z_1$,$z_2$ and $z_3$, respectively. Then $\frac{z_3−z_1}{z_2−z_1}$ is purely imaginary if and only if $\angle \text{A}=\frac{\pi}{4}$.

Proof. Since $\text{ABC}$ is an acute-angled triangle, the orthocentre $\text{X}$ must be inside  $\triangle \text{ABC}$, and points $\text{P, Q, R}$ must be on the inferior arcs $\text{BC, CA, AB}$, respectively.
Note that $$\begin{cases}\angle \text{RPA}=\angle \text{RCA}=\frac{\pi}{2}-\angle \text{A},\\
\angle \text{QPA}= \angle \text{QBA} =\frac{\pi}{2}-\angle \text{A}.\end{cases}$$
Thus,
$ \angle \text{QPR}=\angle \text{RPA}+\angle\text{QPA}=\pi-2\angle \text{A}$. Hence, $\angle \text{A}=\frac{\pi}{4}$ iff $\angle \text{QPR}=\frac{\pi}{2}$. Note that
$\angle \text{QPR}=\text{Arg} \left(\frac{z_3-z_1}{z_2-z_1}\right)$, but $\angle \text{QPR}<\pi$, so that $\frac{z_3-z_1}{z_2-z_1}$ is purely imaginary iff $\frac{z_3-z_1}{z_2-z_1}=ai$ for some $a>0$ iff $\angle \text{QPR}=\frac{\pi}{2}$.
Therefore, $\angle \text{A}=\frac{\pi}{4}$ iff $\frac{z_3-z_1}{z_2-z_1}$ is purely imaginary.


make an algorithm with taking a deck of cards and alternating between red and black [C++]

Question: My current idea is to have two arrays for red and one for black adn just have another for loop with an if that will just add alternating black and red to a third array. I was told this was overcomplicated and I was missing a simpler solution, any guidance here? Im pretty sure I'd use a for loop with an if inside of it, but Im not sure how to do this with an unsorted deck
Comment: Sounds good to me. Im in favor of implementing the easier then refining later. Often the easier is faster to market and also easier to maintain. Implement it on compiler explorer (www.godbolt.org) and post gain here so we can have a look.
Answer: There is a simpler way that avoids copying to two separate 'red' and 'black' arrays. Here's an illustration that demonstrates with an unsorted deck of 4 black and 4 red cards.

Treat red / black cards as 'even' or 'odd'.
Walk the input array element by element.
If it is red (odd), insert into the next available odd slot in the output array.
If it is black (even), insert into the next available even slot in the output array.

Once you've looped through all the input elements, the output array will have cards of alternating color.
Comment: Thanks for this, however how would I practically implement putting it in the next odd slot in the output array?
Comment: I'd declare two integers: `oddOutputIndex = 1` and `evenOutputIndex = 0` to track the next even or odd space to write in the array. Each time you write, add `2` to whichever index you just wrote to.


On the existence of a heavy tailed c.d.f. given a condition based on the CLT

Question: My question is about the existance of a heavy tailed distribution $F$ such that: given two i.i.d. samples $\{X_1,\ldots,X_n\}$ and $\{Y_1,\ldots,Y_n\}$, from $F$, we have
$$\sqrt{n}\frac{\hat{\mu}_X - \hat{\mu}_Y}{\hat{\sigma}}\rightarrow N(0,1)\text{
 in distribution}$$
Where
$$\hat{\mu}_X=\frac{1}{n}\sum_{i=1}^nX_i,$$
$$\hat{\mu}_Y=\frac{1}{n}\sum_{i=1}^nY_i,$$
$$\hat{\sigma}^2 = \frac{1}{n}\left(\sum_{i=1}^n(X_i - \hat{\mu}_X)^2 + \sum_{i=1}^n(Y_i - \hat{\mu}_Y)^2\right).$$
Comment: Any Student t distribution with more than 2 degrees of freedom will work, because the CLT applies in such cases and all such distributions are heavy-tailed.
Answer: I can't prove the existence of a heavy-tailed distribution that will converge to a standard normal as you've described but I did some basic simulations that seem to suggest it could be the case.
Firstly, let's take the Weibull distribution, which is a heavy-tailed distribution. We'll define:
$$X,Y\sim W(\lambda,k)$$
where $\lambda$ and $k$ refer to the shape and scale of the Weibull distribution, respectively. Let's further assume $X$ and $Y$ to be independent. Now, if we define the following:
$$\hat{\mu}_{X}=\frac{1}{n}\sum_{i=1}^{n}X_{i}$$
$$\hat{\mu}_{Y}=\frac{1}{n}\sum_{i=1}^{n}Y_{i}$$
$$\hat{\sigma}^{2}=\frac{1}{n}\bigg(\sum_{i=1}^{n}\big(X_{i}-\hat{\mu}_{X}\big)^{2}+\sum_{i=1}^{n}\big(Y_{i}-\hat{\mu}_{Y}\big)^{2}\bigg)$$
You are looking for the following to be true:
$$Z=\sqrt{n}\bigg(\frac{\hat{\mu}_{X}-\hat{\mu}_{Y}}{\hat{\sigma}}\bigg)\overset{d}{\rightarrow} N(0,1)$$
Using the Weibull random variables defined above, I performed simulations by randomly sampling $n=10000$ times from each of $X$ and $Y$ and calculating the values defined above. I then repeated this process $m=100000$ times to test the convergence we postulated above.
The following plots show the distributions obtained for the simulations. I ran the simulation for 9 different $(\lambda,k)$ pairs to see if the behaviour changes as parameters of the Weibull change.
For each case, the MLE for the final distribution's parameters are calculated, assuming normality of the final distribution $(\hat{\mu},\hat{\sigma})$. As you can see, all the estimates for the mean and variance are close to what you are looking for. Furthermore, for each case, the Jarque-Bera normality test was applied to the sample which resulted in 9 failures to reject the null. I'll leave the interpretation of those results up to you.

I performed the simulations in MATLAB using the code below:
<code>clear all
close all

n=10000;
m=100000;
p1=[1 5 10];
p2=[1 5 10];

figure(1)
figure(2)

for j=1:length(p1)
    for k=1:length(p2)
        for i=1:1:m
            s1=wblrnd(p1(j),p2(k),n,1);
            s2=wblrnd(p1(j),p2(k),n,1);

            mean1=mean(s1);
            mean2=mean(s2);
            std1=sum((s1-mean1).^2)/n;
            std2=sum((s2-mean2).^2)/n;

            a(i,1)=(mean1-mean2)/sqrt(std1+std2)*sqrt(n);
        end

        figure(1)
        set(gcf,'color','w')
        subplot(length(p1),length(p1),(j-1)*length(p1)+k)
        histfit(a)
        xlim([-5 5])
        m=mle(a,'distribution','normal');
        ttlstr=sprintf('$\\hat{\\mu}=$%.8f, $\\hat{\\sigma}=$%.8f',m(1),m(2));
        title(ttlstr,'interpreter','latex');
        parstr=sprintf('$Z(\\lambda=$%d, $k=$%d$)$',p1(j),p2(k));
        xlabel(parstr,'interpreter','latex');

        figure(2)
        set(gcf,'color','w')
        subplot(length(p1),length(p1),(j-1)*length(p1)+k)
        qqplot(a)
        m=mle(a,'distribution','normal');
        if jbtest(a)
            xlabel('JB test: Reject $H_{0}$','interpreter','latex');
        else
            xlabel('JB test: Fail to reject $H_{0}$','interpreter','latex');
        end
        ttlstr=sprintf('$\\hat{\\mu}=$%.8f, $\\hat{\\sigma}=$%.8f',m(1),m(2));
        title(ttlstr,'interpreter','latex');
        ylabel('');
        box on;
    end
end
</code>
Comment: Thx for your insights!


Are there any advantages to using OpenSolaris over linux other than ZFS?

Question: Are there any advantages to using OpenSolaris, other than ZFS, rather than using a common linux distribution such as CentOS or Ubuntu?
I ask because I'm interested in using OpenSolaris on AWS to take advantage of ZFS-snapshots for backing up to S3 -- specifically for MySQL backups. I'd like to know if OpenSolaris has clear advantages over CentOS for running webservers in the cloud.
Comment: community wiki?
Answer: Yes, many. Just to name a few :

DTrace, which allows you to display detailled and precise statistics about ressource usage using one line scripts
SMF, which allows a clean and streamlined management of services. For example, it restarts services that crash and display short explanations about services refusing to stard.
the included firewall is very simple to use.
Loooong support cycle (somewhat depending on Oracle but for the past it has been long)
xVM, Xen integration made trivial
Zones, very simple to create, administer and use.

I could go on for a while. I have switched my personal machines from Debian to OpenSolaris and am not looking back.
Answer: The downsides :

very little drivers. If you plan to use anything but very standard hardware, be prepared for lots of pain. Even getting an off-the-mill IBM server running is atrocious.
disk performance sucks. I mean compared to the standard ill-configured ext3 linux disks, ZFS flies. However compared to a properly configured XFS it's unbelievably slow.
Lots of idiosyncrasies break from old Unix hats habits entrenched in our souls for 30 years :-)
Comment: I agree with your first comment but my experience hasn't been that ZFS is slow.  There are some known raid/sata controllers that have issues with OpenSolaris though but that goes back to your first point.  However your third point is a personal problem not a problem with OpenSolaris.  Jumping from Linux to Unix is not going to be without some idiosyncrasies.  As GNU userspace tools are different than what you'll find on a Unix.  But it's annoying having to figure out the basics again like how to get the output you expect from something like `ping host`.
Comment: "my experience hasn't been that ZFS is slow."

Yeah, it all boils down to what you're calling "slow". Real life performance on similar serious hardware is much lower ( locally or through NFS).
Answer: Some other OpenSolaris points:

API stability, Gnu/Linux has no commitment on interfaces so software, and especially device drivers, can break with a new kernel or library release. Recompilation is often required for modules. (Open)Solaris has committed interfaces that stay compatible with new releases.
Snap-upgrade (linked to ZFS). You can rollback to a previous system installation should you mess something for some reason.
fair share scheduler / real-time scheduling class available standard
RBAC (grant Administrator Role to yourself), simpler to administrate and use than sudo, fine grain privileges removing many of the root suid requirements.
NFSv4 ACLs with ZFS
network virtualization (crossbow)
branded zones (Gnu/Linux and Solaris 10 zones).
ZFS deduplication, this is pretty new (dev releases) but really cool.


Condensing a mercurial repository - recommanded way?

Question: Let's say I have a repository 'Main', and Max and co work on a clone each. Max has some local commits ('f'&'g') that are not yet pushed to 'Main'. This is how it looks now (pipes being pushs/pulls):
A--B1--B2--C--D1--D2--D3--E (Main)
|          |  |           |
A--B1--B2--C--D1--D2--D3--E--f--g (Max)

'B1' and 'B2' as well as 'D1', 'D2' and 'D3' are changes that only make sense together. We would like to combine 'B1' and 'B2' to a single changeset 'B' and combine 'D1', 'D2' and 'D3' to a single changeset 'D'. The new structure should look like this:
A--B--C--D--E (Main)
|     |     |
A--B--C--D--E--f--g (Max)

My (main) question is: What is the reccommended way of doing this?

Now let's make things worse:
We have a branch that was merged within the change-sets that we want to collapse. It would look like this:
A--B1--B2--C--D1--D2------D4--E (Main)
|          |  \-------D3-/    |
|          |                  |
A--B1--B2--C--D1--D2------D4--E--f--g (Max)
              \-------D3-/

The new history should look like this:
A--B--C--D--E (Main)
|     |     |
A--B--C--D--E--f--g (Max)

How would you do that?
Thanks in advance.
Answer: It depends on how much effort you want to put into this. While I don't know a solution within Mercurial itself (I only know history editing functions which can't cope with merges), Git does have the functionality you need:
If I would really have to do such an operation, I would

Try to convince the management that this is not worth it
Try harder to convince the management that this is not worth it
Make a backup! The following steps involve destructive operations, so consider this as not optional. You have been warned.
exort the repo with hg-git into a git repository
export the complete (git) history into a fast-import-stream with git fastexport --no-data --all > history.fi
Create a Pseudohistory by editing history.fi, dropping your unwanted revisions
import the adjusted history into the git repo with ``git fast-import -f < history.fi`
check extensively if the newly created history is in fact the way you want it to have
clone Max into a local work repository
Remove successors of commmit A in the local work repository
pull your updated history back from git (again with hg-git) into the local work repository
check, if the Mercurial history matches your expectation (diffs of commits between the new and old repos, metadata (time stamps, committer names, ...)
Remove successors of commmit A in every repo (Main, Max and every developer clone)
hg push -r E Main the partial history back to Main out of the work repository
hg push -r g Max the complete history back to Max out of the work repository
Comment: Thanks. Managed to convince management :-) But I'll keep that in mind. It seems to be a sound solution.


Trigonometry exercise

Question: Here's the exercise:

Let there be a triangle $[PQR]$, with a perimetre of 10 units. Point $R$ belongs to the perpendicular bicector of $[PQ]$. $\cos{R} = \frac{7}{8}$. What is the area of $[PQR]$?
Comment: What is your work on this question ? it is surprising that you haven't recognized that PQR belongs to a  special category of triangles : which one ?
Answer: First you have to notice that $PQR$ is a isocele triangle (that is, $PR$ and $QR$ have the same length).
Let's call $M$ the middle of $PQ$.
Let's call $r$ the semi-angle in $R$.
Then you have the following equations:
$cosR=\frac78=cos{2r}=2cos^2r-1$, that is $cos^2r=\frac{15}{16}$
and $PQ+2PR=10$
and $RM^2+PM^2=PR^2=RM^2+(\frac{PQ}{2})^2$
as well as $RM=PR  \times \cos r$
Then $RM^2=PR^2\times \frac{15}{16}$
Hence $(\frac{PQ}{2})^2=\frac{1}{16}$, or $PQ=\frac12$
Hence $PR=\frac{19}{10}$
The area of $PQR$ is $PM \times RM=\frac14 \times\frac{19}{10} \times \frac{\sqrt15}{4}=\frac{19\sqrt15}{160}$
Comment: I don't agree to help somebody that doesn't want to work by (him/her)self : nothing else than the raw question !
Comment: Well, the question came up this morning, at 8:15, a colleague of mine, presented the exercise. We are going to have a mathematics test at 11:20, I tried to work it out, but, having classes in between, I don't have much time. I thought this would be the best way to figure it out, not being able to do it myself and not having much time to work on it. So, had Martigan not (which I deeply appreciate) helped me, the exercise would remain unsolved for the extent of time in which it would be useful.

Trigonometry exercise


Trouble with domain delegation

Question: I suspect I have a problem with domain delegation.
Notes:

Following addresses and names are examples
I have two public static IPs and own a domain name
I'm using Debian 9 and Bind 9

I want something like this (IPs are public):
on 0.0.0.0 is DNS server ns1.example.com which points example.com to 0.0.0.1.
I succesfully configured ns1.example.com as authoritative and forwarding DNS server (with above configuration).
I DMZ port 53 (UDP).
Next step I tried to delegate domain (example.com) from Registrar's DNS server to my own (ns1.example.com) I get "wrong record".
When I contacted Registar's helpdesk the tell me I did not register the server, and I should contact my hosting provider (which is me...). What do they mean?
Comment: For IP addresses, please use the designated ones for documentation: 192.0.2.0/24 or 198.51.100.0/24 or 203.0.113.0/24. See https://tools.ietf.org/html/rfc5737
Comment: Note that DNS does not use only UDP, but also TCP so if you filter that you will get problems. Also it is a bad idea to have the same server being authoritative and recursive (is this what you mean by 'forwarding'?).
Comment: It would help if you get the true names involved, that will be far quicker to solve the problem. If you are using a gTLD based domain name you need to register the name server at registry, through your registrar. They should be able to help you otherwise you can change it. It also depends if the nameserver is internal/external and in-bailiwick or not. In short, you do not provide enough information to help you.
Comment: You need to ask your registrar to set up what are known as "glue records".  Once that is done, you can use ns1/ns2.example.com as the primary and secondary name servers on your actual domain registration for example.com
Answer: Because ns1 is under example.com you must "register" this IP with them, these are called GLUE records.  Essentially A records added to the zone .com. so servers know what IPs to query.

Trouble with domain delegation


Por que recebo "usuario" como indefined?

Question: Estou recebendo usuario como Indefined mas não estou entendendo o motivo. Podem me ajudar?
import React from 'react';

class Main extends React.Component {

    state = {
       listaMensagens: [
            {
                usuario: "",
                mensagem: ""
            }
        ]

    }

    adicionaMensagem = (newUser, newMessage) =>{

        const novaLista = this.state.listaMensagens
        novaLista.push(newUser, newMessage)

        this.setState({
            listaMensagens: novaLista
        })

    }

    onChangeUsuario = (event) => {
        this.setState({usuario: event.target.value})
    }

    onChangeMensagem = (event) => {
        this.setState({mensagem: event.target.value})
    }

  render(){
    const listaRenderizada = this.state.listaMensagens.map((user)=>{

        return

{user.usuario}

{user.mensagem}

    })

    return (

{listaRenderizada}

        <input nome={"usuario"} onChange={this.onChangeUsuario} placeholder={"Usuário"} value={this.state.usuario}></input>
        <input nome={"mensagem"} onChange={this.onChangeMensagem} placeholder={"Mensagem"} value={this.state.mensagem}></input>
        <button onClick={this.adicionaMensagem} type={"submit"}>Enviar</button>

    );
  }
}

export default Main;

Comment: E ai entendeu a resposta?
Comment: Entendi. Obrigado!
Answer: Não foi colocado no estado do componente duas propriedades usuario e mensagem e por isso this.state.usuario e this.state.mensagem não existem e por isso da mensagem undefined, ou seja, não definido, o estado correto a ser criado:
this.state = {
    usuario: "",
    mensagem: "",
    listaMensagens: [
      {
        usuario: "a",
        mensagem: "b"
      }
    ]
}

o exemplo correto com algumas alterações no código:

class Main extends React.Component {
    constructor() {
       super();
       this.state = {
          usuario: "",
          mensagem: "",
          listaMensagens: [
            {
                usuario: "a",
                mensagem: "b"
            }
         ]
       }
    }
    adicionaMensagem = () => {
        const {usuario, mensagem} = this.state;
        this.setState({
            usuario: '',
            mensagem: '',
            listaMensagens: [
              ...this.state.listaMensagens,
              {usuario, mensagem}
            ]
        });
    }

    onChangeUsuario = (event) => {
        this.setState({usuario: event.target.value})
    }

    onChangeMensagem = (event) => {
        this.setState({mensagem: event.target.value})
    }

    render() {
       return (

{this.state.listaMensagens.map((user) =>

{user.usuario} - {user.mensagem}

)}

              <input nome="usuario" onChange={this.onChangeUsuario} placeholder={"Usuário"} value={this.state.usuario}></input>
              <input nome="mensagem" onChange={this.onChangeMensagem} placeholder={"Mensagem"} value={this.state.mensagem}></input>
              <button onClick={this.adicionaMensagem} type="button">Enviar</button>

       );
   }
}

ReactDOM.render(  , document.getElementById('root'));

Carregando ...

Comment: Entendi! Muito obrigado!!!


Tell if parity check matrix is linearly independent

Question: I know these are parity check matrixes of linear codes $C_1$ and $C_2$.
$H_1=
\begin{matrix}
  1 & 0 & 1 & 0 & 1\\
  0 & 1 & 0 & 1 & 1\\
  1 & 1 & 0 & 0 & 1\\
 \end{matrix}$
$H_2=
\begin{matrix}
  1 & 1 & 1 & 0 & 0 & 0 & 0 & 0\\
  1 & 0 & 1 & 1 & 1 & 0 & 1 & 0\\
  1 & 1 & 0 & 1 & 0 & 1 & 0 & 1\\
  1 & 1 & 1 & 1 & 1 & 0 & 0 & 1\\
 \end{matrix}$
I need to find the number of code words belonging to each of the codes $C_1, C_2$. I know that I can solve $Hx=0$ and get all words that way. But I have seen examples were this is done by computing the dimension as $k = cols - rows$ and thereby the words are $2^k$ and saying that this can be done because these parity check matrixes rows are obviously linearly independent.
How can I easily verify that this is the case? I suspect there is a neat trick involved, and not much actual computation.
Answer: Many times the $(n-k)\times n$ parity check matrix $H$ of a $[n,k]$ code
is written in the form
$$H = [P_{(n-k)\times(k)} \mid I_{(n-k)\times (n-k)} ]$$
which makes the independence of the rows obvious.  But for your matrices,
you can try finding the reduced-echelon matrix with the same row space.
For example, what happens if you add the first and second rows of $H_1$ into
the third row?


Remove similar documents in Python

Question: I have a folder with series subtitles.
I would like to get from the folder one subtitle file per episode.
My problem is that some of the subtitles are on the same episode but with different name like
/data/netfilx/reality_subtitle/Top Chef/Top.Chef-Texas.S09E02.720p.HDTV.x264-MOMENTUM.HI.srt
/data/netfilx/reality_subtitle/Top Chef/Top.Chef-Texas.902.720p.HDTV.x264.MOMENTUM.srt
/data/netfilx/reality_subtitle/Top Chef/Top.Chef-Texas.9X02.HDTV.XviD-MOMENTUM.HI.srt
/data/netfilx/reality_subtitle/Top Chef/Top.Chef-Texas.S09E02.HDTV.XviD-MOMENTUM.srt

so they are very similar, but not 100% identical.
How can I remove the duplicates documents and remain just with the distinct episodes subtitles?
I would attach what I tried but unfortunately I'm pretty clueless...
Comment: he wrote clearly: "they are very similar but not 100% identical."
Comment: Please attach what you tried up to now..
Comment: Use `os.listdir()` to loop through subfolders (and files) and check if each element is unique
Comment: Are the duplicates completely identical?  If so, just getting the SHA1 or similar for each file and only keeping one per hash should be quick and efficient.
Answer: You can use the cosine similarity between the documents.
The assumption is that similar documents will have a high similarity ,
and then you can apply a threshold above which documents will be considered as identical.
For example, if those are your documents:
1."The child went home today, and his mother waited for him"
2."My car is big"
3."The kid went to his house today, while his mama waited for him to come"

I use vpekar code from the answer and I do the below:
>>> v1 = text_to_vector("the child went home today, and his mother waited for him")
>>> v2 = text_to_vector("My car is big, so said my mother")
>>> v3 = text_to_vector("The kid went to his house today, while his mama waited for him to come")

and the cosine similarities between the vectors are:
>>> get_cosine(v1,v2)
0.10660035817780521

>>> get_cosine(v1,v3)
0.48420012470625223

>>> get_cosine(v2,v3)
0.0

So you obviously see that documents 1 and 3 are the most similar - and thus may be subtitles of the same episode.
So, to summarize:

1. you need to apply (n choose 2) comparisons (check every possible pair).
2. If the cosine similarity between 2 documents is higher then a threshold you will find by trial and error -
    the subtitles are probably of the same episode - and you should remove one of them.

Remove similar documents in Python


Pytest: run test one by one

Question: I've multiple test functions created in a file. Example:
def testA():
   change_user_permission_to_allow()
   assert action == success
   change_user_permission_to_deny()

def testB():
   assert action == fail

## Multiple other tests...

By default, user are denied for action. When I run testB individually, it passes. When I run the test file as a whole.

pytest testfile.py

The testB fails. When I debug the user permission is allowed. Seems like testA is making issue in testB. Is there a way to tell pytest to run test one after another?
Comment: This is a typical symptom of an incomplete cleanup. Unit tests should undo everything they changed at the end.
Comment: I only see that you seem to run a function that **seems** to do the opposite of the function before. Without showing the actual content of this function it is hard say what was not cleaned up.
Comment: @KlausD. That is done at the end of `TestA` as you can see. I'm unsure whats causing the incomplete cleanup
Comment: _Seems like testA is making issue in testB_ is a symptom of an incomplete cleanup. Fix `testA` so it resets user permissions correctly. If you need help with that, please provide a [mcve]. The current answer will make your test suite more fragile instead of fixing things on the long run.
Answer:
you can read the pytest-ordering: run your tests in order
With pytest-ordering, you can change the default ordering as follows:

import pytest

@pytest.mark.order2
def test_foo():
    assert True

@pytest.mark.order1
def test_bar():
    assert True

$ py.test test_foo.py -vv
============================= test session starts ==============================
platform darwin -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.2 -- env/bin/python
plugins: ordering
collected 2 items

test_foo.py:7: test_bar PASSED
test_foo.py:3: test_foo PASSED

=========================== 2 passed in 0.01 seconds ===========================

Answer: I was looking for this also
  --sw, --stepwise      exit on test failure and continue from last failing
                        test next time
  --sw-skip, --stepwise-skip
                        ignore the first failing test but stop on the next
                        failing test.
                        implicitly enables --stepwise.

Pytest: run test one by one


For every integer $n$ , find how many elements of order $n$ there are in $S_5$

Question: I know that $S_5$ has order $5!$, knowing that numebr of elements of order $n$  refers to the number of elements $x$ such that $x^n$ is the identity element, but $x^m$ is not for any $m<n$. However, I don't know where to start to solve the question.
Answer: Write an element of $S_5$ in its cycle form. If there are cycles of length $a_1,a_2,\ldots,a_n$, then it is not hard to show that the element has order $\text{lcm}(a_1,a_2,\ldots,a_n)$.
The different combinations of cycles which can appear are precisely the partitions of $5$, i.e.
$$
\begin{align*}
1+1+1+1+1\\
2+1+1+1\\
2+2+1\\
3+1+1\\
3+2\\
4+1\\
5
\end{align*}
$$
Elements of the resulting form have orders $1,2,2,3,6,4,5$ (by taking lcms). Do you see how to finish from here?


Industry Standard for Psychological Mapping of Emotion to Musical Keys

Question: I have found several references to map a key to a psychological feeling or psyche archetype. Is there an industry standard for musical scoring?
Comment: There is no recognised general association between keys and feelings. However, there are reasons why in certain situations, different keys may sound like they have different qualities to them - https://music.stackexchange.com/questions/61600/why-are-different-keys-necessary-important, https://music.stackexchange.com/questions/3486/does-it-really-make-difference-to-play-a-song-in-a-different-key, https://music.stackexchange.com/questions/43168/are-sharp-keys-bright-and-flat-keys-dark, https://music.stackexchange.com/questions/15221/whats-the-point-of-keys-other-than-c-and-am may be of interest.
Comment: How meaningful could such an "industry standard" possibly be? What are the correct 12 (or 15, or however many keys you want to consider) psychological feelings or archetypes? If you want to understand how music and emotion are related, introspect. And pay attention to how music appears to affect others.
Answer: (Expansion of my comment).
This is one of those questions where there's a fairly straightforward answer - 'no'! There is no recognised, generally-applicable association between particular keys and particular emotional scopes.
There are various reasons why, on a certain instrument, tuned in a given temperament, in a certain musical context, a certain key might be said to have certain characteristics. But not in such a way that you can isolate keys and come up with any meaningful direct correlation between keys and feelings.
It is true that many learned musicians do speak of associations between keys and emotions, but I believe that they are misleading themselves - I think that it's all too easy, when experiencing a powerful emotional pull from one key and then experiencing a different emotion from another, to fall into the trap of thinking that there's something of that emotion associated with those keys in an absolute way.
Comment: I don't think they're necessarily misleading themselves (though they may well be) but it's just that such responses are very, very subjective.
Comment: @Bob I guess I meant misleading themselves into making the leap from the subjective to the objective - leading to enumerations such as those [here](http://biteyourownelbow.com/keychar.htm), glorious though they are!
Answer: From what I have read, before equal temperament, the key qualities were much more distinct. I know they were sometimes associated with different moods (such as the dark C minor Beethoven is so famous for using), but I don't know if those associations have continued in the era of equal temperament.
One thing I did learn from my composition professor is that modulating to a key with more sharps increases the tension in the music because one is moving in the direction of the dominant. Modulating towards more flats (or fewer sharps) relaxes the music because it moves in the direction of the subdominant. This is not related to a specific mood or psychological state, but could be used to evoke feelings.


Psexec failing to connect the remote VM

Question: I have got two machines (machine1 & machine2). My task is to execute few commands remotely via PSEXEC from machine1 to machine2. Sadly these machines are from different network domains. Admin Share is enabled in both the machines.
machine2 can be accessible only by establishing to VPN on machine1. PSEXEC works fine when I establish VPN on the machine1 to access machine2. I am also able to access Admin share via run ---> \\ip\Admin$
Tricky part here is to execute the PSEXEC without establishing VPN on machine1.
To achieve this I have disabled the firewalls on machine2. Now without VPN, I can connect machine2 from machine1 via RDP (Remote Desktop), but not able to successfully run PSEXEC nor able to access Admin share on machine2.
Below is the command/error:
Command: PSexec \\{machineip} -u {username} -p {password} cmd
Error:
Could not access {machineip}
The network path was not found

Guess as Admin share on machine2 is not accessible without Establishing VPM PSEXEC fails to execute. If the above guess is valid, I would like to know how to access Admin Share from a different domain/network.
Comment: Can anyone have a look..? if any additional info needed ..please comment
Comment: Added an answer, but don't do this.  Try telling us what you're trying to do here/why you can't have the VPN established, and maybe we can figure out a way to do whatever it is without making your machine so incredibly insecure.
Answer: It's fairly uncommon (and unsafe) to open up file sharing to the internet, which is what it looks like you're trying (or expecting) to do.  PSExec operates over ports 445 and 139, and I'd expect that one or both of those ports are being blocked by one or both of the edge devices on the two networks at play here.
And PSExec does require that you be able to access the administrative share to work.
So basically, the way you'd connect to a remote machine via PSExec is to open up ports 445 and 139 on the [hardware] firewall(s), establish a NAT rule (if needed), and then use the command normally.
However, do NOT actually do this, as opening up port 139 to the world is about the worst thing you can do.

Psexec failing to connect the remote VM


Wikipedia article Tensors may contain an error.

Question: I have a question regarding the article at https://en.wikipedia.org/wiki/Tensor.
A quote from that article follows:

"The components of a vector can respond in two distinct ways to a change of basis where the new basis vectors $\hat e _i$ are expressed in terms of the old basis vectors $e_j$ as,
$$\hat e _i = \sum \limits _{j=1} ^n R_i^j  e_j .$$
Here $R_i^j$ are the entries of the change of basis matrix."

If $e_j$ is a basis vector, as stated in the quoted sentence, then it is necessary to accept that $e_j$ is the $j$-th vector in the basis vectors.  The product shown between the change of basis matrix $R$ with each basis vector $e_j$ appears then to be wrong.  Unless the author is referring to each component in two basis vectors, where the $\hat e$ vector produced is indexed by $i$ while the $e$ vector is indexed by $j$.
However that appears to be strange (besides being pointless since my understanding is that if you have the change of basis matrix $R$ then you already know what the new basis vectors are, simply the column vectors in $R$).  If $R$ is indexed as shown then each product is of a column vector component in $R$'s $i$ column indexed by $j$, with a $j$ component in the basis vector $e$.  If $n=2$ then $R$ is a $2 \times 2$ matrix and $\hat e _1 = r_{11} e_1 + r_{21}  e_2$.  That is inconsistent with how I learned to form the product of a matrix with a vector, so I consider it strange.
Can someone kindly disambiguate this for me?  I appreciate your time to consider it.
Comment: The author is using the [Einstein notation](https://en.wikipedia.org/wiki/Einstein_notation), which is fairly common when working with tensors in mathematical physics.
Comment: The notation clearly indicates that the index of summation is $j$ and $\widehat e$ is indexed by $i$.
Comment: Thank you for the comments.  I am mostly clear on the indexing and notation.  I looked at e_j as a list of vectors and my first comment was that it appears to be incorrect with respect to the index on R.  According to the indexing shown, the entire set of e vectors are indexed through by j for EACH e-hat_i vector produced.  That is inconsistent with what I've understood about a change of basis from one vector space to another.
Comment: If I accept these are vectors being indexed then the consequence seems to require that a vector e-hat_i is produced by the sum of all products of R(j,i) components (matrix column indexed by j) with every corresponding vector e_j.  To be honest, I don't see how to construct that sum of products.  I'm not saying it can't be done.  Maybe you can explain how that is accomplished.
Answer: You are confusing two things. First, when you have a matrix $R = (R _i ^j)$  ($i = 1, \dots, m$ indicates the row, $j = 1, \dots, n$ indicates the column) and a vector $v = (v_j) _{j = 1, \dots, n}$ (having $n$ rows and $1$ column), you can form their product $Rv$ which is a vector with $m$ lines and $1$ row; the $i$-th component of this vector is $\sum \limits _{j=1} ^n R _i ^j v_j$.
Second, when you have a matrix as above and $n$ vectors $e_1, e_2, \dots, e_n$, you may create $m$ new vectors $\hat e _1, \hat e _2, \cdots, \hat e _m$ according to the formula $\hat e _i = \sum \limits _{j=1} ^n R _i ^j e_j$.
Note that in the first paragraph you multiply the entries of $R$ with some numbers (the components of $v$), while in the second paragraph you multiply them with vectors. (Note also that in the paragraph quoted from Wikipedia $m=n$.) The two formulae look identical, but the natures of the objects involved therein are different (numbers versus vectors).
Comment: Alex, thanks for your time to respond.  My understanding it that the lower index on R "i" indicates the column "index" so as you iterate i down the column you are picking matrix components from a ROW.  In the summation shown "i' is the free index and "j" is iterated for each product in the sum, j=1, n.
Comment: I agree that you can produce new vectors using this matrix multiplication but I find it strange in that is is not consistent with my previous experience with change of basis matrices.  It may be technically correct but it does not appear to be functionally correct in the context of change of basis.  Besides, as you probably know, a change of basis matrix is formed by taking the new basis vectors as columns in the matrix.  So how can I see R as a change of basis if e-hat vectors are "new basis" vectors.  In this Tensor topic it is strange to me but I admit to having a limited exposure to this.
Comment: @JohnHunsberger: Alas, I don't think that I can help you any further: this matter is so clear to me, that I cannot understand what you don't understand.
Comment: LOL, I am pretty dense.
Comment: Shouldn't "$n$ lines and $1$ row" be "$n$ rows and one column"?
Comment: @egreg: Corrected. I've never understood why English speakers say "row" instead of "line", and this confuses me even after so many years.
Comment: @JohnHunsberger: There's no need to accept an answer just to be polite. If an answer does not entirely satisfy you, just wait for a potentially clearer one, nobody will feel offended.
Comment: Good advice.  Thanks.


STS/Eclipse showing Potential resource leak, why?

Question: I have a service method which connects to MySQL and get data in ResultSet and in finally closed it's PreparedStatement, but STS showing a warning at return statement as

Potential resource leak: 'resultSet' may not be closed at this
  location

Method:
    public boolean checkData() {
        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        boolean status = false;
        try {
            dbConnection = icrud.getConnection();
            preparedStatement = dbConnection.prepareStatement("query on table");
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                status = resultSet.getBoolean("STATUS");
            }
            return status;  //Potential resource leak warning shows here.
        } catch (Exception e) {
            LOGGER.error("Exception Occurred:: " , e);
        } finally {

            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                    preparedStatement = null;
                }
            } catch (SQLException e) {
                LOGGER.error("Exception Occured while Closing statement" , e);
            }

            try {
                if (dbConnection != null) {
                    dbConnection.close();
                    dbConnection = null;
                }
            } catch (SQLException e) {
                LOGGER.error("Exception Occured while closing connection" , e);
            }
        }
        return status;
    }

As per Doc,

When a Statement object is closed, its current ResultSet object, if
  one exists, is also closed.

So I am closing Statement in finally though its showing warning. I have checked by closing result set in finally still warning doesn't go off.
Is it false positive? or Am I doing something wrong?
Comment: It's needlessly complex. Java has try-with-resources since Java 6 or 7. Use it. https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Comment: Because STS doesn't know about this rule. It just sees that you have created a Closeable, and haven't closed it explicitly. So it is a **potential** resource leak.
Comment: @JBNizet Ohh so it's just false positive warning, safe to ignore right? and whatever pattern for closing db connection and resources I am following is correct?
Comment: And most importantly, don't catch Exception, and don't ignore it. This method should throw a SQLException, not catch it. Or at least throw another exception if a SQL Exception occurs.
Comment: @JBNizet In addition, in the light of connection and statement pools, closing the statement may not always really close the result set (usually in buggy pool implementations or pools that take shortcuts for 'performance').
Answer: You are returning "status" without closing your connections. The "finally" clause isn't executed when you get to the return statement.
Comment: How? Can u explain?
Comment: dbConnection.close();
    preparedStatement.close();
    return status;
Comment: Please confirm that after return statement finally won't get executed..
Comment: I was wrong, it would execute. But maybe STS doesn't recognize that?


How to minimize $\max(x_1, x_2)$ and $x_1^2 + 9x_2^2$ subject to constraints?

Question: My textbook came up with a solution without explanation. I'm looking for a systematic way of solving the following optimization problems and similar ones (by hand), because I'm drawing a blank:
minimize

$$\max(x_1, x_2)$$ and after, $$x_1^2 + 9x_2^2$$
subject to

$$2x_1 + x_2 \ge 1$$
$$x_1 + 3x_2 \ge1$$
$$x_1 \ge 0, x_2 \ge 0$$
BTW the answer is $\left(\dfrac{1}{3}, \dfrac{1}{3}\right)$.
Comment: Edited question to reflect second objective $f(x_1, x_2)$ function example and fix title.
Comment: @Magdiragdag the question wants to minimize objectives in the form $f(x_1, x_2)$ over the given constraints in R2.
Comment: Oh, it really wants to minimize the maximum of $x_1$ and $x_2$...
Comment: Did you draw a picture? At least of the area you're optimizing over?
Comment: What is meant by minimize $\max(x_1, x_2)$ and $x_1^2 + 9x_2^2$?  Do you mean minimize $\max(x_1, x_2) + x_1^2 + 9x_2^2$?
Comment: @Jared just two different problems (same constraints), sorry for confusion
Answer: Let us enter in the Karush–Kuhn–Tucker framework,
with
$$
f(x,y) = -\max(x,y);\\
g_1(x,y) = 2x+y-1;\\
g_2(x,y) = x+3y-1.
$$
The Lagrangian is
$$
L(x,y,\lambda) =
-\max(x,y) + \lambda\cdot g(x,y)
$$
and the solution is, in the region $x\neq y$ (where $L$ is smooth):
$$
\begin{cases}
0&=&-1_{x>y} + 2\lambda_1 + \lambda_2  \\
0&=&-1_{x<y} + \lambda_1 + 3\lambda_2 \\
0&=&\min(\lambda_{i} , g_{i}(x,y)), & (i=1,2).
\end{cases}
$$
Hence, both $\lambda_i =0$
and the system has no solution.
In the region $x = y$,
$\max (x,y) = x$.
$$L(x,y,\lambda) =
-x + \lambda\cdot g(x,y) =: M(x,\lambda).
$$The new system for $M$ is:
$$
\begin{cases}
0&=&-1+ 3\lambda_1 +4\lambda_2\\
0&=&\min(\lambda_{i} , g_{i}(x,x)), & (i=1,2).
\end{cases}
$$
As we can't have $
g_1(x,x)=0=g_2(x,x),
$ either $\lambda_1=0$ or $\lambda_2=0$, then
$$
x\in\{1/3, 1/4\}.
$$
But if $x=y=1/4$, $2x+y<1$ and the point is not an admissible solution.
Then the solution is
$$
x=y=\frac 13;\\
\min_{g_{1,2}(x,y)\ge 0} \max(x,y)
= -\max_{g_{1,2}(x,y)\ge 0} (- \max(x,y))
\\ = \max(1/3,1/3) = 1/3.
$$

For the second problem,
the equations are
$$
\begin{cases}
0&=&-2x + 2\lambda_1 + \lambda_2  \\
0&=&-18y + \lambda_1 + 3\lambda_2 \\
0&=&\min(\lambda_{i} , g_{i}(x,y)), & (i=1,2),
\end{cases}
$$
hence  $(\lambda_1,\lambda_2)\neq (0,0).$
If $\lambda_2 = 0$:
$$
\begin{cases}
0&=&-2x + 2\lambda_1   \\
0&=&-18y + \lambda_1  \\
1 &=& 2x+y
\end{cases}
$$
then $x=18y, y=1/37, x = 18/37$. Then $x+3y = 21/37<1$: this is not the solution.
The solution is such as
$$
\begin{cases}
0&=&-2x + \lambda_2   \\
0&=&-18y + 3\lambda_2  \\
1 &=& x+3y
\end{cases}
$$
then $x=3y, y=1/6, x=1/2$.
Comment: it means that if $\lambda\neq 0$ then the inequality becomes an equality; and that $\lambda \ge 0$ in general (this is actually more clear in the [french version](http://fr.wikipedia.org/wiki/Conditions_de_Kuhn-Tucker)).
Comment: For the first solution, I'm not understanding the last equation of the systems, with 0 = min(...). Where did that come from? The others I understand from gradient of the lagrangian
Comment: Is it still obtained from differentiating the lagrangian with respect to the remaining variables, i.e. lambda 1 and 2?
Comment: when you write "Is it still obtained", what is 'it'?
Comment: The final equation in the systems, 0 = min(...)
Comment: Roughly, the sign of $\lambda$ is obtained because you want to be inside the domain and not outside. And if $\lambda\neq 0$ then the lagrangian is modified to take care of the constrain with equality, then there must be equality in it.
Comment: Oh I see, from KKT (the French wiki states this) the min = 0 equation combines positivity and complimentary slackness.


How to store a user-filled HTML table in local storage and then display it in a different results HTML page?

Question: Summary of my program:

Users fill out a HTML table (I'm not having problems with this step) in table.HTML page
HTML table is stored in localStorage (using .SET on table.innerHTML)
HTML table is displayed (using .GET) in a different results.HTML page

My attempt is below:
(INSIDE TABLE.HTML PAGE) HTML TABLE DESIGN

                    Criteria
                    ✅
                    ❌

                Details

                Name

                ❌

                Height

                ❌

                Colour

                ❌

                Age

                ❌

(INSIDE TABLE.HTML PAGE) BUTTON WHICH, ON CLICK, WILL SAVE THE HTML DATA IN LOCAL STORAGE AND ADD IT TO THE RESULTS HTML PAGE
    <button id="save_table" type="button">Click to save HTML data</button>

(INSIDE RESULTS.HTML PAGE) RESULTS.HTML PAGE WHICH I WANT THE TABLE DATA FROM LOCAL STORAGE (FROM TABLE.HTML) TO BE ADDED TO

 //JS function saveTableData() used to display table here

JS FILE USING LOCALSTORAGE .GET and .SET
function saveTableData() {
    localStorage.setItem('table', document.getElementById('table-scroll').innerHTML);

    document.getElementById("show_table_data").innerHTML = localStorage.getItem("table-scroll");
}

window.addEventListener('DOMContentLoaded', function() {
        document.getElementById('save_table').addEventListener("click", () => {
            saveTableData();
        });
      });

I've tried using the div element's .innerHTML attribute to try and store the table data in LocalStorage and subsequently display the table data from LocalStorage in a separate HTML page, but can't seem to get it to work! Any suggestions would be much appreciated :)
EDIT WITH BOTH FUNCTIONS:
function saveTableData() {
    localStorage.setItem('table', document.getElementById('table-scroll').innerHTML);

}

function loadTableData() {
    document.getElementById("show_table_data").innerHTML = localStorage.getItem("table");
}

window.addEventListener('DOMContentLoaded', function() {
        document.getElementById('save_table').addEventListener("click", () => {
            saveTableData();
        });
      });

      window.addEventListener('DOMContentLoaded', function() {
        document.getElementById('save_table').addEventListener("click", () => {
            loadTableData();
        });
      });

Error I'm receiving: Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
at loadTableData (script1.js:1138:58)
at HTMLButtonElement. (script1.js:1149:13)
Answer:
you have non-matching keys when you store table in local storage and when you query it:

storing:
    localStorage.setItem('table', document.getElementById('table-scroll').innerHTML); // key is 'table'

retrieving:

    document.getElementById("show_table_data").innerHTML = localStorage.getItem("table-scroll"); // key is 'table-scroll'

you use the same function saveTableData to both store and retrieve the data on different pages. Current implementation can work on the first page (will store the data) but then will probably throw an error because documetn.getElementById('show_table_datad') will return undefined (there is no such table in TABLE.HTML. On RESULTS.HTML  this function won't be able to work because:

there is no trigger for it.
it should throw an error on document.getElementById('table-scroll') because this table exists on a different page.

You should split this into two functions: saveTableData and loadTableData.
Comment: Hey @purple - I made an edit in my original post and took on your advice. I split the original function into two functions, but for some reason I'm getting this error (which I've also included in the edit). Would you be able to shine some light on it?
Comment: Also @purple, would I add both functions on the same table.html page, or would I add the saveTableData() function to table.html and loadTableData() function to the results.html table?
Comment: You should only include functions you need on each page. `saveTableData` on `TABLE.HTML` and `loadTableData` on `RESULT.HTML`. You get the error because now the button on `TABLE.HTML` still tries to do both tasks: save the data and load the data. You need different buttons on different pages and assign different event handlers to them


What is the parameter nu in oneClass svm?

Question: According to this link, nu specifies the nu parameter for the one-class SVM model. The nu parameter is both a lower bound for the number of samples that are support vectors and an upper bound for the number of samples that are on the wrong side of the hyperplane. The default is 0.1. The nu parameter must be in the range [0,1].
I do not understand it very well, graphically as it would be?
Of theory I find the rank to which nu belongs, but what is the goal of nu for oneClass SVM, is nu equal to C?
Answer: The goal of $\nu$ is similar to that of $C$. The parameter $\nu$ is there to finetune the trade-off between overfitting and generalization. The problem with $C$ is that it is positive and unbounded which makes it difficult to choose optimally during cross-validation. Thus, the range $[0,1]$ makes the regularization more interpretable in terms of $\nu$ but empirically, people have found it more difficult to optimize in terms of $\nu$.
The relationship between $\nu$ and $C$ is given by the formula $\nu= \frac{A+B}{C}$ where $A$ and $B$ are some constants that are not easy to calculate.
The explanation/intuition about the interpretation of $\nu$ given in the link you've mentioned is pretty accurate. $\nu$ is upper bounded by the fraction of outliers and lower bounded by the fraction of support vectors. Just consider that for default value $0.1$, atmost $10\%$ of the training samples are allowed to be wrongly classified or can be considered as outliers by the decision boundary. And atleast $10\%$ of your training samples will act as support vectors (points on the decision boundary).
Comment: I need some reference of some book for my thesis, please
Comment: The creator of libsvm Chih-Jen Lin, has a nice well-cited article on nu-SVM titled "Training ν-Support Vector Classifiers: Theory and
Algorithms" where you can find the things I have mentioned in more detail. You can search the title and author on google scholar and get the bibtex or other formats for citing the article.
Comment: your answer I solve my doubt
Comment: help me with my new question please:  https://stats.stackexchange.com/questions/347294/what-is-the-parameter-sigma-in-svm
Comment: i not understanding: boundary points in the decision boundary
Comment: It just means points on the decision boundary. Google what support vectors actually mean. You'll get it.
Comment: hello I need your help we can talk in chat please


Header was shaking when scrolling down

Question: Note: Please try to use mousewheel when scrolling down. Also please be nice to mousewheel. Move it slowly.
I have a little question about scrolling. I am trying to reduce the header height when page scrolled to the down as most creative websites do.
But in this case when I was tried to scroll down with mouse screen was shaking. Also sometimes its do with scrolling with mousewheel. All files added to the js fiddle. Please look at jsfiddle below. I hope I can express myself. Thanks in advance.

$(document).ready(function () {
 $(window).scroll(function () {
    if ($(window).scrollTop() >= 30) {
      $('.header-bottom').addClass('sticky');
      $('.header-bottom').css('line-height','80px');
    } else {
      $('.header-bottom').removeClass('sticky');
      $('.header-bottom').css('line-height','160px');
    }
  });
});
body {
  margin: 0;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}
.sticky {
  position: sticky;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
}

.content > div {
  margin-bottom: 100px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Comment: I see no shaking elements...
Comment: Please move scroll bar with mouse wheel slowly.
Comment: I see the issue, you need to use the scroll bar with the mouse slowly and not scroll down with the mouseweel
Comment: Works fine for me too on Firefox. Which browser do you use?
Answer: do position: fixed; instead of position: sticky; in the sticky class

 $(window).scroll(function () {
    if ($(window).scrollTop() >= 30) {
      $('.header-bottom').addClass('sticky');
      $('.header-bottom').css('line-height','80px');
      $('.content').css('margin-top','120px');
    }else {
      $('.header-bottom').removeClass('sticky');
      $('.header-bottom').css('line-height','160px');
      $('.content').css('margin-top','20px');
    }
  });
body {
  margin: 0;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}
.sticky {
  position: fixed;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
  -webkit-transition: .45s;
  -moz-transition: .45s;
  -ms-transition: .45s;
  -o-transition: .45s;
  transition: .45s;
}

.content > div {
  margin-bottom: 100px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Comment: I was try to made with fixed. But its hiding first div. Sticky pulls the first div "Lorem ipsum". Any suggestion for that?
Comment: Explain why `position: fixed` is better than `position: sticky`, because I see same output as from OP example
Comment: @AliÖzen I don't have the perfect answer for your first question but it's most likely because elements with position sticky have a relation with the elements around them as for fixed elements they aren't restricted they have relation just with the window. Also I edited my answer you just have to change margin-top because the content div doesn't have a relation with the element above it anymore
Comment: Yes, this solves the problem perfectly. Nothing shakes now at least in newest Chrome (69.0.3497.100 (Build oficial) (64 bits))
Comment: Yes it worked little bit. I just want to combine them. Not shake. Not jumping div or hiding divs. Header must pull divs without shake. I am open any kinda solution.
Answer: You add
. After header-top and header-bottom move into

And add css;
.header { height:190px;}
If you using position:fixed insted position:sticky this could be useful.
The problem will be solved.

$(document).ready(function () {
 $(window).scroll(function () {
    if ($(window).scrollTop() > 30) {
      $('.header-bottom').addClass('sticky');
    } else {
      $('.header-bottom').removeClass('sticky');
    }
  });
});
body {
  margin: 0;
}
.header {
  height:190px;
}
.header-top {
  line-height:30px;
  background: blue;
}
.header-bottom {
  line-height:160px;
  background: red;
  -webkit-transition: .5s;
  -moz-transition: .5s;
  -ms-transition: .5s;
  -o-transition: .5s;
  transition: .5s;
}
.sticky {
  position: fixed;
  line-height:80px;
  top:0;
  width: 100%;
}

.content {
  margin-top: 20px;
}

.content > div {
  margin-bottom: 100px;
}

.margin {
  margin-top:190px;
}

Content

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora nobis, suscipit consequuntur! Neque modi libero praesentium rerum, pariatur, assumenda obcaecati laudantium officia iste excepturi, molestias quibusdam quae sed nihil laborum.

Necessitatibus, omnis odit ipsam, repudiandae beatae minima! Voluptates molestias vitae fuga officiis, aperiam earum quas laboriosam cupiditate hic vero reiciendis, numquam corporis, assumenda rem iure expedita animi magnam perferendis delectus.

Eum odit hic delectus vel facilis nisi cupiditate ad enim recusandae ex, commodi sunt ullam distinctio, architecto quam nulla cumque possimus nihil qui unde magni provident ratione obcaecati fuga. Beatae.

Iusto repellendus dolore atque architecto consequatur magni nulla animi possimus reiciendis, soluta similique recusandae voluptate reprehenderit, aspernatur repellat ab provident facere magnam sit unde, accusantium explicabo. Ducimus odit aliquid, minima!

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Et cum sapiente placeat quis. Aut nobis ea amet aliquid, voluptatibus laudantium, atque doloremque accusantium nulla iste tempore nemo. Totam non eos distinctio. Quaerat, dolorem, possimus. Dolores molestiae nam natus.

Comment: That worked like a charm. Thats what i want. Thanks.

Header was shaking when scrolling down


Problems with Media gallery

Question: I am using the media-gallery module to create dynamic galleries for a site.
I have a problem when I edit a node; I get the following error:

Notice: Undefined index: media_gallery_format in locale_field_node_form_submit() (linea 405)

I have read Undefined indexes in locale_field_node_form_submit(), but I didn't resolve the problem. The issue report suggests that the error depends from a local language, and that I should change one line in media-gallery.module, but I don't understand where that line is, and how to change the code.
Can anybody help me?
Comment: The solution reported in the issue report is to replace any occurrence of `unset($form[$id])` with `$form[$id] = array('#language' => NULL)` in the module file; it just a matter of doing a "search and replace" on a file. What do you exactly don't understand?
Comment: Thank you kiamlaluno!! I dont understand where can i replace that string (problebly in media-gallery.module in line? ), sorry for my english...
Comment: Sorry kiamlaluno but i must replace all strings in "function media_gallery_form_media_gallery_node_form_alter(&$form, &$form_state)" with occurence "unset($form[$id])" with "$form[$id] = array('#language' => NULL)" ?
Comment: See my answer.
Answer: The solution reported in the issue report is to replace every occurrence of unset($form[$id]) with $form[$id] = array('#language' => NULL) in all the module file; you just search for the first string, and you replace it with the second string. The module file is media_gallery.module.
Who suggests the fix doesn't report in which line you find unset($form[$id]) because you probably find more occurrences of that string, and the user doesn't want to make a list of all the lines containing that string. It is also useless to make such list, as an editor can easily make a search and replace for the strings listed in the issue report.

Problems with Media gallery


Regex to select all spaces between a special enclosure

Question: I am trying to write a regex for Javascript that can select all whitespaces in between AMPScript brackets, the syntax for the Lang is something like this

%%[

set @truth = 'this is amp'

IF @truth == 'this is amp' THEN
set @response = 'amp rocks'
ELSE
set @response = '...'
ENDIF

]%%

So far, I am able to select all the characters inside the given brackets using this expression:
%%\[(\s|.)*?\]%%

But this selects all the characters inside the enclosure, is there a method I can use to only select spaces/new lines/tabindents only?
Thanks in advance!
Answer: I believe this is what you want:
(?<=%%\[(\s|.)*)\s*(?=(\s|.)*\]%%)

https://regex101.com/r/EWhbuX/1
Edit
Here's a breakdown of the regular expression:
1.
First we start with a Positive Lookbehind (?<=   )

This will make sure that the pattern that's following this, will be preceded by the pattern inside, but will not be include it in the matches.

In this case we want our matching pattern to be preceded by %%[ and any other character %%\[(\s|.)*
So, our resulting code for the Positive Lookbehind is
(?<=%%\[(\s|.)*)

2.
Next comes the pattern that we actually want to match after our Lookabehind, and (spoiler alert), before a Lookahead that we'll define later.
In this case, that's just any whitespace character, so our pattern will be
\s

(Yes, I just noticed that we don't even need the * in my original answer)
3.
Similarly to what we did at the beginning of the expression with the Lookbehind, we now need a Positive Lookahead (?=   )
This is to make sure that our whitespaces will be  followed by any character and ]%% (\s|.)*\]%%.
So this is our resulting Lookahead:
(?=(\s|.)*\]%%)

4.
Put everything together and you have your regular expression!
(?<=%%\[(\s|.)*)\s(?=(\s|.)*\]%%)

Comment: Much needed! Thank you, can you explain me the method you have used??


an error in spark sbt assembly

Question: In spark installing README,I write command './bin/spark-shell',
I got some hint follwing:
Found multiple Spark assembly jars in /opt/spark-0.9.0-incubating-bin-hadoop1/assembly/target/scala-2.10:
spark-assembly-0.9.0-incubating-hadoop1.0.4.jar
spark-assembly_2.10-0.9.0-incubating-hadoop1.0.4.jar
Please remove all but one jar.
I ever try to remove one of them ,but I fail to success.
If somebody can deal with it ,please tell me.
thanks.
Answer: all you need to do is just cd to the assembly/target/scala-2.10 dir, and use the sbt to compile again.
this is caused by the incompatible between different compile method, you may used the maven and sbt both?
Answer: The problem is that the JARs are built into the assembly JARs when you run
sbt/sbt clean assembly
What I did is:
sbt/sbt clean package
This will only give you the small JARs. The next steps is to update the CLASSPATH in the
bin/compute-classpath.sh script manually, appending all the JARs.
With :
sbt/sbt assembly
We can't introduce our own Hadoop patch since it will always pull from Maven repo, unless we
hijack the repository path, or do a 'mvn install' locally. This is more of a hack I think.
Comment: How to update the classpath manually?. I am gettin an error while initializing sparkContext. Please see [this](http://stackoverflow.com/questions/25898282/error-while-defininng-sc-in-sparkcontext-pyspark)

an error in spark sbt assembly