Add new column in pandas data frame based on condition and replace Nan values from different columns

Question: I'm trying to add a new column in a data frame based on certain conditions using numpy, so the frame looks like.
import pandas as pd
import numpy as np
rawData = ({'a': [None,2,3], 'b': [5,6,8],'currency':['AUD','SA','NZD']})
df = pd.DataFrame(rawData)
print(df)

    a  b currency
0  NaN  5      AUD
1  2.0  6       SA
2  3.0  8      NZD

adding column based on condition:
mask1 = df['currency'].isin(['AUD'])
choice_mask1 = df['a']
mask2 = df['currency'].isin(['SA','NZD'])
choice_mask2= df['b']

df['c'] = np.select([mask1,mask2],[choice_mask1,choice_mask2],default = 0.00)

print(df)

  a  b currency    c
0  NaN  5      AUD  NaN
1  2.0  6       SA  6.0
2  3.0  8      NZD  8.0

So the output in C column is having NaN values, which I don't want.
So if there is NaN in column a, Newly added column needs to consider the values from column b.
I'm very new while using numpy, so please help me.
Answer: You can simplify the code
df['c'] = 0
cond = (df['currency'].isin(['AUD'])) & (df['a'].notnull())
df['c'] = np.where(cond, df['a'], df['b'])

    a   b   currency    c
0   NaN 5   AUD         5.0
1   2.0 6   SA          6.0
2   3.0 8   NZD         8.0

Edit: As @Ben.T pointed out, if you are looking at observations with different currency you need to tweak the conditions.
rawData = ({'a': [None,2,3, 5, 3], 'b': [5,6,8, 1,6],'currency':['AUD','SA','NZD', 'AUD', 'US']})
df = pd.DataFrame(rawData)

df['c'] = 0
cond1 = (df['currency'].isin(['AUD'])) & (df['a'].notnull())
cond2 = (df['currency'].isin(['SA','NZD'])) | (df['currency'].isin(['AUD'])) & (df['a'].isnull())

df.loc[cond1, 'c'] = df['a']
df.loc[cond2, 'c'] = df['b']

    a   b   currency    c
0   NaN 5   AUD         5.0
1   2.0 6   SA          6.0
2   3.0 8   NZD         8.0
3   5.0 1   AUD         5.0
4   3.0 6   US          0.0

OR using np.select
mask1 = (df['currency'].isin(['AUD'])) & (df['a'].notnull())
choice_mask1 = df['a']
mask2 = (df['currency'].isin(['SA','NZD'])) | (df['currency'].isin(['AUD'])) & (df['a'].isnull())
choice_mask2= df['b']

df['c'] = np.select([mask1,mask2],[choice_mask1,choice_mask2],default = 0.00)

Comment: @Ben.T, I agree, I just noticed that the code does not account for a different currency. Posting an edit. Thanks:)
Comment: This code is slightly different as the column `b` becomes the default value, not 0 as in the OP code. On the example data, it works as all rows meet one of the two conditions. Not sure it matters, just an observation :)
Comment: @Ben.T, the column c will take the value of column b only in case a is null. Check the code with the following df to see the output. rawData = ({'a': [None,2,3, 5], 'b': [5,6,8, 1],'currency':['AUD','SA','NZD', 'AUD']})
df = pd.DataFrame(rawData)
Comment: I agree with you that the code gives the column a in the case wanted, I was talking about if you have another currency than AUD, SA or NZD. According to the OP code, the value should be 0 while your code gives the column b. try with `rawData = ({'a': [None,2,3, 5], 'b': [5,6,8, 1],'currency':['AUD','SA','NZD', 'USD']})`. Should 0 but get 1 in column C last row. I know OP did not talk about that point, but it was to notice that the default value is not 0 anymore
Answer: one possibility is to use fillna with value from the column b when creating choice_mask1 such as
choice_mask1 = df['a'].fillna(df['b'])

and the rest is the same. Your output is then like:
     a  b currency    c
0  NaN  5      AUD  5.0
1  2.0  6       SA  6.0
2  3.0  8      NZD  8.0

Answer: it's actually pretty straightforward using combine_first:
df['c'] = df.a.combine_first(df.b)

edit: this doesn't actually answer your question, as you seem to want to mask your results, so in that event, @ben.t's answer is better.


CSS Specificity for transparent and none border

Question: I'm styling the page which has consecutive boxes with bottom border except for the last box. I applied class .box for all the boxes and added .box_last to hide the border only for the last box.

.box {
  border-bottom-style: solid;
}

.box_last {
  border-bottom-style: transparent;
}

However, I realized that the browser is still applying my .box styling. But when I changed the .box_last from transparent to none, the browser overrode the first style and the border is disappeared.
I have searched for a few CSS specificity articles but hasn't got the answer yet. Can anyone explain for me? Thanks in advances.
Comment: transparent is `color`, not `style`.
Answer: The reason border-bottom-style: transparent; is not working is because transparent is a color, not a style. This should work fine:
.box_last {
  border-bottom-color: transparent;
}

Or without an extra class:
.box:last-child {
  border-bottom-color: transparent;
}

Comment: Can you please accept my answer on the left? Thanks!


How to apply grepl for data frame

Question: I want to use grepl for multiple patterns defined as a data frame.
df_sen is presented as
sentence
"She would like to go there"
"I had it few days ago"
"We have spent few millions"

df_triggers is presented as follows:
trigger
few days
few millions

And I want to create a matrix where sentence x triggers and on the intersection to see 1 if trigger was found in a sentence and 0 if it was not.
I have tried to do it like this:
matrix <- grepl(df_triggers$trigger, df_sen$sentence)

But I see the error message that I have more than 1 pattern in grepl().
The desired output is:
                                 few days    few millions
"She would like to go there"        0              0
"I had it few days ago"             1              0
"We have spent few millions         0              1

Comment: Try an sapply loop over the patterns: `sapply(df_triggers$trigger, grepl, df_sen$sentence)`
Comment: You're welcome. Please post it as a solution
Comment: It would be better if you could post the solution as an answer below the question. Thanks!
Comment: @djhurio thank you for your comment. Posted there as well.
Comment: And the thing is that I have 2500 sentences. So I cannot implement it like `few days | few millions`
Comment: @docendodiscimus Thank you! It worked well!
Answer: sapply(df_triggers$trigger, grepl, df_sen$sentence)

from @docendodiscimus worked.

How to apply grepl for data frame


Double realloc error...?

Question: I have a function that is used to expand an array (graph) and add a new value at the end. The first request to the function goes fine, but something goes wrong when I do it a second time...
Code:
struct station *addStation(struct station *graph, struct station newStation, size_t  *stationCount){
  size_t newCount = *stationCount+1;

  graph = realloc(graph, newCount*sizeof(struct station));
  *stationCount = newCount;

  graph[*stationCount] = newStation;

  return graph;
}

and the request:
  Station *graph;
  graph = malloc(146*sizeof(Station));

  graph = loadStations(graph, &stationCount);

  Station newStation = graph[0]; // Dummyvalue

  printf("StationCount:%d\n",stationCount);

  graph = addStation(graph, newStation, &stationCount);

  printf("StationCount:%d\n",stationCount);

  graph = addStation(graph, newStation, &stationCount);

Because of the second line graph = addStation... I get some memory output error in the terminal:
StationCount:146
StationCount:147
reseplanerare: malloc.c:2369: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted (SIGABRT) (memory print created)
I do not understand why this happens...
Answer: C arrays are zero-based so graph has valid indices [0..newCount-1]
graph[*stationCount] = newStation;

is writing beyond the end of your allocated memory.  This results in undefined behaviour.  I'd guess that in your case it is corrupting a guard word used by the heap manager to detect exactly this sort of memory corruption.
You can fix this by changing the array index you write to:
graph[newCount-1] = newStation;

Double realloc error...?


Enabling VNC Server Mode on an Amazon EC2 Windows Instance

Question: I have installed RealVNC on my Amazon EC2 Windows Instance.
I want to use the free version, so I have to use the VNC Authentication option, where a password is set in the VNC config.
BUT: I can only see the VNC config for user mode. When I run VNC in User Mode on the server, I can connect to the server.
I cannot set the auth mode and auth password for the VNC Server Mode. The RealVNC docs say that there should be a systray icon for the server, and there isn't.
I assume that the issue is related to the Windows 2008 R2 security model.
How do I:
1.) Change the VNC server so that the systray icon shows?
or
2.) Change the VNC config in some other way?
Answer: I'll add some information to a VERY specific case of AWS Windows Instance and that is the GPU family.
According to AWS:

"When using Remote Desktop, GPUs that use the WDDM driver model are replaced with a non-accelerated Remote Desktop display driver. To access your GPU hardware, you must use a different remote access tool, such as VNC. You can also use one of the GPU AMIs from the AWS Marketplace because they provide remote access tools that support 3-D acceleration."

From:http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using_cluster_computing.html#install-nvidia-driver-windows
So you DO NEED VNC on your server if you want to take advantage of any 3d rendering.
Answer: Have you considered using RDP instead?  If you need to access the console you can use the /admin command line switch with mstsc which will let you see the console session in windows.
As far as RealVNC, it has been a while, but if I recall, VNC has to be installed in "service-mode" rather than user mode.  See http://www.realvnc.com/products/open/4.1/winvnc.html#ServiceMode  Basically in a nutshell it install VNC as a service that runs on the host.  That way it survives users sessions starting and stopping.
But use RDP if you can, it's built in and designed for this.
Comment: If you use an instance type which has GPU resources (e.g. g2.2xlarge), using RDP is actually not a good idea, since no graphics drivers get loaded for an RDP session. Even Amazon's documentation states you need to use something VNC for these instance types.


24 16th notes in a 4/4 measure; Tuplets?

Question:
They're not labeled tuplets, but they probably are since there cannot be 24 16th notes in a 4/4 measure. They don't appear to be a standard triplet though since it still doesn't fit (with each triplet equal to 2 16th's).
Comment: Shidouuu - please don't edit the answer into the post. I have rolled back to your previous version to take that out.
Comment: Neither a time signature nor a barline in sight - graphic snippet can be improved.
Comment: Can't really do anything about that since the last time signature change is several measures back. I've already stated it in the title
Answer: They are sextuplets - 6 semiquavers in the time of 4.  They probably thought it was obvious enough, since they are grouped clearly in 4 crochet beats.


Is it possible to compute these probabilities concerning a 6-digit password using theory of Markov chains?

