MySQL Changing from Null to Non Null

Question: I have got a field that has been setup to allow for Null, but am now wanting to change that to not allow for Null.
When ever I try to change this I can't because PhpMyAdmin has set all the previous records to Null.
How can I fix this problem?
Is there a query I could put that will remove all the Null values and set the field to Non Null?
Answer: Of course.  But what do you you mean by "remove all the NULL values?"  Does that mean to delete all the rows that have a NULL in that field?  If so, you could do this:
DELETE FROM your_table WHERE your_field IS NULL;

If you want to keep those rows, you'll have to put some other value in that field.  Is there one that makes sense?  If so, you could do this:
UPDATE your_table SET your_field = 42 WHERE your_field IS NULL;

(Where, of course, 42 is whatever value you want to use instead.)
If you want to keep the rows, and there isn't any other value you could use, then the NULLs that are there now should stay, and it might be time to reevaluate why you want to set the field to NOT NULL.
Comment: +1; NULL isn't simply a lazy placeholder for some special value, it indicates the absence of a value, and in a well-designed database, that has some significance.
Comment: +1 for suggesting 42 as a placeholder value. And for understanding `null`.
Answer: You seem a bit confused as to what a null realy is. Here's an article I've published somewhere else that should be safe to republish here:
Null means there is no predefined value.
When a column is created in a table in a database there are some constraints that can be added. One of those constraints is wether or not the column allows null values.
A field on a row will be null if it is not explicitly set to something else. You can either supply a default value when the table is created, or you can set a value when adding a new row to the table, or update the row later on. To add or update rows in a table the INSERT and UPDATE commands are used.
When a field is null all comparisons to that field will also be null. This means that all boolean algebra misbehaves when a null value is involved:
* True AND Null is Null
* False AND Null is Null
and so on …
Ordinary mathematics doesn't work either since 5 + Null equals Null.
An interesting side effect of this is that when you compare two fields that are both null the result will not be true, it will be null.
To still be able to work with fields that can contain null values there are a couple of options: Both T-SQL (Microsoft SQL Server) and MySql has the functions COALESCE() and ISNULL().
ISNULL(): returns a predefined value if the value you are looking for is null. SELECT ISNULL(null, 2) will return 2
COALESCE(): returns the first value in a predefined list that is not null: SELECT COALESCE(a, b, c, d ...)
In MySql there is also a null safe comparison operator: a <=> b It will return 1 (true) if both values are null and 0 (false) if either value is null.
When it comes to counting rows in a table you also need to be aware of the implications of null. SELECT COUNT(*) FROM TableName will return the total amount of rows in the table, but SELECT COUNT(FieldName) FROM TableName will will only return the amount of rows where the column 'FieldName' is not null.
Quite often the database designer, more or less by lazyness, sets a default value for all columns in a table or constrains all feilds to not allow null. When the database designer does that everyone that uses the database is forced to make up 'magic' values when ever there is no actual value to use.
Suppose we have a table for storing vehicle information and in that table we have a column to store the fuel type of each stored vehicle. What fuel type should be used for a bicycle? If the column allows null the answer is easy; since there is no engine on a bicycle there is no fuel type to use, so just set the field to null on all rows representing bicycles. If the database designer instead had put the contraint on the column that null is not allowed the developer have to make up a value to represent 'no fuel type'. If the field is an integer zero might be used to do that. Furthermore, if there is a table that contains all viable fuel types that the vehicle table is supposed to reference to find names and descriptions for fuel types the developer have to put fake fuel types in the table so that the database management server can enforce the data integrity of the database.
Null is a very nice feature of databases that lots of 'ordinary' programming languages don't have, but a database developer and designer needs to keep track of where and how it is used.
Comment: I honestly read through, and while I could confirm this is true, which paragraph was aimed at answering the "Is there a query ..." part of the question?
Comment: FWIW, there's also a SQL-99 predicate `IS [NOT] DISTINCT FROM` that works like MySQL's proprietary `<=>` operator.  PostgreSQL, IBM DB2, and Firebird support `IS [NOT] DISTINCT FROM`.
Comment: Actually none, but the question asked for a way to remove null values and I got the feeling he wouldn't have asked at all if he had a grasp of what null is.
Answer: UPDATE my_precious_table
SET stinky_field TO my_favourite_non_null_value
WHERE stinky_field IS NULL;

MySQL Changing from Null to Non Null


What do these left arrows or angle brackets mean to the left of a chord?

Question: I almost wonder if this is a weird way to draw an arpeggio, but they seem like distinct arrows or left angle brackets each on a line to the left of a chord in piano music on the left-hand bass clef.  They span the entire chord's length and include lines that don't have notes.  How would you interpret this?  I can't find a related answer or this listed in any reference.

Edit: This is a hymn called "Living for Jesus" composed by C. Harold Lowden.  This is the third to the last bar.  At the bottom of the page it says "Copyright, 1945. Renewal. The Rodeheaver Co., owner."  It's a part of hymnal "Inspired Hymns" printed 1967 - second printing, copyright 1951 by Singspiration, Inc., compiled by Alfred B. Smith.  Published by Zondervan Publishing House of Grand Rapids, Michigan.  The arrangement looks a lot different than others I've seen online for the same song, including a lot of grace notes in the chorus.
Comment: I would have voted for quite long ledger lines combined with a parenthesis-like symbol, but the topmost "arrow" does not correspond to a required ledger line.
Comment: Yep, definitely overstrike,  not arrows, as @guidot said
Answer: It's a weird arpeggio line. Can't think of anything else it COULD be!
You've added the information that this was published in 1967.  I'm wondering if it was produced with one of those 'music typewriters' that were popular in the mid-20th century before being blown out of the water by computer typesetting.  I don't think it's Letraset.
Comment: @ToddWilcox I don't know much about the engraving process.  For a hymnal, would you expect there to be several engravers, or might there be one engraver or firm that I could potentially track down and find a comment about this tactic, for?  The engraver would be employed by the publisher, right?
Answer: Just to put an exclamation point on @LaurencePayne's answer, here's the same measure of the same arrangement from https://hymnary.org/tune/living_for_jesus_a_life_that_lowden


Using a Markov Chain to find the limiting probability?

Question: Let's say a website makes available only one of three online quizzes A, B and C, daily.
If the majority of visitors pass the quiz then the next day the website will randomly publish either quiz A, B, or C with equal probability $\frac{1}{3}$.
If the majority of visitors fail the quiz then the next day the website will publish only quiz A (with probability one).
The probability of passing a quiz is:
$P(A) = \frac{3}{10}$, $P(B) = \frac{6}{10}$, $P(C) = \frac{9}{10}$

QUESTION: suppose that the testing procedure has been running for a
  large number of days without interruption. Let $\xi_A$ be the
  proportions of the total number of days in which quiz A was used.
  (This can be thought of as being the "limiting probability" that quiz
  A is used).
HINT: Use the stationary distribution (G, B) = ($\frac{3}{7}$, $\frac{4}{7}$) and use this stationary distribution to work out $\xi_A$ (apply appropriate conditioning and limiting operations).

My thoughts thus far: The bit where it says "limiting operations" is confusing me slightly on what it means? Is the following approach correct? I feel it is but I'm new to stochastic modelling..
I can model this as a Markov Chain with transition matrix (where rows sum to one):
$\left[\begin{array}{ccc}
0.6 & 0.4 \\
0.3 & 0.7 \\ \end{array}\right]$
i.e. A good day (G) follow by another G day = $(\frac{1}{3})(\frac{3}{10})+(\frac{1}{3})(\frac{6}{10})+(\frac{1}{3})(\frac{9}{10}) = \frac{6}{10}$
and a bad day (B) followed by a G day =  $(\frac{1}{1})(\frac{3}{10})+ 0 + 0 = \frac{3}{10}$.
Step 1: I worked out that the stationary distribution is $P(G)=\frac{3}{7}$ and $P(B)=\frac{4}{7}$.
Step 2: using a bit of conditional probability, then the probability of quiz $A$ being used on day $n$ is:
P(quiz A on day n) = P(quiz A and day n-1 is G) + P(quiz A and day n-1 is B)
$= P(A|G)*P(G) + P(A|B)*P(B)$
$= (\frac{1}{3})(\frac{3}{7}) + (\frac{1}{1})(\frac{4}{7})$
$= \frac{5}{7}$
Step 3: Apply limiting operations? What does that mean?
Comment: It seems to me that using only two states doesn't fully capture what's going on, because (since quiz A has a special treatment and quizzes B and C have different passing probabilities) in order to determine the transition probabilities you need to know what quiz was offered.
Comment: @whuber The quiz offered is dependent on whether the results from the previous day were (G)ood or (B)ad. The transition matrix is what is given in my notes (it took me quite some time to confirm the probabilities). This is all the information I have. Steps 2 and especially 3 are my main worry.
Comment: The problem with the $(G,B)$ representation is that it only indirectly models what is of interest. Because the question asks about the proportion of days on which quiz $A$ is given, a direct (and quite the easiest) attack on the problem would include the state "$A$ was given," for then you just read off the answer directly without having to take that time to compute the probabilities.
Answer: This problem describes five situations, or states.  Although it can be solved (somewhat painfully, in my view) using just two of them, as a good principle of modeling we should start out by contemplating all five.
The states, and the transitions among them, are:

$A$: Quiz $A$ is given.  This transitions to $G$ ("Good") when a majority passes it.  Presumably the chance that a majority passes is the same as the chance that one person passes it, $3/10$.  (I say "presumably" because this "obvious" deduction depends on implicit assumptions, such as that the chances of passing are independent among people, and without those assumptions the deduction can be false.)  Otherwise this transitions to $Z$ ("Bad") with probability $1-3/10 = 7/10$.
$B$: Quiz $B$ is given.  This transitions to $G$ with probability $6/10$ and $Z$ with probability $1-6/10=4/10$.
$C$" Quiz $C$ is given.  This transitions to $G$ with probability $9/10$ and $Z$ with probability $1-9/10=1/10$.
$G$ (a "good" day): This transitions to $A$, $B$, and $C$ with equal probabilities of $1/3$ each.
$Z$ (a "bad" day): This transitions to $A$ with probability $1$.

