vector changes to matrix at computation

Question: This is probably a rookie mistake that I'm missing somewhere but I can't for the life of me find anything related to my problem on the web.
I have a vector b1 of size 5 by 1, and i have another vector dsdb1 which is also 5 by 1.
When I write b1 += tau*dsdb1 I get the error "non-broadcastable output operand with shape (5,1) doesn't match the broadcast shape (5,5)"
Now, no one of these is a matrix. I even deleted this line and instead printed both sizes for b1 and dsdb1. For b1 it printed (5,1) and for dsdb1 it printed (5,). tau is just a scalar.
Why is it changing dsdb1 to a 5 by 5 matrix when computing?
Comment: How is the vector defined? What object is it? Part of numpy?
Comment: both are numpy vectors. b1 is random initially. dsdb1 is computed via a rather lengthy process, but ends with numpy.sum, so yes, i believe both are numpy vectors
Comment: can you print these out with their types ?
Comment: `dsdb1 it printed (5,)` ?
Comment: both are numpy.ndarray, just checked. and b1 is size (5,1), and dsdb1 is size (5,). Whatever that means. yes. it printed (5,).
Comment: there you go, it should be `(5,1)` instead of `(5,)` . double check how you are creating your dsdb1
Comment: dsdb1 is computed correctly. as in the values are correct. it is computed via dsdb1 = np.sum(dw2_mul_h,axis = 1) where dw2_mul_h is (5,60000). the np.sum returns a (5,) vector.
Answer: I managed to fix it by using a temp variable, setting it to correct size, and iterating over dsdb1. i still don't know what caused the bug.

vector changes to matrix at computation


Vanishing measure sets and Expectation

Question: During my research, I was required to prove a particular result. I shall just ask what I needed for my result to hold.
Let $X_n$ be a sequence of random variables that are integrable and suppose we have for some constant $C>0$ that
$$\lim_{n \to \infty} P[X_n \leq C] = 0$$
Then does it follow that
$$\lim_{n \to \infty}E[X_n1_{\{X_n \leq C\}}] = 0$$
?
I don't know if the result true or not. However as a start, I was able to show that
$$\limsup_{n \to \infty}E[X_n1_{\{X_n \leq C\}}] \leq 0 $$
However I have no idea how to proceed from here and show
$$\liminf_{n \to \infty}E[X_n1_{\{X_n \leq C\}}] \geq 0 $$
This wouldn't be a problem if $X_n$ were non negative but since that is not given, I am stuck here. I appreciate hints or counterexamples to this. My guess, if I had to make one, is that this result isn't true...
Comment: Unless these are almost surely positive, no.
Answer: Consider $X_n$ such that $P(X_n= n^2)= 1-\frac{1}{n}$ and $P(X_n=-n^2)= \frac{1}{n}$.
This has $\displaystyle\lim_{n \to \infty} P[X_n \leq C] = 0$ for all $C \gt 0$ but $\displaystyle\lim_{n \to \infty}E[X_n1_{\{X_n \leq C\}}] = \lim_{n \to \infty}-n=-\infty$.
Comment: So my guess was right. Thank you very much Henry. I'll have to find an alternative way to prove my result...

Vanishing measure sets and Expectation


Qual view foi usada nesse layout

Question: galera eu to criando um app que a pessoa faz um cadastro,e nesse cadastro tem nome,fotos e várias informações e eu queria listar essas informações e fotos dessa forma,alguém sabe oq foi utilizado ? nessa galeria vc desliza o dedo e vai carregando novas fotos
Answer: Nesse exemplo aí foi usado o CardView com o RecyclerView.
Existem exemplos do google pra utilizar os guidelines deles de material design e alguns tutoriais na internet.
Se você quiser um tutorial, tem esse aqui: Getting Started With RecyclerView and CardView
Existem pessoas que vendem templates de implementações bem feitas dos guidelines do google. Um exemplo seria o MaterialX (disponível no google play).

Qual view foi usada nesse layout


how can i use wss in node.js, if the https server is a separate node.js application?

Question: I've created a multiplayer game with websockets in nodejs (using the ws lib), which works just fine. For debugging, I connected to the websocket server with my client webpage by just opening the html file via file:// protocol.
I wanted to have the page hosted on my web-server which uses https. This web-server also uses nodejs, but because the webpage is served via https, it cannot create a connection via ws and needs wss. Security downgrading and so on.

My problem is that I've got two separate programs: the https webserver and the websocket "game" server.
When i try connecting to the ws server i get:

Uncaught DOMException: The operation is insecure.