Question:

Consider the situation of decoding a 6-digit password that consists of the symbols A to Z and 0 to 9, where all possible combinations are tried randomly and uniformly.

Consider the following decoding method: At first a combination is chosen randomly and uniformly. At the next trial a digit from this combination is chosen uniformly at random and its entry is substituted by a uniformly randomly chosen element from $\left\{A,...,Z,0,...,9\right\}$. This procedure is repeated until the password is found.
(a) What is the probability that the correct password will never be entered?
(b) What is the probability that eventually the same combination will be entered two consecutive times?

I think it is very difficult to compute these probabilities by pure combinatorical thoughts, isn't it? As you can see here: 6-digit password - a special decoding method
So I asked myself if it is possible and smart to see this decoding strategy as a kind of Markov chain maybe? Maybe it is easier then to solve?
This task is asked in the context of a lecture concerning Markov chains, so it is at least not devious to have this assumption.
Hope you can help me.
Comment: Um, why are you asking the same question again and again?
Comment: @HenningMakholm I asked them not again and again. First was with combinaoric, second was again with combinatoric, this was with Markov chains.
Answer: Kolmogorov's 0-1 law immediately gives (b) $1$.
(a) must be $0$ too, but the law doesn't immediately apply because a priori the probabilities are not independent.
We can instead use the law to prove that with probability $1$ we will eventually reach the correct combination in the particular way that starting with attempt number $6n$ for some $n$ we will randomly select the right digits for positions 1, 2, 3, 4, 5, 6, in that order. The probability of this happening for different $n$s is independent, so the law applies. And since there's a probability of $1$ to find the right code in a special way, the probability of finding it at all must also be $1$.
Comment: Can you explain me how I can model the decoding method as a markov chain?
Comment: @Salamo: Um .. expressing it as a Markov chain is completely straightforward. There's a state for each of the possible "current" combinations, and it can turn into a different state in $6\cdot 36$ equally probably ways (except that 6 of those actually don't change the combination and so combine into a single transition with probablity $1/36$).


Creating SearchAPI searches without using Views

Question: I am using SearchAPI on a website with 20,000 entities indexed. Searching through them with SearchAPI is pretty simple. Its fast. I want to keep it as fast as possible with very low overhead, without using Views.
I've created the appropriate code needed to create a form, blocks, and a page callback via a custom module. What I would like to do is have someone use a custom search form, hit submit, and be sent to the search results page callback.
What is the best way to store and read from form values in a page callback? Is there any way to have values persist outside of $_SESSION? Or is that the best method? If I wrote a method in my search class that inspected $_POST and did proper validation on it, would it be better to use that to keep executing a search based on that?
I already have paging methods worked out in the code, but kind of scratched my head on how to execute a form, then when using a pager, keep those values for querying the next set. I think I am close, but wanted some input if there is a way I am not seeing.
Comment: Just wondering why you are trying to write your own custom code to create a form, block, page callback etc, and not using http://drupal.org/project/search_api_page that will do all of this for you?
Comment: Because I want to search by multiple fields, not just one. It's not just a general text search, I want to have 5-9 different fields to search by. I also want control over the form, and its placement on the page, the labels, etc. I want the search in the sidebar wherever I want to display it. I don't want a search form at the top of the search page itself. Also, it isn't outputting a pager, and I want to theme the results page, the result itself, result counter, and show filters. Also, its loading entities from the database- I am using cached HTML of SearchAPI.
Answer: Realized I never added a follow up. Search API Page does not solve all the cases, and this is possible in Drupal 8 as well.
A query string was added on form submission, redirecting to my url + query string args. These prefill form values (sanitized of course) and modify the initial Search API query. Extra work was done to store some data in session, so that the query could be repeated on detail pages for sidebar results (prev/next navigation in the same result set).
Using the normal Drupal pager worked fine as well.
As part of this work, a module was born: https://www.drupal.org/project/search_api_view_modes
Here is an example of doing it in Drupal 8: https://gist.github.com/kevinquillen/cad07541347385744b161a26690ab75d
Taking this route allows you to create and provide a very tailored, controlled experience.


Contradictory results of ADF and KPSS unit root tests