The transition matrix $\mathbb{P}$ for $(A,B,C,G,Z)$ therefore is
$$\left(
\begin{array}{ccccc}
 0 & 0 & 0 & \frac{3}{10} & \frac{7}{10} \\
 0 & 0 & 0 & \frac{3}{5} & \frac{2}{5} \\
 0 & 0 & 0 & \frac{9}{10} & \frac{1}{10} \\
 \frac{1}{3} & \frac{1}{3} & \frac{1}{3} & 0 & 0 \\
 1 & 0 & 0 & 0 & 0
\end{array}
\right).$$
This is bipartite: the transitions alternate between states in $\{A,B,C\}$ and states in $\{G,Z\}$.  By taking two transitions at once--which models what happens in the course of a single day--we can study the evolution of the distribution in states $\{A,B,C\}$ and, separately, the evolution in states $\{G,Z\}$.  As expected, $\mathbb{P}^2$ decomposes into a direct sum.  One block is for the $\{A,B,C\}$ transitions,
$$\mathbb{P}_{ABC} = \left(
\begin{array}{ccc}
 \frac{4}{5} & \frac{1}{10} & \frac{1}{10} \\
 \frac{3}{5} & \frac{1}{5} & \frac{1}{5} \\
 \frac{2}{5} & \frac{3}{10} & \frac{3}{10}
\end{array}
\right)$$
and the other is for the $\{G,Z\}$ transitions,
$$\mathbb{P}_{GZ} = \left(
\begin{array}{cc}
 \frac{3}{5} & \frac{2}{5} \\
 \frac{3}{10} & \frac{7}{10}
\end{array}
\right).$$
From these matrices (in the usual purely mechanical ways) we deduce the stationary distributions $(5/7,1/7,1/7)$ for $(A,B,C)$ and $(3/7, 4/7)$ for $(G,Z)$: these are the (normalized-to-sum-to-unity) left eigenvectors with eigenvalues $1$.  From them we immediately read off the answers to question 1 ($5/7$, the $A$ component of the first eigenvector) and question 2 ($3/7$, the $G$ component of the second eigenvector).
These are stationary distributions.  Let's track what actually happens when we start, say, in state $A$ (initially, quiz $A$ is given).  In this simulation, which used only the transition matrix $\mathbb{P}_{ABC}$, the majority failed $A$, so $A$ was given again; the majority failed again; finally the majority passed, and $B$ was randomly assigned; and so on.  I have plotted the results for the first $100$ days:

After 100 days, quiz $A$ had been given $72$ times ($0.72$ of the total), quiz $B$ $17$ times ($0.17$), and quiz $C$ $12$ times ($0.12$).  Clearly these realized frequencies do not equal the limiting probabilities of $5/7 \approx 0.714$, $1/7 \approx 0.143$, and $1/7$, respectively, but they are approximately the same.
After running a simulation for a million days(!), though, the counts happened to be $713446$, $143495$, and $143060$: each, as a fraction of the total, is considerably closer to the limiting probabilities.
Were we to re-run these simulations, the results would likely differ from the results I have obtained, and they would still differ from the limiting probabilities.  However, the differences in proportions for the million-day simulation would be relatively small.  It is only in this limiting, approximate sense that the stationary distributions of the Markov chain describe what really might happen as the chain evolves in the real world.


Update table column using sum()

Question: I am trying to do two thing with my SQL code. I want it to copy data from another column (hours) , that's located in another table (works- table), and place it into a new column (numHours) in a different table (Employee- table). However, I want it to use the sum of the hours worked for each employee id (eid) and then place that sum into the new column.
This is what I wrote, but two things are wrong. When I execute just the select statement every employee id has the same number of hours worked. When I run the whole statement I get this error
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);

These are my tables
CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,

CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);

CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,

CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);

CREATE TABLE Works(
eid INT,
did INT,
hours INT,

CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did  FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);

How would I properly code this?
Comment: Tag your question with the database you are using.
Answer: I believe you want this:
UPDATE Employee
    SET numHours= (SELECT sum(w.hours) From works w WHERE employee.eid = w.eid)
    WHERE numHours IS NULL;

Notes:

The condition on numHours belongs in the UPDATE, not the subquery.
You want a correlated query, not a full join (and don't use commas in the FROM clause ever!).
There is no need for a column alias in the subquery.
There is no need for GROUP BY in the subquery.
Comment: @TickleMonster . . . An explicit `join` is unnecessary.  The correlated subquery seems to do what you want.
Answer: Use JOIN and UPDATE:
UPDATE E
SET E.numHours=H.totalHours
FROM Employee E JOIN
    (Select sum(hours) AS totalHours,eid
     From works
     Group by eid)H on H.eid=E.eid
WHERE E.numHours IS NULL

Explanation:
Inner query will select Total hours for each employee. Then use it to update Employee table.

Update table column using sum()


Colliding/overlapping full and differential backups in SQL Server

Question: I am trying to set up a monthly full backup and a daily differential. The full backup is currently on the 1st, but I might change it to the first Saturday. I need to retain full backups for a few months (multiple sets).
My question is: on the first of the month how can I prevent the differential backup from running? I don't want them both going at the same time, or the differential to run based on a previous full...if that makes sense.
Is there a way to exempt certain days of the week or month from the differential schedule? I wasn't able to find any way to do that in the Maintenance Plan Wizard...
This is on SQL Server 2012 Enterprise
Thanks
Comment: From this it seems that they should block. Can anyone confirm (maybe with 2012)? http://blogs.msdn.com/b/arvindsh/archive/2008/12/30/concurrency-of-full-differential-and-log-backups-on-the-same-database.aspx
Answer: If you want that proposed schedule, your best bet is to run your backups from Windows Task Scheduler. The "monthly" option allows you to pick the days of the month using a set of check-boxes.
Another option is to simply run differentials after the time you run your full backup; pick a delay that suits your situation.
And, yes, on Sql2012, a full backup will block a concurrent differential backup. I just kicked off a full backup of a catalog (that takes about a minute to run on my SSD), then in another window kicked off a differential on the same catalog; the differential waited for the full backup to complete.
Comment: Oh interesting, so it does actually block, not cancel. So basically you had a full backup, and "immediately" after an "empty" differential backup. Is that correct?
Comment: Yes. And as part of my backup sproc, it also runs "RESTORE VERIFYONLY" against the backup file that was created, so it's as close to "good" as you can get without actually doing a restore.


What's the "u'" at the beginning of every field in MongoDB?

Question: There's nothing here because the question fit into the title field.
Comment: http://stackoverflow.com/search?q=python+string+u are related questions.
Answer: Probably, you're using the Python client, and seeing Unicode strings.


Cannot cast from Object to boolean

Question: This is the error I am receiving,
org.apache.jasper.JasperException: Unable to compile class for JSP:

    An error occurred at line: 13 in the jsp file: /index.jsp
    Cannot cast from Object to boolean

This is my code:
Controller Servlet
if(authentication.verifyCredentials(request.getParameter("username"),
   request.getParameter("password")))
{
        session.setAttribute("username", request.getParameter("username"));
        session.setAttribute("loggedIn", true);
        dispatcher.forward(request, response);
}

I also tried this,
session.setAttribute("loggedIn", new Boolean(true));

JSP
<%
    if(session.getAttribute("loggedIn") != null)
    {
        if(((boolean)session.getAttribute("loggedIn")))
        {
            response.sendRedirect("Controller");
        }
    }
%>

Yes I researched and also saw the previous stackoverflow post; however I still cannot resolve my problem.
Please assist.
Answer: Try casting it to Boolean (nullable) instead of boolean in the JSP:
if(((Boolean)session.getAttribute("loggedIn")))
{
    response.sendRedirect("Controller");
}

Comment: Remember, all the lowercase types are built-in primitive types not extending `Object`. If you want to use them with references, you need to use the uppercase versions, which are "boxed" types.
Comment: Thank you for handy tip! Onward I can't forget 'Boolean' :)
Answer: try with
   if(((Boolean)session.getAttribute("loggedIn")))

instead of:
   if(((boolean)session.getAttribute("loggedIn")))

attribute has to be taken as Boolean, not as primitive type

Cannot cast from Object to boolean


Basic probability theory

Question: I was recently given the following statistics: On a particular highway, 18% of drivers are black, 63% of drivers searched by the police are black. So, a black driver is 7.7 times more likely to be searched.
I'm having some difficulty deriving the figure 7.7 myself. Am I correct to interpret the 63% as the conditional probability of being black given that you have been searched by the police as being 0.63? Thus, 0.37 as the probability of not being black given that you have been searched by the police.
Furthermore I'm not sure how we would arrive at the probability of being searched given that you are black (in order to make the comparison and arrive at 7.7). Or is this even the correct probabilistic interpretation of the sentence?
(if anyone is interested, this data is from an economics paper by Knowles, Persico and Todd, 2001)
Comment: It would be helpful to reproduce a full quotation from the text, since the way that the claim is phrased can make a difference.
Comment: @gota The odds ratio is the only probability metric that works to describe any $2 \times 2$ table association, but it's so frequently reported as a risk ratio that, when it's possible to do so, a risk ratio is reported instead. However, it should be noted that the probabilities quoted here aren't risks.
Comment: I honestly don't know what "7.7 times more likely" mean. e.g. what does it mean when people say "'A' happens 7.7 times more likely than 'B'" and you find out that P(B) = 0.9?
Answer: 82% are "not black" and comprise the other 37% who are searched. So, in an abuse of statistical notation,
<code>
P(Search | black) / P(Search | not black) =
  = P(Black | search)/P(Black) / (P(not black | search) / P(not black) )
  = (0.63 / 0.18 ) / (0.37 / 0.82)
  = 3.5 / 0.45
  = 7.7
</code>
Comment: That's very odd... In your calculation P(Search | black) = 3.5... whaaat?!
Comment: @gota you're right. It's a reverse conditional. The point is that P(search) cancels out of the ratio when applying Bayes rule. I made this semi-explicit.

Basic probability theory


Who were the best pre-WW2 footballers in the world?

Question: Alfredo Di Stefano
There are plenty of footballers that have been considered the greatest player in the world during their career, but they all appear to be post-WW2, such as Alfredo Di Stefano.
Alfredo Di Stefano, Wikipedia

Alfredo Stéfano Di Stéfano Laulhe (4 July 1926 - 7 July 2014) was an Argentinian footballer and coach, who, besides having played for the Argentine national team, also played for Selection Spanish. He is considered one of the greatest footballers in history.

Pele
And of course Pele during his time was considered the greatest player in the world, and is debatably considered the greatest player of all time.
Pele, Wikipedia

Edson Arantes do Nascimento (Brazilian Portuguese: [ˈɛtsõ (w)ɐˈɾɐ̃tʃiz du nɐsiˈmẽtu]; born 23 October 1940), known as Pelé ([peˈlɛ]), is a Brazilian former professional footballer who played as a forward. Regarded as one of the greatest players of all time and labelled "the greatest" by FIFA, he was among the most successful and popular sports figures of the 20th century. During his playing days, Pelé was for a period the best-paid athlete in the world.

Johan Cruyff
After Pele retired, the designation of greatest player in the world probably fell to Johan Cruyff.
Johan Cruyff, Wikipedia

Hendrik Johannes Cruijff OON (Dutch: [ˈjoːɦɑn ˈkrœyf] (About this soundlisten), internationally spelled Cruyff; 25 April 1947 – 24 March 2016) was a Dutch professional football player and coach. As a player, he won the Ballon d'Or three times, in 1971, 1973, and 1974. Cruyff was a proponent of the football philosophy known as Total Football explored by Rinus Michels, and is widely regarded as one of the greatest and most prolific players in the history of the sport.

Diego Maradona
Then Diego Maradona.
Diego Maradona, Wikipedia

Diego Armando Maradona (Spanish: [ˈdjeɣo maɾaˈðona]; 30 October 1960 – 25 November 2020) was an Argentine professional football player and manager. Widely regarded as one of the greatest players in the history of the sport, he was one of the two joint winners of the FIFA Player of the 20th Century award. Maradona's vision, passing, ball control, and dribbling skills were combined with his small stature, which gave him a low centre of gravity allowing him to manoeuvre better than most other players. His presence and leadership on the field had a great effect on his team's general performance, while he would often be singled out by the opposition. In addition to his creative abilities, he possessed an eye for goal and was known to be a free kick specialist. A precocious talent, Maradona was given the nickname "El Pibe de Oro" ("The Golden Boy"), a name that stuck with him throughout his career. He also had a troubled off-field life and was banned in both 1991 and 1994 for abusing drugs.

Zinedine Zidane
After Diego Maradona the mantle was probably taken up by Zinedine Zidane.
Zinedine Zidane, Wikipedia

Zinedine Yazid Zidane (born 23 June 1972), popularly known as Zizou, is a French former professional football player who played as an attacking midfielder. He is the current manager of La Liga club Real Madrid and is one of the most successful managers in the world. Widely regarded as one of the greatest players of all time, Zidane was an elite playmaker renowned for his elegance, vision, passing, ball control, and technique. He received many individual accolades as a player, including being named FIFA World Player of the Year in 1998, 2000 and 2003, and winning the 1998 Ballon d'Or.

Cristiano Ronaldo
And most recently, Cristiano Ronaldo. Though some may argue Lionel Messi.
Cristiano Ronaldo

Cristiano Ronaldo dos Santos Aveiro GOIH ComM (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaɫdu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for Serie A club Juventus and captains the Portugal national team. Often considered the best player in the world and widely regarded as one of the greatest players of all time, Ronaldo has won five Ballon d'Or awards and four European Golden Shoes, both of which are records for a European player. He has won 31 major trophies in his career, including seven league titles, five UEFA Champions Leagues, one UEFA European Championship, and one UEFA Nations League title. Ronaldo holds the records for the most goals (134) and assists (42) in the history of the UEFA Champions League. He is one of the few recorded players to have made over 1,000 professional career appearances and has scored a record 770 senior career goals for club and country. He is also the second male to score 100 international goals and the first European one to achieve the feat.

Who were the best pre-WW2 footballers in the world?
But there was life before these players. But we rarely hear about footballing life before WW2, giving the impression it all begins in the late 1940's. So I ask, who were considered the greatest pre-WW2 players in the world?
Comment: Considered by *whom*? As currently worded, I think this question is too open to opinion-based answers, such as that of jashinjashua.
Comment: This is probably highly subjective, since the sport wasn't as popular at this time. I know a few but I'm not sure they were actually *the* best or just really good.
Comment: @dly I am looking through the 1930, 1934 and 1938 world cup all stars team. I think i've pinpointed the 1920's and 1930's two superstars. At least on paper anyway. But I wont say who I have in mind just in case someone else thinks they know who was considered the best at the time.
Answer: A few names I can think of are:

José Andrade

José Leandro Andrade (22 November 1901 – 5 October 1957) was an
Uruguayan footballer who played at wing-half. He was nicknamed 'The
Black Marvel' (maravilla negra). During his prime he was regarded as
one of the finest footballers in the world, contributing to the
Uruguay national football team's domination of international football
during the 1920s, winning two consecutive Olympic Gold Medals and then
the first FIFA World Cup.

Giuseppe Meazza

Throughout his career, he played mainly for Internazionale in the
1930s, scoring 242 goals in 365 games for the club, and winning three
Serie A titles, as well as the Coppa Italia; he later also played for
local rivals Milan, as well as Turin rivals Juventus, in addition to
his spells with Varese and Atalanta. At international level, he led
Italy to win two consecutive World Cups: in 1934 on home soil, and in
1938 as captain; he was named to the All-star Team and won the Golden
Ball Award at the 1934 World Cup, as the tournament's best player.
Along with Giovanni Ferrari and Eraldo Monzeglio, he is one of only
three Italian players to have won two World Cups.

Heinrich Stuhlfauth

He actually invented modern goalkeeping 100 years ago.

From 1916 to 1933 he played in 606 games for 1. FC Nürnberg, then a
dominating team in German football, winning five national
championships (1920, 1921, 1924, 1925, 1927). Between 1918 and 1922
Nuremberg did not lose in 104 association games, with a goal
difference of 480:47.
He also gained 21 international caps, captaining the German national side in six appearances. He surpassed the record of Eugen
Kipp (19 games) for the most appearances for the national team. His
last international cap was a 0–2 loss against Italy in Frankfurt in
1930.
Stuhlfauth was considered one of the best goalkeepers of his time, along with legendary Spanish keeper Ricardo Zamora. He was known
for being one of the first "playing" goalkeepers, actively
participating in the game. In games he always wore a grey sweater and
a flat cap.

Dixie Dean

William Ralph "Dixie" Dean (22 January 1907 – 1 March 1980) was an
English footballer who played as a centre forward. He is widely
regarded as one of the greatest players of his generation and was
inducted into the English Football Hall of Fame in 2002.
Born in Birkenhead, he began his career at his hometown club Tranmere
Rovers before moving on to Everton, the club he had supported as a
child. He was particularly known for scoring goals with his head. Dean
played the majority of his career at Everton before injuries caught up
with him and he moved on to new challenges at Notts County. He is best
known for his exploits during the 1927–28 season, which saw him score
a record 60 league goals. He also scored 18 goals in 16 appearances
for England.


SQL Server 2014 packages from SSDT 2015

Question: Hello I created a package in SSDT 2015 and I am trying to run it on SQL Sever 2014.
I tried "save a copy of .." and got it saved on the SQL server.  When I create a Job and try to execute the package I get an error:

Could not load package "\pl_dump" because of error 0x80131430.

I have been trying to get this working for days and see so many different tutorials and different software to download with no success.  Does anyone know how to deploy and run a package from SSDT 2015 to SQL server 2014?
Comment: Last time I checked, we could run earlier version packages into newer versions, but not vice versa. That means, reverse compatibility is not supported.
Comment: I found that I can downgrade the package to 2014 in the project properties!
Comment: @MrDellimore i downvoted your question because you reposted the correct answer instead of accepting it.
Comment: I didn't see the answer until later.  I appreciate the resource though.  Sorry I am new to stack overflow and not sure the proper etiquette in commendation.
Answer: when creating package using visual studio 2015 you have to select that this package is targeted to SQL Server 2014.
Go To the integration services project properties -> Configuration properties -> Set TargetServerVersion to SQL Server 2014

Side Note: SSDT 2013 is the related version for developing SQL SERVER 2014 packages, but SSDT 2015 supports backward compatibility
Comment: I couldn't find your setting in my VS 2010(SSIS 2012).
Comment: @PrabhatG BACKWARD COMPATIBILITY STARTS WITH VS 2015
Comment: A user is allowed to accept any answer they choose, even if it's one they post themselves. The problem here was they didn't give proper credit to you (@Hadi) for the suggestion to downgrade. I've corrected that by editing their answer to what it should have looked like to begin with. It doesn't look to me like an attempt to plagiarize. I interpret "I found that I can" as a sideways reference to your answer, evidence more of poor English skills than an attempt to steal credit. Also, I'm not deleting their answer by mod fiat; it can stand on its own merits now and be voted on by the community.
Answer: As Hadi suggested, I downgraded the package to SQL Server 2014 in the project properties.
I then saved the package on the file system and set the folder security to "everyone" on the server after getting permission issues.  I also made sure to set the security of the package and project to encrypt sensitive data with a password.

SQL Server 2014 packages from SSDT 2015


$p$-value when standard deviation is zero

Question: What test can be used to indicate a $p$-value when both sets of data in a comparison have standard deviation of 0? For example, Set 1 has values of 1, 1, 1 and Set 2 has values of 5, 5, 5.
Or is it OK to just say that since the standard deviation are 0 for each set and no numbers are the same in each set, that the $p$-value is <0.05?
Comment: What kind of distribution/experiment does your data come from? Sometimes the mean and deviation are related, e.g. Poisson distribution.
Answer:
I think it may make sense to conduct a statistical test on this kind of data, but you haven't given much context to know what could be done.
You definitely cannot just conclude that $p < 0.05$ just because there is no variance in the samples.  One problem is that to reach a p-value, you need to define a null hypothesis.  It's not clear from your question that you've defined a null hypothesis. (What kind of equivalence would be looking for?  Means, medians, stochastic equality?) A second problem is that you still need to take the sample size into account.  Imagine the edge case where you have one observation for each sample.  Can you jump to $p < 0.05$ in this case?
One case you might get data like in your example would be if there are two candidates for a job, say, and you have three independent ratings for each, on a discrete 1 to 5 scale, like a Likert scale.  In this case, we can treat the responses as ordered categories and conduct a Cochran-Armitage test. The following does this in R, using functions from a couple of different packages.

Another option may be certain permutation tests.
<code>if(!require(coin)){install.packages("coin")}
if(!require(multiCA)){install.packages("multiCA")}

Input =(
"Rating      1 2 3 4 5
Set
Set1         3 0 0 0 0
Set2         0 0 0 0 3
")

Table = as.table(read.ftable(textConnection(Input)))

library(coin)

chisq_test(Table,
           scores = list("Rating" = c(-2, -1, 0, 1, 2)))

   ### Asymptotic Linear-by-Linear Association Test
   ###
   ### data:  Rating (ordered) by Set (Set1, Set2)
   ### Z = -2.4495, p-value = 0.01431
   ### alternative hypothesis: two.sided

library(multiCA)

multiCA.test(Table)

   ### Multinomial Cochran-Armitage trend test
   ###
   ### data:  Table
   ### W = 6, df.Set = 1, p-value = 0.01431
   ### alternative hypothesis: true slope for outcomes 1:nrow(x) is not equal to 0
</code>
Comment: or more easily a two-sample Wilcoxon/Mann-Whitney test: `wilcox.test(x=c(1,1,1),y=c(5,5,5))`
Comment: Yes, and another point to make is that the *p* value will change depending on the test selected.  For example, with Cochran-Armitage I got a *p* value of 0.014, with Mann-Whitney 0.047, with Mood's median test 0.10, and attempting to use a t-test or ordinal regression failed.  And of course the interpretation of the results each of these tests varies.
Answer: The short answer is that you cannot do a statistical test on this type of data. The reason is because there is no way to measure chance variation.
I don't remember where I heard this analogy, but this may be a case where you need to ask yourself if a statistical inference is necessary. The analogy is ¿What is the $P$-value to assess that chickens have fewer legs than cows? Of course, barring any anomalies, your data sets will be {2,2,2,...,2} and {4,4,4,...4} (not even sure a sample size for either needs to be provided).
Hope this helps.
Comment: (1) Tests are possible even without ways to "measure chance variation." (2) *Of course* one can test such data: it comes down to what distributional assumptions will be made.  Even with no assumptions at all it's possible to construct reasonably powerful tests (such as permutation tests).
Comment: Please apply this to the chicken/cow example. ¿How does one meaningful interpret a permutation of the data?
Comment: @GreggH Not the greatest assumption given what we know about legs, but you could say that from a naive approach, legs are discrete countable and so given no other a priori information we could assume counts of legs are Poisson distributed. Based on just that assumption, you would conclude that you need to observe some number of chicken and cow legs to reject a null hypothesis that leg numbers are drawn from a Poisson distribution of equal mean for chickens and cows. You'd also likely conclude that the Poisson distribution was a poor choice, but it would have been a more conservative one.
Comment: I think I may be able to articulate my reservations slightly better. I am unconvinced of @whuber's first assertion.  Even in part two, with the suggestion of use of permutations, there is an introduction of what might be expected by chance. (And my first follow-up comment was about context, but I'm not sure that is relevant.) If there is no assessment of what happens by chance, ¿what exactly is the foundation of statistical inference (parametric or not)?
Comment: See https://stats.stackexchange.com/a/1836/919 for #1.  For #2, chance typically enters explicitly through random sampling or as a modeling assumption.  By rejecting the possibility of all statistical testing you are effectively asserting that these data could not have arisen in such ways, but that conclusion is not generally true.


como saber se console.log no JS tá retonando um dado sensível, ou é um console.log desnecessário?

Question: Boa tarde a todos.
Sou totalmente iniciante em programação, e estou com atividade para realizar que devo conferir os arquivos do JS, e verificar se tem console.log, e caso tenha, devo verificar se é para um dado "sensível", ou se é desnecessário ter.
Devo checar todos os arquivos com essas duas situações, e pontuá-los para meu mentor.
Meu problema é que, não sei identificar quando se trata de dado sensível ou desnecessário.
Alguém pode me ajudar a tentar entender?
Obrigada.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Considerando que a aplicação está finalizada e/ou "em produção", teoricamente não deve haver nada sendo logado no console. Então você pode considerar que todos os console.log são desnecessários. Se são dados sensíveis, depende do que for considerado sensível por vocês... E se tiver dado sensível sendo exposto por console.log, o buraco é mais embaixo – dados sensíveis não deveriam estar presentes em nenhum lugar do javascript, ou estarão necessariamente expostos. Isso inclui o código-fonte e a memória (por exemplo, um dado sensível recebido de um servidor e armazenado em variável js).
Answer: Ola. Eu entendo que sua preocupação por seguranca é bem valida e legitma.
Conceitualmente, o console. log é uma função que imprime um texto no console (no caso do JavaScript será possível visualizar através da ferramenta do desenvolvedor). Você utilizará esta função para te auxiliar no desenvolvimento, exibindo valores de variáveis em determinado ponto do código por exemplo (em tempo de execução).
Na pratica, o console é utilizado como uma especie de debug da aplicacao para validar se chegou aonde queria por exemplo.
Assim que eu termino o que tenho que fazer, eu costumo tirar todos os consoles da tela.
Comment: O console.log é tipo um "system.debug"?
Comment: Ele não chega exatamente ser um system.debug, mas ajuda muito na orientação se o sistema está comportando na forma que espera, entrando no bloco que vc quer, com o valor que vc quer.


Como declarar uma chave de Array MultiDimensional - Javascript

Question: Ola,
Gostaria de saber como eu faço para concatenar duas chaves de um array, a ideia seria mais ou menos assim:
dados['azul'][i] = id;

Em que o Array dados possui a chave que é uma cor pré definida e a sua segunda chave é um i incrementado com o valor de ID e tudo isso dentro de um for...
Cade vez que ele entrar no laço ele irá fazer um case para adicionar o valor do ID do elemento dentro da chave correta.
Caso seja da cor esperada, azul por exemplo, ele irá adicionar um novo valor ao array, no entanto serão adicionados vários outros valores, conforme o laço for executado.
O resultado seria algo assim:
dados[azul]{
  [2] = valordeID;
  [1] = valordeID;
}
dados[preto]{
  [2] = valordeID;
  [1] = valordeID;
}

E assim sucessivamente, alguma sugestão?
Comment: Possível duplicata de [array multidimensional javascript](https://pt.stackoverflow.com/questions/140466/array-multidimensional-javascript)
Comment: A marcada como duplicata não resolveu?
Answer: Se o que você quer é um Objeto que guarde um Valor e tenha uma Chave, acredito que você possa usar um Map .

var myMap = new Map();
myMap.set('azul', seuArray);

Comment: Na realidade eu acho que isso não funcionaria, pois a ideia é que sejam acrescentados vários valores a uma cor e não um array pronto.


How to create a permission with logic

Question: I need to create a permission to allow users to see the content overview page (/admin/content) only during business hours (9 AM to 5 PM).
Drupal core comes with the "Access the Content overview page" permission; but I need "Access the Content overview page during work hours".
I know how to create a permission and how to test that the user has the permission. What I don't understand is how to assign some logic to a permission itself (for example, within business hours).
I can do this in mymodule.permissions.yml.
access content overview within business hours:
  title: 'Access the Content overview page within business hours'
  restrict access: TRUE

I can check the user has the permission with \Drupal::currentUser()->hasPermission('access content overview within business hours').
How can I make the permission return TRUE only during business hours?
How can I check the permission only when the users visits the content overview page?
I can foresee multiple use cases for needing some logic implementation within the permission itself, for example when allowing/restricting access to certain pages depending on whether the environment is development or production, or allowing/restricting access depending on the value of some fields.
- EDIT -
As suggested in the comments, I've started by creating the following three files on my module; but it doesn't work. The CustomAccessChecks::access never gets called.
File: custom_access.services.yml
services:
  custom_access.route_subscriber:
    class: Drupal\custom_access\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  custom_access.access_checker:
    class: Drupal\custom_access\Access\CustomAccessChecks
    tags:
      - { name: access_check }

File: src/Access/CustomAccessChecks.php
<?php

namespace Drupal\custom_access\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

File: AdminRouteSubscriber.php
<?php

namespace Drupal\custom_access\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', '\Drupal\custom_access\Access\CustomAccessChecks::access');
    }
  }
}