I only found instructions on how to set up wss by creating a https server, but i already have one.
Do i need to combine the two programs?
Could i maybe just serve the single page for the game with http?
Is there some other technology, which doesn't have these security restrictions? (i don't care about encryption for the websockets)
Comment: Best approach would be to use a proper server for both (don't use `file://`), and for both to be on HTTPS. They *could* be the same server (in a single app), or they could be on separate servers (both with HTTPS support), depending on how you want to organize things.
Comment: What prevents you from upgrading your "gameserver" to https?
Comment: @derpirscher
I used [greenlock](https://www.npmjs.com/package/greenlock) to get https for my webserver. I tried doing that for my "gameserver" , it says it is serving, but i cannot connect by any means. [i used this example](https://git.coolaj86.com/coolaj86/greenlock-express.js/src/branch/master/examples/websockets/server.js). I also referenced the greenlock.d directory of my webserver. That didn't seem to cause any errors ,but I am unsure if it actually worked.
Answer: I was able to make it work:
Instead of wanting to use the https server from the web-server, i "upgraded" my http-server for the "gameserver" to https. I didn't want to "create" another https server, because i thought it would cause errors, but i already made a http server indirectly anyways, with  new WebSocketServer.Server({ port: PORT });.
To create the https server and use it for the WebSocketServer i used this code:
    let cert = fs.readFileSync(pathtocertkey, "utf8");
    let key = fs.readFileSync(pathtopublickey, "utf8");
    let options = {key: key, cert: cert};
    let server = require("https").createServer(options);
    const wss = new WebSocketServer.Server({ server: server});

After that i could listen to any port with server.listen(PORT,callback).
I also wasn't sure how or if i could get the cert i got with greenlock. But I found it undergreenlock.d/live/[yourdomain]/
With greenlock.d being the configDir specified in greenlock.init(options).
For the client i need to connect like this :
ws = new WebSocket("wss://mydomain:"+PORT);'


How to stack all values in two columns into a single column

Question: I have a data set like this:
 dt <- tibble(
  TRIAL = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
  GYF = c(1, 2, 3, 1, 6, 3, 2, 3, 1),
  AD = c(7.54, 1.564, 10, 0.89, 0, , , 1.5, 0)
)

# # A tibble: 9 x 3
#   TRIAL    GYF    AD
#   <chr> <dbl> <dbl>
# 1 A         1   7.54
# 2 A         2   1.564
# 3 A         3   10
# 4 B         1   0  .89
# 5 B         6   0
# 6 B         3
# 7 C         2
# 8 C         3   1.5
# 9 C         1   0

This is what I want to achieve: I want all values of GYF and AD column to be stacked and having the Header and the Trial Value in the first column.
# # A tibble: 9 x 4
#   TRIAL    Trait    Traitvalue
#   <chr> <chr> <dbl>
# 1 A        GYF   1
# 2 A        GYF   2
# 3 A        GYF   3
# 4 A        AD   7.54
# 5 A        AD   1.564
# 6 A        AD   10
# 7 B        GYF   1
# 8 B        GYF   6
# 9 B        GYF   3
# 10 B      AD   0.89
# 11 B      AD    0
# 12 B      AD
# 13 C      GYF   2
# 14 C      GYF  3    1.5
# 15 C      GYF  1     0
# 16 C      AD
# 17 C      AD 1.5
#18 C       AD 0

Answer: You can use pivot_longer from tidyr and dplyr pipe for renaming and ordering:
dt %>% pivot_longer(., c("GYF", "AD")) %>%
  arrange(., TRIAL, name) %>%
  rename(Traitvalue=value,
         Trait=name)

  TRIAL Trait Traitvalue
   <chr> <chr>      <dbl>
 1 A     AD          7.54
 2 A     AD          1.56
 3 A     AD         10
 4 A     GYF         3
 5 A     GYF         2
 6 A     GYF         3
 7 B     AD          0.89
 8 B     AD         NA
 9 B     AD         NA
10 B     GYF         1
11 B     GYF         6
12 B     GYF         3
13 C     AD          1
14 C     AD          1.5
15 C     AD          0
16 C     GYF         2
17 C     GYF         3
18 C     GYF         1

Answer: You can use function melt (but it works correctly with data.frame):
melt(as.data.frame(dt), id.vars = "TRIAL", variable_name = "Trait")

If yhou want to sort it (as in you example) you can use arrange:
... %>% arrange(TRIAL)


What are the disadvantages of dichotomizing an ordinal DV?

Question: I have an ordinal dependent variable in my model. Personally I find dealing with binary variable a lot more simple, although I have been told that by dichotomizing my DV I will lose information. What exactly would be lost?
Comment: Your job, perhaps. When I used to work for a manufacturing company, the Quality Engineers were putting great effort & ingenuity into devising ordinal measurement scales to replace crude pass/fail assessments. I don't think I'd've been there very long if I'd dichotomized them because I found binary variables simpler to deal with.
Comment: Not just lose information, but you'll bias your estimates -- the estimated mean of all the categories will be shifted toward the mean of the categories you lumped it in with. Your standard errors will be affected. All manner of things happen. Whether this is only mildly bad or terrible depends on a number of things, including what you're trying to achieve, but generally it's to be avoided.
Answer: Everything.  The meaning of the variable is lost, information is lost, and statistical power is diminished.  Why even consider this?
Why is it so difficult to deal with ordinal regression models?  If using a proportional odds model and you want to interpret effects in terms of odds ratios, you still get an odds ratio for each predictor.  Instead of being the ratio of odds that $Y=1$ it's the ratio of odds for $Y\geq j$ for arbitrary $j$.
You can also use ordinal models to estimate exceedance probabilities and mean $Y$ (plus quantiles of $Y$ if $Y$ is continuous).


Android: Finish activity with class name

Question: My app has a button that act as the back button on android. However it appears on top of any other applications, I want the user to press on the "back button" i.e. my custom back button in order to close the current activity. I can get the current activity name and so my question is how do I finish an activity with only the class name? Thanks
Comment: Why implement your own back button when Android already has one?  This is not good usability.
Answer: This my scenario
A-> B->C
When c got success I want again come to A if user pressed back button then dont want A I want B
In that case I took on static boolean variable if set true flag on C after successful transaction if user press back then false.
on B I check on
<code>@Override
protected void onRestart() {

    if (isSuccessfully) {
        finish();
    }
    super.onRestart();

}
</code>
Answer: Your question is not clear, but I think all you want to do is close the current activity when you click a button so that you go back to the previous activity. Add the following click listener to your back button
<code>  new View.OnClickListener() {

       public void onClick(View view) {

           MyActivityName.this.finish();

       }
  }
</code>
Comment: Actually I am doing that in a service, where I can't call finish. And I can only get the activity name of the running activity, which is the one I want to close when the user clicks the custom back button
Comment: In that case, I've just written an answer for another question I think should be relevant, take a look here: http://stackoverflow.com/questions/21351974/how-to-perform-back-button-action-in-another-app/21352046#21352046
Comment: You should pay attention to simons comment above which I've upvoted. This seems like a bad usecase anyway, so you might be approaching the problem the wrong way
Comment: However I want to close other third parties apps, how can I achieve that? And actually I am developing an app that has different controls on floating over other apps, including a back button, that's why I am asking how can I close a running activity


Metaregression on meta-analysis of proportion with metaprop and metafor

Question: [EDITED for more clarity]
I performed a meta-analysis of single proportion with logit transformation, which I made using the metaprop function, with a random intercept logistic regression model as the default option in the meta package.
Let's say for example that i want to meta-analyze the proportion of asymptomatic on the total number of patients, and I have a moderator:
moderator <- c(1,2,2,2.5,4)
m1 <- metaprop(c(10,20,30,40,50), c(100,300,400,330,240), comb.fixed=FALSE, prediction=TRUE)

So I have defined the meta-analysis object in m1.
To perform a meta-regression with the moderator, I use the TE of the meta-analysis, with the following code:
model1 <- rma(yi=m1$TE, sei=m1$seTE, method="ML", mods = ~ moderator)

Which gave me as  result:
tau^2 (estimated amount of residual heterogeneity):     0.0000 (SE = 0.0224)
tau (square root of estimated tau^2 value):             0.0011
I^2 (residual heterogeneity / unaccounted variability): 0.00%
H^2 (unaccounted variability / sampling variability):   1.00
R^2 (amount of heterogeneity accounted for):            100.00%

Test for Residual Heterogeneity:
QE(df = 3) = 6.5458, p-val = 0.0879

Test of Moderators (coefficient 2):
QM(df = 1) = 26.2205, p-val < .0001

Model Results:

           estimate      se      zval    pval    ci.lb    ci.ub
intrcpt     -3.2733  0.2623  -12.4772  <.0001  -3.7875  -2.7591  ***
moderator    0.4735  0.0925    5.1206  <.0001   0.2922   0.6547  ***

Two question are:

It is correct to conduct the meta-regression like this? it won't be better to use the transformed proportion in the meta-regression model?

For example with a code like this:
model2 <- rma(yi=transf.ilogit(m1$TE), sei=transf.ilogit(m1$seTE), method="ML", mods = ~ moderator)

which gave me totally different result:
Mixed-Effects Model (k = 5; tau^2 estimator: ML)

tau^2 (estimated amount of residual heterogeneity):     0 (SE = 0.1933)
tau (square root of estimated tau^2 value):             0
I^2 (residual heterogeneity / unaccounted variability): 0.00%
H^2 (unaccounted variability / sampling variability):   1.00
R^2 (amount of heterogeneity accounted for):            0.00%

Test for Residual Heterogeneity:
QE(df = 3) = 0.0128, p-val = 0.9996

Test of Moderators (coefficient 2):
QM(df = 1) = 0.0308, p-val = 0.8607

Model Results:

           estimate      se    zval    pval    ci.lb   ci.ub
intrcpt      0.0114  0.6430  0.0177  0.9859  -1.2490  1.2717
moderator    0.0444  0.2532  0.1754  0.8607  -0.4519  0.5407

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If I exponentiate the coefficient from the first meta-regression model, I get an OR; see for example:

round(exp(coef(summary(model1))[-1,c("estimate", "ci.lb", "ci.ub")]), 2)

Which gave me the OR of 1.47 [95% CI 0.02-98.71]
is it correct to say that "for each unit increase of moderator, the odds of bein asymptomatic increase by 47%"?

Sticking with the model 1, I may need to plot the relationship between the moderator and the prevalence of asymptomatic disease. Following the instructions reported here: https://www.metafor-project.org/doku.php/plots:meta_analytic_scatterplot, and with a little tuning (since I have to transform the logit transformed proportions in the plot) i used this code:

preds <- predict(model1, newmods=c(1:4), transf=transf.ilogit)
plot(NA, NA, xlim=c(1,4), ylim=c(0,1), xlab="Moderator", ylab="Prevalence")
lines(1:4, preds$pred, col="black")
lines(1:4, preds$ci.lb, lty="dashed", col="black")
lines(1:4, preds$ci.ub, lty="dashed", col="black")
size <- 1 / sqrt(m1$seTE)
size <- size/10 / max(size)
symbols(moderator, transf.ilogit(m1$TE), circles=size, inches=FALSE, add=TRUE, bg="black")

Which gave me this plot:

Is that ok to represent in the plot the relationship between the moderator and the transformed proportion, even if the meta-regression was conducted with the untransformed one?
Comment: The transformed se is not the se of the transformed effect.
Comment: I believe the first code and ensuing results are appropriate... Remember though that ecological fallacy is still a risk: https://en.wikipedia.org/wiki/Ecological_fallacy
Comment: @Joe_74 thank you - obviously the results should be interpreted at a study level rather than at individual level. Assuming that the first code is correct, a) is a plot like the one that I added (in which I have transformed the logit-transformed proportion into the actual proportion) formally correct to represent the relationship from the meta-regression?
b) Is there any reference paper that can be referenced as for the methodology to perform this kind of meta-regression?
Comment: @mdewey ok so this is one first error in the second code. So is it more correct to perform the meta-regression according to the first one string (i.e. untransformed TE and seTE)?
Comment: I believe the plot and the interpretation are correct
Answer: If you start out your analysis using a random intercepts logistic regression model, then I would suggest to stick to that framework also for your meta-regression analysis (your model1 does not use logistic regression, but uses the 'standard' inverse-normal model of the logit transformed proportions as outcome). The meta package actually uses rma.glmm() from the metafor package to fit logistic models, so your model m1 could be obtained directly with:
m2 <- rma.glmm(measure="PLO", xi=c(10,20,30,40,50), ni=c(100,300,400,330,240))
m2
predict(m2, transf=transf.ilogit)

And rma.glmm() can also be used to fit your meta-regression model with:
m3 <- rma.glmm(measure="PLO", xi=c(10,20,30,40,50), ni=c(100,300,400,330,240), mods = ~ moderator)
m3

The only change required in your code for the plot is size <- 1 / sqrt(m3$vi).
Comment: Thank you @Wolfgang for your answer. Can I use your help also for the question 2 and 3?
Do you agree with the interpretation reported in question 2? Do you think that the plot reported in my question is formally correct to represent the relationship (by transforming the proportion?)
Comment: Other question is - fitting the model with the moderato with the rma.glmm as in your code, I do not get any R2. Is this normal? How can I find the amount of the heterogeneity explained by the moderator?
Comment: Yes, I would say your interpretation in 2 is correct and yes, the plot for 3 is also fine. As for $R^2$, you can get it yourself with `(m2$tau2 - m3$tau2) / m2$tau2`. Since $\hat{\tau}^2$ is reduced to 0 in `m3`, you get 100%. But since $k$ is small, I would treat this with a lot of caution.
Comment: thank you, your help is really appreciated.
Can I ask you why the rma.glmm() function do not incorporate in the output the R2 statistics?
Comment: No particular reason. Just did not implement this so far.


Multiple shipping addresses

Question: We're building a Drupal 7 website with Drupal Commerce and our client would like to give the customer the ability to add multiple shipping addresses on the registration page.
The customer would then be given the option to select one of these addresses during checkout.
Is this native functionality or can we deliver this via a module?
Answer: Lucky you, someone built exactly that:
Commerce Addressbook Extra

This module for Drupal Commerce extends Commerce Addressbook module and allows to add customer profiles from Register form.

It sits on top of Commerce Addressbook

Commerce Addressbook is a module that allows authenticated customers to reuse
  previously entered addresses during checkout.
  They can manage all entered addresses in their user panel (user/%user/addressbook).

Multiple shipping addresses


MS SQL update query on int column with an empty value

Question: My table has two columns - col1 (int, null) and col2 (int, null) which I want to be able update with an empty values or null statement.
My code looks like:
            $newkeylimit = $allkeylimits[$row['Group_ID']];
            if($newkeylimit == ''){ $newkeylimit = NULL ; }

            $newproflimit = $allproflimits[$row['Group_ID']];
            if($newproflimit == ''){ $newproflimit = NULL ; }

            $sql = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."', col1 = '".$newkeylimit."', col2 = '".$newproflimit."' WHERE Group_ID = '".$row['Group_ID']."'";
            $result = mssql_query($sql)
                or die( "ERROR: Group update query failed" );

After code execution I'm getting 0 in each column where suppose to be an empty value or NULL. Default values for col1 and col2 are set to NULL.
Any idea what I'm doing wrong? Thanks
Comment: OK, I have changed code above to:     if(empty($newkeylimit) && empty($newproflimit)){
     $sqlup = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."', col1 = null, col2 = null WHERE Group_ID = '".$row['Group_ID']."'";
    }

    else {
    $sqlup = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."', col1 = '".$newkeylimit."', col2 = '".$newproflimit."' WHERE Group_ID = '".$row['Group_ID']."'";    } and it works, somehow.
Answer: You can't set to 'NULL'. You set to NULL instead.
Try this.
        $newkeylimit = $allkeylimits[$row['Group_ID']];
        if($newkeylimit == "''"){ $newkeylimit = "NULL" ; }

        $newproflimit = $allproflimits[$row['Group_ID']];
        if($newproflimit == '""'){ $newproflimit = "NULL" ; }

        $sql = "UPDATE ".$mssql_table_prefix."Groups SET Group_Name = '".$newgroupname."',                col1 = ".$newkeylimit.", col2 = ".$newproflimit." WHERE Group_ID = '".$row['Group_ID']."'";