Question: To check whether the data is stationary or not, I computed KPSS and ADF test and got the following results
adf.test(td,alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  td
Dickey-Fuller = -3.7212, Lag order = 3, p-value = 0.03058
alternative hypothesis: stationary

Here, the p-value is <0.05, which suggests that the data is stationary.
kpss.test(td, null="Level")
Warning message:
In kpss.test(td, null = "Level") : p-value smaller than printed p-value
KPSS Test for Level Stationarity

data:  td
KPSS Level = 1.7174, Truncation lag parameter = 1, p-value = 0.01

kpss.test(td, null="Trend")

    KPSS Test for Trend Stationarity

data:  td
KPSS Trend = 0.17075, Truncation lag parameter = 1, p-value = 0.02938

Here, the data seems to be accept level stationarity and trend stationarity as the p-values are less than 0.05. Since the results of ADF and KPSS contradict, I am confused whether the data is stationary or not. Please let me know if my understanding is wrong somewhere or if I need to perform some more test in this case.
Answer: Please have a look at my answer to the following question. What is the difference between a stationary test and a unit root test? Here is the most important part of the answer:
If you have a time series data set how it usually appears in econometric time series I propose you should apply both a Unit root test: (Augmented) Dickey Fuller or Phillips-Perron depending on the structure of the underlying data and a KPSS test.
Case 1: Unit root test: you can't reject $H_0$; KPSS test: reject $H_0$. Both imply that series has unit root.
Case 2: Unit root test: Reject $H_0$. KPSS test: don`t reject $H_0$. Both imply that series is stationary.
Case 3 If we can't reject both test: data give not enough observations.
Case 4 Reject unit root, reject stationarity: both hypothesis are component hypothesis – heteroskedasticity in series may make a big difference; if there is structural break it will affect inference.

Edit:
In case 4 a more profound approach would be to apply a variance ratio test. The variance ratio test renders you a value between 0 and 1 if the data is "between stationarity and a unit root". As the variance ratio test does not only affirm or reject a null hypothesis, but gives you a continuous value it can capture mixtures in more detail. It may also give you insight to visualise the data.
Comment: Also note that a series can be I(0) (absence of unit root) and nonstationary at the same time. That is because there are many forms of nonstationarity, and unit root is just one of them. Probably you are trying to say so in Case 4, but I am not sure.
Comment: @fredi : Interestingly the results of PP test and Acf itself contradicts. PP.test has p value less than 0.01 where ACF test has p-value 0.3
Comment: **Phillips, P. C. B.; Perron, P. (1988). "Testing for a Unit Root in Time Series Regression". Biometrika. 75 (2): 335–346. doi:10.1093/biomet/75.2.335.** report that the Phillips–Perron test performs worse in finite samples than the augmented Dickey–Fuller test. Do you have a small sample?
Comment: Related: https://ideas.repec.org/a/eee/ecolet/v61y1998i1p17-21.html
Answer: "Here, the data seems to be accept level stationarity and trend stationarity as the p-values are less than 0.05."
The H0 for KPSS is that the data is stationary. So shouldn't we reject the H0 (p-values <0.05) and infer non-stationary?
Answer: You are not comparing test statistic (ADF statistic and KPSS statistic) against the critical value and are just looking at p-value. If you check, it is still possible that they give contradictory results. But the result will be ADF says its stationary while KPSS says it is non-stationary. This means that unit root does not exist and the stationarity is trend stationarity.
Comment: I thought KPSS can handle trend stationarity. Can you elaborate a bit on this?
Answer: It would have been good to have a reproducible example to test and understand better.
That said, I'm speaking from the deepness of my ignorance as I'm learning these days, and had exactly the same problem of yours.
I ended up finding that in my time series I was having multiple rows with the same timestamp (e.g. [[2020-05-22, 20], [2020-05-21, 10], [2020-05-12, 5],[2020-05-22, 20], [2020-05-21, 10], [2020-05-12, 5]]).
This was due to the presence of another feature to make those entries necessary for other calculation.
But it turned out that having those duplicates were creating issues, which I solved by summing up the values before getting the new dataframe digested by both KPSS and ADF.
At that point, both of them revealed the non stationarity.
Perhaps the OP case is the same.
Kudos to the other answer from where I guess I learnt something too.


Exchange 2007, expired passwords and mail forwarding

Question: We have a handful of users that require a company email address and have all emails forwarded to an external address; usually they are third-party contractors and only need email.
Since these users never login to a workstation and may or may not log into OWA, their passwords will expire.
When the password expires, will the forwarding stop?
Answer: No, the forwarding will not stop. They simply would not be able to log directly into their company mailbox using Outlook/OWA. So no worries!


In Cricket T20 World Cup 2021, why are Bangladesh & SriLanka Demoted to Group A/B with Afghanistan Promoted to Group 2?

Question: In general, Bangladesh & Sri Lanka are more-or-less stable/well-known/competent teams, but it seems like they have to qualify from Group A/B to move to higher rounds. By itself, that is fine; but Afghanistan is definitely not a stable/well-known/competent team which already moved up to Group 2.
What are the decisions, events and choices which made this situation?
Answer: This is explained in the Wikipedia article for the tournament:

As of 31 December 2018, the top nine ranked ICC Full Members, alongside hosts India, qualified directly for the 2021 tournament. Of those ten teams, the top eight ranked sides qualified for the Super 12s stage of the tournament. Sri Lanka and Bangladesh did not qualify for the Super 12s, instead being placed in the group stage of the competition.

While you may claim that "Afghanistan is definitely not a stable/well-known/competent team", it is a fact that they had a higher ranking than both Sri Lanka and Bangladesh at the cut off date (31 December 2018), which would seem to me to be almost the definition of competence.  As of 6th October 2021, that is still the case, with Afghanistan ranked 8th, ahead of all of West Indies, Sri Lanka, Zimbabwe and Ireland.
Comment: I think at this point your question is moving from something which is on-topic for this site to something opinion based and therefore off-topic.
Comment: Thanks for your comments, but this is mostly a repeat of the facts on which the question is based. Yes, Bangadesh and Sri Lanka did not qualify, but why ? How did World Champions Sri Lanka go below new comers Afghanistan ? I want to know why this happened. I have attempted to answer it ....
Comment: I saw your earlier edit which was fine, but the next edit was changing my question entirely, hence I have reverted that ; I only want to know about the 3 teams mentioned, not all the 12 teams ....
Answer: It appears that a combination of many factors helped Afghanistan rise in Cricket.
Here are few factors:
(1) India helped in highlighting the team by organizing matches in India, even going to the extent of coaching and giving a temporary "home-ground" to the Afghanistan team.
[[ https://theprint.in/theprint-essential/the-rise-and-rise-of-afghan-cricket-with-a-little-help-from-india/69256/ ]]

The Indian support
India has played its part in the Afghanistan cricket story. In 2015, the BCCI offered the Shaheed Vijay Singh Pathik Sports Complex in Greater Noida as a temporary "home-ground" to the team.
Afghanistan even "hosted" a three day T20 series against Bangladesh at Dehradun.
"All teams touring India will play one cricket match against Afghanistan for which arrangements have been made," BCCI acting secretary Amitabh Choudhary had said last month.
Former players Lalchand Rajput and Manoj Prabhakar have coached the Afghanistan team, the latter as bowling coach.

(2) Pakistan has helped too.
[[ Same article ]]

In a sense, the war at home has, ironically, contributed to the rise of Afghan cricket. Forced out of homes, several of the players such as captain Asghar Stanikzai, Mohammad Nabi, and Mohammad Shahzad, honed their skills at refugees camps across the border in Peshawar, Pakistan.

(3) Same article mentions that Afghanistan beat West Indies (in World Cup 2019 qualifiers & in 2016) & Bangladesh (in 2018 T20 series)
This sets the stage to move to the Decline of Bangladesh & Sri Lanka ....
(4) Bangladesh is Depending on the Big-5 and is gradually Declining :
[[ https://www.thedailystar.net/sports/bangladesh-cricket/irreversible-decline-1607683 ]]

It seemed that these five cricketers -- three batsmen, the country's greatest all-rounder and its best seamer -- would set examples that lesser and younger cricketers could follow in order to continue a tradition of improved performances. That is no longer true.

[[ https://thefinancialexpress.com.bd/views/what-happens-to-bangladesh-cricket-after-the-big-five-1627017692 ]]

The currently 9th ranked team in ICC Ranking for ODIs, Sri Lanka sets an example of how unexpectedly a world-class team's performance can decline after the retirement of some great cricketers of the nation.
Whether Bangladesh has to go back to where they were in the early 2000s or not after the retirement of the 'big five' depends on the future prospects and how they are utilised.

(5) Sri Lanka is gradually Declining over the Political Interference & the Infighting between Players & Management & the Financial crisis.
[[ https://www.tbsnews.net/sports/inevitable-fall-sri-lankan-cricket-what-actually-happened-252751 ]]

Political interference has been pretty acute cricket in Sri Lanka for quite some time now. And it is ruining their game
....
The most anyone has heard about Sri Lankan cricket in the last few days is probably about the dispute between the players and the board on players' huge pay cut and the unrest that followed. Well, they have also lost the ODI series to Bangladesh, for the first time in their history. ....  And they are currently at the bottom of the ODI Super League and at risk of not qualifying directly for the upcoming 2023 cricket world cup.
....
Just to remind, Sri Lanka won the CWC in 1996 and played in two consecutive finals in 2007 and 2011. They were the champions of the T20 WC in 2014. But all those feel like distant memories now.
....
Financial crisis definitely played a big part in the fall.

(6) Sri Lanka is gradually Declining over Retirement Of Key Players.
[[ https://www.probatsman.com/three-reasons-behind-the-decline-of-sri-lankan-cricket ]]

With such a great composition already serving the country, the inclusion of any youngster looked very hard at that time. This is where Sri Lanka did not plan much for a future and relied heavily upon the existing players who were match-winners for them and that is what cost them.

This covers why Afghanistan has moved Up while Bangladesh & Sri Lanka have moved Down ....


Confused (disoriented?) by questions about orientation

Question: I believe I have a reasonable basic understanding of orientation. Yet, i'm finding myself utterly confused when facing a specific question. Here are several examples:

Exhibit an ordered basis of positive orientation for $S^2$ (as a boundary of $B^3$) at an arbitrary point point $p=(a,b,c)$.
Let $f: S^2 \to (-1,1)$, be gicen by $f:(x,y,z) \mapsto z$. Exhibit an ordered basis of positive orientation for a typical point
  on $f^{-1}(t)$.
Show that the boundary orientation of $S^k = \partial B^{k+1}$ is the same as its preimage orientation given by:

$$g:\mathbb{R}^{k+1} \to \mathbb{R}, g(x)= |x|^2$$

(The questions are taken from the book "differential topology" by Guillemin and Pollack).
My issues:

I don't quite understand how an answer is supposed to look like. Couldn't i just say $\{v_p,w_p\}$ is a basis for $T_p S^2$ so (if $n_p$ is the outward pointing normal) according to whether $sign(n_p,v_p,w_p)$ is positive or negative i can switch $v_p$ and $w_p$ and obtain a positive orientation?
Same problem with (1). Only now there's another issue. I'm not sure what's the correct formal way of computing an orientation of a preimage like $f^{-1}(t)$. Would it be right to look at $(T_p f o \pi_p)^{-1}(1)$ where $\pi_p: T_p S^2 \to T_p (f^{-1}(t))$ is the projection?
Same as (2), plus some general unfocused non-specific confusion.

I must say that I didn't have any problems with the chapter itself, everything was done in a coordinate-free way that didn't raise these problems.
Thanks for the help.
EDIT: In the book an orinetation is defined as a continuous choice of equivalence class on the tangent space at each point where the relation is:
$$v \sim w \iff Av=w \text{ for some $A$ with } |A| > 0$$
I do feel comfortable with the definition of an atlas with positive determinant transition functions as well.
Answer: To get you started, here are some hints for question 1.
Start with you are given: a point $p \in S^1$ with coordinates $p = (a,b,c)$.
Now, it is fine to use the symbols $v_p,w_p$ as names representing positively oriented basis vectors for the tangent space of $S^2$ at the point $p$. But don't fool yourself: writing down names for those vectors is not the same as giving formulas for them. Your formulas should be functions of the coordinates $a,b,c$ of the point $p$. In other words, your answer should have the format

$v_p = \langle f(a,b,c), g(a,b,c), h(a,b,c) \rangle$
$w_p = \langle k(a,b,c), l(a,b,c), m(a,b,c) \rangle$

where $f(a,b,c)$ is some completely explicit formula, as are $g$, $h$, $k$, $l$, and $m$.
The key geometric fact you need about $S^2$ is that the normal vector of $S^2$ at the point $p=(a,b,c)$ is precisely $\langle a,b,c\rangle$. Then you also need that the tangent space at $p$ is precisely the orthogonal subspace of the normal vector.
So then, you just need to do some linear algebra to find formulas for the functions $f,g,h,k,l,m$ so that the matrix
$$\begin{pmatrix} a & b & c \\ f(a,b,c) & g(a,b,c) & h(a,b,c) \\ k(a,b,c) & l(a,b,c) & m(a,b,c) \end{pmatrix}
$$
has positive determinant, and so that its second and third rows are orthogonal to its first row. The key words here are "Gram-Schmidt orthogonlization".
Comment: Thanks, things do make a bit more sense now.


Find discontinuities in an array of date in php

Question: I have a sorted array of dates that looks like so :
$dates = Array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');

In this array we have two times (sometimes more, but it's normal in my script) the date Oct 1st but it's missing the 4th.
How can I detect that there is a discontinuity between the first value of the array, and the last value of the array (again, my array is sorted by ascending dates) ?
Comment: Have you tried anything yet? Also: do you know up front what the interval will be? By that I mean: in this case, the interval should be 1 day, is this always the case? Where are you getting these dates from, perhaps you can ensure you only get valid data, instead of having to check in your PHP code
Comment: Data come from a user text input. I get the array of dates using `preg_match_all()` on the user input. But I wanted to make sure the user or my regular expression did not miss any date as the input should not be discontinued. Cheers.
Comment: In that case, wouldn't it be easier to have the user put in 1 date, then select how many subsequent dates he wants to put in? then you could do `$start = new DateTime($userInputDate);` and then loop `while($inputSubsequentDays--) {`, creating a new date on each iteration, adding it onto an array
Answer: $dates = array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');
$continued = true;
foreach ($dates as $key => $date) {
    if (!empty($dates[$key+1])) {
        $cDate = new DateTime($date);
        $next  = new DateTime($dates[$key+1]);
        $interval = $next->diff($cDate);
        if ($interval->d > 1) {
           $continued = false;
        }
    }
}

$continued = false then discontinuity present.
Answer: It's probably worth looking into the DateTime class, and its goodies. In particular DateTime::diff, which returns a DateInterval instance. This enables you to safely subtract 2 dates, and determine what the time difference between those dates actually is. cf the manual.
In short, I've put together a little function that can be used to determine oddities in an array of date strings:
$dates = array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');
$obj = array();
foreach ($dates as $date)
{//create an array of DateTime instances from the $dates values
  $obj[] = new DateTime($date);
}
/**
 * @param array $dates (an array of DateTime instances)
 * @param string $intervalProperty = 'd' (valid valus are y, m, d, h, i, s)
 * @param int $interval = null (the value $intervalProperty should have)
 * @return array of null|DateInterval
 */
function getOddDiffs(array $dates, $intervalProperty = 'd', $interval = null)
{
    $diffs = array();
    for($i=0, $j=count($dates)-1;$i<$j;++$i)
    {//iterate $dates
        $diff = $dates[$i]->diff($dates[$i+1]);//compute diff
        if ($interval === null && $diff->{$intervalProperty})
            $interval = $diff->{$intervalProperty};//set $interval if needed/possible
        if ($diff->{$intervalProperty} !== $interval)
        {//if interval value !== $interval (type+value check required in case $interval is null)
            $diffs[] = $diff;//return the diff
        }
        else
        {
            $diffs[] = null;//null means ok
        }
    }
    return $diffs;//return results
}

If you want to see it in action:
Demo here
Comment: Thank you for your time and answer. I chose the one from @sgt as it is in my opinion simpler and does just what I needed, even though your solution is probably more complete and versatile.
Comment: @Fredovsky: You're welcome. However: thank-you comments are discouraged on stackoverflow. You are requested _not_ to post them, but instead vote for the answers that helped. You can only accept 1 answer, but you can vote for as many as you want (PS: [this is where the thank-you comments being discouraged is explained](http://stackoverflow.com/help/someone-answers))
Answer: function hasDiscontinuities($dates)
{
    // remove duplicates
    $dates = array_unique($dates);

    // get the last day
    $parts = explode('-', end($dates));
    $lastDay = (int) $parts[2];

    // if the amount of dates is smaller than the last day, there must be discontinuities
    if (count($dates) < $lastDay) {
        return true;
    }

    return false;
}

Edit regarding Elias Van Ootegem's comment, duplicates now are threated as discontinuities:
function hasDiscontinuities($dates)
{
    // duplicates count as discontinuities
    if ($dates != array_unique($dates)) {
        return true;
    }

    // get the last day
    $parts = explode('-', end($dates));
    $lastDay = (int) $parts[2];

    // if the amount of dates is smaller than the last day, there must be discontinuities
    if (count($dates) < $lastDay) {
        return true;
    }

    return false;
}

Second edit because of the added details in the comments:
function hasDiscontinuities($dates)
{
    // duplicates count as discontinuities
    if ($dates != array_unique($dates)) {
        return true;
    }

    $firstDate = new DateTime($dates[0]);
    $lastDate = new DateTime(end($dates));

    // if the difference in days is not the same as the amount of elements in the array, there are discontinuities
    if (count($dates) != $lastDate->diff($firstDate)->days + 1) {
        return true;
    }

    return false;
}

Comment: The duplicates should be treated as discontinuities, too IMO. Just make sure that the return value allows the caller to determine if any found mismatch was an interval of 0, and let them handle it
Comment: Thanks, but not sure this would work with an array covering several months (eg. ending the 2nd of November in this example) or not starting on the 1st of the month. (Sorry these details were not in the description).
Comment: @Fredovsky: Which is no problem for my suggested solution, that's why I suggested to use `DateTime` from the start. It can handle any valid date string.


Tied flat to natural?

Question: I'm a beginner piano player and came across the following notation in a booklet:

in a beginner's arrangement for Fauré's "Sicilienne". My question is regarding the bow on the bottom staff.
I'm pretty sure that that is not a slur but is intended to be a tie. This is because the bottom staff is noted with "sempre legato" at the beginning of the piece and there are no other slurs in the whole bottom staff apart from three examples of the above. My assumption is that this is an editorial mistake, and either the flat or the natural should not be there, or be in parenthesis as an alternative.
It is worth the note that the piece is in G Minor, thus the E's would be flat by default.
Is my assumption correct that this is a mistake in the sheet music and this is a tie over E♭ on the bottom staff?
Answer: It's a slur, not an error in your score.
Here is the measure you're asking about, in the original score (IMSLP, Hamelle edition, PDF page 5, first measure):

What your edition has done is rearrange the chords so that the Eb from the first chord in the right hand gets moved to your left hand.
Comment: @D.Kovács Yes, my take on it is the same as yours: reinforcement of the legato.
Comment: Thank you for the elaborate answer! Next time I have a question, I'll make sure to include the measure number (even for arrangements). I really was confused because of the "sempre legato" at the beginning of the score, because my edition really doesn't include any slurs on the bottom staff apart from the one I posted. This means the bow does not carry extra information, it just reinforces the "legato everywhere" already present, correct?
Comment: Which agrees with the markings in my cello part
Answer: It can't be a tie. Ties essentially elongate particular notes - usually because there isn't an appropriate note shape to show that length of note, and for other non-pertinent reasons here.
So, those lines must be slurs, which is exactly in line with 'legato', which means smoothly. One chord will blend into the other, as smoothly as possible. But no ties - none of the notes are the same.
Answer: Others have noted that the markings are slurs, not ties, but failed to mention a visual distinction.  Although ties and slurs look similar, and although some layout artists treat them interchangeably, a properly-drawn tie should sit horizontally entirely between the notes being connected, while a properly-drawn slur should extend horizontally to reach a point above or below the notes being connected.
Comment: In practice though, I very rarely see this distinction done, or if there is any difference it's too small to be noticeable.  The only surefire way to know it's a tie and not a slur is if they're both the same note, which in this case they explicitly are not.
Comment: Do standard score-writing packages (e.g. Lilypond) make the distinction in that way?
Comment: That would be nice, but rather subtle when sight-reading. A far better guide is - are they the same notes (tie),or different (slur)?
Comment: Good point, I personally like to see ties practically connected to the end of the first note and the beginning of the second note. With slurs I like to have a larger gap between the slur and the note head either above or below the note so they look very different from each other.
Comment: @Tim: If a note before a cross-bar-line tie has an accidental, it will apply to the portion of the note after the bar-line, and must generally *not* be repeated (though a courtesy accidental may be appropriate for e.g. a tie that crosses a page boundary).  If a slur connects two notes on the same line or space, however, and the first has an accidental but the second does not, then the second note should revert to the key signature.
Comment: That's a fair point. A valid point. I think anyone writing such (either way) ought to be aware of any ambivalence,(wrong word, but you get the picture!) and write accordingly. The whole point in writing music out is to make it as clear as possible for the reader. Who, if experienced, may well be able to work out from surrounding harmony what the 'new' note will be. Reading such for the first time may also give aural clues!
Comment: @Tim: I don't have enough familiarity with the music transcription features of this site to produce an example, but the visual distinction between ties and slurs will usually be pretty clear to anyone who looks at them side by side.  That having been said, a cross-bar-line slur between an accidental-modified note and its unmodified counterpart would definitely merit a cautionary accidental.

Tied flat to natural?


Available node language only English

Question: I have a custom content type with  "Set custom language as default for new content" and "Require language". Custom default language is Current language.
Entity translation is defined with "Current language" as "Default language"
and "Exclude Language neutral from the available languages" enabled.
I have 24 languages enabled but when creating a new node, only English appears as a language. But I need to be able to set any of the 24 languages
What am I  missing?
Answer: Change interface lang to the node target lang
The configuration you describe will always only allow one language when creating new nodes: the current language of the interface.
That is because you have Set custom language as default for new content. (and the current one as the default).
If you want to create content in other languages, you have to visit the node creation page in that target language (/fr/node/add/article if you're using prefixes).
Or allow other langs to be chosen
But if you want to be able to choose which language to assign to a node no matter what interface language you're currently using you have to untick the   Set custom language as default for new content. while keeping Require language (Do not allow Language Neutral).
That way your interface may be English, but you'll be able to choose any language in a drop-down to assign to that node.
Comment: I actually first tried to modify the Multilingual settings, but they are not editable. As the node is managed by features and strongarm, I tried to exclude all the variables from being handled by features and in the strongarm file I modified the corresponding definition i18n_node_options_ but a feature update doesn't change anything.
Comment: I put Current language as the default language because this was the only parameter I was able to change. The language however doesn't adapt to the interface. So even if I have /fr/node/add/project_fr and an interface well in French, I still only get English as only available language.
Answer: Please check the following:
1. In Entity translation settings page: "Use only enabled languages" is checked or not
2. If it is checked, then check in the admin/config/regional/language page that all languages are actually enabled not just added
3. If languages are added and enabled, then uncheck the option in 1
Comment: All the languages were already enabled, I followed your steps though, and nothing changed, only English is available

Available node language only English


What is the name of this kind of visualization, with arrows showing count of different subsets?

Question: What is the name of this kind of visualization? It uses arrows to show the count of parts of the sample set of an experiment.

This is from

"Measuring Reproducibility in Computer Systems Research." Christian Collberg, Todd Proebsting, Gina Moraila, Akash Shankaran, Zuoming Shi, Alex M Warren. March 21, 2014.
Answer: It is called a Sankey Diagram. A notable example is Charles Joseph Minard's visualization of Napoleon's invasion of Russia.
(Edit) Also of interest may be these questions:

What's a good tool to create Sankey diagrams?
What is the proper name for a "river plot" visualisation


Using embedded ActiveMQ Artemis in Spring Boot 3 with OpenWire protocol

Question: I am trying to use an embedded ActiveMQ Artemis broker in my Spring Boot 3 application and activate the OpenWire protocol.
This should be possible with an acceptor like tcp://0.0.0.0:616161?protocols=CORE,OPENWIRE as it says here.
I added these to dependencies to use the ActiveMQ Artemis broker.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-artemis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>artemis-jakarta-server</artifactId>
</dependency>

and use this BOM from Spring Boot
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>3.2.1</version>
    <scope>import</scope>
    <type>pom</type>
</dependency>

But when I start the Application this is logged:
AMQ222203: Classpath lacks a protocol-manager for protocol OPENWIRE, Protocol being ignored on acceptor TransportConfiguration(name=artemis, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyAcceptorFactory) ?scheme=tcp&port=61616&host=0-0-0-0&protocols=CORE,AMQP,OPENWIRE

To enable the amqp I added the dependency:
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>artemis-amqp-protocol</artifactId>
</dependency>

When I do the same with the OpenWire (also Spring does not provide a version for this dependecy):
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>artemis-openwire-protocol</artifactId>
    <version>2.31.2</version>
</dependency>

The server start crashes with this error:
Caused by: java.lang.ClassNotFoundException: javax.jms.InvalidClientIDException
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]
    ... 49 common frames omitted

I downloaded the ActiveMQ Artemis bundle and started the server with the same configuration there and it is starting with OpenWire support. I looked into the lib folder of the bundled server and there is also a artemis-openwire-protocol jar is included.
<parent>
    <artifactId>artemis-protocols</artifactId>
    <groupId>org.apache.activemq</groupId>
    <version>2.31.2</version>
</parent>
<artifactId>artemis-openwire-protocol</artifactId>

The standalone ActiveMQ Artemis broker is able to accept OpenWire clients. What do have I to do to enable it with the embedded ActiveMQ Artemis broker? Any hints?
Answer: In short, there currently is no way to support OpenWire clients of any kind using the ActiveMQ Artemis Jakarta broker. I've opened ARTEMIS-4567 to support this.
The problem is that the artemis-openwire-protocol dependency you're using depends on org.apache.activemq:activemq-client:5.18.3 which contains the actual OpenWire protocol implementation as well as the OpenWire JMS client implementation. This dependency uses and implements classes in the javax namespace which are incompatible with Spring Boot 3.x (which uses the jakarta namespace). Because of this code in artemis-openwire-protocol itself also references classes in javax.
Lastly, it's worth noting that existing OpenWire JMS clients using the javax namespace may break when using a broker with OpenWire + Jakarta.
If you really need to use JMS applications that use the javax namespace then I recommend you replace the OpenWire JMS client jars in those applications with the core JMS client jars from ActiveMQ Artemis (i.e. org.apache.activemq:artemis-jms-client). If your JMS applications are written properly (i.e. they don't use any implementation objects) then it should be a straight-forward switch. Just replace the jars and the update your jndi.properties files. The core JMS client uses the core protocol which isn't tightly coupled with JMS so you can mix and match clients & brokers using both namespaces.
Comment: Thank you for your answer. The problem ist, that I want to provide the openwire protocol with the embedded broker. I can not change the clients of the broker. We want to update your broker application to spring boot 3 and there the Broker implementation changed from ActiveMQ to Artemis. The clients of our application should not notice this change (expect some required URL changes). As the standalone Artemis is able to provide the Openwire protocol without any further setup I guess the problem is the dependecies used my the spring boot starter. But I can not figure out, what I have to change.
Comment: There is nothing that you can change due to the fact that there is no OpenWire protocol implementation for ActiveMQ Artemis that supports Jakarta.


Data loss when using the service-based database?

Question: I use the command "insert into" to add a record to the database, but when I run the application, the data I added does not exist, ie the database is empty.
I've closed the connection, but no data is stored, what can I do?
Code:
<code>SqlConnection cn = new SqlConnection(global::app.Properties.Settings.Default.DatabaseConnectionString);
try
{
    string  sql = "INSERT INTO tbl (field) VALUES ('"+ lblText.Text + "');";
    SqlCommand sqlc = new SqlCommand(sql, cn);
    cn.Open();
    sqlc.ExecuteNonQuery();
} catch (Exception ex) { } finally { cn.Close(); }
</code>
Comment: Are you overwriting the .mdf each time you run? Normally a lone .mdf file is a bad idea anyway, you should rely on a serious database connecting to the engine and creating the DB there.
Comment: put breakpoint, debug it, check the log, make sure pointing to correct and yeah, show your code!
Comment: SqlConnection cn = new SqlConnection(global::app.Properties.Settings.Default.DatabaseConnectionString);
            try
            {
                string sql = "INSERT INTO tbl (field) VALUES ('"+ lblText.Text + "');";
                SqlCommand sqlc = new SqlCommand(sql, cn);
                cn.Open();
                sqlc.ExecuteNonQuery();

            }
            catch (Exception ex)
            {

            }
            finally
            {
                cn.Close();
            }
Comment: You wrapped your code with try..catch so it silently swallows all errors. Remove the try..catch or debug your code when it gets to the `catch` line to see what the error was.
Answer: Ofer Zelig is correct that you should not be ignoring exceptions, so the first thing to do is confirm that an exception is not being thrown.  If it is then address that specifically.
Assuming there's no exception, Alejandro is correct that you are quite possibly overwriting the database every time.  That is the default behaviour.
He is, however, wrong about using an MDF data file in your app.  There's nothing wrong with doing so as long as it's not a multi-client application.  The database is still attached to a SQL Server instance at run time.
When you add a service-based database to your project, the MDF file becomes a source file.  Just like all source files, the running application knows nothing about it.  When you build, that MDF file is copied into the output folder along with the EXE.  It's that copy that you connect to at run time and that copy that you make changes to.  By default, each time you build a new copy is created, thus overwriting any changes you made to the old copy.
Select your data file in the Solution Explorer and open the Properties window.  Change the 'Copy to output directory' property to "Copy if newer" from the default "Copy always".  Now, a new copy will only be created if you have actually changed the source file, e.g. changed the schema.  That means that any changes you make during one run will remain in the database the next time you run, even if the project gets built in between.  If you want to look for the data in the database, just make sure that you look in the copy in the output folder and not the source in the project folder.
Comment: I realized my problem, thank you very much
Comment: thanks Ofer Zelig and Alejandro


Want to learn composing and producing music with a DAW. Where do I start?

Question: I am a computer engineer and a passionate music listener. I have been listening to movie scores and soundtracks for many years now and it has really inspired me to want to learn more about music and how to create it. I am especially inspired by Hans Zimmer's work.
I have no knowledge of western music or terms of music of any kind. I want to learn to compose and produce music and I don't know where to start. I basically want to learn how to produce music for film and T.V. Nowadays people are making amazing music using computers and I am wondering: how do they do that?  It is not quite possible for me to go to music school to start learning music at this time.
Specifically:

Is music theory necessary to compose music?
I want to compose music on computer (DAW). What are some things that I need to learn that will allow me to do this?
Does learning piano or keyboard give me enough ability and knowledge to start composing music with a DAW?
Comment: First off, you'll need to invest some money if you want it to sound at all real...
Answer: What you're asking is similar to "I want to write great software, but I'm not a programmer and have no knowledge of computer science or programming or anything like that. Will I be able to write great software if I just get the right IDE?"
I'm a programmer too; take it from me: YES theory is extremely important for what you want. Given that you are a programmer, I don't think you would need to take lessons in a school; you're probably used to learning new stuff by yourself (new languages, frameworks, tools, etc).
Learning theory helped me greatly in all aspects of my music: listening, arranging, playing with a band, composing, etc. That amazing music you hear in TV shows, etc was made by people who know a lot about music; the DAW or anything else they use to create the music is secondary to their knowledge.
In your case, getting the right reading material would help you a lot. I recommend you get your hands on a copy of The Jazzmaster Cookbook by Jim Grantham; if you find it too advanced to start with, get some other books about music theory so that you get up to speed on the major scale, minor scales, you know how a chord is made, how to make new ones, infer valid chords within a given scale, etc. Then you can move on to the Cookbook, where you can learn a lot about improvisation, composition, arranging, creating melody lines, chord progressions and all the stuff you need to create new music.
Learning some keyboards will also help you a lot; you'll be able to play stuff in real time instead of just creating music with point-and-click. Even if you don't record your final piece by playing, it will speed up certain processes such as testing new sound patches, effects, etc. You don't have to become really good at it, just some basic chords and melody with the right hand will be very useful to you, and you can get a small MIDI controller, 1.5 or 2 octaves (a really small keyboard that you can have on your desktop, connected to your computer, ready for whenever you need it).
Don't be afraid/discouraged/lazy/whatever about learning music theory. It's not that hard, although the way it is often taught may not be the best way for a programmer to learn it, I bet you will quickly pick up on the underlying structure and logic; don't get too entangled on the chord naming schemes and all that nomenclature stuff; what really matters is that you understand how a scale is made, a chord is made, how they relate to each other so you can make your own chord progressions, melodic lines, etc.
Comment: Perhaps OP is satisfied writing hacky spaghetti software? ;-)
Comment: Right heheh... he never said what kind of computer engineer he was...
Answer: I'm happy to hear you're brave enough to start producing music with no musical background but being a passionate listener.
You don't need a lot of money to do great sounds but in the beginning having a sample pack, great VST plugins and full version of a DAW does speed up the process of learning. ~300€ for the software and samples will do fine for more than a year. Don't begin with too difficult DAW. You can always try a demo version before choosing your way. In my early days I did use the free demo version of Fruity Loops for more than a year, it worked fine.
Also, you don't necessarily need to know terminology, music theory or how to use the DAW. I personally know professional musicians with very little knowledge of the theory behind their music. I also think that too much theory does make composing and using your imagination difficult. Your current lack of knownledge can be used as an advantage if you have the time to try and see certain things for yourself. That is the best way possible to learn and begin making music your own way.
If I got your question 2) right, you must be asking "What should I have" and "What should I do".
You already know the soft- and hardware you should have. I can't really say if you should get a MIDI keyboard or not. The keyboard does give you the ability to actually play something and figure out the connection between a key on the keyboard and a certain sound. It's sometimes faster to sketch the outlines of a melody with the keyboard and make a simple melody really fast. If you buy keyboards, consider carefully the amount of octaves you need to be able to play. More about this concern here.
Then again the 'point-and-click' way doesn't restrict you to only composing something you can actually play. For orchesteral and soundtrack -kind of music you are able to pick notes for a chord freely from a wide range. I've done this, it's possible and it's easy. You don't have to learn scales or notes first or buy a keyboard. Besides, it's free.
Having a little knowledge of music theory, you can still train your ear. If you compose music, you have to be able to hear "good" and "bad" notes. Train every day by listening music and trying to copy melodies to the patterns on your DAW either by clicking with your mouse or playing them on keyboard. As soon as possible begin making your own music along with just playing with the melodies and trying new things. Your first song may be a short loop and that's absolutely fine.
The best thing you could possibly do is trying to achieve a certain sound and melody from a song you like. If you put time and effort to it, you will most likely come up with something better, not the exact replicate of the riff. That will also give you a template from which you can easily modify something different by transposing single notes and playing with rhythms.
Something concrete you would begin with would be making a melody with strings. For that you will need a soundbank covering about 8 octaves of string sounds. Concentrate only on making a good atmosphere with long chords, you can move to rapid arpeggiations later. Imagine for example the song played in the beginning of a movie. Play a single note, find another note that sounds good with the first one, play them together. Then find notes played after the first ones that satisfy your ear.
Another style to compose is to pick three or four chords for a bassline. Then improvise a melody played along with the bassline.
Always think also from the listeners point of view: would I listen to this or not? What would Hans Zimmer do if this was his song?
Exact answer to your third question is: No. I have a friend who has been playing piano for 13 years. He is really strictly restricted to scales, circle of fifths and other rules not yet being capable of composing music. If you want to learn how to compose music, don't focus on learning something else. I don't agree with the other answers telling you to read books to learn how to compose. You will most likely get bored and not coming up with anything new.
Comment: I'm unashamed to say my first "in" to properly understanding music was through getting a DAW and just messing around.  Cheap version of cubase, about 10 years ago, with the default VST instruments and a cheap microphone.  Can't say I had the most immaculately produced work haha, but I certainly learnt a lot, and grew massively as a musician from my tinkering.  And these days there is so much free information out there, and free VSTs/soundfonts are completely passable, you could probably make some half-decent sounding stuff with little money. Certainly learn an awful lot from trial and error.
Comment: yes!  theory is useful, but only if it's linking back to what your ears are telling you.  Best thing for this person would be to try and produce some DAW "covers" by ear, and learn what's going on in the music they already like.  Creating using your ears is what gets someone composing, not reading books (while books are great to take your composing onto the next level).
Answer: Is music theory necessary to compose music?
I remember writing a little tune (about ten years ago) just to try out a computer program. At that time, I knew nothing about music, and I had no interest in learning to compose or play music. I basically wrote a couple of measures (I had no idea what a measure was at the time) using only trial and error. It took me much longer than it should have because I had no idea what I was doing.
Theory is important, but I think most people give it more attention than it deserves. Not knowing any theory at all can slow you down a lot (too much trial and error, unless you have ears like Mozart's). Knowing too much theory can restrict your creativity, and keep you from developing your ears. For example, one of the first things you learn in theory is scales. Scales are made of 7 or 5 notes (most often), knowing scales means that you have only 7 notes to choose from instead of all twelve notes. So knowing scales speeds you up. But it also makes it harder for you to use chromatics (notes outside the scale) because you're always expecting the notes to come from the scale.
Short answer: you can compose without without theory, but it would be extremely difficult to compose without training your ears. Focus on ear training, and learn only basic music theory (major minor sales, basic chords).
I want to compose music on computer (DAW). What are things that i need to follow to make me capable of that?
I can't answer this question since I don't use DAWs. I use notation software like MuseScore.
Does learning Piano or keyboard gives me enough ability and knowledge to compose music basically on DAW's?
Yes is does! To be able to write music efficiently, you need good ears. And to develop your ears you need to experiment and try out ideas quickly. Not only does the keyboard allow you to do so, but you can also use it as an input device to your DAW. In fact, I think it's very hard to achieve anything without one (or at least some other instrument). Anybody who's serious enough about composing on the computer uses a midi keyboard no matter what instrument they play simply because it's much easier and quicker than the mouse and keyboard.
PS: Don't forget to train you ears. Try this free ear training tool: Functional Ear Trainer. It's my favorite ;)
Cheers!
Comment: wonderful wonderful wonderful answer.  When I hear people saying you must read and read before trying to create for yourself, it reminds me a little of this https://www.youtube.com/watch?v=D_orL8BFFqo
Answer: A quick note for when you decide to start using a DAW: If you have a Mac, it has GarageBand on it for free. GarageBand is a full-featured DAW, and since it doesn't cost anything, it's a good tool for learning how to use a DAW (an entire skill set in itself). It isn't as powerful as other DAWs, though, so at some point, you are going to want to buy something better.
Answer: Here are the basic answers to your questions:

Technically no, but being a computer engineer it should be very simple for you to learn basic theory. You can get away with knowing nothing about music and making a good rhythm or melody, but music theory will help you understand why it sounds good and will help you if you are creatively stuck.
I would personally get your feet wet first in just basic composition before you star using a DAW. I would recommend getting a trial of finale notepad because it is rather simple and you can do a lot without having to record yourself playing or trying get two samples to act similarly. The only downside is you would need to understand basic theory to make the software useful because it is based off creating sheet music. For that program, you need nothing but your computer. If you are set on doing a DAW though, you would need an instrument of some kind and an interface between your computer and your instrument.
Because most DAW would have you record yourself, you would need to have a good grasp of an instrument before you could effectively write and compose music. I would invest in some kind of keyboard and try to get basic lessons. Keyboard have a wide range of sounds and instrument types.

Like stated above, I would take baby steps and not just try to jump in head first. I will make everything a lot easier if you learn a little at a time and then try to compose little pieces and then move towards your goals.
Comment: You don't really *need* a MIDI or USB keyboard to work with a DAW. It makes certain things easier or faster, but in most cases you can draw out the notes you want with just mouse and (computer) keyboard. I have done it both ways, but now I usually use a [grid controller](https://www.ableton.com/en/push/) to input notes. There are plenty of good producers out there who don't play keyboard very well.
Answer: If you want to get started creating music quickly on your computer, with no knowledge of music, I would recommend looking at a loop-based DAW such as Sony Acid.  With these systems, you can download loops, which are bits of recorded music on various instruments, and combine them on your computer to make new music without knowing how to play those instruments.
Acid has a free version so you can get started without spending any money.
To answer your questions: It is possible to create music on your computer without any knowledge of music theory or the ability to play an instrument.  However, if you are serious about creating music, learning how to play a musical instrument will help greatly.
Answer: If you are willing to learn major and minor scales, and Basic Chords on a keyboard, you can do so by applying these simple formulas.
W = Whole Step
H = Half Step
Major Scale: W W H W W W H
Minor Scale: W H W W H W W
You Can Build 12 Major and 12 Minor Scales by applying the above said Formulas
Now Major Scale is 1st note + 3rd note + 5th note
Minor Scale is 1st note + 3Flat (reducing half step) + 5th note in the respective scale.
Other wise you can use another formula to find chords.
Lets take, C major.
Now root is C
 Count 4 keys leaving C and reach the 4th key on the keyboard
1st Key - C#/Db, 2nd Key - D, 3rd key is - D#/Eb, 4th is E which is the second note in C major Chord. Now to find the third note, Count 3 more keys leaving E, and the 1st key is F, 2nd key is F#/Gb and the 3rd Key is G. Now hold the Ist key C, 2nd Key E and 3rd Key G together you C E G which is the Cmajor Chord.
Like wise for C minor the inverse of C major which is Root + 3halfs + 4 halfs
which is C D#/Eb G.
Like wise you have formulas for all 6th chord, 7th, 9th to 13th chords, augmented, diminished, even for Chord progression which i am not able to explain now....
I know this doesn't make any sense to you at the moment, but when you learn how the chords are formed, it is going to be very easy for you to form chords instead of remembering all lot of notes and stuff. I hoe this might help you to some extent to start off....
Answer: Since you mention that you're especially inspired by Hans Zimmer's work, you may want to take a look at this:
https://www.masterclass.com/classes/hans-zimmer-teaches-film-scoring


Meio de fazer uma comparação entre três variáveis

Question: Estou precisando fazer uma comparações entre três variáveis no meu código PHP.
if($a == $b == $c) {
   return true;
} else {
  return false;
}

Tenho muitas ideias de como fazer isso, mas quero saber qual a melhor maneira de conseguir esse resultado.
Comment: O que é a "melhor maneira"? A mais rápida? A mais legível?
Answer:
A solução mais simples, direta e objetiva é
return ($a === $b && $a === $c);

caso você queira apenas comparar valores, e não os tipos, pode usar assim:
return ($a == $b && $a == $c);

neste ultimo caso, usando == em vez de ===
Um comentário:
Na pergunta você usou este if:
if($a == $b == $c) {
   return true;
} else {
  return false;
}

Quando você usa uma condição lógica, como ($a == $b), o resultado ja é true ou false. Num caso desses você pode simplesmente retornar o resultado com return ( $a==$b ), pois o if é totalmente redundante e desnecessário, visto que a comparação ja é a resposta desejada.
Answer: Acho que a mais eficiente é:
if ($a === $b && $a === $c) {
    return true;
}
return false;

Lembrando que == testa se as variáveis têm valores equivalentes (por exemplo, um 0 equivale a um null) e o === testa se as variáveis são do mesmo tipo E possuem o mesmo valor.
Answer: É como você fez, porém tem que testar uma coisa por vez e usar o operador equivalente ao E/AND.
// Nota: bloco de código alterado. Espero que da próxima vez os colegas
//       estejam mais preocupados com o foco da questão e comentários
//       relacionados a performance e redução de erros do que ficar preso
//       estilo de código, em especial quando for apenas uma cópia do código
//       original e não tenha sido solicitado um regractoring completo
if ($a === $b && $b === $c) {
   // Bloco de código
} else {
  // Outro bloco de código
}

Além do fato de que há diferença entre o operador igual ==, que diz que os valores são iguais, e o operador idêntico === que além de ter o valor igual, o tipo é o mesmo, tem mais uma coisa bem importante na ordem dos operadores:

Ao usar o operador &&, sempre ponha a condição menos custosa em primeiro lugar, pois se ela falhar a segunda nem será testada

E outra coisa bem importante

Cuide a ordem das operações com && pois ela fará diferença se uma operação só pode ocorrer se a anterior ocorreu antes, ou se uma das operações gerará erro que a outra não for verdadeira.

As duas informações na caixas amarela costumam ser esquecidas ou só são percebidas tarde, quando o desenvolvedor percebe que houve alguma mensagem de erro no sistema.
Comment: Quem deu -1 pode explicar o motivo? O que está errado na minha resposta?
Comment: Eu manti ela porque a pergunta do autor foi sobre os condicionais testar igualdade sobre mais de dois operadores, não sobre return, e expliquei diferenças bem mais importantes para o foco da questão que envolvem **performance** e **redução de erros de execução**. Da próxima vez que  for negativar resposta de outra pessoa a uma pergunta que você também respondeu, a não ser que alguém já tenha reclamado e você dê um +1 no comentário da pessoa, comente porque deu -1. É agressivo esse comportamento. Tenha em mente ao pensar nisso de novo com outros.
Comment: A resposta está boa +1. Creio que, se já houve confusão do AP ao usar `$a == $b == $c`, então era importante sim explicar sobre o uso do operador `&`.
Answer: A maneira mais fácil de fazer isso é separando as comparações, dessa forma você vai conseguir saber exatamente qual está dando true ou false.
Exemplo:
<?php
if(($a == $b) && ($a == $c)) {
    return true;
} else {
    return false;
}
?>

Dessa forma se você precisar conferir cada uma das comparações separadamente depois fica bem mais fácil.


OpenWRT Barrier Breaker - Router does not route

Question: I've upgraded my TP-Link 1043 router to OpenWrt 14.07. Everything is perfect, Wifi and LAN are bridged, LAN machines can access each other by name, I can SSH into the router, and the router can access the internet on the pppoe-wan interface.
The is one small problem though. The router does not route. The internet is not accessible from the LAN. With one funny exception: DNS lookups do work.
The /etc/config/firewall file contains the following section:
config forwarding
    option src 'lan'
    option dest 'wan'
    option mtu_fix '0'

But when I list the POSTROUTING chain of iptables, there is nothing
# iptables -L POSTROUTING
iptables: No chain/target/match by that name.

# iptables -t nat -L POSTROUTING
Chain POSTROUTING (policy ACCEPT)
target     prot opt source        destination

UPDATE
So I tried adding the masquerading manually, and that seems to work:
# iptables -t nat -A POSTROUTING -o pppoe-wan -j MASQUERADE
# iptables -t nat -L POSTROUTING
Chain POSTROUTING (policy ACCEPT)
target     prot opt source        destination
MASQUERADE all  --  anywhere      anywhere

And voilá, suddenly the internet works from the LAN.
But why is the iptables rule not added based on the UCI config in /et/config/firewall?
UPDATE 2
I added the fixing iptables rule to the custom rules on the web interface. Then I checked, it was indeed inserted into /etc/firewall.user which is included into /etc/config/firewall. But after a reboot, the rule is not listed by iptables. And no internet in the LAN. Seems like a UCI config parsing issue...
UPDATE 3
It turns out I had no firewall at all. My /etc/config/firewall is completely ignored. It's just that the lack of filter rules is difficult to notice.
Comment: There's no `POSTROUTING` chain in the filter table, it's in the nat table. So you would have to do: `iptables -t nat -L POSTROUTING`
Answer: Masquerading is only set up by OpenWrt if the output zone is configured for it.
For instance:
config zone
        option name 'wan'
        option masq '1'
        #...everything else

Or in the web interface:
Comment: I've just checked, the option you mentioned is set.
Comment: @SzG I'd guess you have something else going on. Better look at the _entire_ firewall config. I also suggest you set `mtu_fix '1'` or you will have trouble passing packets out to the Internet due to path MTU issues.
Comment: According to Barrier Breaker docs, mtu_fix is deprecated.
Comment: @SzG Deprecated maybe, but that's not the same thing as nonfunctional. It's your router, you can ignore me if you want. :)
Comment: Yes, thanks, I'll try, but my UPDATE 2 points to a different direction.
Comment: @SzG Hm. Well yes, UCI can be really touchy. I don't think they've worked all the bugs out of it yet. Worst case you could just reset the config and try again.
Comment: Funny thing is, this is the factory firewall config. Not only Barriers are Broken, it seems. :-)
Answer: UCI config parsing seems to be broken. Issue temporarily fixed by adding a line to /etc/rc.local:
iptables -t nat -A POSTROUTING -o pppoe-wan -j MASQUERADE


How to calculate the probability of this normally distributed event?

Question: I am trying to solve the following probability problem:

The gross weekly sales at a certain restaurant is a normal random
  variable with mean \$2200 and standard deviation \$230. What is the
  probability that the total gross sales over the next 2 weeks exceeds
  $5000?

Source: here
Clearly, this problem is asking for the sum of two normal random variables. I am assuming that each week's earnings are independent of each other. It is well known that the sum of 2 independent normal distributions will be a normal distribution with the sum of their mean and variances. That means:
Let the earnings be $X$ in the first week and $Y$ in the second week.
$$
X \sim Norm(\mu,\sigma^2) \text{ and Y } \sim Norm(\mu,\sigma^2) \\
X + Y \sim Norm(\mu+\mu,\sigma^2+\sigma^2) = Norm(2\mu,2\sigma^2)
$$
Thus, we see that:
$$
X, Y \sim Norm(2200,230^2)
$$
Hence, the total earnings in 2 weeks would be:
$$
X + Y \sim Norm(2(2200),2(230^2))
$$
The suggested answer in the source states that:
$$
X + Y \sim Norm(4400,460)
$$
I do not agree with this even after looking at the intermediate steps. Am I misunderstanding something here? Could someone please advise me?
Comment: One problem in the answer of the paper is that a normal distribution is denoted as $\mathcal N(\mu, \sigma)$. This is not usual.
Comment: Yes. Indeed. I scoured my textbook and the Internet for the definition of normal distribution before deciding to ask here as I am unsure of myself.
Answer: You're correct.  The solution that you linked to states:
$$\sigma(X) = \sqrt{Var(X)} = \sqrt{Var(X_1) + Var(X_2)} = \sqrt{2\sigma^2} = \sqrt{2} \sigma = 2(230) = 460$$
where the author is calling the two weeks' sales $X_1$ and $X_2$.  Somehow in the second-to-last equality the author slipped and replaced $\sqrt{2}$ with $2$.
Comment: Thanks! It really left me puzzled. I am bad at probability but looking at that answer really put me in doubt.


Electric guitar bridge lifted too much, intonation problems

Question: I bought a used Fender Mexican strat online many months ago. Its bridge came lifted. I read some threads here (I'm posting them below) that say this can lead to intonation problems, and indeed I've never been able to get all strings in tune (the upper string is always at a higher pitch than the strings below, so if e.g. E and A are in tune, A can't be in tune with D).
I'd very much like to leave the bridge tilted like this, so I could pull or push it with my hand (like Jeff Beck does), but I'm afraid of breaking the bridge.
I don't know what's the gauge of the strings because I haven't changed them, but to me they feel like regular 10 gauge.
My questions are:

Do I have to make the bridge for this Mexican strat flat (or can I fix the intonation just with the saddle screws)? If yes, how do I do it (just by changing springs position and/or adding more tension springs?)?
If I can leave the bridge lifted, can I push/pull it with my hand, or will it break something (i.e., I should only move the bridge with the tremolo arm, and not with my hand)?

Pics:

Related:
guitar bridge lifted-up
Guitar bridge out of place?
Answer: To get the Jeff Beck floating bridge thing, you need to be able to go both up and down, and I think you've used up all the down. Here's Carl Verheyen explaining how to set up a Strat so it floats, which should guide you.
I would tighten the claw and retune to balance. That should make it behave more nicely and allow intonation. Best of luck.
Comment: I can't get deeper into proper setup for a Strat than Fender can. https://support.fender.com/hc/en-us/articles/212774786-How-do-I-set-up-my-Stratocaster-guitar-properly-
Comment: On the last picture, the piece that connects the springs to the wood is called the claw, and if you tighten it, it will tighten the spring tension, making the bridge flatter. Then, I'd set string height (the allen screws at the top of the saddles), then intonation. Tune up, fret the 12th fret. If sharp, detune and move the saddle back some. If flat, move it forward. Don't adjust with strings under tension.
Comment: This video is perfect, thanks for sharing it! But by retuning to balance, do you mean loosening/tightening the saddle screws? Sorry for the silly question, I'm very new to this technical understanding, all I've ever done with a guitar was playing it
Comment: This is great info, thank you for it! Searching now for tutorials to set the string height, I also found an interesting series on Youtube for setting up the guitar https://www.youtube.com/watch?v=9ILFo9oUsl8 Thank you very much for your explanations, now I have the essential knowledge and courage I needed to finally fix this
Answer: Several things. First is that the arm is a lever. A lever gives more leverage. So using our hand instead will produce less leverage, so less chance of breakage.
Second is with the bridge like that, there's lots of movement to raise the strings' pitch, but little to drop it. The bridge needs to be able to move both ways, so tighten the screws underneath until you have the balance you want. Three springs is o.k., but why not put them all parallel.
Third is there will be room to sort out intonation, which at the moment, looking at the saddles, isn't right anyhow. The tiny springs are only there to take up slack and stop rattles, if needed, they can be made shorter.
Comment: Thank you for all your points! I was wondering why the springs weren't in parallel, seemed like a weird configuration, but I didn't want to mess it up. I'll put them in parallel now. And sorry, but just to be sure: the way to fix the intonation would be just by changing the saddle's tiny springs' tension? Or should something else also be done?
Comment: Looking now at the saddle's picture I also spotted something unusual, the strings for both Es aren't aligned in the middle, like the other strings. Do you think this could be an issue?


IOS 8: doesn't sent emails

Question: my IOS app has a button to send emails - running on IOS 6,7 it works fine but
on devices running IOS 8 the email opens, no error appear in app or logs, but the email is not being received
I've been googling it as well as looked in apple site as well as other tutorials I don't see any differences from what I have written... any ideas?
<code>- (IBAction) emailBtn_Click:(id)sender
{
    MFMailComposeViewController *emailComposer = [[MFMailComposeViewController alloc] init];
    emailComposer.mailComposeDelegate = self;
    if ([MFMailComposeViewController canSendMail] == YES)
    {
        [emailComposer setSubject:@"hi"];
        [emailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

        [self presentViewController:emailComposer animated:YES completion:NULL];
    }
    else
    {
        NSLog(@"Can't Open Email");
    }
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"e-mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"e-mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"e-mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"e-mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    [self dismissViewControllerAnimated:YES completion:NULL];
}
</code>
Answer: use this code, may help you
<code>- (IBAction) emailBtn_Click:(id)sender
{

if([self canDeviceSendEmail])
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.modalPresentationStyle=UIModalPresentationFullScreen;
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Report"];
    [picker setTitle:@""];
    NSString *emailBody = [NSString stringWithString:@"Message"];
    [picker setMessageBody:emailBody isHTML:YES];
    [picker setToRecipients:[NSArray arrayWithObject:@""]];
    [picker setCcRecipients:[NSArray arrayWithObject:@""]];

    [self presentViewController:picker animated:YES completion:^{

    }];
}
else{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:@"You must have an email account configured to use this feature."
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,nil];
    [alert show];
}

}

-(void)mailComposeController:(MFMailComposeViewController*)controller
     didFinishWithResult:(MFMailComposeResult)result
                   error:(NSError*)error {

//[self dismissModalViewControllerAnimated:YES];
[self dismissViewControllerAnimated:YES completion:^{

}];
}
- (BOOL)canDeviceSendEmail{
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
return mailClass != nil && [mailClass canSendMail];
}
</code>

IOS 8: doesn't sent emails


Looping through GET request with multiple parameters of different length

Question: Follow up question to this question I asked a few days ago:
I still have to call the API for every element of the list but now I need some additional parameters. I have a list of values for every parameter with different lengths. Every customerId has multiple keywordIds and areaIds (which always have the same length for a given customer).
Every customer has different keywords. So for example the first five keyword IDs belong to the first ID in customerlist. The next three keyword IDs to the second ID in customerlist, and so on.
I tried it with zip, but I only get the first entry for the first keyword of the first customerid instead of all entries for every keyword of every customer (in this case the information for the keyword 1172646 and the area 29010 from the customer 803818 where isareafirst = false).
import json
import requests
import itertools

API_BASEURL = "https://exampleurl.com/"
API_TOKEN = "abc"
HEADERS = {'content-type' : 'application/json',
           'Authorization': API_TOKEN }

customerlist = [803818, 803808, 803803,803738,803730]
keywordlist = [1172646, 1218994,1218992 1218993,1218992, 1218995, 1218993, 1173529, 1235569,1187456,1187455,1187453]
arealist = [29010, 28882, 28882, 28882, 28882, 28882, 28882, 28882, 31237,31237, 31237,31237]
isareafirstlist = [False, False, True, False, False, False, True, False, False,False, False, False]

def get_history(endpoint):
        responses = []
        for i,j,k,l in zip(customerlist,keywordlist, arealist, isareafirstlist):
            api_endpoint = endpoint
            params = {'customerid' : i,
                      'keywordid' : j,
                      'areaid' : k,
                      'isareafirst': l}
            response = requests.get(f"{API_BASEURL}/{api_endpoint}",
                                 params = params,
                                 headers = HEADERS)
            res = json.loads(response.text)
            responses.append(res)
        return (responses)

I also tried itertools.zip_longest, but this just gives me errors where I received empty lists with zip
def get_history(endpoint):
    responses = []
    for i,j,k,l in itertools.zip_longest(customerlist,keywordlist, arealist, isareafirstlist):
        api_endpoint = endpoint
        params = {'customerid' : i,
                  'keywordid' : j,
                  'areaid' : k,
                  'isareafirst': l}
        response = requests.get(f"{API_BASEURL}/{api_endpoint}",
                             params = params,
                             headers = HEADERS)
        res = json.loads(response.text)
        responses.append(res)
    return (responses)

So how can I loop through the API with every combination that is possible?
Comment: Try `list.itertools.product(*list_of_lists)` where `list_of_lists` is the list of `[customerlist, keywordlist, arealist, isareafirstlist]`.
Answer: Would this implementation help?
import itertools
customerlist = [803818, 803808, 803803,803738,803730]
keywordlist = [1172646, 1218994,1218992, 1218993,1218992, 1218995, 1218993, 1173529, 1235569,1187456,1187455,1187453]
arealist = [29010, 28882, 28882, 28882, 28882, 28882, 28882, 28882, 31237,31237, 31237,31237]
isareafirstlist = [False, False, True, False, False, False, True, False, False,False, False]
list_of_lists = [customerlist, keywordlist, arealist, isareafirstlist]
for _ in itertools.product(*list_of_lists):
    print _


Como mudar a cara do site quando acessado pelo celular?

Question: Situação:
Tenho um site com designer para large screens, criei um template para mobile, tipo um aplicativo. Por isso quero que esse template seja mostrado apenas quando acessado pelo mobile, ao contrário mostre o convencional.
Como faço isso? Existe algum comando ou tag para isso no html ou no css?
Comment: Sua pergunta está vaga demais que podem gerar muitas respostas, você precisa especificar qual é seu ambiente de desenvolvimento, quais frameworks está usando e se possível uma página index como exemplo.
Comment: Estou usando HTML/CSS/JSCRIPT/ (estilo1.css)  no site desktop, no mobile quero usar um template adaptado (estilo2.css) . Apenas preciso saber como faço para quando acessar o site no computador eu usar o estilo1.css e quando acessar no celular eu usar o estilo2.css.
Answer: Use as media queries do CSS.
O CSS Tricks tem um repositório com as media queries para as principais telas.
Exemplo de uso:
<code>@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2) {

  /** Formatar o menu para telas de iPhone 4 e 4s **/
  nav {
    color: white;
    background-color: #333333;
    position: fixed;
    top: 0;
  }

}
</code>
Comment: @Mr.Iago, aconselho o uso de Media queries também, pois, o conceito de mobile ainda não foi totalmente definido, embora todos saibamos diferenciar. No caso, as mediaqueries são mais ágeis que uma verificação via javascript, e além disso, mais úteis em quesitos de estilização, já que é para isso que serve o CSS, podendo reutilizar as queries para estilizar outros elementos


Artifactory - hide the "last downloaded" info

Question: We are using the Artifactory tool to distribute gradle files and other artifacts to customers, secured by a per customer login.
However, if those customers get Webapp access (which they need to for example change their passwords) they can see all repositories and artifacts they have (read) access to, including WHO last downloaded the file.
Is there any way of changing this, besides building our own password change site?
Comment: I'm sure it depends on your use case, but I don't think it's generally recommended to use Artifactory to distribute to customers, for a number of reasons. Instead, Bintray is designed for this.
Comment: just to add to @DarthFennec - artifactory is a repository manager
Answer: Right now there is no way to remove the "Last Downloaded" information from the JFrog Artifactory screen. If that is a requirement you have, you can always reach out to the JFrog support team to have them log an enhancement request.
As an alternative, if you really want to use Artifactory for this use case, you might want to consider giving each customer their own repository and only giving them access to that repo. Artifactory stores files only once. The first time a file is uploaded, Artifactory calculates a checksum and stores the file accordingly (including putting a record in a database). If files are uploaded again, or copied to multiple destinations, only the database is updated to create a record mapping the file's checksum to its new location as well. On the positive side, you've got the artifacts stored once and your customers only see their own repo. On the down side, you'll end up with many more repos in Artifactory.


What does `clang-check` do without `-analyze` option?

Question: clang-check, Clang's built-in static analysis tool, has an -analyze option, for which the help string just says "Run static analysis engine." With this flag, I see very little output from running clang-check on several of my files; without it, I see a lot of warnings.
Isn't running the static analysis engine the main purpose of running clang-check, which is a static analysis tool? Why do I see less output when running the engine, and what does the tool do without the flag?
Answer: Running clang-check without any options runs the -fsyntax-only mode (checking for correct syntax). Only if you specify -analyze, the static analysis tool is executed, see http://clang-analyzer.llvm.org/available_checks.html for a full list of executed checks.

Note 1: you can do various other stuff with clang-check, e.g. AST dumping.
Note 2: you cannot specify -fsyntax-only and -analyze at the same time.
Comment: It sounds like `-analyze` should *always* emit *more* output, then, which does not appear to be the behavior I'm seeing...
Comment: No, it doesn't. `-analyze` does not combine `-fsyntax-only` and its own checkers.
Comment: Oh, it sounds like I misunderstood your second point, then. So `-analyze` won't emit errors for code that (according to Clang) isn't even syntactically valid?


Can I programmatically control the account number when creating a new account in MetaTrader 4?

Question: I have a C++ plug-in for MetaTrader 4 that allows me to create new accounts in it for trading purposes. I would like to be able to dictate to MT4 the account number when creating the new account. Might any one know whether this is possible and how it might be done?
Answer: The account number is generated by the broker upon account creation - So the simple answer is No; you cannot control it. The only way would be to generate an account number, and based on it anticipate what the next account number will be. This is only possible if the account number algorithm is broker-specific. This would surprise me though. I am willing to bet that account numbers are generated by MetaQuotes server with a one-way-function.
Comment: This is not entirely accurate, please see answer blow.
Answer: You can specify the account number in the login field of the UserRecord struct your are using in the call to UserRecordNew method. If the account already exits you will get an error from the method as apposed to RET_Ok.
Answer: If you use any API, you can manually enter the account number. If the specified account number exists, the system will reject your request. Is there any particular reason you want to enter custom numbers while opening the account?
Answer: It is not possible to control the account number. The justification of this is the fact that the account number is developed by the broker upon the opening of an account.The only way that this would be possible would be if one was to generate an account number and use this number to anticipate what the next account number will be. This approach is however, possible if the account number algorithm is broker-specific.


AQGridview - Loading images from web (URL)

Question: I'm new in iPad development. I'm using AQGridView to build my first ipad app. With the following code, I'm trying to load images from web URLs into each cell of the grid but, when I scroll down and come back up the images are not the same like they should, so they reload to display the good one.
Here's the code I use to load my images.
<code>dispatch_async(dispatch_get_global_queue(0, 0), ^{
    UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgPath]]];

    dispatch_async(dispatch_get_main_queue(), ^{
        _imageView.image = img;
        [self setNeedsLayout];
    });
});
</code>
I think the problem comes from here, when calling the dispatch_get_main_queue(). But I dunno how to fix that. If someone has an idea it would for sure help me!
Much thanks in advance!
Regards,
Answer: Apple has a demo of a clean solution to exactly this problem in LazyTableImages


Invertibility of a polynomial map equivalent to a condition on the ideal generated by the coordinates?

Question: Let $k$ be an algebraically closed field.
Let $$F=(F_1,\ldots,F_n) \colon k^n \to k^n$$
be a polynomial map.
I'm trying to understand the relation between the conditions:

$F$ is invertible.
$\langle F_1,\ldots, F_n \rangle = I(F^{-1}(0))$ is a maximal ideal.

If $F$ is invertible, then $F^{-1}(0)\in k^n$ is a singleton, and the corresponding ideal is maximal. It equals the radical of $\langle F_1,\ldots, F_n \rangle$, but does it equal $\langle F_1,\ldots, F_n \rangle$ itself ?
How about the converse ?
Answer: A morphism of affine varieties is invertible if and only if it the associated map of affine coordinate rings is an isomorphism. In your case, this says that $F: k^n \rightarrow k^n$ is invertible if and only if the map $F^*: k[x_1,\dots,x_n] \rightarrow k[x_1,\dots,x_n]$ given by $g(x_1,\dots,x_n) \mapsto g(F_1,\dots,F_n)$ is a ring isomorphism.
In particular, if $F$ is invertible, the image of the ideal $\langle x_1,\dots,x_n\rangle$ under $F^*$ is maximal. This image is precisely the ideal $\langle F_1,\dots,F_n\rangle$.
I claim a partial converse: if $\langle F_1,\dots,F_n\rangle$ is maximal, then $F^*$ is injective. To see this, note that injectivity is equivalent to $F_1,\dots,F_n$ being algebraically independent over $k$. By Noether's normalization, algebraic dependence of $F_1,\dots,F_n$ would imply that $k[x_1,\dots,x_n]$ is integral over $k[y_1,\dots,y_r]$ for some $y_i$ and $r<n$. This in turn would imply that the transcendence degree of $k(x_1,\dots,x_n)$ over $k$ is less than $n$, a contradiction.
Note: In my original answer, I carelessly asserted $$\langle x_1,\dots,x_n\rangle = \langle F_1,\dots,F_n\rangle \implies k[x_1,\dots,x_n]=k[F_1,\dots,F_n].\,\,\, (*)$$ This would imply $\langle F_1,\dots,F_n\rangle$ maximal iff $F^*$ is an isomorphism. After seeing this related post, I realized $(*)$ is false: the subalgebra generated by a set of elements need not contain their ideal. As @GeorgesElencwajg points out in his answer to the referenced question, a counter example is given by $\langle y, x+xy \rangle = \langle x,y\rangle$, since $k[x,y] \neq k[y,x+xy]$.