As expected, visiting '/admin/content' as the main administrator $account->id() === 1 works, but when visiting as another authenticated user, I still can access the page.
What I'm missing?
Comment: I believe the most voted answer in this question https://drupal.stackexchange.com/questions/204582/alter-the-access-of-menu-link-before-rendering outlines what you need to do.
Comment: That's probably a good solution.
Comment: @GiorgosK and Kevin Thank you so much for the suggestion. I've updated my question above to include some code that I've added to my "custom_access" module. This code is mostly copied from the other answer as a prof of concept. Still not including the logic for the time of the day, though.
Answer: When the access to a route doesn't depend uniquely on a single permission, you need to implement what Access checking on routes describes.

Implement a service tagged access_check
Associate it with the route

Since you are altering the route defined from another module, you need to also follow Altering existing routes and adding new routes based on dynamic ones.
example.services.yml
services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

  example.access_checker:
    class: Drupal\example\Access\CustomAccessCheck
    tags:
      - { name: access_check }

RouteSubscriber.php
namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', 'example.access_checker::access');
    }
  }

CustomAccessCheck.php
namespace Drupal\example\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;

/**
 * Checks access for displaying configuration translation page.
 */
class CustomAccessCheck implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return ($account->hasPermission('access content overview within business hours') && $this->checkTimeAccess()) ? AccessResult::allowed() : AccessResult::forbidden();
  }

}

The checkTimeAccess() method I didn't write should check if the user is trying to access the route during the business hours.
I cannot tell what happens with a route using the _permission requirement when it is altered to use also the _custom_access requirement. I didn't find the Drupal core code handling the access to a route, so I cannot say which requirement is used first.
I didn't also find a way to remove requirements from a route when altering it.
Comment: Thank you for your help. I tried your code but it didn't work.
Comment: Using kint($route) I can see that there is a requirement `'_permission' => string(27) "access administration pages"`. It may be possible that Drupal is going with that requirement, which comes first. It is interesting that on D8 this particular route is overriden by a views, and I can see in the views administration that the path that is set is "/admin/content/node", however; this page really uses "/admin/content". I wonder whether this doesn't work because the views, or because of the requirement.
Comment: /admin/content/node is the default tab shown on /admin/content; it's not /admin/content/node that overrides /admin/content. As far as I recall, the permission to see /admin/content/node is inherited from /admin/content, so a user who doesn't have the permission to visit /admin/content cannot visit /admin/content/node either.

How to create a permission with logic


Accessing temperature data on ESXi5.1?

Question: For ESXi5.1 (VMWare vSphere) images, I can see temperature data on the vSphere user interface (under Monitor / Hardware Status). I tried scouring the available snmp data using snmpwalk, but can't find the data anywhere in there.
Maybe I'm missing something. Does anybody know the right MIB for temperature data?
Otherwise, how can that data be accessed?
By the way, this is a machine installed from an image provided by HP.
EDIT:
The hardware is ProLiant DL360 G7.
I don't wish to monitor the server, but rather to plot the available temperature meters.
Comment: Please provide your HP server model number and generation.
Answer: Why do you want to specifically monitor the temperature data of the server?
Are you feeding it to a monitoring solution or NMS like OpenNMS, Zabbix, etc.? Or are you just concerned about the thermal health of the server?
The model of server matters a little, because different ProLiant systems have different temperature thresholds and thermal profiles. Please let us know what you're using.
Generically, the common approach to this is to set the proper alarm actions for your server's health in your vCenter. This assumes you're using vCenter to manage the system. If so, set your SNMP monitoring system to receive traps for "Host hardware temperature status" events, that's a good way to monitor the system. In fact, by default, vCenter sends traps on these events.