Comment: As mentioned below - code is passing NULL as string not int. Also IF statements are not valid for me (searching for double apostrophes or quotations)
Answer: You are passing a string instead of NULL to the server.  Get rid of the apostrophes (') for col1 and col2.
Comment: My code hasn't apostrophes (') for col1 and col2. Even switching if($newkeylimit == '') to if(empty($newkeylimit)) doesn't help
Comment: got it! I'm passing NULL as string anyway when passing variable with open/closed apostrophes. Thanks.
Comment: No clue who did that, but your answer is better then below one which is not correct because he is passing NULL as string as well.


How get empty record on date field with entityQuery?

Question: I am on a custom entity with custom fields and i try to get all empty record on date field :
Field was create with CCK, so the field storage has a table.
<code>  $query = \Drupal::entityQuery('test_entity');
        $query->condition('field_date',NULL,'=');
        $ids=$query->execute();
</code>
This doesn't work for date field.
Comment: yes, so i replace with $query->notExists('field_date'); that seems to work, i ll try more test
Comment: Have you looked in the DB and confirmed that the values for those columns are actually null and not something else? The column is text or integer, depending on which field type you selected, so as far as a database query goes, there's nothing special about comparing it to null
Comment: it's a field create with the drupal interface, so the field is in fact a table, she has no record
Comment: That'll be it then - the query will do an `INNER JOIN` on the field data table because you've included it in the conditions, and there's no data, so nothing to compare to null. Hence no results.
Comment: Oh brilliant, they accounted for that situation this time round, good news. Please do put an answer on once you've confirmed that works, this will be useful to a lot of people in time
Answer: Since the field is stored in a single table, this is how i get all empty record from my entity where my custom field is empty :
<code> $query = \Drupal::entityQuery('test_entity');
        $query->notExists('field_date');
        $ids=$query->execute();
</code>
Comment: Just for the record, here's the documentation for exists/notExists : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.2.x
Comment: What about when it's in multiple tables?
Comment: you need to add more conditions, like id or another field for filter. But your first filter is your entity ( entityQuery('test_entity')
Comment: This is great for when you add a new field to a content type but you can't bulk save them all for some reason.
Comment: This is not working on a few fields. Any idea why it will behave like this?   $appeal_query = \Drupal::entityQuery('node')->condition('status', 1)->condition('type', 'appeal')->notExists('field_appeal_country');


Not able to print variables of content type

Question: I want to print variables of a particular content type, but I have not found any way. Here is my code.
function mytheme_preprocess_node_mytype(&$vars) {
  echo '
';print_r($vars); echo '
';
}

This function is in template.php. Is there a problem with my code?
Comment: which version. D7 or D6?
Answer: Try this: (D7)
function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('
' . print_r($vars, true) . '
');
}


What is Puppet's equivalent of input validation using stdlib in Ansible?

Question: Problem
The following issue appears in the ansible-sensu-client:
{"timestamp":"2017-01-19T09:49:14.803754+0000","level":"fatal","message":
"check name cannot contain spaces or special characters","object":{"handlers":
["mailer","sms"],"command":"check-ports.rb  -p 234","interval":30,"standalone":
true,"name":"port 234"}}

At the moment the user needs to debug the sensu-client logging in order to find the issue, will the issue could be prevented by validating the input.
Aim
To avoid that users that use this role will use names that contain spaces or special characters, e.g.:
sensu_client_checks_metrics_common:
  - cmd: check-cpu
  - cmd: check-memory-percent
  - cmd: check-ntp
  - cmd: check-swap-percent
    handlers:
      - mailer
  - cmd: metrics-cpu
    handlers:
      - relay
  - cmd: metrics-memory-percent
    handlers:
      - relay
  - cmd: metrics-disk
    handlers:
      - relay
  - cmd: metrics-disk-usage
    handlers:
      - relay

by letting the Ansible run fail and indicate that the input is invalid
Discussion
In Puppet one could use Stdlib to validate input, e.g. is variable X a String and does Y equals Hash? For example, in this module the version should be a string and if that is not the case the Puppet run will fail:
validate_string($version)

and indicate that version needs to be a string.
How to validate input in Ansible as well?
Answer: You can use assert module in the beginning of your roles to validate variable values:
- assert:
    that:
      - "my_param <= 100"
      - "my_param >= 0"
    msg: "'my_param' must be between 0 and 100"

Comment: And what could be done if strings need to be checked that reside in a variable that is a hash?
Comment: @030 give an exampe, please
Comment: added the `sensu_client_checks_metrics_common` example
Comment: not sure what you want to check here, but you can use `parent.child.string_to_check` like with any other variables


Managed hosting firewall vs managing own firewall

Question: I posted on stackoverflow as to the overall benefits of managed hosting vs non-managed hosting.
The more I think about it, it seems to boil down to one question: should I use a managed host because they take care of the firewall, or would I be okay managing my own, software firewall?
The sites on the box do get quite a lot of traffic but as for throughput and what-not, it's not something I know much about.
Ideally, i'd take my sites over to a Linode stack and manage incoming connections using iptables or an alternative.
Here are some example hardware solutions a managed host would provide:

Cisco Pix 501, Pix 506, Pix 515 and ASA 5505 and ASA 5510 Firewalls, configurable in a control panel
the likes of an enterprise firewall such as FortiGate 110C

Aside from this, I do not need managed hosting, so I appreciate your suggestions.
Answer: The advantage of a dedicated firewall device is that your server won't have to deal with the traffic that's going to be dropped (you can still have your interfaces saturated if you're filtering on the target box).
If you are expecting a substantial amount of traffic and a good portion of that may be dropped a dedicated firewall (either from your provider or one you manage yourself) is probably a good idea.
If you are not expecting to drop large amounts of traffic and don't think you'll saturate your server's connection with junk a local firewall may be "good enough", but I'm always in favor of separating the firewall role out onto dedicated hardwware: A PIX, ASA, or a dedicated box running PFSense or similar software are all good choices.
Comment: The problem is, since we managing the hardware ourselves - rather we'll use a company that sets up your box in a datacentre - the only solution I can think of is to use a *managed hosting* solution. Obviously a local firewall gets past these issues.
Comment: What would be a good 'local firewall' solution, as opposed to just using `iptables`.
Answer: having an external firewall like the ons you have mentioned may be helpful if your box is compromised, It's unlikely the firewall will also be compromised. This will stop hackers running certain services and you may be able to check the firewall logs to determine the source of the attack to prevent it in future. also as has been mentioned the firewall will take some load off your server.
In my opinion in practice neither of those benefits is enough to justify an external managed firewall in most cases. The load on the server that the firewall would have stopped will be negligible. If your server is hacked you will have other things to worry about than slightly restricting what they can do and having secure logs from the firewall is unlikely to be of much practical benfifit in the long run.
Use iptables and don forget to block outgoing as well as incoming traffic.


Abrir Função onclick no Select option

Question: Preciso abrir o seguinte onclick no option do "Select"..
Como abrir um onclick no option do select assim:
Quero fazer isso aqui:

span1

Funcionar assim:

<select>
    <option onClick="Select(0, this);">1 </option>
    <option onClick="Select(1, this);">2</option>
</select>

OBS.: Não posso usar ID nem CLASS pois utilizarei a função "CLONAR" do jquery então caso for dupliacado na função clonar o ID e a ClASS não funciona.
Comment: Pode explicar melhor sua dúvida? Você quer que um evento seja disparado quando o usuário clicar em alguma opção de um select?
Comment: Se tu quiser executar uma função ao selecionar uma opção do select, use o **onchange** no select, quando houver mudança no select ele dispara a função.
Comment: @EduardoBreno já testei onchange e não deu..
Comment: @Giovane, exatamente, abrir uma função do select ao clicar no option, já testei com onchange e não deu....
Comment: @Alh que tipo de função? O `Eduardo Breno` esta certo, você deve usar `onchange` quando num `select`. Mostra ai qual função vc quer executar, explique melhor tudo que podemos ver como fazer funcionar com o `onchange`.
Comment: @Giovane, quero abrir o Onclick fazer o mesma função que nos links que faz o onclick aqui: https://jsfiddle.net/pfmfoe30/14/
Comment: @Alh o que a função deve fazer?
Comment: @Giovane, no js fiddle você pode verificar, ao clicar em "span1" nota que abre uma div especifica, e na div "span2" e "span3" também..
Answer: Uma resposta baseada no seu exemplo:

$('#selectSpan').on('change', function() {
 Select(this.value, this);
})

function Select(index, el) {
    var spans = el.parentElement.querySelectorAll('span');
    for (var i = 0, l = spans.length; i < l; i++) {
        spans[i].style.display = i == index ? 'block' : 'none';
    }
}

<select id="selectSpan">
  <option value="-1" selected>Nenhum</option>
  <option value="0">span1</option>
  <option value="1">span2</option>
  <option value="2">span3</option>
</select>

span1
span2
span3

Em vez de passar o valor por parâmetro no seu onClick você deixa o valor do index do span no value do option, assim no onChange do select você consegue resgatar o valor desejado.
Comment: Se não quiser depender de posicionamento, poderia ainda definir ids para os span, e usa-los como value do options. +1 por se basear no exemplo do autor da pergunta.
Comment: @Giovane, funcionou ao clicar em "executar" mas ao criar um arquivo html com o código não funcionou, estranho. Mesmo assim não posso utilizar ID pois irei usar a função "clonar" do jquery e da conflito com ID's!
Comment: Como está o seu HTML? Está importando a lib jquery?
Answer: Você pode ter o resultado necessário utilizando o evento onchange do select.
Caso o parâmetro necessário para o sua função seja o valor select, você pode acessa-lo utilizando this.value no corpo da função (contanto que ela tenha sido executada dentro do escopo do select).
Caso você queira definir diferentes parâmetros para cada option, porém não relacionados com value do option, você pode utilizar os atributos prefixados com data- como no exemplo:

<select id="select">
    <option data-param="parametro-1">1</option>
    <option data-param="parametro-2">2</option>
</select>

Answer: @Alh, segue um exemplo sem usar jquery com javascript para melhor entendimento.
Sugiro a utilização de jquery como a resposta do @Giovane

function nomeDaFuncao(elem){
  var indiceDoSelectEscolhido = elem.selectedIndex;
  var valorDoElementoEscolhido = elem.options[indiceDoSelectEscolhido];

  alert("Indice: "+indiceDoSelectEscolhido
    +"\n"+"Valor: "+valorDoElementoEscolhido.value
    +"\n"+"Texto dentro do Select: "+valorDoElementoEscolhido.innerHTML );

}
<select id="selectSpan" onchange='nomeDaFuncao(this)'>
  <option value="-1" selected>Nenhum</option>
  <option value="0">span1</option>
  <option value="1">span2</option>
  <option value="2">span3</option>
</select>

span1
span2
span3

Abrir Função onclick no Select option


What setup to use with a shotgun condenser microphone to record on a laptop?

Question: I've been using a USB headset and an external web camera both connected to a laptop to record educational videos. The way I record the videos is by looking directly at the web camera which is located on top of an external monitor connected to a laptop. A visual example can be seen in an example photo below.

I'd like to stop wearing a headset, and instead, record using a microphone. There are great USB microphones and Lavalier microphones out there such as the Rode SmartLav+, but I have an sE Electronics ProMic Laser microphone lying around not being used and I'd like to put it to use if possible instead of buying another microphone.
Would it be feasible to create a setup that would allow this microphone to be used for such a purpose and for those who know all the ins and outs of this topics, what accessories would you recommend getting? Can this microphone go on a swivel mount and be placed just next to the external web camera? Would anything else be needed?
Answer: There is no reason for that not to work, the best is always to try ;).
This microphone is fitted with 3.5mm Jack which you can normally fit straight in the microphone input of your computer. If your computer is fitted with a combined jack (4-rings, manage loudspeakers and a microphone through one jack) then you will need an adaptator.
This mic seems to be hypercadoid: it get nearly only the sound which is coming in front of it, so you need to place it just in front of you. With such a directional mic, it will be hard to get feedback but still: do not put your loudspeakers facing the mic (in your back).
Comment: I meant feedback, in term of this horrible squeaky noise you sometimes have in sonorized events. It does happen if the mic is catching the sound from the loudspeakers, creating a loop (https://en.wikipedia.org/wiki/Audio_feedback). This is annoying, but as your mic is really directional you should not have any problems ;).
Comment: The information you provided is helpful and interesting. I will position right next to the web camera. And I am curious, when you say it will be hard to get feedback, does feedback, in this case, mean the microphone catching other sounds? I am planning to run the microphone through the Nvidia RTX voice software to eliminate any noise from outside.


PHP add an item from an array

Question: Let's say i have this array:
$array = (1,2,4,5);

Now how do i add missing 3 in above array in the correct position index/key-wise?
Answer: Try:
array_splice($array, 2 /*offset*/, 0 /*length*/, 3 /*value*/);

Note that this will reorder the input array's keys from 0 to n-1.
(Edit: The return value is not used in this case.)
Comment: Yes, I already had corrected my answer. It returns the elements that were extracted, which is nothing in this case. It modifies the original input array by reference.
Comment: konforence, -1 turns into +1 ;)
Answer: array_merge(array_slice($array,0,2),array(3),array_slice($array,2))

Answer: Maybe I'm missing the complexity of your question, but doesn't the following give you what you want?
$array[] = 3;
sort($array);

Answer: Last but not least:

Append new stuff at the end of the array
Sort the array when you finally need it: asort()
Answer: function insertMissingIntoArray($values = array(), $valueIncrement = 1) {
    $lastValue = 0;
    foreach ($values as $key=>$val) {
        if ($key != 0) {
            if ($val != $lastValue + $valueIncrement) {
                array_splice($values, $key, 0, $val);
            }
            $lastValue = $val;
        }
    }
    return $values;
}

Used like this:
$values = array(1,2,4,5,7,9);
$fixedValues = insertMissingIntoArray($values, 1);
// $fixedValues now is (1,2,3,4,5,6,7,8,9)

Answer: function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}