While I can see individual temperatures for the 27 sensors on my ProLiant DL360 G7, I don't actually care if it's the 3rd memory module that's overtemp or the drive backplane. I care whether the host thinks it's healthy overall or not...

Now, if I'm off-base here, and you don't have vCenter are are trying to monitor a single server, use either this guide or this guide to establish an SNMP configuration on your ESXi server.
You may also be able to pull the relevant information from your ILO's web interface, via SNMP passthrough or even SSH. Some of that is covered in: automatic get server temperature via HP iLO
Comment: fantastic answer, I'm going to use the iLO directly.

Accessing temperature data on ESXi5.1?


Returning variable in def paragraph

Question: Why didn't python return the variable in def paragraph? It worked if not in def paragraph.
Here is my code:
def find_message(text):
    t=''.join([c for c in text if c.isupper()])
    return t

find_message("How are you? Eh, ok. Low or Lower? Ohhh.")

It didn't return anything, but if run the same thing without using def it worked well:
s = 'How are you? Eh, ok. Low or Lower? Ohhh.'
t=''.join([c for c in s if c.isupper()])
print t

Please help, thanks!
Comment: It is returning, you just do nothing with the returned value!
Answer: I know this sounds dumb but perhaps this will work?
def find_message(text):
   t=''.join([c for c in text if c.isupper()])
   return t

# IMPORTANT! Print returned message
print find_message("How are you? Eh, ok. Low or Lower? Ohhh.")

Comment: I think this is right, assuming you're running the above code as a script rather than interactively.

Returning variable in def paragraph


Zeros of zeta function

Question: I am a beginner of analytic number theory. In studying about zero of zeta function, i faced a Question.
Is there any zero $s=\sigma +t i$ of Riemann zeta function such that $\sigma> 1$ ??There is no answer, of course.
I want to know its proof as simple as possible
Comment: That is pretty clear from the integral representation of the $\zeta$ function, or just from Euler's product $$\zeta(s)=\prod_{p\in\mathcal{P}}\left(1-\frac{1}{p^s}\right)^{-1}$$
Comment: Possible duplicate of [The Riemann zeta function $\zeta(s)$ has no zeros for $\Re(s)>1$](http://math.stackexchange.com/questions/1097963/the-riemann-zeta-function-zetas-has-no-zeros-for-res1)
Comment: @DietrichBurde It seems like that question specifically ask for a proof using the Euler product.
Answer: By Hurwitz's theorem, if $U \subseteq \Bbb{C}$ is a connected open set and $(f_n)$ is a sequence of analytic functions on $U$ which do not attain the value zero on $U$ and converge to an analytic function $f$ uniformly on compact subsets of $U$, then $f$ is either identically zero or never attains the value zero on $U$. The proof is an easy application of the argument principle.
If we take $f_n(s) = \prod_{m=1}^n (1-p_m^{-s})^{-1}$ and $U =\{s \in \Bbb{C}: Re(s)>1\}$, then $(f_n)$ converges uniformly on compact subsets of $U$ to $\zeta(s)$. Since $\zeta(s)$ is not identically zero and none of the $f_n$ attain the value zero on $U$, it follows that $\zeta$ has no zeros in $U$.
It is necessary to use complex analytic techniques to prove this, I believe. Maybe you can get away with a longer argument that uses only real variable techniques somehow.
Answer: Using Dirichlet series (no complex analysis required)

Theorem. Suppose $f,g$ are arithmetic functions such that
  $$F(s)=\sum_{n=1}^\infty\frac{f(n)}{n^s}\quad\text{and}\quad G(s)=\sum_{n=1}^\infty\frac{g(n)}{n^s}$$
  converge absolutely at $s\in\mathbb C$. Let $h=f*g$ be their Dirichlet convolution. Then
  $$F(s)G(s)=\sum_{n=1}^\infty\frac{h(s)}{n^s}=: H(s)$$
  (and the latter series converges absolutely at $s$).

Proof. Given absolute convergence, we can rearrange the terms. $\square$

With $f=\bf1$ and $g=\mu$ we have $f*g=1$ for $n=1$ and $0$ otherwise.
If $\sigma>1$, both $F(s)=\zeta(s)$ and $G(s)$ converge absolutely. So
$$\zeta(s)G(s)=1.$$
In particular, it follows that $\zeta(s)\neq0$.
Comment: I think you missed something important. How do you show that $\frac{1}{\zeta(s)} = \sum_{n=1}^\infty \mu(n)n^{-s}$ converges for $Re(s) > 1$ without the Euler product ?
Comment: @PeterHumphries How do you show $|\mu(n)|\le 1$ without the Euler product ?.. (hint : by using that $1$ is completely multiplicative... which is exactly the same as the Euler product)
Comment: @PeterHumphries What I mean witth "something important" is that for any Dirichlet series $F(s) = \sum_{n=1}^\infty a_n n^{-s}$, finding a bound for the coefficients $b_n$ of $\frac{1}{F(s)} = \sum_{n=1}^\infty b_n n^{-s}$ is much harder whenever $a_n$ isn't multiplicative.
Comment: So suggesting you can avoid the Euler product here is a very bad idea.
Comment: Come on, we all agree that there's a little bit of work to be done to go from the series to the Euler product _(which may not be obvious to someone who is new to analytic nt)_, and we all agree that the Euler product is intimately related to multiplicativity. Anything else that has to be said? :)
Comment: This is the simplest proof I know. (At least, if $\zeta$ is defined as series.)
Comment: It converges absolutely for $\Re(s) > 1$ by the triangle inequality and the fact that $|\mu(n)| \leq 1$. No Euler product needed.
Comment: @user1952009 not exactly the same. The difference is one does not need  convergence theorems for infinite products to understand this approach.
Comment: Yes, multiplicativity must be used in some way, either in terms of the Euler product or in terms of that showing $f * g = 1_{n = 1}$ and $|\mu(n)| \leq 1$.
Comment: I don't think avoiding Euler products is necessarily a bad idea. Zero-free regions tend to only really be interesting for Dirichlet series arising from multiplicative functions, and this proof works in that setting. For example, if you want to prove $L(s,\pi)$ is nonvanishing in $\Re(s) > 1$, where $\pi$ is a cuspidal automorphic representation of $\mathrm{GL}_n$, then this proof works. On the other hand, the proof isn't really shorter as the multiplicative inverse of the coefficients of the Dirichlet series $L(s,\pi)$ are more complicated (yet still don't grow too fast).
Comment: @PeterHumphries Come on, you are not serious. So as formal Dirichlet series : $\prod_p (1+\sum_{k \ge 1} p^{-sk}) = \sum_{n=1}^\infty n^{-s}$ so that $\sum_{n=1}^\infty \mu(n) n^{-s} = \prod_p (1-p^{-s}) \implies  \mu(n) \in \{-1,0,1\}$ and what Barto wrote follows. That's all I said : don't think you can avoid the Euler product.
Comment: Yes, but that's as formal Dirichlet series. It takes half a page of work to rigorously show that Dirichlet series in their regions of absolute convergence are equal to their Euler product. So either way, you need to do some extra work.
Comment: @PeterHumphries Not at all !! It is obvious that $\prod_{p < N} \frac{1}{1-p^{-s}} = \sum_{n \in A_N} n^{-s}$ where $A_N$ is the set of integers having no prime divisor $\ge N$, and hence $\zeta(s) = \lim_{N \to \infty}\sum_{n \in A_N} n^{-s} = \prod_p \frac{1}{1-p^{-s}}$ for $Re(s) > 1$ where changing the order of summation is allowed

Zeros of zeta function


The directory sites/default/files does not exist

Question: I received the "The directory sites/default/files does not exist" error on a 7.43 install. In this situation, Drush is not available so I am doing a browser install.
I had this error once before in 2014 according to my notes. I don't know whether it's specific to the server I'm on or a general issue because I've done setups on other servers and don't remember seeing that particular error. In the previous situation, I noted that I changed the permissions on default to 777. I am always loathe to set much of anything to 777 so I am wondering whether it needs to be kept at 777 or is there some point after setting up the site that I can switch it to something more secure.
Comment: Have you created files folder under default during installation?
Comment: I did not create the files folder. I know that it will be needed for uploaded files, though. Setting the permissions on default to 777 allowed the Drupal install to create that folder.
Comment: tell me more  about what are you doing this,  your OS, your webserver, ....
it's completely related to permission
Comment: This question is from 2015 and the project is over, but the problem turned out to be a server set up error. The server admin was very responsive, but new to Linux servers, as all the other servers she manages are Windows servers. Their one Linux box had a ransomware infection, so they totally rebuilt it. The setup had some problems.
Answer: Your perms should (arguably) never be 777 on anything, but your exact situation will dictate that. 755 is often more appropriate for writeable folders, 644 for writeable files, but it depends on how your server is configured, and who owns the files.
You do need to create the sites/default/files folder manually, before the web-based installation can proceed, and your web server user must be able to write to that folder. You also need to create sites/default/settings.php, make it writeable, then remove those write perms once installation has completed. Drupal's status report will tell you about this if you haven't already done it.
There's not a lot more to it, just make sure the perms on all your files and folders are sensible for all the users that can interact with them. Securing file permissions and ownership has the full details, I'd recommended reading and fully understanding that page before going any further.
Comment: I wish I would have made more extensive notes last time. Do I understand you correctly that the Drupal install function that runs through the browser can work just fine with 755? The system admin told me that I would have to set some of the permissions to 777 and then switch them back. I will check out the resource.
Comment: You should never set 777 on anything. 755 should be the highest permission level you would set on a directory.


Vandermonde matrix unique solution to polynomial equation

Question:
I want to verify if I am thinking of parts b) and c) correctly.
To find its kernel, we must find the nullspace of the matrix equation
$
\begin{bmatrix}
5^5 & 5^4 & 5^3 & 5^2 & 5 & 1 \\
4^5 & 4^4 & 4^3 & 4^2 & 4 & 1 \\
3^5 & 3^4 & 3^3 & 3^2 & 3 & 1 \\
2^5 & 2^4 & 2^3 & 2^2 & 2 & 1 \\
1 & 1 & 1 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 1
\end{bmatrix}
\begin{bmatrix}
a_5 \\
a_4 \\
a_3 \\
a_2 \\
a_1 \\
a_1
\end{bmatrix}
=
\begin{bmatrix}
0 \\
0 \\
0 \\
0 \\
0 \\
0 \\
\end{bmatrix}
$
Due to the fact that this is a vandermonde matrix with distinct geometric ratios for its rows, this matrix has full rank and thus has a trivial nullspace I think?
Then, to show part c that there is a unique polynomial such that $f(j) = a_j$, can we then just say that
$
\begin{bmatrix}
5^5 & 5^4 & 5^3 & 5^2 & 5 & 1 \\
4^5 & 4^4 & 4^3 & 4^2 & 4 & 1 \\
3^5 & 3^4 & 3^3 & 3^2 & 3 & 1 \\
2^5 & 2^4 & 2^3 & 2^2 & 2 & 1 \\
1 & 1 & 1 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 1
\end{bmatrix}
\begin{bmatrix}
a_5 \\
a_4 \\
a_3 \\
a_2 \\
a_1 \\
a_1
\end{bmatrix}
=
\begin{bmatrix}
a_5 \\
a_4 \\
a_3 \\
a_2 \\
a_1 \\
a_0 \\
\end{bmatrix} $
has a unique solution due to nontrivial nullspace?
Comment: It seems that replacing "nontrivial nullspace" by "trivial nullspace" in the last line above, something you derive just before,  gives that your system has exactly one solution. This is what you are after. It is not necessary to calculate the solution explicitly by inverting the matrix.
Answer: Well, you are right saying that this is a Vandermonde matrix and hence is invertible, however, this exercise is basically how one proves this fact. You can use the formula to compute such a determinant (which does not use this exercise), but I guess this is not the spirit of the assignment.
How about saying instead that $T$ is invertible, since if $f\in V$ is such that $T(f)=0$, then $f$ has $6>5$ distinct roots, so that $f=0$.
For the rest of the exercise, your solution is fine.
Comment: Oh sure, that is certainly a way to see it, a bit overkill though! :)
Comment: Ah thank you, algebraic closed-ness of $\mathbb{C}$ is so much nicer than inverting the matrix.
Comment: In fact, it will work in any field, what I used is the fact that in a field a polynomial cannot have more roots than its degree. Why do you think algebraic closedness of $\mathbb{C}$ is relevant to the discussion?
Comment: That is true. However in this question I was referring to the fact that a degree 5 polynomial will have  exactly 5 roots over C for sure, so it will have $\leq$ 5 roots over $\mathbb{R}$


Java add objects to ArrayList of objects in a for loop

Question: What I want to do is store arrays in an ArrayList of Objects of type Array int A[][]
My class Matrices:
public class Matrices {
    private int M[][];

    public int[][] getM() {
        return M;
    }

    public void setM(int[][] M) {
        this.M = M;
    }
}

My main code where I create an ArrayList of the Matrices class, I load an array that was already loaded in int[][]A, in each iteration k I create an object m of type Matrices and save the changes in each iteration k in an ArrayList of Matrices in Matrices.add(m), later I show what I want to obtain and what the code returns.
ArrayList<Matrices> matrices=new ArrayList<>();
//Crea matriz
int[][] A=panel.CreaMatriz();
//Fin Crea matriz
//Inicio Floyd
for (int k = 0; k < nodos.size(); k++) {
    //agrega la matriz al ArrayList
    Matrices m=new Matrices();
    m.setM(A);
    matrices.add(m);//ERROR ONLY THE LAST OF ITERATION K IS SAVED
    //area.setText(panel.EscribeMatrices(matrices.get(k).getM()));
    //Fin agrega la matriz al ArrayList
    for (int i = 0; i < nodos.size(); i++) {
        for (int j = 0; j < nodos.size(); j++) {
            if (A[i][k]+A[k][j]<A[i][j]){
                A[i][j]=A[i][k]+A[k][j];
            }
        }
     }
}

I what I expect is.
 0    3    1     ∞
  ∞   0     ∞    ∞
  ∞   4    0    1
 3     ∞    ∞   0

 0    3    1     ∞
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

 0    3    1     ∞
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

 0    3    1    2
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

The code only prints 4 times the last matrix created at the end of iteration k.
 0    3    1    2
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

 0    3    1    2
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

 0    3    1    2
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

 0    3    1    2
  ∞   0     ∞    ∞
  ∞   4    0    1
 3    6    4    0

Comment: `A` is reused for each iteration, so each iteration overwrites the previous values in `A`. `setM` does not copy `A`.
Answer: Here:
int[][] A=panel.CreaMatriz();

A is a reference to an array of array (a matrix).
Every time you add it to setM() you add the same reference. So,  you might be thinking you're adding different arrays, but you're actually adding the same array and modifying the same array.
You need to create a new array each time, probably something like this:
A = new int[x][y]; // or get it from panel.CreaMatriz();
Matrices m=new Matrices();
m.setM(A);
matrices.add(m);

Note: By the way, the code convention is to name your variables and method in lowercase, so the following is preferred.
private int m[][];

....

int[][] a = panel.creaMatriz();


What is the "as syntax" pointed out by tslint?

Question: I upgraded tslint and now it complains about:
ERROR: src/Metronome/JobFetcher.ts[13, 32]: Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.

The offending code looks like:
const jobs = <JobConfig[]> <any> await rp(fetchJobsOptions);

What is the as syntax though and why should I use it?
Answer: Refactor your code like this:
const jobs = await rp(fetchJobsOptions) as JobConfig[];

As pointed out in the TypeScript Deep Dive book by Basarat Ali Syed, it says about type casting:

as foo vs. <foo>
Originally the syntax that was added was <foo>. This is demonstrated
below:
var foo: any;
var bar = <string> foo; // bar is now of type "string"

However there is an ambiguity in the language grammar when using
<foo> style assertions in JSX:
var foo = <string>bar;
</string>

Therefore it is now recommended that you just use as foo for
consistency.
Type Assertion vs. Casting
The reason why it's not called "type casting" is that casting
generally implies some sort of runtime support. However type
assertions are purely a compile time construct and a way for you to
provide hints to the compiler on how you want your code to be
analyzed.
Answer: If you want to suppress the error, you can as well go to tslint.json and include
...
"rules": {
    "no-angle-bracket-type-assertion": false,
    ...
}
...

provided you don't mind consistence as said.


Apresentar valores que constam numa tabela mas não na outra

Question: Bom dia.
Sou novo na parte de Base de dados e em SQL e estou com uma dúvida num exercício da faculdade.
O objetivo do exercício é:

Consegui fazer a parte de apresentar o número, descrição da conta, nome do fornecedor e localidade, contudo apresenta-me todos os valores e pretendo apenas aqueles em que as contas balanço não constam em nenhuma fatura porém não estou a conseguir fazer essa parte.
Junto envio código
select NúmeroConta, Descrição, Nome, Localidade
from  ContasBalanço join Fornecedores
on ContasBalanço.NúmeroConta = Fornecedores.ContaBalançoPredefinida join Facturas
on Fornecedores.IDFornecedor = Facturas.Fornecedor
where

Na minha opinião, penso que a condição que falta adicionar é no Where contudo não sei como fazer essa parte.
Junto deixo também foto das tabelas.
Contas Balanço:

Fornecedores:

Faturas:

ItensFaturas:

Agradecia imenso se alguém me conseguisse ajudar. Tal como disse sou novo nisto e estou a gostar de aprender base de dados e acho isto interessante, contudo surgiu me este pequeno problema e não sei como resolver.
Cumprimentos
Answer: Para compreender mais sobre Joins, recomendo ler este artigo ou este outro.
Basicamente, o que você precisa é de todos os dados de uma tabela(Contas Balanço) enquanto precisa apenas verificar a outra(Fatura) para selecionar os dados requisitados, nesse caso o ideal seria fazer um left join, assim o script ficaria da seguinte forma:
select NúmeroConta, Descrição, Nome, Localidade
from  ContasBalanço join Fornecedores
on ContasBalanço.NúmeroConta = Fornecedores.ContaBalançoPredefinida
left join Facturas
on Fornecedores.IDFornecedor = Facturas.Fornecedor
where
Facturas.IDFactura is null
ORDER BY ContasBalanço.NúmeroConta;

Outra solução para um problema semelhante pode ser encontrada aqui.
Comment: Já consegui resolver. Muito obrigado pela ajuda. Bastou adicionar Left join Facturas e a condição on ......... e funcionou. Muito obrigado.
Comment: Muito obrigado pela resposta
Comment: Percebi que havia um erro no meu script, então editei a resposta, caso teste e não funcione, por favor comente aqui!
Comment: O seu script funciona, e muito obrigado por me estar a ajudar. Também dei conta que faltava uma tabela na pergunta que coloquei. As contas balanço só devem ser apresentadas se não houver nenhum registo em ItensFaturas e não em Faturas. Contudo, penso que ItensFaturas está dependente de Faturas. Inicialmente pensei em utilizar o seu código mas substituir Faturas por ItensFaturas mas logo percebi que não dava pois são dependentes. Como é que poderei fazer?
Comment: Editei novamente a resposta, verifique se agora o retorno está adequado.
Answer: Vou te dar algumas dicas, primeiramente você deve organizar o seu código deixar bem estruturado de forma que você consiga ler as informações com mais facilidade:
SELECT cbal.NúmeroConta, cbal.Descrição, forn.Nome, forn.Localidade
FROM ContasBalanço cbal
  INNER JOIN facturasacturas fac
    ON fac.ContaBalançoPredefinida = cbal.NúmeroConta
  INNER JOIN Fornecedores forn
    ON forn.IDFornecedor = fac.Fornecedor
ORDER BY cbal.NúmeroConta ASC

Veja como separei as linhas, SELECT, FROM, INNER, ON, ORDER BY.
Quando uma coisa pertence a outra como o ON no INNER eu utilizo uma identação adicional.
Vamos para o seu exercício, primeiro veja todas as tabelas que se relacionam entre si e que você irá utilizar e faça os relacionamentos, INNER JOIN, LEFT JOIN, etc...
Eu não sei se está faltando alguma tabela no seu código mas não encontrei a tabela ItensFactura. Mas toda vez que você realiza o INNER JOIN você só irá trazer os dados se existirem nas duas tabelas, por isso não vejo necessidade de usar o WHERE.
No caso para utilizar o WHERE você deveria utilziar o LEFT JOIN que ele traz  todos os dados da tabela do FROM e só traz os dados da tabela do LEFT caso exista dados, senão as colunas virão em branco. Faça o teste.
No caso de se utilizar o WHERE com LEFT JOIN você deveria fazer o seguinte:
SELECT cbal.NúmeroConta, cbal.Descrição, forn.Nome, forn.Localidade
FROM ContasBalanço cbal
  LEFT JOIN facturasacturas fac
    ON fac.ContaBalançoPredefinida = cbal.NúmeroConta
  INNER JOIN Fornecedores forn
    ON forn.IDFornecedor = fac.Fornecedor
WHERE fac.IDFactura IS NOT NULL
ORDER BY cbal.NúmeroConta ASC