usage:
array_insert($a,2,3);

Comment: You've actually rebuild `array_splice()`
Comment: That's the reason why there're so many array functions in PHP: writing your own is normally faster that reading the subtleties of built-in ones in the manual :)
Comment: wow, we learn something new everyday. thanks for the pointer @Harmen :) +1

PHP add an item from an array


JSON request payload with collection navigation properties?

Question: Does the OData JSON protocol (any version) support a request payload that contains a single entity (i.e. not batched) which contains a navigation property, where the navigation property contains a set of deferred entries?
I've studied the spec, and it looks like this is not defined, or at least not defined for versions 2 and 3...

126.96.36.199.2 Entity Set (as a JSON Array)
  "The syntax of the JSON representation of a collection of entities is defined by the grammar
  listed in this section. The grammar rule "entitySetInJson" defines the
  version 1.0 JSON representation of a collection of entities that may
  be used in both request and response payloads. The grammar rule
  "entitySetInJson2" defines the version 2.0 and the version 3.0 JSON
  representation of a collection of entities for response payloads only.
  There is no change between the version 1.0 and the version 2.0 or
  version 3.0 formats for use in request payloads that are defined by
  this specification."

and

220.127.116.11.10 Links
  The syntax of the JSON representation of a collection of links is
  defined by the grammar listed in this section. The grammar rule
  "linkCollJson" defines the version 1.0 JSON representation of a
  collection of links that can be used in both request and response
  payloads. The grammar rule "linkCollJson2" defines the version 2.0 and
  version 3.0 JSON representation of a collection of links for response
  payloads only. This specification does not define a version 2.0 or a
  version 3.0 JSON representation of a collection of links for use in
  request payloads.

To me this says that in OData V1 it is possible to upload an object with URI values ascribed to its collection navigation properties, and that in V2 and V3 that is not possible. The ATOM serialization does not call out this distinction.
Is my understanding correct, or have I missed something. And can anyone provide me some background on the reason for the changes described above?
Many thanks in advance.
Eric
Answer: The spec is a bit unclear at this point but what it means when it says that 2.0 and 3.0 versions are not specified for request payloads, it means that in request payloads you should use the 1.0 version of the payload since no new versions are defined.
It is possible to insert a new entity with expanded navigation property which contains a collection of entities. For example you can insert a new Category along with 5 Products which belong to that category.
The deferred links are also possible and what that does is to bind the new entity to the existing entities referenced by those links.
Note though, that WCF Data Services currently only supports this on inserts (POST), it doesn't support it on updates (PUT/MERGE/...).
Comment: Thanks Vitek. We are not using WCF but instead are using the MSFT OData Library within our own MVC framework. This allows us to support PUT/MERGE (& PATCH) as well. I did notice that if I select ODataVersion.V1 that the library parses a body containing a collection navigation property and for V2|V3 it fails. IOW the functionality appears to have been dropped from OData. I've been hesitant to take a dependency on the V1 behavior for two reasons. First, it seems that it would lose support of client frameworks over time and second, we may need to use V2|V3 features in a concurrent request.
Comment: I don't know which version of the library you use (try the latest CTP from October please). In any case there were changes to how the expanded navigation properties are read in request payloads especially in JSON (to align with the current WCF DS behavior). In any case it would be interesting to see what payload works in V1 and doesn't work in V2/V3.
Comment: We are using the Feb 11 2011 'alpha' version: http://odata.codeplex.com/releases/view/60787

This was an update to the Oct 27 2010 version (which we started with).
Comment: Is there a more recent version? If we don't provide version 1 for the data service version header the serializer will throw the following: "A node of type 'StartArray' was read from the JSON reader when trying to read the start of a feed with a feed wrapper object. A 'StartObject' node was expected."
Comment: Please try the latest CTP: http://blogs.msdn.com/b/astoriateam/archive/2011/10/13/announcing-wcf-data-services-oct-2011-ctp-for-net-4-and-silverlight-4.aspx
It might be fixed there, please let me know.
Comment: Thanks Vitek, looks like that did the trick. Is the source for the OData library going to be released again? We had a workaround for lack of timespan deserialization in JSON, and it looks like that's still not implemented (which is a shame since it's a one-liner).
Comment: It will be released after we release the RTM. The RTM will support the Edm.Time as well, I'm actually surprised that didn't make it into the CTP, oh well :-).
Comment: Thanks again.