Note o WHERE, IS NOT NULL significa que ele não irá trazer nada que for nulo, no caso as faturas que não foram emitidas.
E por ultimo ordenei os dados com o ORDER BY ASC (Ascendente) conforme o solicitado pelo exercício. o ORDER BY DESC ordena de forma decrescente, faça o teste.
Outra dica que dou ao iniciar no SQL é entender tudo que está fazendo, entender cada comando e pensar no que irá fazer antes de fazer, assim você aprende bem rápido. Espero ter ajudado!
Comment: Muito obrigado pela resposta e pelas dicas


nginx configuration to allow allias url to access my current url

Question: Mu current Nginx configuration is working fine with this url:
https://myhostname.com
But I have created a different alias for same server, say myhostname1
Now when I try to access the url
https://myhostname1.com
it throws error

XMLHttpRequest cannot load
  https://sg-stg-bms-cdn001.eng.vmware.com//scripts/services/appStatusService.js?pingpong=2831234.
  The 'Access-Control-Allow-Origin' header has a value
  'https://myhostname.com' that is not equal to the supplied origin.
  Origin 'https://myhostname1.com' is therefore not allowed access.

Both the host myhostname and myhostname1 is pointing to same IP and DNS entry.
I tried adding this line to my nginx configuration but that seems not working
   location / {
      add_header 'Access-Control-Allow-Origin' '*';
..........

But still that doesn't seems to be working. Can anyone please help wher I am missing.
Answer: This link is probably more helpful than my summary but: either 'include (/path/to/sites-enabled)' at the end of your document and at that location have a config file detailing enabled sites, or, add blocks on a per-server basis (server{port; path; name; etc} you should already have one in the appropriate file for server{listen 80; server_name myhostname.com; index index.htm; root /path/to/root/folder}).
Answer: This message is telling you that your request violates javascript's same-origin security policy. If you're accessing the site with a browser, that message is probably coming from the browser, not from nginx. The same-origin policy in javascript security protects users from malicious websites attempting to use the browser's javascript to interact with other websites. Without this sandboxing, a malicious webpage could use the browser's javascript engine to interact with other websites -- perhaps change the user's email password, edit her facebook page, and so on.
You can selectively extend this security by adding http headers for cross-origin sharing (CORS). Nginx can do this for you. Here's how:

If your config includes this directive, add_header X-XSS-Protection "1; mode=block";, remove it (or comment out). That removes a security provision that tells browsers to disallow CORS.
Selectively extend cross-site scripting by adding CORS headers to requests. In the location block of each host, add these directives:

add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;

Using "$http_origin" limits CORS to *.yourdomain.com, but you can also use 'Access-Control-Allow-Origin' '*' always, opening CORS to all sites -- a weaker security model. Newer versions of nginx require a third argument (always in this example). You're missing that in your config.
Comment: I tried adding add_header 'Access-Control-Allow-Origin' '*' always

But it doesn't seems to be working.. not sure where I am missing
Comment: Did you do everything I listed in my answer or only that one directive? You need all of it.


Selecionar parte de uma imagem

Question: Dada a seguinte imagem:

Como posso fazer em javascript para selecionar um país e pinta-lo?
Comment: http://jqvmap.com/
Answer: "Como posso fazer em javascript para selecionar um país e pinta-lo?" (Imagens rasterizadas)
https://en.wikipedia.org/wiki/Flood_fill
https://en.wikipedia.org/wiki/Graph_traversal
https://en.wikipedia.org/wiki/Connected-component_labeling
http://www.algorytm.org/podstawy-grafiki/flood-fill/flood-fill-js.html (implementação recursiva 4 e 8 direções) (áreas < ~40000 pixeis)

'use strict';

let draw = async ( ) => {

const targetColor = 0xffffffff|0; // int32 rgba (cor branca).
let randomColor; // cor de preechimento.
const colorTolerance = 55; // 55 // 1 - 128 - 1020.
/*
let src = 'JirA9.gif'; // https://i.stack.imgur.com/JirA9.gif
*/
let src = URL.createObjectURL( new Blob( [
( await (await fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/4d/BlankMap-World.svg' )).text() )
.replace( /#000000/g, '#ffffff' )
.replace( /#ffffff/g, '#99aaff' )
.replace( /#c0c0c0/g, '#ffffff' )
], { type:'image/svg+xml' } )
);

let canvas = document.getElementById( 'Mapa' );
let W, H, ctx;

let load  = (   ) => {
W = img.naturalWidth;
H = img.naturalHeight;
canvas = Object.assign( canvas, {
style: `
transform: scale(${canvas.width / W}, ${canvas.height / H});
transform-origin: 0px 0px;
`,
width:  W,
height: H
} );
ctx = canvas.getContext( '2d' /*, { alpha: false }*/ ); // Chromium bug
ctx.fillStyle = '#99AAFF'; // '#FFFFFF';
ctx.fillRect( 0, 0, W, H );
ctx.drawImage( img, 0, 0 );
}

let img = Object.assign( new Image( ),
{ /*crossOrigin: 'anonymous',*/ src: src, /*onload: load*/ } );
img.addEventListener( 'load', load );

let rv = new Int32Array( 1000 );
crypto.getRandomValues( rv );
rv.sort();
//rv.sort((a, b) => b - a);
let it = 0;

let click = ( ev ) => {
let x = ev.offsetX * W / W|0;
let y = ev.offsetY * H / H|0;
randomColor = rv[ ++it ];
let imgData = ctx.getImageData( 0, 0, W, H );
let data = new Int32Array( imgData.data.buffer );
if( data[ ( y * W + x ) ] != targetColor ) return;
let pixToCheck = [ x, y ];
/*
while( pixToCheck[0] ){ // ===> Algoritmo I
y = pixToCheck.pop();
x = pixToCheck.pop();
data[ ( y * W + x ) ] == targetColor && ( data[ ( y * W + x ) ] = randomColor ) && pixToCheck.push(
(x), (y + 1), // N
(x), (y - 1), // S
(x + 1), (y), // E
(x - 1), (y)  // O
);
}
*/
let color, colorDiff;
while( pixToCheck.length > 0 ){ // ===> Variante A
y = pixToCheck.pop();
x = pixToCheck.pop();
color = data[ ( y * W + x ) ];
if( !( color != randomColor ) ) continue;
colorDiff = (targetColor & 255) - (color & 255) + (targetColor >>>  8 & 255) - (color >>>  8 & 255) + (targetColor >>> 16 & 255) - (color >>> 16 & 255) + (targetColor >>> 24 & 255) - (color >>> 24 & 255);
if( !( colorDiff > -colorTolerance && colorDiff < colorTolerance ) ) continue;
data[ ( y * W + x ) ] = randomColor;
pixToCheck.push(
(x + 1), (y),
(x - 1), (y),
(x), (y + 1),
(x), (y - 1)
);
}
ctx.putImageData( imgData, 0, 0 );
}

canvas.addEventListener( 'click', click );
}; draw()
<canvas title="click" id="Mapa" width="1000" height="508"></canvas>

Nota: No código acima variante A e algoritmo I podem ser usados em separado com as seguintes diferenças:

Resultado com https://i.stack.imgur.com/JirA9.gif
Imagens SVG sem elementos rasterizados:

(async () => {

let Mapa = document.querySelector( '.Mapa' );
let srcSVG = new DOMParser()
.parseFromString( await (await fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/4d/BlankMap-World.svg' )).text(), 'image/svg+xml' )
.querySelector( 'svg' );
srcSVG.style.transform = `scale(${Mapa.width.baseVal.value / srcSVG.width.baseVal.value}, ${Mapa.height.baseVal.value / srcSVG.height.baseVal.value})`;
srcSVG.style.transformOrigin = '0 0';
srcSVG.addEventListener( 'click', ( ev ) => {
if( ev.target.id != 'ocean' ) ev.target.style.fill = `rgba(
${ Math.random() * 256 & 255 }, /*R*/
    ${ Math.random() * 256 & 255 }, /*G*/
        ${ Math.random() * 256 & 255 }, /*B*/
            ${ 1.0 } /*A*/
            )`;
            }
);

Mapa.parentNode.replaceChild( srcSVG, Mapa );
})();
<svg xmlns="http://www.w3.org/2000/svg" class="Mapa" width="1000" height="508"></svg>
Answer: Imagino que a solução mais eficaz seria o uso de SVG; Sugiro que busque um mapa como esse em svg, sendo ele representado de tal forma que se assemelhe ao exemplo abaixo:
<svg id="mapa-mundi">
  <path id="brasil" d="..." />
  <path id="usa" d="..." />
</svg>

E então vc poderia manipular livremente cada país usando JQuery e colorindo cada país de maneira independente, baseado na interação do usuário...

$("#mapa-mundi > path").on("click",function() {
  $(this).toggleClass('colored');
});

Answer: Pintar exatamente a imagem eu acho que não é possível, pelo motivo de ela ser uma imagem .gif.
Há algumas outras opções, mas trabalhosas...

reproduzir cada país como uma imagem separada, sem fundo, colocando-as sobrepostas a uma imagem com o fundo azul. "Recortar" e Posicionar estas imagens será bem trabalhoso. Vc pode usar o GIMP para recortar as imagens. Para cada recorde vc deverá salvar uma nova imagem
Nomear os arquivos como -Branco. A parte importante seria o "-Branco", que deve ser exatamente igual
Criar uma cópia destas imagens coloridas. As inserindo na mesma posição da imagem em branco, com style='display:none' para escondê-la, nomeie-as como "-Pintado", o "-Pintado" deve ser exatamente igual.
Em cada uma das imagens, tanto nas brancas como nas coloridas, colocar o seguinte código:
onclick="pais = this.src.split(-); this.src=(pais[1]=="Branco"?pais[0]+"-Pintado":pais[0]+'-Branco')

Vc pode testar isso com imagens simples antes, como quadrados ou algo assim, antes de arriscar-se a ter todo o trabalho de separar as imagens
Outra opção seria vc usar uma imagem vetorial com , mas isso também te daria trabalho.
A opção do Vector maps é a mais indicada caso você não precise exatamente desta imagem

Selecionar parte de uma imagem


In what language is C# compiled

Question: Since I've been developing on c# this is a curiosity I have. Does anybody know that
Comment: C# is a language, so it is not complied, or even written(programmed). By the way, I think you ment in what language the C# compiler is written?
Comment: possible duplicate of [Was C# compiler written in C++?](http://stackoverflow.com/questions/631059/was-c-sharp-compiler-written-in-c)
Comment: The C# compiler prior to version 4 was written in C++. The next version will be written in C#. Anders Hejlsberg mentioned it at the last BUILD event I believe.
Answer: What exactly do you mean? If you mean what is the compiler written in then I am unsure but ultimately C# and any of the .NET languages compile down to an Intermediate Language (IL), which provides a common language which then runs within the Common Language Runtime (CLR) virtual machine. The combination of IL and the CLR allows .NET languages to inter-operate seamlessly.
This is then compiled to byte code for the target machine.
If you use ILDASM then you can inspect the IL code which C# etc. are compiled down into.
It is also possible to write your own IL code using the System.Reflection.Emit namespace and the ILGenerator class.  It is useful for generating runtime proxies.
Comment: Info about the compiler implementation here: http://stackoverflow.com/questions/631059/was-c-sharp-compiler-written-in-c
Comment: +1 Nice, I got my terms mixed up.
Answer: CLR - Common language Runtime. That is then JIT compiled to the local machines byte code.
See here for more information: http://en.wikipedia.org/wiki/Common_Language_Runtime
Note that you can also compile C# with Mono which is an alternative to .NET . See here: http://www.mono-project.com/Main_Page
Comment: Note you can turn javascript off, or hit escape while the page is loading to avoid the blackout.
Comment: Thanks for the tip, Dessus - this blackout has been a real nuisance today...
Comment: CIL is really the link I meant to give. Its here: http://en.wikipedia.org/wiki/Common_Intermediate_Language
Answer: I would assume that the .Net runtime and the C# compiler are written in C/C++
Comment: http://stackoverflow.com/questions/631059/was-c-sharp-compiler-written-in-c
Comment: There is a .net version (unofficial) here: http://blogs.msdn.com/b/jmstall/archive/2005/02/06/368192.aspx . I have also heard from a conference that Microsoft research were writing a version of the compiler in C#. I can't find links for that tho.

In what language is C# compiled


O que é RDD (resilient distributed dataset)?

Question: Estou estudando sobre o Spark no Python e o acrônimo RDD sempre aparece. Entretanto eu não consigo compreender o que é de fato esta nomenclatura.
Assim sendo, eu gostaria de saber o que é resilient distributed dataset (RDD) no contexto do Spark?
Answer: Resilient Distributed Datasets (RDD): abstraem um conjunto de objetos distribuídos no cluster, geralmente executados na memória principal. Estes podem estar armazenados em sistemas de arquivo tradicional, no HDFS (HadoopDistributed File System) e em alguns Banco de Dados NoSQL, como Cassandra e HBase. Ele é o objeto principal do modelo de programação do Spark, pois são nesses objetos que serão executados os processamentos dos dados.
Recomendo dar uma lida neste artigo :
https://www.devmedia.com.br/introducao-ao-apache-spark/34178
Mas resumindo isso, basicamente é um meio de vários computadores processarem o mesmo job,task.
Answer: A abstração principal que o Spark oferece é um conjunto de dados distribuído resiliente (RDD), que é uma coleção de elementos particionados nos nós do cluster que podem ser operados em paralelo.
Em spark existem funções de ação e transformação, as de transformação são lazy evaluation e sendo assim só serão executadas quando alguma ação for chamada.
Uma informação importante é que os RDDs são imutáveis.
Criando um RDD:
lst = [2, 4, 5, 6, 7]
testData = sc.parallelize(lst)

Tipo do objeto:
type(testData)
pyspark.rdd.RDD

Chamando uma ação:
testData.count()
5

Outra ação:
testData.collect()
[2, 4, 5, 6, 7]

Transformação:
# lazy evaluation
testFltr = testData.filter(lambda x: x > 3) # observe que uma nova variável vai ser criada pois é imutável.

Agora com a ação a transformação será feita:
testFltr.collect()
[4, 5, 6, 7]

Answer: Para simplicidade dataset -> conjunto de dados , distributed -> distribuído , resiliente -> capacidade de manter o funcionamento em caso de falhas ,  os dados são distribuídos para serem processados em paralelo no cluster se uma partição parar outra pode reprocessar ou seja assumir os dados da partição que deu erro e o processamento continua sem erros .


Java SE Security features to protect application data from the user

Question: I've worked through Java SE Security features.
As far as I understood the whole idea of this standard feature is to protect the user from malicious software.
For both java applications on the web, for which SecurityManager is enabled by default and security policies restrict application access to user machine with ability for the user to grant additional permissions.
And local java application, for which SecurityManager is disabled by default with ability for the user to enable it for concrete application and apply security policy to the application.
Is Java SE SecurityManager applicable to protect sensitive application data from the user?
If yes what is high level scenario for the developer to achive this?
Answer: If you're sending data to the users machine you are out of luck. There are no DRM features.
If you don't want users to access data, don't send the data to them. Keep it on your own servers and provide clients with a remote interface onto it.
Answer:
Is Java SE SecurityManager applicable to protect sensitive application data from the user?

No.  Whatever security Java provides is all for the user, not for 'protecting us/our code from the users'.
Comment: Note:  I read that to mean something it might not mean.  Please clarify whether you mean 'protect sensitive data the user provides to the app.' or 'protect (our) sensitive data from the user seeing or altering it'..


TypeError: Cannot read property 'days' of undefined in qml

Question: Below is a snippet of my code in which I get the error above.days is nested model:
ApplicationWindow {
id:appWindow
width: 1000
height: 600
visible:true
flags:Qt.FramelessWindowHint
//color: "transparent"

 property var monthName:0
 property string notesText: monthlistModel.get(monthofdayCalendar.currentIndex).days.get(newdayCalendar.currentIndex).hours.get(dayList.currentIndex).notes

   Settings {
       property alias notesText: appWindow.notesText
   }

Below is the listmodel with nested models:
                  ListModel{
                      id:monthlistModel
                      Component.onCompleted: {
                                 let months = [
                                                {
                                                        monthName: 0,
                                                        days: createDays(31)
                                                },
                                                {
                                                        monthName: 1,
                                                        days: createDays(29)
                                                },
                                                {
                                                        monthName:2,
                                                        days: createDays(31)
                                                },
                                                 {
                                                        monthName: 3,
                                                        days: createDays(30)
                                                },
                                                 {
                                                        monthName:4,
                                                        days: createDays(31)
                                                },
                                                 {
                                                        monthName: 5,
                                                        days: createDays(30)
                                                },
                                                 {
                                                        monthName: 6,
                                                        days: createDays(31)
                                                },
                                                 {
                                                        monthName: 7,
                                                        days: createDays(31)
                                                },
                                                 {
                                                        monthName:8,
                                                        days: createDays(30)
                                                },
                                                 {
                                                        monthName: 9,
                                                        days: createDays(31)
                                                },
                                                 {
                                                        monthName: 10,
                                                        days: createDays(30)
                                                },
                                                 {
                                                        monthName: 11,
                                                        days: createDays(31)
                                                }
                                    ]
                            append(months)
                    }
                     function createDays(dayCount) {
                            let days = []

                            for (let i = 0; i < dayCount+1; i++) {
                                    days.push({
                                                            day: i ,
                                                            hours: createHours()
                                                        }
                                                        )
                            }
                            return days
                    }

                    function createHours() {
                            let hours = []
                            for (let i = 0; i < 25; i++) {
                                    hours.push({
                                                            hour: i,
                                                            notes: ""
                                                        }
                                                        )
                            }
                            return hours
                    }
            }

The application code is in below link
https://gist.github.com/cgiannakidis70/a5f0f73440013424fc0dedd7e3300f75
How to solve the above error?
Thanks in advance.
Answer: This is in heavy need of some refactoring in general.
That point aside, your ListModel should contain ListElements, not javascript objects and nested arrays. Might be worth a good readthrough on the ListModel documentation. Here's a somewhat-related question to help out a little more.


Evaluate $\lim_{h\to 0}\frac 1 h\int_{-\infty}^\infty g\left(\frac x h\right)f(x)\,\mathrm dx$

Question: $g:\mathbb R\rightarrow \mathbb R$ is a continuous function such that $g(x)\geq0\, \forall x\in \mathbb R \,$ and $g(x)=0$ if $|x|\geq 1$
and $$\int_{-\infty}^\infty g(t) \,\mathbb\,dt=1$$ $f:\mathbb R\rightarrow \mathbb R$ is a continuous function. Then evaluate $$\displaystyle\lim_{h\to 0}\frac 1 h\int_{-\infty}^\infty g\left(\frac x h\right)f(x)\,\mathbb dx$$
MY TRY:By using the condition of $g$, it is clear that $$\displaystyle\int_{-1}^1 g(t) \,\mathbb\,dt=1$$But now problem is that how we implement it to solve our problem.Thank you.
Note:Ans is $f(0)$
Comment: I don't suppose $g$ is differentiable, is it? It would make life easier.
Answer: Simply substituting $u=x/h$ gives
$$ \frac{1}{h} \int_{-\infty}^{\infty} g\left(\frac{x}{h}\right)f(x)\,dx
= \int_{-\infty}^{\infty} g(u) f(hu) \,du
= \int_{-1}^{1} g(u) f(hu) \,du $$
where the latter equality follows from the definition of $g$.
Given that both $f$ and $g$ are continuous on the closed interval $[-1,1]$, they are uniformly continuous there, so we may pull the limit under the integral:
$$ \lim_{h\to 0} \frac{1}{h} \int_{-\infty}^{\infty} g\left(\frac{x}{h}\right)f(x)\,dx
= \lim_{h\to 0} \int_{-1}^{1} g(u) f(hu) \,du
=  \int_{-1}^{1} g(u) \cdot\lim_{h\to 0}f(hu) \,du$$
Finally, by continuity, $\lim_{h\to 0}f(hu) = f(0)$ and
$$ \lim_{h\to 0} \frac{1}{h} \int_{-\infty}^{\infty} g\left(\frac{x}{h}\right)f(x)\,dx
= f(0)\int_{-1}^{1}g(u) du = f(0)$$
Answer: Since $g\left(x\right)=0
 $ if $\left|x\right|\geq1
 $ we have $$I_{h}=\int_{-\infty}^{\infty}g\left(\frac{x}{h}\right)f\left(x\right)dx=\int_{-h}^{h}g\left(\frac{x}{h}\right)f\left(x\right)dx
 $$ and now using the mean value theorem for integrals we have that exists some $c_{h}\in\left[-h,h\right]
 $ such that $$I_{h}=f\left(c_{h}\right)\int_{-h}^{h}g\left(\frac{x}{h}\right)dx=hf\left(c_{h}\right)\int_{-1}^{1}g\left(u\right)du=hf\left(c_{h}\right)
 $$ hence $$\lim_{h\rightarrow0}\frac{I_{h}}{h}=\lim_{h\rightarrow0}f\left(c_{h}\right)=\color{red}{f\left(0\right)}$$ from the squeeze theorem and using the fact that $f$ is continuous.