BTW, Edm.Time is incorrectly described in the examples on this page: [link](http://www.odata.org/developers/protocols/overview#AbstractTypeSystem)

The examples show a format based on the time portion of Edm.DateTime but the spec (referenced in the same row) and the implementation say otherwise.


Find $\int\cosh^\frac{1}{2}u~du$ and/or $\int\frac{1}{\cosh^\frac{1}{2}\theta}~d\theta$

Question: I am trying to find a function of the form $y=f(x)$ such that the volume of the solid generated by the function between any two points around the $x$ axis is numerically equal to its length bewteen the same $2$ points. Using integrals, we can express this as an equation:
$$\pi\int y^2dx=\int\sqrt{\left(\frac{dy}{dx}\right)^2+1}\quad dx$$
ie
$$\pi y^2=\sqrt{\left(\frac{dy}{dx}\right)^2+1}$$
Rearranging, we get the differential equation
$$\frac{dy}{dx}=\sqrt{\pi^2y^4-1}$$
I tried to solve this first by separating the variables:
$$\int\frac{1}{\sqrt{\pi^2y^4-1}}~dy=x+c$$
So the next step is obviously to find
$$I=\int\frac{1}{\sqrt{\pi^2y^4-1}}~dy$$
Now here lies the problem. I tried to go about this using $2$ methods, each using different substitutions:
1.
Let $\pi y^2=\cosh u$:
$$\sinh u\frac{du}{dy}=2\pi y\implies dy=\frac{1}{2\pi y}\sinh{u}~ du$$
$$\implies I=\frac{1}{2\pi}\int\frac{1}{y}du=\frac{1}{2\sqrt{\pi^3}}\int\cosh^\frac{1}{2}u~du$$
How can I find the following?
$$\int\cosh^\frac{1}{2}u~du$$
2.
Using the substitutions $\pi y^2=p$ followed by $p=\cosh \theta$ gives us the result
$$I=\frac{1}{2\sqrt{\pi}}\int\frac{1}{\cosh^\frac{1}{2}\theta}~d\theta$$
Again, how I can I find the following?
$$\int\frac{1}{\cosh^\frac{1}{2}\theta}~d\theta$$
Thanks for your help.
Comment: I doubt there exists a closed-form solution; [Wolfram](https://www.wolframalpha.com/input/?i=integral+sqrt%28cosh%28x%29%29+dx) returns the result of your first being an elliptic integral.
Comment: @EeveeTrainer I do not consider elliptic integrals not closed-form, merely non-elementary.
Comment: @EeveeTrainer thanks, that's very interesting. So there is no (elementary) curve that satisfies my criteria.
Answer: As mentioned in comments, there is no solution with elementary functions. However, if you have Byrd and Friedman – the great big book of elliptic integrals and functions – this problem falls very easily.
The second integral $\int\cosh^{-1/2}\theta\,d\theta$ is the slightly easier one to tackle, for B&F 296.00 gives
$$\int\frac1{\sqrt{\cosh\theta}}\,d\theta=\sqrt2F\left(\cos^{-1}\frac1{\sqrt{\cosh\theta}},m=\frac12\right)+K$$
Substituting $\cosh\theta=\pi y^2$ gives
$$I=\frac1{\sqrt{2\pi}}F\left(\cos^{-1}\frac1{y\sqrt\pi},\frac12\right)+K$$
Comment: You've now answered both of the questions I've asked within the last 2 days :)


Get row values of CSV file having particular value using python

Question:
I have multiple
I want to get rows of Name.
I know how to get by index using dataframe but I want to get using row name as index might change.
like
(row=="Name" ) or (row== "name")

output be like :

Thanks in advance!
Comment: Please [don't post images of code, error messages, or other textual data.](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors)
Answer: If you want the name column name = df['Name']


Determining the Taylor series of $\sqrt{x}$ on $x_0 = 1$

Question: I've attempted to determine the Taylor series of $\sqrt{x}$, centered on $x_0 = 1$. Here's what I have thus far:
$f(1) = 1$
$f'(1) = \frac{1}{2\sqrt{x}} = \frac{1}{2}$
$f''(1) = -\frac{1}{4x^{3/2}} = -\frac{1}{4}$
$f^{(3)}(1) = \frac{3}{8x^{5/2}} = \frac{3}{8}$
$\vdots$
Trivially, the Taylor series is of the form:
$$1 + \frac{1}{2(1!)}(x-1) - \frac{1}{4(2!)}(x-1)^2 + \frac{3}{8(3!)}(x-1)^3 + \cdots$$
Notice that the denominators are of the form $2^n(n!)$. We also have an alternating term, $(-1)^{n+1}$
$$\to \sum_{k=0}^{\infty} = \frac{(-1)^{k+1}(x-1)^n}{2^n(n!)}$$
When I graph this, however, it doesn't seem to be a particularly nice approximation of $\sqrt{x}$ anywhere.
Comment: Your formula for the general term does not work for $n=3$ (and is not correct for higher $n$'s either). It should be $$
\frac{{\frac{1}{2}\left( {\frac{1}{2} - 1} \right) \cdots \left( {\frac{1}{2} - n + 1} \right)}}{{n!}}(x - 1)^n.$$ See https://en.wikipedia.org/wiki/Binomial_series
Comment: Dulicate https://math.stackexchange.com/questions/3937085/taylor-polynomial-for-sqrt-x/3937133#3937133 ?
Comment: Possible duplicate: [Taylor series of $\sqrt{1+x}$ using sigma notation](https://math.stackexchange.com/q/732540)
Answer: Let $f(x)=\sqrt x=x^{1/2}$. Then:

$f'(x)=\frac12x^{-1/2}$;
$f''(x)=-\frac1{2^2}x^{-3/2}$;
$f^{(3)}(x)=\frac{3}{2^3}x^{-5/2}$;
$f^{(4)}(x)=-\frac{3\times5}{2^4}x^{-5/2}$

and so on… So,$$n>1\implies f^{(n)}(1)=\frac{(-1)^{n-1}(2n-3)!!}{2^n}.$$
Answer: What do you worry about ? The four first terms that you computed do match the square root fairly closely.


"Standard" drum notation alternatives

Question: For the purpose of playing live, working through ("popular") songs involving verse, chorus, bridge, intro, outro, etc., is there a standard notation that drummers use to help them know what to play, and when?
Note: I want to exclude staff music from this discussion. I am given a piece of paper with the lyrics printed out, and with chords written above. I am comfortable adding the time signature and tempo (q = 120bpm or what have you), but is there a standard way that professional drummers would "markup" their chord charts?
I would like to notate dynamics such as:

when to come in
when to lay out
who starts the song (me clicking in, guitar riff, ...?)
what volume I'm playing
what beat am I using (e.g. Hats, ride, Tom, etc.)
builds, breaks, etc.

Admittedly, staff music would be better, but it is not practical, especially considering that we do not always stick to a predetermined arrangement for the song.
Hopefully there's a simple answer like "yes, The Chaz. It's called the _ method"
Thanks.
Comment: No, The Chaz. There ain't. The premise that you don't always stick to a predetermined arrangement doesn't support the conclusion that you need an alternative to standard musical notation: by definition, any 'alternative method' will reflect a predetermined arrangement. As for 'practical', a beer coaster, standard musical notation of key sections, and a decent memory constitute a real-world practical solution.
Comment: Wikipedia has articles on "Percussion Notation" and "Drum tablature"
Comment: @Red: "Percussion Notation" is exactly what I am not looking for. "Drum tablature" is not a good fit either. It would take me ten (?) minutes to transcribe the simplest kick snare beat...
Answer: Staff music, and indeed pretty much any system of musical or rhythmic notation, is just a means to an end. You are free to invent any system you want, borrowing symbols from any discipline or making them up as you go. As long as they have meaning to you, that's the most important thing.
Since you don't want sheet music (understandable, given that sheet music, even a lead chart, can require several pages per song to convey all the information it provides), you will have to do at least some of this invention on your own; other than standard notation and drum tablature, there isn't any other standardized percussion notation, like there is for certain regions/genres for melodic lines and chord structures (like chord/lyric charts, Nashville Number System, etc etc).
Here's one system a drummer I worked with uses: For well-known rock/blues patterns he simply writes the name of the pattern shorthand, or builds it from the kick up in a way that makes sense. Example: "K1&3-S24-HC8" is "Kick on 1 and 3 with a third hit on the 'and' before 3, snare on 2 and 4, closed-hat 'clicks' on eighth notes"; pretty much your standard rock pattern. "FOF-S24-HC8O68" is "Four-on the floor kick, snare on 2 and 4, closed high-hat clicks on 8th notes, open the hat on the 6th and 8th clicks of the bar".
For fills, turns and complex lines:

Draw two lines across the page. Top line is your "hand" line. Bottom line is your "foot" line. You may choose to add an extra line or two to differentiate hand and foot; this can make it easier to read but requires more space and can be harder to make changes.
Divide this "staff" into as many bars as you need for a pattern.
Write the beats of each bar above the "staff", leaving space in between the beats and staff for additional marks. You may subdivide as necessary.
Now, pick or invent some symbols that are easy to draw, easy to tell apart, and have meaning to you, and assign each symbol to a particular instrument or manipulation possible with the kit. Things to think about:

Most drums/cymbals have pretty much one way to hit them and so will only need one symbol. You can make special notations about exactly how to hit either (center/edge/rim, bell/center/edge) with a variation of the symbol or by making notes above the line.
For toms, consider using differentiable but related symbols common to that "family". Similar for cymbals.
For the snare, you can either notate how to hit it (rim tap, off-center hit, center hit, rimshot) above the hits, or use different symbols.

Now, while listening, simply mark down the rhythms of each instrument by writing that symbol on the appropriate line, on the appropriate beat or subdivision. You can build it up in layers or, if it's easy to pick out, just write it all down left to right. If many things happen on one beat or subdivision, you can write them vertically above and below the line
If the rhythm isn't obvious, or a lot of hits come together, you can notate the rhythm in pseudo-standard notation above the line, or you can make additional notes of any type you choose.
In patterns where which hand (or foot) makes which hit are important, they can be notated easily with patterns of L and R written over each hit as necessary.
Rolls get a wavy line after the initial "hit"; you can increase or decrease the height of the line to indicate crescendo and decrescendo. If the roll's hits must be at specified intervals (16ths, triplet 16ths, 32nds) that can be written above.

Keep in mind that all of this notation is just a way to quickly take down a non-standard line or pattern, to remember said pattern for later practice. Most of these will be one or two bars; the basic pattern for a section should either be easy to remember or should be written in some acceptable shorthand, and variations of starting and stopping a particular layered rhythm can just be scribbled in next to the words where you should start it.  You should never be trying to "sight-read" based on this, nor expect anyone else to do so.
Answer: Unfortunately, the way professional drummers do this is exactly what you have said you don't like.
As @RedGritty said - percussion notation and drum tablature are the simplest ways to do this. Typically in rock bands it is more likely to be tablature, and in orchestras percussion notation as these then fit with the rest of the music.
This then gives you when to come in, notation for fills, crescendos and builds etc., and for things like who starts the song, you would just write that at the start as a comment, same as other staff notation.
Comment: Thanks for the answer. Are you a drummer, by chance? If so, what would you do in my situation (chord sheets)?
Comment: No - I would love to be able to drum, but adding feet into the mix screws up my coordination. Luckily my middle daughter seems to be a natural. The drum scores I have seen are all from session work (not even with my own band as we tend to play and record, rather than notate our works.)
Answer: Yes, an interesting question. Technically, no, there is no such standand, unfortunately. It is clear that standard notation does not work particularly well for drummers, out of the box. Hence, long time ago, I also invented a system that worked for me. It goes something like this:

where each mark has a meaning (time, fill, not playing, bass only, x-stick). They can also be combined within one bar (i.e. accents, pause...).
This approach offers

visibility
rhythm

This is all nice and easy to see in one glance but there are problems, just like with any other system.
There are other methods, that I'm collecting at my notation page. The "sketch sheet" method aligns more with what I'm trying now - currently I'm trying to use real sheets and just put a bunch of repeat marks to highlight only the important information. I.e.

This is a simple tune but it demonstrates the method. Note that this is a bastardized version, where I'm using multi-bar rest marks to indicate repetition, not the actual marks, which would look like this:

A multi-bar repetition sign would help here to avoid the clutter.
I'm lately leaning toward this method as it has the following advantages:

it is a standard
can be played in a music notation software (i.e. MuseScore) to remind oneself of complex fills or rhythms easily
it is the real notation, meaning there are marks for everything you'd want to put on there (dynamics, tempo, measure...)
it is minimalistic enough to fit on one page (great for tablets)

The time will show how this will work out. The chord sheets you get from the authors are next to useless to me and I've found no good way to adapt them. I need the bar and rhythm marks.
Edit 2020-11-05: Well, after two years I have to admit that I'm using the standard notation exclusively. All the tunes I play fit onto a cover page and are easy to read on a tablet. Depending on the song complexity, this can be more or less cluttered but all the relevant marks are there. Just skip the ones you don't need.

"Standard" drum notation alternatives


Graph of smooth functions

Question: It's well known that if a function $f: \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}$ ( possible multivariable) is smooth, then it's graph $((x,y) \in \mathbb{R}^{n+m}: y = f(x))$ is a smooth manifold. This follows from a simple usage of inverse function theorem.
My question is if the reverse is true, i.e, if the graph is a smooth manifold, does it imply that the map is smooth in itself?
Answer: No. Consider the graph of $y=x^{1/3}$, the manifold is smooth but the function is not. Admittedly there does exist a smooth function for this manifold, but I'm assuming that you've already partitioned the dimensions into $y$ and $x$ prior to constructing the function.

Graph of smooth functions


jQuery UI selection -- help with inefficiencies

Question: I have a calendar, and the user should be able to select dates (they are basically table cells).  The problem is that jQuery UI support for selection is a bit sketchy.  In particular, if the user uses the CTRL key to select or unselect dates, I can't seem to get a total list of selected elements very easily upon the selection "stop" event.  Here is what I am currently doing, but it seems very inefficient:
<code>global.selected = [];

$('#calendar').selectable({filter: 'td',

selected: function(event, ui)
    {
    for (var a = 0, id = +ui.selected.children[0].id, found = false; a < global.selected.length; a++)
        {
        if (global.selected[a] == id)
            {
            found = true;
            break;
            }
        }
    !found && global.selected.push(id);
    },

unselected: function(event, ui)
    {
    for (var a = 0, id = +ui.unselected.children[0].id; a < global.selected.length; a++)
        {
        if (global.selected[a] == id)
            {
            global.selected.splice(a, 1);
            break;
            }
        }
    },

stop: function(event, ui)
    {
    console.log(global.selected);
    }
}
</code>
Answer: I'm brand new to jQuery, but I'd approach it this way and avoid the global all together.
<code>$('#calendar').selectable({
    filter: 'td',
    stop: function(event, ui) {
        var selected = $.map($('#calendar > tbody > tr > td.ui-selected'),function(el) {
            return el.id;
        });
        console.log(selected);
    }
});
</code>


Why does node_access_view_all_nodes() return true for anonymous users?

Question: On a Vanilla Drupal install (tested on D8 and D9), this will print "1":
drush eval 'echo node_access_view_all_nodes() . PHP_EOL;'

Stepping through the code reveals that it happens because there is a default grant for ALL nodes (nid = 0) for anonymous users in the node_access table (as far as I can see).
My question is about the rationale of behind this. The function description states:

Determines whether the user has a global viewing grant for all nodes.

Why would the anonymous user have the permission to view all nodes by default? Why does this not correspond to what I see when trying to access various nodes as the anonymous user? Some nodes (e.g. unpublished nodes or anything blocked by a node_access hook) do return 403 when trying to load them as the anonymous user, so it obviously does not have access to all nodes. Is there another level of access checking hidden somewhere?
Comment: I just looked through the code for the function (https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_access_view_all_nodes/8.8.x). It does not contain any rules about anonymous users. It's a function that acts dynamically based on hooks implemented (or not) by the modules on your system. We cannot know the modules implemented on your system, so it's impossible to answer this question.
Comment: I will rephrase the question!
Answer: whenever drupal needs to check if a current user has the right or not to see a specific node it passes through this process :
1. check if current user bypass node access
In determining access rights for a node, \Drupal\node\NodeAccessControlHandler first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. user 1 (administrator) will always pass this check.

2.check Hook_node_access implementations
Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly forbid, or ignore the access request. If at least one module says to forbid the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted,
in the Example bellow whenever any user(except admin) tries to view a node we will check if field_prevent_webmaster is checked the user will get access forbidden message.
/**
 * Implements hook_ENTITY_TYPE_access
 */
function modul_name_node_access(\Drupal\node\NodeInterface $node, $operation, AccountInterface $account) {

  // 1.limit the action according to the  operation performed on the requested entity
  switch($operation){
    case 'view': // when a user visit a node page ex : /node/52

      // 2.limit the current operation according to the current account information
      if( in_array('webmaster',$account->getRoles()) ){
        //3. then further limit the current operation according to the current requested node entity field
        // ex : if field_prevent_webmaster is checked prevent a user form
        // viewing the node through the /node/{id}
        if($node->hasField('field_prevent_webmaster') ) {
          if ($node->field_prevent_webmaster->value == TRUE) {
            return AccessResult::forbidden(); // send Access denied message to the client
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed(); // send Access denied message to the client
          }
        }

      }
      break;

    case 'delete':// in /admin/content page u won't find the 'delete' button
      if( in_array('webmaster',$account->getRoles()) ){

        if($node->hasField('field_prevent_webmaster') ){
          if(  $node->field_prevent_webmaster->value == true){
            return AccessResult::forbidden();
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed(); // send Access denied message to the client
          }
        }

      }
      break;

    case 'update': // in /admin/content page u won't find the 'update' button
      if( in_array('webmaster',$account->getRoles()) ){

        if( $node->hasField('field_prevent_webmaster')){
          if(  $node->field_prevent_webmaster->value == true){
            return AccessResult::forbidden();
          }
        }

        if($node->hasField('field_allow_webmaster') ) {
          if ($node->field_allow_webmaster->value == TRUE) {
            return AccessResult::allowed();
          }
        }

      }
      break;
  }
}

3.Getting permissions from node_access table
If all modules ignore the access request, then the node_access table is used to determine access and this more complicated then the previous 2 so we need to understand :
the node access table

nid: The node id that will be affected by this permission line.
gid(like user): the grant id, is simply a way to associate a user with a node.
realm(like user type): It can be pretty much anything you want to consider it as a user type that groups a set of grant ids (gid).
grant_view: Boolean indicating whether a user with the realm/grant pair can view this node.
grant_update: Boolean indicating whether a user with the realm/grant pair can edit this node.
grant_delete: Boolean indicating whether a user with the realm/grant pair can delete this node.

Example according to the node_access table bellow:

the user that have gid=2 and realm=node_atuthor, he can view and update the node 52.
the user that have gid=2 but a realm=node_super_user, he can view , update and delete the node 52.

Hook_node_access_records()
when a node is saved this hook will be executed, which enables us to fill the node_access table with the permission privileges that have already explore in the previous step.
/**
 * Implements HOOK_node_access_records
 **/
function entity_access_node_access_records(\Drupal\node\NodeInterface $node) {
   $grants = [];
   if( $node->isPublished() == TRUE) {
     $grants = [
       [
         'realm' => 'node_author',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 1,
         'grant_delete' => 0,
         'priority' => 0,
       ],
       [
         'realm' => 'node_viewer',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 0,
         'grant_delete' => 0,
         'priority' => 0,
       ],
       [
         'realm' => 'node_super_user',
         'gid' => $node->getOwnerId(),
         'grant_view' => 1,
         'grant_update' => 1,
         'grant_delete' => 1,
         'priority' => 0,
       ]
     ];
   }
  return $grants;
}

Hook_node_grants()
is called every time access to a node is requested to determine access and this is what is used to check the node_access table and decide who what nodes the current user can see:
/**
 * Implements Implements HOOK_node_grants
 */
function entity_access_node_grants(AccountInterface $account, $op) {

  // Allow the user that have 'see_omar_is_nodes' permission and that is also not omar :
  if ($account->hasPermission('see_omar_is_nodes') && $account->id() != 3){
      // to get This gid realm grants ( to see his content + Omar is content)
      $grants = [
        'node_super_user' => [$account->id()],
        'node_viewer' => [3]
      ] ;
  }

 // else if the user acount id =3 (omar)
  else if ($account->id() == 3){
    // get This gid realm grants of current user
    $grants =[
      'node_author' => [3]
    ] ;
  }

Comment: Great outline of the process!
Comment: @Jaypan thank u for the appreciation
Answer: The node grants system allows for SQL queries to select multiple nodes, limiting them according to a user's access level. Without the grants system, when creating lists of nodes, all nodes would have to be first loaded with an SQl query, then looped through in PHP with an access checker. This is very inefficient, and also makes it nearly impossible to have any kind of efficient method of pagination. Node grants allow for loading nodes with an included permission check as part of the SQL query.
When any module implements node grants, nodes become blacklisted, and permission to perform actions on them needs to be created through a grant. If a node grant exists, permission is given.
However, node grants are added to a system as part of modules. It's very possible that a system will not have any modules that implement any node grants. If I recall correctly, that is the case on a vanilla install, and I believe your comments support that.
With no node grants system, there is no system by which to restrict access to nodes in SQL queries, and therefore it means all nodes are accessible in SQL queries.
node_access_view_all_nodes() is a helper function that determines if an access query even needs to be made, bypassing the access part of the SQL query when no modules implement a grants system.

Some nodes (e.g. unpublished nodes or anything blocked by a
  node_access hook) do return 403 when trying to load them as the
  anonymous user, so it obviously does not have access to all nodes. Is
  there another level of access checking hidden somewhere?

Once nodes have been loaded, each node passes through a different access control system in PHP; hook_node_access(). That system of access control is independent from node grants. Node access is a PHP process that determines whether an operation (view, update, delete) can be performed on a loaded node. Node grants are a system that is used when querying nodes, to allow for SQL queries that implement access controls, without requiring PHP.
Comment: Good answer (+1) but not 100% comprehensive. From what I have read since asking the question, the `node_access` table ignores the published state by default. When you install a module that implements grants, the default grant for all nodes disappears as soon as you `rebuild permissions`. Then `node_access_view_all_nodes` starts to return `0` for the anonymous user. Feel free to include this in your answer. Otherwise I'll write an additional answer with some examples later.
Comment: Also: The default behaviour is documented at https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/group/node_access/8.8.x ("Tagging a query with "node_access" does not check the published/unpublished status of nodes") but it doesn't mention that this behaviour changes once you have a module implementing grants.


Identify chord proggression

Question: Hi Im new to the site so please inform me if I am doing anything wrong.
So,4 arpeggiated chords all sixteenth notes
The arpeggio goes as follows:
F-G-G#-C-D#-G-G#-C
D-F-G-B -D-F-G-B
C#-F-G-A# -C#-F-G-A#
C-F-G-A#  C-G-A#-C
My speculations are that it is either an
Fm-G7-Gm-Cm   (iv-V7-v-i)
a somewhat classic chord progression leading to the tonic
or
Cm-Bmadd4-BbM-A#Madd2
Something like a descending kind of progression wich Im not aware of...
Or maybe a mix of these two?How you guys would analyse this and what is its harmonic function?Thanks in advance.Sorry for bad english!
Answer: Some of the enharmonics are confusing you, I think.
F-G-G#-C-D# is better understood with Ab and Eb instead of G# and D#. This is just an F9 chord.
D-F-G-B is a G7 chord.
C#-F-G-A# is also better understood with Db and Bb; this is a G7b5 (aka G half-diminished seventh).
C-F-G-A#, once again should be conceptualized with a Bb instead of an A#. This is a C7sus4.
Note that I'm not accounting for inversions, but definitely pay attention to the descending chromatic motion in (what I am assuming is) the lowest voice.
Comment: No arguments about the enharmonics, but, given that it _appears_ that G is held as a pedal through the last three chords, then if the D♭ of the third chord is in the bass, you've got a fairly standard Phrygian ♭vii6 as a passing harmony between G7 and C7. I say "appears" advisedly - it seems persistent enough to be a pedal note, but it would be nice to see the score to see if the Gs appear at the same octave. If so, even arpeggiated they will act as a pedal.
Comment: I agree 100%; it's always tough to analyze harmonies without a larger context.
Comment: That first chord would be an F minor 9th, not an F9.  Also the second chord includes a #9.

Identify chord proggression


Find the degree of the polynomial

Question: Let $\alpha,\beta $ be two complex numbers with $\beta \neq 0$ and $f(z)$ be a polynomial function on $\Bbb C$ such that $f(z)=\alpha $ whenever $z^5=\beta $.What can you say about degree of $f(z)$?
My effort:
 I am unable to find the number of roots of $z^5-\beta =0$ .As $\Bbb C$ is algebraically closed so any polynomial would split and hence $z^5-\beta=0$ has exactly $5$ roots counting multiplicity.
So $f-\alpha $ has degree atleast $5$ if $z^5-\beta =0$ has distinct $5$ roots
Is it correct?I am unable to provide a specific answer.
Please give some hint.
Answer:
$z^5 − \beta=0$ has exactly 5 roots counting multiplicity

If it had roots with multiplicity $\gt 1$ then those would be roots of its derivative as well, but $(z^5 - \beta)' = 5 z^4$ which has $0$ as its only root, and $0$ is not a root of $z^5 - \beta$ since $\beta \ne 0$. Therefore $z^5 - \beta = 0$ must have $5$ distinct roots.

So $f−\alpha$ has degree at least 5

And, since $f(z) = z^5 - \beta + \alpha$ satisfies the requirements, degree $5$ is the actual lower bound.
Answer: There are exactly $n$ distinct complex roots to the equation $z^n-1=0$. They are given by $\cos \frac{2\pi k}n +i\sin \frac{2\pi k}n$, for $k=0,1,2,\ldots, n-1$.
Now you can use Lagrange interpolation formula to construct a polynomial that should take specific values at given points.

Find the degree of the polynomial


PHP merge array on nulls

Question: I have 2 * array and I want to merge them, but each of theme have some NULL rows.
$a = array(
    'a' => NULL,
    'b' => 1,
    'c' => 1
);

$b = array(
    'a' => 1,
    'b' => NULL,
    'c' => 1
);

So, code:
$c = array_merge($a,$b);

Will give $c:
array {
  'a'=> 1
  'b'=> NULL
  'c'=>1
}

Is there build in or simple way to do margin ($a,$b) like following, but now $a is overwritten for every same index from $b. I want $b to be overwritten by $a index if $b index is null - in example $b['b'] should be overwritten from $a
All NULL rows should be filled if possible.
Answer: I think you can use array_filter function to remove null values in both array and then merge them
$a = array(
    'a' => NULL,
    'b' => 1,
    'c' => 1
);

$b = array(
    'a' => 1,
    'b' => NULL,
    'c' => 1
);

$b  = array_filter($b);
$a  = array_filter($a);
$c = array_merge($a, $b);
var_dump($c);

This will output
array(3) {
  ["b"]=> int(1)
  ["c"]=> int(1)
  ["a"]=> int(1)
}

LIVE SAMPLE
As side note i would add that using array_filter without second parameter will end up in deleting all NULL values as well as EMPTY array etc. If you want to only remove NULL values so you will need to use array_filter($yourarray, 'strlen');
EDITED
If you want to preserve NULL if both arrays have it with the same key and supposing that both arrays have same number of keys/values, then you will need to loop inside your array and build a new array preserving NULL where you need
$a = array(
    'a' => NULL,
    'b' => 1,
    'c' => 1,
    'd' => NULL
);

$b = array(
    'a' => 1,
    'b' => NULL,
    'c' => 1,
    'd' => NULL,
);

$c = array();
foreach($a as $key => $val)
{
    if($key == NULL && $b[$key] == NULL)
    {
        $c[$key] = $val;
    } else if($key != NULL && $b[$key] == NULL) {
        $c[$key]= $val;
    } else if($key != NULL && $b[$key] != NULL) {
        $c[$key]= $b[$key];
    } else {
        $c[$key]= $b[$key];
    }
}
var_dump($c);

This will output
array (size=4)
  'a' => int 1
  'b' => int 1
  'c' => int 1
  'd' => NULL

LIVE SAMPLE
Comment: basing on your solution I've tried this - seems to be working and more simple http://phpfiddle.org/lite/code/rqz-sd4
Comment: What if there will be 'd' index null on only 1 of arrays. I mean overwrtie 'nulls' if possible, if not they should stay. In this case ALL nulls will be removed.
Comment: @Kluska000 i've updated my answer fitting your request, please check it
Comment: @Kluska000 this is nice if it does what you need, i'm glad i helped you. If you feel answer was correct then don't forget to accept it to help people in the future with similar problems.
Answer: I would do it with a simple one liner like this:
$c = array_filter($b) + array_filter($a) + array_fill_keys(array_keys($b),null);

This would preserve all keys and values of $b except where falsey in which case they will be either replaced with values from $a or as a last resort replaced with null.
When merging arrays with the + operator the order in which they appear from left to right equates to the precedence.  So the leftmost position will hold it's value unless the key does not exist.
You can also reverse the order and use array_merge(), but for me it's harder on the eyes:
$c = array_merge(array_fill_keys(array_keys($b),null) + array_filter($a) + array_filter($b));

Answer: None of these answers address merging two arrays that may have different keys, which is what lead me to this SO post. It happens to actually be pretty straight forward fortunately:
function arrayMergeIfNotNull($arr1, $arr2) {
    foreach($arr2 as $key => $val) {
        $is_set_and_not_null = isset($arr1[$key]);
        if ( $val == NULL && $is_set_and_not_null ) {
            $arr2[$key] = $arr1[$key];
        }
    }
    return array_merge($arr1, $arr2);
}

Now, merging these two arrays:
$a = array('a' => NULL, 'b' => 1, 'c' => 1, 'd' => NULL, 'z' => 'zebra');
$b = array('a' => 1, 'b' => NULL, 'c' => 1, 'd' => NULL, 'f' => 'frank');

with:
var_dump(arrayMergeIfNotNull($a, $b));

will produce:
array (size=6)
  'a' => int 1
  'b' => int 1
  'c' => int 1
  'd' => NULL
  'z' => 'zebra'
  'f' => 'frank'

Note this answer also solves the problem of two arrays with the same keys.
Answer: then you have to pass $b as the first parameter
$c = array_merge($b,$a);
you can use this function
function mergeArray($array1, $array2)
{
    $result = array();

    foreach ($array1 as $key=>$value)
    {
        $result[$key] = $value;
    }

    foreach ($array2 as $key=>$value)
    {
        if (!isset($result[$key] || $result[$key] == null)
        {
            $result[$key] = $value;
        }
    }

    return $result;
}

Comment: In this case not null row of $b will be overwritten by null row from $a. All NULL rows should be filled if possible.
Comment: function mergeArray($array1, $array2)
{
    $result = array();

    foreach ($array1 as $key=>$value)
    {
        $result[$key] = $value;
    }

    foreach ($array2 as $key=>$value)
    {
        if ($result[$key] == null)
        {
        }
    }
}
Answer: If you need to preserve keys that have a value of NULL in both arrays, you can use a custom function that ignores those entries from the second array if (and only if) there is a corresponding non-NULL entry in the first array. It would look like this:
function arrayMergeIgnoringNull($arr1, $arr2) {
    $new2 = array();
    forEach ($arr2 as $key => $value) {
        if (($value !== NULL) || !isSet($arr1[$key])) {
           $new2[$key] = $value;
        }
    }
    return array_merge($arr1, $new2);
}
$c = arrayMergeIgnoringNull($a, $b);

See, also, this short demo.

PHP merge array on nulls


Smooth ride with the subway (Optimization with Lagrange multiplier)

Question: I have following problem and im struggeling with it.
I need to find be a twice differentiable function $ h:[0,1] \rightarrow \mathbb{R}$
which fullfills the conditions:

$h(0)=0$ , $h(1)=1$ (the position of the subway train)
$h'(0)=h'(1)=0$ (the velocity)
$\vert h''(t)\vert \leq c\in \mathbb{R}^+$

Such that the cost function $U(h):=\int_{0}^{1}(h''(t))^2 dt$ is minimal.(Also: for which c exists a solution at all?)
I tried with the Lagrange-Ansatz, but i fail already there, as i am not sure how to express the second condition in the lagrange equation.(since the function is "only" twice differentiable so the i  cannot express the first derivative as an integral with the second derivative, can I?), what i got so far:
$\Lambda(h,\lambda_1,\lambda_2)=U(h)+\lambda_1(\int_{0}^1h'(t)dt-1)+ \lambda_2(...)$.
Im glad for every shred of help. Thanks in advance.
Answer: Put $f(t)=h'(t)$. Then you want to minimize the functional
$$\int_0^1 L(t,f(t),f'(t))\,dt\enspace\enspace (1)$$
where $L(t,f,f')=(f')^2$. The corresponding Euler-Lagrange equation is:
$$\frac{\partial L}{\partial f}-\frac{d}{dt}\frac{\partial L}{\partial f'}=0$$
that is:
$$\frac{d}{dt}(2f')=0$$
which implies $f''=0$. It follows that $f$ is a linear function, say, $f(t)=at+b$. Since $f=h'$, we deduce that
$$h(t)=\frac{1}{2}at^2+bt+d$$
Correction
Unfortunately, there does not exist a polynomial of order $2$ satisfying the initial conditions. Since the Euler-Lagrance equation must be satisfied by a stationary function for the functional $(1)$, and since a twice-differentiable function has second derivative identically zero if and only if it is linear, the argument above effectively proves that the general solution must be a polynomial of degree $2$. It follows that your problem has no solution with the initial conditions given.
Comment: Hi thank you for your insights. Sadly the solution does violate the second condition. I think, that the function im looking for should be at least twice differentiable , but not necessarily just twice differentiable...
Comment: You're absolutely right! I corrected my answer, as I now believe there is NO solution satisfying the required initial condition, no matter how many derivatives you are willing to grant the solution.
Comment: You did not take care of the constraint $\int_0^1 f(t)\>dt=1$ in your Lagrangian setup.
Answer: If you allow discontinuities of $h''$ you can argue as follows: By symmetry it is sufficient to solve the problem on $\bigl[0,{1\over2}\bigr]$ with conditions
$$h(0)=h'(0)=0,\quad h\left({1\over2}\right)={1\over2},\quad 0\leq a(t):=h''(t)\leq c\ .$$
One has
$$h'(t)=\int_0^t a(\tau)\>d\tau,\quad h(t)=\int_0^ta(\tau)(t-\tau)\>d\tau\ ,$$
so that we have to minimize $\int_0^{1/2}a^2(t)\>dt$ under the conditions
$$0\leq a(t)\leq c,\quad \int_0^{1/2}a(t)\left({1\over2}-t\right)\>dt={1\over2}\ .$$
This easily implies $c\geq4$ as a necessary condition, whereby in the case $c=4$ the train has to be maximally accelerated during the whole interval $\bigl[0,{1\over2}\bigr]$.
Forgetting about the condition $a(t)\leq c$ for the moment we have to minimize the $L^2$-norm of $a$ under the condition $\langle a,u\rangle={1\over2}$ for a given vector $u$. The minimum is attained for $a_*=\lambda u$ for a certain scalar $\lambda$. Calculation gives
$$a_*(t)=12\left({1\over2}-t\right)\ ,\tag{1}$$
so that $a_*(0)=6$. We therefore can say the following: If $c\geq6$ then $(1)$ is the solution to the problem for the interval $\bigl[0,{1\over2}\bigr]$, and a suitable reflection will take care of the interval $\bigl[{1\over2},1\bigr]$. Since $a_*\bigl({1\over2}\bigr)=0$ the extended $a_*$ will even be continuous on $[0,1]$.
If $4\leq c<6$ the condition $a(t)\leq c$ really enters the picture, and I don't know how to deal with that.
Comment: Thank you professor Blatter, your hints and insight helped a lot and i think  have a solution now (updated my anwsers).
Answer: The post from Christian Blatter and the methods for finding the catenoid-equation gave some new ideas to tackle the problem:
First:
$$h(1)-h(0)=\int\limits_0^1h'(t)dt=\int\limits_0^1\int\limits_0^t h'(s) ds\ dt = \int\limits_0^1\int\limits_s^1h'(s)dt\ ds=\int\limits_0^1h'(s)(1-s)ds=1$$
Second (Ignoring that $h'(t)$ might not be continously differentiable):
$$h'(1)-h'(0)=\int\limits_0^1 h''(t)dt=\int\limits_0^1\int\limits_0^th''(s)ds \ dt=\int\limits_0^1\int\limits_s^1h''(s)dt\ ds=\int\limits_0^1h''(s)(1-s)ds=0$$
Henze our Langrange equation looks like this:
$$\Lambda(h'',h',\lambda_1,\lambda_2)=\int\limits_0^1(h''(s))^2ds+\lambda_1(\int\limits_0^1h'(s)(1-s)ds-1)+\lambda_2(\int\limits_0^1h''(s)(1-s)ds)$$
and therefore:
$$\frac{\partial}{\partial s}\frac{\partial \Lambda}{\partial h''}-\frac{\partial \Lambda}{\partial h'}=0 \Leftrightarrow 2 \frac{d^3 h}{ds^3}-\lambda_1-\lambda_2(1-s)=0 \Leftrightarrow \frac{d^3 h}{ds^3}=\frac{1}{2}(\lambda_1+\lambda_2(1-s))$$
Integration gives us:
$$h(x)=\frac{-\lambda_2}{48}x^4+\frac{(\lambda_1-\lambda_2)}{12}x^3+\frac{c_1}{2}x^2+c_2x+c_3; \ c_i\in \mathbb{R}$$
With the initial conditions one gets:

$c_2=c_3=0$
$\lambda_1=\frac{-1}{2}(48+\lambda_2)$
$c_1=\frac{-1}{12}(3\lambda_1+2\lambda_2)=6-\frac{\lambda_2}{24}$

This delivers:
$$h_{\lambda_2}(x)=\frac{-\lambda_2}{48}x^4+\frac{1}{12}x^3(\lambda_2-\frac{1}{2}(48+\lambda_2))+\frac{1}{24}x^2(\frac{3}{2}(48+\lambda_2)-2\lambda_2)$$
So i got an equation which still contains a unknown variable $\lambda_2$.
Calculating the integral $\int_{0}^{1} (h_{\lambda_2}'')^2 dx=12+\frac{\lambda_2^2}{2880}$. Now we can differentiate for $\lambda_2$ and set it equal to $0$ which gives us:
$\frac{\lambda_2}{1440}=0 \Leftrightarrow \lambda_2=0$
Hence: $h(t)=3 t^2 - 2 t^3$
(and therefore a Solution exists only if $c\geq 6$ otherwise the train will overshoot or won't arrive at all)
I welcome any feedback and i thank uniquesolution and Christian Blatter for their answers.


Is there a way to switch off wpf design surface in Visual Studio 2008?

Question: I would like to know if there is a way to simply turn of the WPF design surface in Visual Studio 2008. I would like to have the xaml editor, but not the design surface as it slows down  the IDE, when I try to open a XAML file. For my workflow having only the source files for xaml would be a better fit as I am doing all visuals in Blend.
Answer: Tools->Text Editor->XAML->Miscellaneous  uncheck Always open documents in full XAML view
alt text http://www.dolittle.com/blogs/einar/WindowsLiveWriter/DisableXAMLdesignerinVisualStudio2008_118F4/image_2.png
The comment below informs of a catch when using this checkbox, that is it only affects files that have not been opened before. A solution from the link to the Microsoft Connect issue in the comment states that

If you really wish to reset the
  open/close behavior for all XAML files
  in your project, you can achieve this
  by closing Visual Studio, then
  locating the SUO file adjacent to your
  SLN file and deleting or renaming it,
  then re-opening Visual Studio. When
  you re-open your solution an new SUO
  will be created and all files will be
  treated as "new". Please note this
  will also remove any other
  solution-specific IDE behavior for
  your solution.
Comment: A small node: This Option only works for files that haven´t been opened before. Visual Studio stores the last state a file was opened in and will use the state on re-open. See https://connect.microsoft.com/VisualStudio/feedback/details/549873/option-always-open-documents-in-full-xaml-view-does-not-work-correctly
Answer: You should be able to right-click the .xaml file and select "Open With..." then select "Source Code (Text) Editor" (optionally clicking "Set as Default" to make it the default). This will open the file in the plain XML editor (you still get syntax highlighting and IntelliSense, too).


Non-differentiability of $\max \limits_i f(i)$

Question: How can we formally show that $\max$ and $\min$ functions are non-differentiable?
In particular, I was looking at the L1 matrix norm defined as:
$\|A\|_1 = \max \limits_{i \le j \le n} \sum \limits_{i=1}^{m} |a_{ij}|$
Surely, because of the absolute values in the definition it won't be differentiable. However, in general, how could we should non-differentiability of $\max \limits_i f(i)$?
Answer: Note that as long as the maximum exists your function is identical to a constant function on that interval. That is suppose;
$ f: \Bbb R \to \Bbb R $ and given an interval $I$ (due to some bound on $f$) $ \max \{f(x) \ | \ x \in I\} $ exists and is equal to $c$. So the function we wish to differentiate is in fact the maximum function. So all we wish to do is to calculate teh derivative of
$ f: I \to \Bbb R $ given by $f(x) = c$ which is nothing but a constant and is sure as the sun and moon differentiable on the interval $I$. But again the maximum or the supremum as some wish to call it must exist.

This was a discussion on real functions. And I believe you are talking about differentiating on $\Bbb R$, the definition of which (including limits) does not accept matrices in its domain. Unless of course you are talking about something I have not learnt about. Hope I helped.
Comment: Good point about max being equivalent to a constant function. Thanks!


How to reduce size of checkbox in windows phone 7?

Question: Hi iam new to windows phone 7.
Iam using checkbox controls in my app.
But the size of checkbox control is not reducing.
I changed height, width, background properties all, but no result.
In my screen iam going to use 30 check boxes without scroll panels.
Thats why iam going to reduce their size.
plz help me
Comment: You might want to rethink your design - the check boxes are that size to be usable in a touch environment; if you were successful in resizing them, it might not be usable.
Comment: ofcourse, you are right. but we need to achieve it as a developer, how can we do it.
Comment: You'll make it easier to help you if you show what you've tried already. You should also note that the default checkbox styling includes padding that makes it easier to be sure you're taping the one you want. If you start putting them close together it'll be easier for users to accidentally tap the wrong one.
Comment: I'm running into the same issue. I just want the checkbox without the layout for its associated label.
Answer: Although I agree with the comments above, sometimes UI design can be compromised -
You can achieve it by adding a ScaleX and ScaleY :
<code><CheckBox Content="CheckBox" FontSize="{StaticResource PhoneFontSizeSmall}"
                      BorderThickness="1">
    <CheckBox.RenderTransform>
        <ScaleTransform ScaleX="0.5" ScaleY="0.5" />
    </CheckBox.RenderTransform>
</CheckBox>
</code>
This worked for me in WP8 - haven't tested in WP7


How to have only one login for multiple websites on the same linux machine?

Question: I'm having multiple websites (like mediawiki, gitea and kanboard) and I'm thinking about making the login the same on all services.
But how do I do that?
I looked at AD but I read that it's Windows only?
I also heard about "FreeIPA" but I read that it's used for linux client machines?
Google is sadly not really helping me with that, as the question is too broad to get good results.
All I want is to make the logins on all my websites the same, so that if I create a user (or change password) once it gets updated on every website/service.
I don't necessarily need the client OS (example: windows login) to be involved, but if that is necessary then I will do that.
Any help or directions would be greatly appreciated.
Comment: The different web apps will need to support a common authentication backend.  Check what authentication methods/plugins each of them support.  If they are just using an internal database then syncing would require some programming effort.
Answer:
I'm having multiple websites (like mediawiki, gitea and kanboard) and I'm thinking about making the login the same on all services.

MediaWiki, Gitea, and Kanboard supports OAuth2, so you may use that. You may need to implement OAuth2 provider though, such as ORY/Hydra or Keycloak.

I looked at AD but I read that it's Windows only?

You can communicate to AD with LDAP, but you may need to check if your websites support LDAP.

I also heard about "FreeIPA" but I read that it's used for linux client machines?

Also uses LDAP.

Google is sadly not really helping me with that, as the question is too broad to get good results.

Try this.
Answer: You can have only 1 credentials for all websitss which are hosted in same LAN this process is call single -sing -ON this can be accomplished by integrating Active directory . For example when your are trying to login into websit the request should call on active directory to get it done coding has be developed at application server