MDX MEDIAN() Function Incorrect Results

Question: I am trying to implement a data cube whereby I can show the average and the median of a measure for a given set of dimensions. Basic example using AdventureWorksDW:
WITH
    MEMBER [Measures].[Median Qty] AS
     MEDIAN ( [Product].[Product Categories].siblings, [Measures].[Reseller Sales-Order Quantity])
    MEMBER [Measures].[avgOrderSize] AS
    CASE
        WHEN [Measures].[Reseller Sales Count] = 0 THEN NULL
        ELSE ([Measures].[Reseller Sales-Order Quantity]  / [Measures].[Reseller Sales Count])
    END

SELECT {[Measures].[Reseller Sales-Order Quantity], [Measures].[Median Qty], [Measures].[avgOrderSize]} ON 0,
NON EMPTY([Product].[Product Categories].[Category]) ON 1
FROM [Analysis Services Tutorial]
WHERE ([Product].[Product Name].&[476]);

The output is:

My [Measures].[avgOrderSize] is correct as it appears to be using the actual measures returned in the query. However, the [Measures].[Median Qty] is not at all correct for what my requirements are. I would have though the value would be around 6 (given that my AdventureWorksDW2012 has 344 reseller orders that include this product). It looks like the MEDIAN() is working across the entire set of products?
I have tried variations on [Product].[Product Categories].siblings including [Product].[Product Name].CurrentMember which returned the identical value as the Reseller Sales-Order Quantity
What am I doing wrong and how can I get the MEDIAN() function to act like I am expecting?
Comment: Do you have a degenerate dimension that has one dimension member for every reseller order (in your real cube I mean)? What version of SSAS and is it Enterprise edition?
Comment: @GregGalloway We do have degenerate dimensions in our real data. I am hoping to understand MEDIAN in the AW data first so I have something to test and compare with. We are using SSAS 2012 Standard Edition.
Answer: Warning. This will be slow. But it should be correct. I'm afraid Median is just an expensive calculation. The first parameter should be a degenerate dimension and an attribute which has one member per row in the fact table.
WITH
    MEMBER [Measures].[Median Qty] AS
     MEDIAN ( EXISTING [Reseller Sales].[Reseller Sales Order Number].[Reseller Sales Order Number].Members, [Measures].[Reseller Sales-Order Quantity])
    ...

Comment: I modified this a bit to work with my version of the AW dimensions. And it seems to return expected results. Marking this as the answer. However, this will not work in our live OLAP our degenerate dimension fails to build due to 4GB files size limit (that was a neat error). It seems we will be unable to show percentiles when using OLAP.
Comment: @wergeld there is a setting to allow larger dimensions: https://technet.microsoft.com/en-us/library/gg471589(SQL.110).aspx but I suspect MEDIAN over that size dimension is pointlessly slow.
Comment: @GregGalloway how come this didn't work? `EXISTING [Product].[Product Categories].siblings` (I don't have this test cube - it is different from the AdvWrks I have access to)
Comment: Yea, this would most likely be non-functional even if we can get the DBAs to increase size limits.We wouldn't be calculating the MEDIAN across the entire data set - we force selection of time, location, and other parameters to narrow the resulting data set.
Comment: The `siblings` just returned the same value as the "Reseller Sales-Order Quantity" which was 2,881. The expected value was 6.
Comment: @whytheq it gave you the median of the product subcategory subtotals. The questioner wanted the row level median
Answer: I've not played with that function yet but a couple of things you could try are:
Add the EXISTING keyword to the calculation:
WITH
    MEMBER [Measures].[Median Qty] AS
     MEDIAN (
        EXISTING [Product].[Product Categories].siblings
      , [Measures].[Reseller Sales-Order Quantity]
     )
...

Add the Exists function although this is probably very similar to the above:
WITH
    MEMBER [Measures].[Median Qty] AS
     MEDIAN (
        EXISTS([Product].[Product Categories].siblings, [Product].[Product Name].&[476])
      , [Measures].[Reseller Sales-Order Quantity]
     )
...

Try this:
WITH
    MEMBER [Measures].[Median Qty] AS
     MEDIAN (
        [Product].[Product Categories].currentmember.siblings
      , [Measures].[Reseller Sales-Order Quantity]
     )
...

Comment: I tried both `EXISTING` and `EXISTS` and this just returns the same value as "Reseller Sales-Order Quantity" which is 2881 (for this product). It looks like this just does the MEDIAN across the set that contains the product (good) but only at the aggregate level (bad) so MEDIAN is only calculated for the single value of the Quantity totaled.
Comment: @wergeld I added a third attempt! this is from viewing the example in here: https://msdn.microsoft.com/en-us/library/ms145570.aspx?f=255&MSPPError=-2147217396
Comment: This returns the same value as my initial query - 1030.5. I have to be missing something simple - I just don't know what it is yet.

MDX MEDIAN() Function Incorrect Results


Complicated Linq filtering without nesting countless if/foreach

Question: I have an collection with given fields:
class InternalConditionModel
{
    public string ProductId { get; set; }
    public double Value { get; set; }
    public DateTime DateFrom { get; set; }
    public DateTime DateThru { get; set; }
    public bool IsSSoldOnlyOnDisplay { get; set; }
}

And have to filter it based on given conditions:
If there is more than one item with the same ProductId within the collection, I check IsSoldOnlyOnDisplay and take the one that yields true. If however there are more than one true, I take the item with the biggest Value.
Doing it via GroupBy(ProductId) and then doing multiple ifs/foreaches is pretty straight forward. But I wanted to know if there is a possibility to streamline it with LINQ into something "prettier".
Answer: This should do it:
var result = items.GroupBy(x => x.ProductId).Select(x => x.OrderByDescending(y => y.Value).FirstOrDefault(y => x.Count(z => z.IsSSoldOnlyOnDisplay) == 1 ? y.IsSSoldOnlyOnDisplay : true));

First we group by the product id. Then we sort each group descending by the value (the item with the greatest value will be first). Of this sorted group, we take the first item. If the group has only one item with IsSSoldOnlyOnDisplay true, the condition of FirstOrDefault is IsSSoldOnlyOnDisplay, otherwise the condition is true, meaning it will just take the first item in the group. Because of the sorting which occured earlier, it will be the one with the highest value.
But think of yourself whether this code is really better than some loops and ifs. I don't recommend forcing everything into a single LINQ query.
Online-demo: https://dotnetfiddle.net/SzuL0p


How to deal with categorical variable - location- with more than 60 levels

Question: I am new to statistics and to categorical variables.
I need to predict the cost based on several variables and it happened that all of my variables are categorical. I tried doing a linear regression between my response (actual cost $) and the following predictor variables:estimated cost($), county, month, and project type.
 I noticed then under the following linear model
lm = lm(actual cost ~ estimated cost)

R-squared is 97%. However, I am looking for a degree of accuracy where 50 % of the projects should be within 5% of the estimated:
sum(abs((lm$fitted.values - actual cost)/actual cost))/nrow(data) >=50%

Under the simple model, although R squared is high, but only 30% of the projects have a 5% or less level of accuracy.
I started adding more predicted variables and I noticed that adj R squared does not increase much (98%), but 48% of the project satisfy the required level of accuracy under the following model:
lm = lm(actual cost ~ estimated cost + county + month + work type)

county: 78 levels
month:12 levels
qork type: 6 levels
The summary(lm) shown that not all p-values of the levels are significant. I then did a stepwise, and the selected model contained the estimated cost, the 12 months and the 5 work types. However, on 38% accuracy was achieved.
I don't know if the linear regression is correct, or if you guys can provide me with the resources to read more about regression with categorical varaibles with large number of levels.
Can I do stepwise with categorical variables? Why the R squared did not increase much? What other analysis can be performed.
I would greatly appreciate any help on this issue!!
Answer: You state that all of your variables are categorical, but I'm going to assume that actual cost and estimated cost are continuous.
It seems that your main goal is prediction and not estimation of parameters. I think that a better approach might be to use a mixed effects model.
library(lme4)
library(lmerTest)
m1 <- lmer(actual_cost ~ estimated_cost + (1|county) + (1|month) + (1|work_type))
summary(m1)

In this model, county, month, and work type are used as crossed random effects. You can also try this:
m2 <- lmer(actual_cost ~ estimated_cost + (estimated_cost|county) + (1|month) + (1|work_type))

Now the relationship between estimated cost and actual cost may also be affected by the county (if there are larger discrepancies between the estimated and actual costs in some counties). Of course, you could extend this to the other random effects as well:
m3 <- lmer(actual_cost ~ estimated_cost + (estimated_cost|county) + (estimated_cost|month) + (estimated_cost|work_type))

Work type only has 6 levels and is perhaps not best used as a random effect, but as a fixed effect, because the impact of the 6 levels on the dependent variable may not follow a gaussian distribution, which is assumed when using it as a random effect (I think you can make different distributional assumptions but I don't know how). So perhaps this:
m4 <- lmer(actual_cost ~ estimated_cost + work_type + (estimated_cost|county) + (1|month))

It may of course also be the case that the impact of the estimated cost on the actual cost is not quite linear. It may be the case that the estimated costs are less accurate (or more accurate) when the estimated costs are higher or lower. You can try adding a quadratic term and see if that improves the model:
m5 <- lmer(actual_cost ~ estimated_cost + I(estimated_cost^2) + work_type + (estimated_cost|county) + (1|month))

I hope this gives you some ideas how to continue.
Comment: Agree, but maybe you could add few sentences on *why* mixed effects model should be used? Why countries should be threated as random effects? The method is not that widely used and taught, so a sentence or two (and/or reference) on the difference of regression and mixed effects model could be helpful. Also I would argue that **months are *not* random** but fixed effects (we have all the months, this is not a random sample of the months!).
Comment: Tim, to my understanding, using a variable as a random or fixed effect has nothing to do with whether we have all of the possible variables (such as months) represented in our data set or not. It has more to do with if we're interested in the specific effect of each month or not.
Comment: Well, there are many definitions (e.g. http://stats.stackexchange.com/questions/120964/fixed-effect-vs-random-effect-when-all-possibilities-are-included-in-a-mixed-eff/137837#137837 ) but one way of thinking of the random effects is that if you have all the possible levels of your variable measured and there is a limited number of them, then you treat them as fixed.
Comment: Ok, I understand. But treating them as random is also a way to keep down the number of estimated parameters and thereby decrease the risk of overfitting, isn't it? Perhaps in this case, there is no need to treat months as random effects if the data set is large.
Comment: Think of interpreting such data as random effects, would it make sens to tell that "months on average have such effect on the outcome"? It would not make much sens because we don't have "a group" of months and we are not interested in their "overall" effect. This is a delicate topic and it does not have 100% clear-cut boundaries but I would argue that months are not a good candidate for a random effect.
Comment: Ok, perhaps you're right. This is an issue of prediction, not of parameter estimation which I'm more used to. In that case, using county as a random effect is questionable as well if all counties are included?
Comment: "It depends...", but given the limited information available, as for me, country is a good candidate for a random effect here as far as OP is not interested in individual effects of countries (i.e. fixed). As I said, I agree with your answer, this is just a comment on treating months as a random effect (see the link I posted above for further discussion).


My dropdown menu is pushing other html elements downwards

Question: I am making a project and I added a dropdown menu on navbar and I don't know why that it seems to push the HTML down when toggled. I tried making its position absolute and top 100% but it didn't work, I am using bootstrap, please help
Here is the main HTML

body{
    background-color: #0b0c10!important;
}

nav{
    background-color: #0b0c10!important;
    color: turquoise;
    text-decoration: none;

}

nav a{
    color: turquoise;
    text-decoration: none;
    font-family: 'Lato', sclear-serif;
}

nav a:hover{
    color: white;
    text-decoration: none;
    transition-duration: 1s;
}

.navbar-nav{
    margin-right: 80px;
    text-align: center!important;
}

.navbar-brand{
    font-family: 'Lobster', cursive;
    font-size: 30px!important;
    margin-left: 30px;

}

  Calcify
  </button>

          More Calculator

          Action
          Another action

          Something else here

Answer: I think you have to add jquery.min.js, popper.min.js, and bootstrap.min.js.
In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start
You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:

Example

 Calcify

      More Calculator

      Action
      Another action

      Something else here

.navbar{
  align-items: stretch!important;
 }
.navbar-nav .dropdown-menu {
  position: absolute;
 }

Comment: Please check the example link that I have posted. Is that how you want to achieve?
Comment: @Ketsmania, Can you upvote if you find my answer useful?
Comment: How would that help?
Comment: No, Whenever I use it on mobile device, the dropdown shifts the containers down
Comment: Please add  to your CSS file .navbar{ align-items: stretch!important; }  and .navbar-nav .dropdown-menu {
    position: absolute;
}
Comment: Yes, it did the work after doing this,but I had to mark the position move important  .navbar-nav .dropdown-menu { position: absolute;!important }
Comment: Yes, you have to do so, to override the bootstrap css.
Answer: for your dropdown items list use
position:absolute;
z-index:5;

this worked for me
Answer:

body{
    background-color: #0b0c10!important;
}

nav{
    background-color: #0b0c10!important;
    color: turquoise;
    text-decoration: none;

}

nav a{
    color: turquoise;
    text-decoration: none;
    font-family: 'Lato', sclear-serif;
}

nav a:hover{
    color: white;
    text-decoration: none;
    transition-duration: 1s;
}

.navbar-nav{
    margin-right: 80px;
    text-align: center!important;
}

.navbar-brand{
    font-family: 'Lobster', cursive;
    font-size: 30px!important;
    margin-left: 30px;

}

  Calcify
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

          More Calculator

          Action
          Another action

          Something else here

Comment: both question and solution looks similar, what's the difference?
Comment: He forgot to add  the `` part he only use ``
Comment: but then , this is still not the solution. Also while answering try explaining what you did and what was the mistake
Comment: I have tried it and that works perfectly well. Maybe there could be another CSS class that overwrites the working code.
Comment: The solution is answered in the above answer's comment. P.S. The  was a mistake, but nothing to do with my problem.


Preparing for exam: recognizing functions in Set Theory

Question: I'm reviewing earlier exams and found this question:
<code>Which of the following relations are functions and which are not?
i.   { <x,y> : x is mother of y},
ii.  { <x,y> : x has as mother y},
iii. { <x,y> : x has as uncle y},
iv.  { <x,y> : x has as lawful partner (m/f) y}.
</code>
As far as I can tell, they are all functions because they take inputs  and produce something, a relationship, based on these inputs. Am I mistaken?
Answer: Recall that a function is a relation which has the following property:

If $\langle x,y\rangle,\langle x,z\rangle$ are in the relation, then $y=z$.

For example, the first example. My mother has three children. Can this be a function?
Comment: Oh, okay. None of them are functions, they are just statements. To become functions, something must be done with the statements, other than just stating them. Yes?
Comment: Also no. You are give relations. Sets of ordered pairs. These sets are defined using a formula (not in a formal language, though). How many mothers can someone have? Does that mean that the relation in the second example is a function or not?
Comment: An equivalent way to describe this is to say that each set of ordered pairs is a function if the first entry of a pair gives all the information needed to determine the second entry.  So look at the first case. Suppose you know the first entry of an ordered pair (the $x$ in an $$ pair).  You also know that $x$ is the mother of $y$.  Does this give you enough information to figure out $y$?


Difference between Men's and Women's Tennis balls?

Question: While watching the 2022 US Open 1st Round match between Raducanu and Cornet, one of the commentators said something along the lines of the following:

[...] the balls are different this year, they are slightly heavier than before, but still different to the men's balls.

Not exact wording, it's from memory, but the gist of the sentence is the same.
This surprised me as a very casual tennis fan, in that I naively assumed that a tennis ball is pretty much the same as any other tennis ball and, if there are differences, then at the elite level I would have thought that there would have been some standardisation across the professional scene, for both men and women.
What are differences between the men's and women's tennis balls (if any; perhaps I misheard the commentator, or he misspoke), and why are they different?
Answer: The ITF has several different tennis ball types that it permits.  Each tournament can choose which balls to use from any that meet the qualifications.  The USTA publishes a list of approved balls based on the ITF standard that are approved in USTA tournaments, including "US Open" balls.
The US Open is the only Grand Slam that uses different balls for Mens and Womens:

While the men use Wilson's US Open extra duty balls, women use Wilson US Open regular duty balls which are enveloped by a thinner and less fluffy felt cover, leading to a faster, more aerodynamic ball, and consternation among some players.

The effect may be to speed up the game some, though that is controversial as a lighter ball will be faster initially but then slow as it has less momentum.
The stated reason, however, is to reduce injury:

"The WTA has always utilized regular felt balls for hardcourt play, and we have now begun to hear from a select number of our athletes that they would like to consider a change to using the extra duty ball," Binder said. "The basis behind using the regular felt ball was that it limited the potential of arm, shoulder, elbow and wrist injuries. This is something that we will continue to monitor and discuss further with both our athletes and our sports science teams."
Answer: This is a somewhat controversial decision taken by the US Open to deliberately use different balls for men and women. Quoting from this iNews article:

While the men play with Wilson's extra duty tennis balls – developed specifically for hard courts – the women play with regular duty balls, which play faster, are less durable and are actually more suited to softer surfaces like clay or indoor courts.

At the other Grand Slams, it is as you expect and the men and women use the same ball.


Classification trees, determining prediction in leaf

Question: My question is how the prediction in the leaf is calculated for classification trees with more than 2 classes.
With regression trees its simple, its just the sample mean of the observations ending up in that leaf of the training sample.
With binary classification its the same and then you decide 1 if the result is >0.5 and 0 if it is <0.5.
But how are we doing it if there are more than two classes? Just pick the class that has the highest relative frequency? Or are we calculating also a mean and then pick the class that is closest to that mean? For instance, mean over observations is 3.4 therefore our prediction is class 3?
Comment: Bagging, boosting, random forests, stochastic gradient descent all exist because single trees are unstable and when reliable have non-competitive predictive discrimination.  I highly advise against any single-tree analysis unless perhaps you have 100s of thousands of samples.
Comment: that does not help at all. I am trying to understand the very basics of those methods...
Comment: To make it more clear: I want to know how we are assigning each region its respective response value in a multiple classes situation.
Answer: Averaging class labels doesn't make sense. Usually in tree based methods, each decision tree predicts a probability distribution over the classes based on the number of samples of each class in the leaf. The final prediction is obtained by averaging each tree's probability. The predicted class is the class that has the highest mean probability. Note that this procedure is not dependent on the number of classes.


using python and saltstack error

Question: I'm writing a small program with SaltStack API in Python and I'm getting an error
import salt.client
SnakeInSalt = salt.client.LocalClient()
SnakeInSalt.cmd('*',test.ping)

The error:
python test.py
Traceback (most recent call last):
File "test.py", line 4, in <module>
SnakeInSalt.cmd('*',test.ping)
NameError: name 'test' is not defined

If I run salt from command line, it works
> sudo salt '*' test.ping

> [sudo] password for z:

> z-ThinkPad:
> True

Answer: Can I assume this is no longer a question you need answered? (I'm going to answer it anyway)
When you run sudo salt '*' test.ping you are running the built in function named ping in the module test.  To see a list of available modules use sudo salt '*' sys.list_modules test.  You can see the list of functions in that module by typing salt '*' sys.list_funtions test.  The command sudo salt '*' test.ping should work for every salt setup in the world and is not a test of any custom state or module you've written.
Yours is broken because your using the wrong syntax and you're calling the cmd module instead of the test module.  Your code should look like:
import salt.client
SnakeInSalt = salt.client.LocalClient()
SnakeInSalt.cmd('*', 'test.ping')

The only difference is that test.ping needs to be enclosed in quotes (double or single).  You can reference https://docs.saltstack.com/en/latest/ref/clients/#salt.client.LocalClient.cmd to see all of the arguments available to .cmd().  What you were lacking was the knowledge that cmd requires the second argument fun (short for function) needs to be a string.  This will not be converted for you so you need to surround it in quotes.
You can also reference https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.test.html#salt.modules.test.ping to see what arguments are required by the ping function of the test module.  Spoiler alert...the answer is none, but it looks like you knew that already.
CHEERS!
Comment: answer them anyway. 99% of the eyes are from the non-asker (the OP)

using python and saltstack error


Manipulating .gif animation with wand

Question: I'm working with wand to basically do a frame-by-frame translation of a gif. I want to transpose an image into each frame of a gif, then save the output animated gif.
def placeImage(gif_name, image_name, save_location):
  with Image(filename = gif_name) as gif:
    with Image(filename = image_name) as image:
      new_frames = []
      for frame_orig in gif_new.sequence:
        frame = frame_orig.clone()
        with Drawing() as draw:
          draw.composite(operator='src_over', left=20, top=20,
            width=image.width, height=image.height, image=image)
          draw(frame)
          new_frames.append(frame)

So now I've got all of these frames (though they're not SingleImage objects, but Image objects) that I'd like to put back together and generate a new gif. Any advice?
I'd like to be able to do something like:
with gif.clone() as output:
    output.sequence=new_frames
    output.save(filename=save_location)

Answer: I just answered something very similar here: Resizing GIFs with Wand + ImageMagick
with Image() as dst_image:
    with Image(filename=src_path) as src_image:
        for frame in src_image.sequence:
            frame.resize(x, y)
            dst_image.sequence.append(frame)
    dst_image.save(filename=dst_path)

Hope that helps!

Manipulating .gif animation with wand


Manage global aliases for multiple npm packages

Question: I have 3 npm projects, all exists under the same root folder. The projects are more complex than the example below (using webpack, JS frameworks, etc.) but to keep it simple for illustration purposes this is the structure:
root
├── root_index.js
├── package.json
├── project_1
│   ├── index.js
│   └── package.json
├── project_2
│   ├── index.js
│   └── package.json
└── project_3
    ├── index.js
    └── package.json

My problem is I find lots of situations in the code where imports, for example from project_1 to project_2 contains lots of '..', for example - '../../../../project_2/some_module'.
Would be nice if I could define a global variable '@project_2' that will point to the project and then I could change my imports to '@project_2/some_module'.
I saw webpack offers some solutions for aliases but I don't use webpack in my root folder, only in each project individually and so I cant use its configuration to control all projects from a single point. I also found this  'module-alias' package but it didn't work properly together with the configurations (mostly webpack) I have in each of the projects.
any idea how can I define these global variables so I could use them in each of the projects?
Answer: It sounds like you want to set up your project as a mono-repo.
I would recommend you to use the yarn workspaces concept and Lerna to help you manage it.
What is mono-repo?
In short, a so-called Mono-Repo is a (git) repository that houses multiple projects. Such projects are called workspaces or packages.
Lerna is a tool that optimizes the workflow around managing multi-package repositories with git and npm.
checkout official website: https://lerna.js.org/
Attaching a good article to help you start with yarn workspaces and lerna:
https://medium.com/hy-vee-engineering/creating-a-monorepo-with-lerna-yarn-workspaces-cf163908965d


Fitting a special mixed model in R - alternatives to optim()

Question: I would like to do something in R that SAS can do using SAS's proc mixed (there is some way to do in STATA es well), namely fitting the so called Bivariate model from Reitsma et al (2005). This model is a special mixed model where the variance depends on the study (see below). Googling and talking to some people familiar with the model did not yield a straightforward approach that is fast at the same time (i.e. a nice high level model fitting function). I am nevertheless sure, there is something fast in R that one can built on.
In a nutshell one is faced with the following situation: Given pairs of proportions $(p_1,p_2)$  in $[0,1]^2$ one would like to fit a bivariate normal to the logit-transformed pairs. Since the proportions come from a 2x2 table (i.e. binomial data) each logit transformed observed proportion has a variance estimate that is to be included in the fitting process, say $(s_1, s_2)$. So one would like to fit a bivariate normal to the pairs, where the covariance matrix $\Sigma$ depends on the observation, i.e.
$(\text{logit}(p_1),\text{logit}(p_2)) \sim N((mu_1, mu_2), \Sigma + S)$
where S is the diagonal matrix with $(s_1, s_2)$ and depends entirely on the data but varies from observation to observation. mu and Sigma are the same for all observation though.
Right now I am using a call to optim() (using BFGS) to estimate the five parameters ($\mu_1$, $\mu_2$, and three parameters for $\Sigma$). Nevertheless this is painfully slow, and especially unsuitable for simulation. Also one of my aims is to introduce regression coefficients for mu later, increasing the number of parameters.
I tried speeding up fitting by supplying starting values and I also thought about computing gradients for the five parameters. Since the likelihood becomes quite complex due to the addition of $S$, I felt the risk of introducting errors this way was too big and did not attempt it yet, nor did I see a way to check my calculations.
Is the calculation of the gradients typically worthwhile? How do you check them?
I am aware of other optimizer besides optim(), i.e. nlm() and I also know about the CRAN Task view: Optimization. Which ones a are worth a try?
What kind of tricks are there to speed up optim() besides reducing accuracy?
I would be very grateful for any hints.
Comment: Some discussion [here](http://r.789695.n4.nabble.com/meta-analysis-on-diagnostic-tests-bivariate-approach-td841694.html#none)
Comment: The answers to this question may be useful: http://stats.stackexchange.com/questions/9535/when-should-i-not-use-rs-nlm-function-for-mle
Comment: @mbq: Thanks for migrating the question. Also thank you for hinting at the other questions.
Answer: This isn't perhaps the solution you anticipated, but I think you could fit this model with brms (i.e. as an interface to Stan), with what it calls a 'distributional model'... see https://cran.r-project.org/web/packages/brms/vignettes/brms_distreg.html
See also the overview vignette here which shows how to fit the binomial model. https://cran.r-project.org/web/packages/brms/vignettes/brms_overview.pdf


Projected mean (p)-distance from a point to the surface of an (n)-sphere

Question: I am considering a point R inside an sphere of radius 1 in dimension d. The point is at a distance x from the center of the sphere, and the axis 0x is thus defined.
The distance between the point and the sphere surface is $L(x,\mathbf{\omega})$, where $\mathbf{\omega}$ is the angle between R and the point considered on the sphere.  In 2D, $\mathbf{\omega}$ is an angle $\theta$, in 3D, it is $\theta,\phi$, etc...
I am interested in the mean distance (to a power $p$) between R and the sphere surface, projected on the axis Ox. The average is done over all possible angles (rather than over all points of the sphere surface).
Physically, this value can be seen as the net force $f$ on R along Ox, when for all angles, the point measures $L$ and gets pulled to the surface with a force $L^p$.
For exemple, in d=1 :
$f^1_p (x)=(1+x)^p-(1-x)^p$
In d=2 :
$f^2_p (x)= \int_0^{2 \pi} d\theta \sin(\theta)L(x,\theta)^p$
with $L(x,\theta)=\sqrt{1-x^2 + x^2 \sin^2(\theta)}$
Interestingly enough, I found numerically that this measure has very funky properties. Namely, $f_p^d$ is linear if p=1 or p=d+1, and is sublinear in between.
My goal was to prove this linearity for p=d+1 recursively, but I am now stuck. Any chance this is a known problem, or that there is a simple solution I overlooked?
Note :
If I'm correct, one can show that :
$f_p^d = 2 \int_0^1 \frac{u^{d-1}}{\sqrt{1-u^2}} f_p^{d-1} \left( \frac{x}{R_1(x,u)} \right) \left(u R_1(x,u) \right)^p du \qquad $ With $R_1(x,u)= \sqrt{ \frac{R_0^2 - x^2}{u^2} + x^2 } $
Edit : numerically, it seems that the mean p-distance $<l_d^p>$from R to the sphere, averaged over all angles $\omega$ is a constant if $p=d$. I'll call this constant $C_d$.
Let us take that as an assumtion to compute $f_{d+1}^d$ :
$f_{d+1}^d = \int_\Omega d\omega \mathbf{u}_x \mathbf{.} \mathbf{u}_\omega L(x,\omega)^{d+1} $
I thought I could integrate by parts, using $f_1^d =  \int_\Omega d\omega \mathbf{u}_x \mathbf{.} \mathbf{u}_\omega L(x,\omega)^1 $ and using $f_{1}(x)=x$. However, this does not really achieve anything.
Comment: Numerically, it also looks like, under this definition of the mean, the mean p-distance (L^p) from a point R to the sphere surface in dimension d is constant if p=d. This is most likely corollary to what I want to show.
Comment: When attempted in cartesian coordinates, you need to integrate $$\int \cosh^{p+1} u\, du$$
Comment: Mmm I'm not sure I see how and why...
Comment: I really left that comment to help me find this post again when I had more time. The idea is that you define the axes so that $R$ is on the $x_n$ axis, and then do iterated integration with that axis first. This integral will have the form $$\int \sqrt{a^2 + (x_n - r)^2}dx_n$$ where $a^2$ is the contribution from all the other $x_i$. The substitution $x_n - r = a\sinh u$ then converts the integral into the form above. Unfortunately Wolfram Alpha gives a result that will be incredibly hard to integrate for the remaining $x_i$, so I don't think it is that helpful.
Comment: Thank you ! I did find an easier way to prove it recursively, but it's going take me a bit of time to write it down. Will do it very soon, though.
Answer: I wrote the solution in a PDF eventually. It's not very complicated algebra but it is a bit long.
http://biophysics.fr/wp-content/uploads/2018/06/derivations-1.pdf


define addition as an instance of Num in haskell

Question: I wish to define addition between two chars as concatination but im unsure of how to properly do so.
my attempt:
instance Num Char where
 (+) (a) (b) = [a] ++ [b]

but the error i get is that the  return type is not the expected one.
My expected output is as stated a list of Char which is formed by concatinating the two chars.
Comment: `(+) :: Num a => a -> a -> a`; you want something with type `Char -> Char -> [Char]`.
Comment: Even if you *did* come up with a definition of `+` that fit the signature, you can't define a `Num` instance without also defining `(*)`, `abs`, `signum`, `fromInteger`, and either `negate` or `(-)`. And if you *do* define them, they still need to obey various laws like `a + b == b + a` and `x + fromInteger 0 == x`. The kind of operator overloading provided by type classes is not the free-for-all, any-definition-goes kind provided by other languages.
Comment: @chepner The built-in `Natural` type doesn't have a reasonable definition of `negate` or `(-)`, and it breaks a lot of the "laws" (which aren't actually defined in the report).
Answer: Rather than overload (+) with non-numeric semantics, define your own character "addition" operator.
import Data.Function

-- The ^ is meant to suggest lifting values into a list.
(^+) :: a -> a -> [a]
x ^+ y = (++) `on` pure
-- Or more simply,
-- x ^+ y = [x, y]

Then 'a' ^+ 'b' == "ab". (^+) will work for creating a two-element list of any type, not just Char.
> 'a' ^+ 'b'
"ab"
> 3 ^+ 4
[3,4]
> [1,2] ^+ [4,5]
[[1,2],[4,5]]

Comment: Bringing out the big cannons, eh? `on`, `pure`... you just barely missed generalizing `(++)` to `(<>)` to make it as inscrutable as possible. We have lost touch with how simple Haskell can be, it seems. `a ^+ b = [a, b]` (Upvoted anyway.)
Comment: Sorry, I performed what I thought was an edit suggestion but ended up actually editing the answer; my SO is a bit rusty.  I agree with the main idea of the answer, but proposed a more reasonable implementation of `^+`.  Feel free to edit back if you feel like the original implementation is more reasonable.
Comment: @JustinL. You have enough reputation that your edits don't need peer review: you're expected to know well enough how things work and not make wantonly unreasonable edits. Case in point: this edit was totally reasonable.
Comment: I'd prefer an addition to the answer rather than omitting the `on` solution altogether.
Answer: This is impossible. The (+) function in Num has type a -> a -> a, so the return type must be the same as the parameter type. You cannot add two Char and receive a String as a result. More generally, you should not implement Num for things other than arithmetic on numbers.
Comment: The compiler would not complain, but any humans reading your program would.
Comment: The [docs for `Num`](https://www.stackage.org/haddock/lts-13.12/base-188.8.131.52/Prelude.html#t:Num) specify a few laws that instances should satisfy, and concatenating strings wouldn't fit them. For example, string concatenation wouldn't satisfy addition commutativity. The compiler will not object, but such instance will have weird behavior, unobvious to other people, and thus will lead to subtle bugs.
Comment: I see, but if i took two strings as input and concatinated them, in other words a typesignature [Char] -> [Char] -> [Char], it would then be possible to define (+) on [Char] ?
Comment: Also, it occurs to me now, the compiler *would* complain. You must define an instance for `[a]` in general, and cannot specialize to only `[Char]`. You could define addition for lists to be concatenation, but of course this would be widely reviled.


Setting custom plugin in sidebar open by default - Jupyterlab

Question: In Jupyterlab, the file browser plugin is open by default. How do you change this to have your custom plugin open by default on launch.
In the activation function of my custom plugin, i have the following snippet and I think the change needs to be in here-
// If the layout is a fresh session without saved data, open my custom plugin
  app.restored.then(layout => {
    if (layout.fresh) {
    console.log('This is a fresh launch, open custom plugin by default');
     //do something here
    }
  });

Answer: You can do something like that in your active function:
app.restored.then(() => {
  labShell.activateById(formationPanel.id);
});

Inspiration: https://github.com/jupyterlab/jupyterlab/blob/master/packages/filebrowser-extension/src/index.ts#L687


Unable to download large files from Sonatype Nexus

Question: Nexus version 3.1.0-04
During a build, I receive the following error downloading an artifact from Nexus.

Download >http://10.148.254.17:8081/nexus/content/repositories/central/org/assertj/assertj-core/2.4.1/assertj-core-2.4.1.jar
  :collection:extractIncludeTestProto FAILED
FAILURE: Build failed with an exception.

What went wrong:
  Could not resolve all dependencies for configuration ':collection:testCompile'.
  Could not download assertj-core.jar (org.assertj:assertj-core:2.4.1)
  Could not get resource 'http://xxx.xxx.xxx.xxx:8081/nexus/content/repositories/central/org/assertj/assertj-core/2.4.1/assertj-core-2.4.1.jar'.
  Premature end of Content-Length delimited message body (expected: 900718; received: 6862

This appear to be a problem with large files stored in Nexus.
If I try and download the file via wget or curl, it also fails.
c:>wget http://xxx.xxx.xxx.xxx:8081/nexus/content/repositories/central/org/assertj/assertj-core/2.5.0/assertj-
core-2.5.0.jar

--13:57:06--  >http://xxx.xxx.xxx.xxx:8081/nexus/content/repositories/central/org/assertj/assertj-core/2.5.0/assertj-core-2.5.0.jar
             => `assertj-core-2.5.0.jar'
  Resolving proxy.xxxx.com... done.
  Connecting to proxy.xxxx.com[xxx.xxx.xxx.xxx]:xxx... connected.
  Proxy request sent, awaiting response... 200 OK
  Length: 934,446 [application/java-archive]
0% [                                     ] 6,856          1.44K/s    ETA 10:27
13:57:21 (1.44 KB/s) - Connection closed at byte 6856. Retrying.

c:>curl -O http://xxx.xxx.xxx.xxx:8081/nexus/content/repositories/central/org/assertj/assertj-core/2.5.0/assertj-core-2.5.0.jar

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed
    0  912k    0  6862    0     0    613      0  0:25:24  0:00:11  0:25:13   613
  curl: (18) transfer closed with 927584 bytes remaining to read

Any ideas why?
Comment: This isn't really a large file, checking Maven Central it's only 600kb more or less, and we've seen MUCH larger files going in and out of Nexus Repository. File an issue here to begin with: https://issues.sonatype.org/browse/NEXUS , and maybe try moving to the newest version as well (3.2.1 as of today).
Comment: Just upgraded to Nexus 3.2.1, same results with every operation above.
Comment: It looks like this was also filed as a Jira ticket.  The answer is here:  https://issues.sonatype.org/browse/NEXUS-12435?focusedCommentId=395835&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-395835  ... a local virus scanner is interfering with these downloads.
Answer: In my case by docker layer was blocked. I solved this problem by changing the timeout in System>Http>Connection/Socket timeout.


Is this subset with conjugate columns of $GL_n(\mathbb C)$ connected?

Question: Let us assume $n=2k$ to be even and for a matrix $A \in M_n(\mathbb C)$, we let $(a_1, \dots, a_n)$ denotes the columns. We define a set
\begin{align*}
\mathcal E =\{M \in GL_n(\mathbb C): m_i = m_{i+1}^* \text{ for } i = 1, 3, \dots, 2k-1\} .
\end{align*}
This says, the columns of every $M \in \mathcal E$ come in conjugate pairs. I am wondering whether this set is connected. If not, how many connected components will there be.
Answer: Let $D$ be the direct sum of $n/2$ copies of $\pmatrix{1&1\\ i&-i}$. Then $f:GL_n(\mathbb R)\ni X\mapsto XD\in\mathcal E$ is a homeomorphism. Hence $\mathcal E$ has the same number of connected components as $GL_n(\mathbb R)$, i.e. two.


Find all slots in a given range

Question: How to find all the date slots in a range..
From Date 01- Jan -2014 00:00:00 A.M
To Date 15-Oct-2014 00:00:00 P.M
Event Start Date 03-Jan-2014 10:00 A.M occurs every 3 days once mean 03, 06, 09, etc
I need to calculate like below using c#
03-Jan-2014
06-Jan-2014
09-Jan-2014
12-Jan-2014
etc,etc
How this calculations can be done in c#? tried in DB and failed, check Display next event date
Comment: Did you try with [`AddDays()`](http://msdn.microsoft.com/en-us/library/system.datetime.adddays%28v=vs.110%29.aspx) method first?
Comment: @SonerGönül, AddDays i can add. But how can i add it in a loop till the end?
Comment: @SonerGönül, sometime they asking me to do it every tuesday :(
Answer: As I mentioned in my comment, you can use DateTime.AddDays() method like;
DateTime dt1 = new DateTime(2014, 1, 1);
DateTime dt2 = new DateTime(2014, 10, 15);
DateTime start = new DateTime(2014, 1, 3);

while (start < dt2)
{
    Console.WriteLine(start.ToString("dd-MMM-yyyy"));
    start = start.AddDays(3);
}

Here a demonstration.
If you want to show 15-Oct-2014 also as a result, just change your start < dt2 condition to start <= dt2
Output will be;
03-Jan-2014
06-Jan-2014
09-Jan-2014
12-Jan-2014
15-Jan-2014
18-Jan-2014
21-Jan-2014
24-Jan-2014
27-Jan-2014
30-Jan-2014
02-Feb-2014
05-Feb-2014
08-Feb-2014
11-Feb-2014
14-Feb-2014
17-Feb-2014
20-Feb-2014
23-Feb-2014
26-Feb-2014
01-Mar-2014
04-Mar-2014
07-Mar-2014
10-Mar-2014
13-Mar-2014
16-Mar-2014
19-Mar-2014
22-Mar-2014
25-Mar-2014
28-Mar-2014
31-Mar-2014
03-Apr-2014
06-Apr-2014
09-Apr-2014
12-Apr-2014
15-Apr-2014
18-Apr-2014
21-Apr-2014
24-Apr-2014
27-Apr-2014
30-Apr-2014
03-May-2014
06-May-2014
09-May-2014
12-May-2014
15-May-2014
18-May-2014
21-May-2014
24-May-2014
27-May-2014
30-May-2014
02-Jun-2014
05-Jun-2014
08-Jun-2014
11-Jun-2014
14-Jun-2014
17-Jun-2014
20-Jun-2014
23-Jun-2014
26-Jun-2014
29-Jun-2014
02-Jul-2014
05-Jul-2014
08-Jul-2014
11-Jul-2014
14-Jul-2014
17-Jul-2014
20-Jul-2014
23-Jul-2014
26-Jul-2014
29-Jul-2014
01-Aug-2014
04-Aug-2014
07-Aug-2014
10-Aug-2014
13-Aug-2014
16-Aug-2014
19-Aug-2014
22-Aug-2014
25-Aug-2014
28-Aug-2014
31-Aug-2014
03-Sep-2014
06-Sep-2014
09-Sep-2014
12-Sep-2014
15-Sep-2014
18-Sep-2014
21-Sep-2014
24-Sep-2014
27-Sep-2014
30-Sep-2014
03-Oct-2014
06-Oct-2014
09-Oct-2014
12-Oct-2014

Answer: If you want to use LINQ then you can do:
DateTime dtStart = new DateTime(2014, 1, 1);
DateTime dtEnd = new DateTime(2014, 10, 15);

int difference = 3;
List<DateTime> result = new List<DateTime>(new[] { dtStart });
result.AddRange(Enumerable.Range(0, (dtEnd - dtStart).Days / difference)
                           .Select(r => dtStart = dtStart.AddDays(difference)));

Comment: Is it possible from the given date, check the next monday date?
Comment: @Billa, yes it is possible but it would require a different code, and it is out of context with this question.

Find all slots in a given range


Convergence in probability implies convergence in $L^2 $

Question: Let $(X_n)_n$ a sequence of gaussian r.v. such that for any $m$ and $ n$
$(X_n − X_m)$ is gaussian.
If $X_n \overset{P}{\longrightarrow X}$ then $X_n \overset{L^2}{\longrightarrow}X$ (more precisely in $ L^p ,\ p\in [1, +∞)$).
I tried to do this: convergence in probability implies convergence in law , and convergence in law of gaussians implies (Paul-Levy) that $ X \sim N(m,\sigma^2) $ with $m=\lim\limits_{n \to \infty} m_n $ and $\sigma^2=\lim\limits_{n \to \infty} \sigma^2_n$.
Convergence in probability also implies that the limit is a.s. unique.
Because $L^2$ is complete it is enough to prove that the sequence is Cauchy. Using the hypothesis :
$\int \lvert X_n-X_m \rvert^2 dP= \mathbb{E}[(X_n-X_m)^2]= (m_n-m_m)^2+(\sigma_n^2+\sigma_m^2)$
And i can find, fixed $\epsilon>0 , \hspace{0,3cm} n^* \in \mathbb{N} \hspace{0,3cm} $such that $\hspace{0,1cm} \forall m,n \geq n^*\hspace{0,4cm}  (m_n-m_m)^2+(\sigma_n^2+\sigma_m^2)<\epsilon \hspace{0,2cm}$ because of the limits above.
I would like to know where is the mistake and how i could fix it. I think i'm mistaken because the absolute moment equals the moment only if p is even, moreover it seems like i'm using convergence in probability only for the a.s. uniqueness of the limit. Any help would be appreciated.
Answer: There is a mistake in your computation of $\mathbb E(X_n-X_m)^{2}$. It is not given that $X_n$ and $X_m$ are independent so it is not possible to compute this in terms of $m_n,m_m$ and $\sigma_n, \sigma_m$ at all!.
Here is a valid proof:   $X_n-X=\lim_{m \to \infty} (X_n-X_m)$ in probability. This implies that $X_n-X$ is Gaussian for each $n$. This, together with $X_n -X \to 0$ in probability implies that $\mathbb E(X_n-X)^{2} \to 0$.
Comment: @AndreaBaleani I have also added a valid proof.
Comment: Thanks! The hypothesis tells me that $(X_m-X_n)$ is gaussian and by linearity i can say that it's expected value and variance are the difference and sum of those respectively. If i call $Y=X_m-X_n$, knowing that it is a certain $N(m,\sigma^2)$  can't i use on $Y$ the formula for it's 2-order moment and substitute $m$ and $\sigma^2$ ?
Comment: There is no  problem with the mean but you cannot compute the second moment. We don't know what $E(X_nX_m)$ is.  @AndreaBaleani
Comment: Ok i got it, i mistakenly used that variance of the difference is the sum of the variances (but there's 2covariance also...). Thank you very much.


Trombone C Vs Bb : Fundamental Vs transposing

Question: I'm an amateur tenor trombone player. I learnt to play by playing with other, never learnt much music theory.
I have a question regarding the "name" of the trombone. The traditional tenor trombone is the Bb trombone, or Bb/F trombone if there is a valve attachments. I understand that this name comes from its fundamental : when played "closed", this is the note played.
However, it is also a "non-transposing" instrument, and trombone parts are therefore written in ut/do/C. So trombone parts (at least mine) usually states "Trombone C".
This confuses me a lot when I try to talk about other instruments :

The alto trombone is usually said to be "Eb" : what does this means ? is this a transposing instruments? Are the parts written in Eb (like sax alto i think?)? Or is the fundamental Eb ?
I think that the sax family alternates between Bb and Eb instrument (soprano in Bb, alto in Eb, tenor in Bb, and so on). Is this the same Eb? Clearly not for the tenor : the tenor is transposing as are Clarinets and Trumpets (when they play a C, it "sounds" like a Bb).

In general, what do we mean by "this instrument is in Bb", or "in C". It seems to me that the Bb trombone is in C, which is frustratingly complicated for me. Why do we bother using the fundamental of the instruments in its name?
Edit
For example, the same vending site (Thomann for example) will call :

A Bb trumpet, a trumpet tuned in Bb (standard). Hence transposing.
A Bb trombone, a non-transposing trombone (in C) but with Bb fundamental.
Is this because the name for both refers to the fundamental? But that's messy because the trumpet player "thinks/plays" a fundamental C (hence a Bb in concert pitch).
Comment: Does this answer your question? [What is a transposing instrument?](https://music.stackexchange.com/questions/5374/what-is-a-transposing-instrument)
Comment: Trombones in C and Bb are different instruments.
Comment: Hi and thanks for the interest. No its not the same issue. I know that there exists different instruments. But the "standard" tenor trombone has a Bb fundamental hence named a "Bb trombone". But its also  a non-transposing instrument, the parts are written in ut hence written as "trombone C" because there are written in concert pitch (the "C").
Comment: Low brass instruments (trombones, tuba, euphonium) are "non-C non-transposing instruments". This means that while they may have different fundamentals, their music is always read and sounds at "concert pitch". The one exception to this UK brass music, which is usually written on treble clef.
Answer: For trombonists, the transposition (or not) depends on the musical context you're playing in:
In UK brass banding trombones are treated as a Bb transposing instrument - parts are treble clef - see a written C - play 1st position (closed) and sound a Concert Bb
In orchestral, big band, etc., trombones are treated as concert pitch instruments. Parts are often in bass clef (though they can use one of several other clefs trombonists have to read) - see a written Bb - play 1st position (closed) and sound concert Bb.
But in general, if an instrument is said to be "In Bb" then it means that playing a written C sounds a concert Bb. Or instruments in Eb, play a written C, sound a Concert Eb.
There's no confusion if you keep in mind what sounding pitch you actually want. So instead of just saying "I'm playing a Bb", say "I'm playing a Concert Bb".
Comment: Ok, my confusion could come from the fact that I've never encountered your first "UK brass band" case. I've played mainly in France and Spain.
And I agree with your remark " an instrument is said to be "In Bb" then it means that playing a written C sounds a concert Bb". That's why I've always consider trombones to be in C, and got really confused with all the "Bb trombones"
Answer: Bb- and Eb-trombones are Bb- or Eb-trombones because they are actually transposing instruments like Bb trumpets or Eb horns and because they have this root tone Bb (or Eb) when played in closed (or zero) position.
Some trombonists - are who are aware of this - can read music in C notation but then they mind that the C of orchestra pitch is position 5 (as if they would read a written  D for Bb-instruments.
Edit:
There seems to be also a confusion between the labeling of positions:
What we called zero position (closed position) is called position 1!
look at the posted picture, so the classical trombonist will play a C in the orchestra in position 6)

https://whatbrassplayerswant.com/slide-positions-trombone/
For brass band players who read treble clef notes, the written notes and slide positions are shown below. This image shows the notes as sharps
Comment: I'm sorry but that's still unclear. There is a big difference for me between the Bb Trombone and the Bb trumpet (as per the links provided). When in zero position, I agree that they both play a Bb, but the trombonist "knows" that he plays a Bb, while the trumpet player thinks "C". That's why (as far as I've seen over the last 20 years) trumpets parts are always written in Bb, while trombone parts are always written in C.
Comment: Is that correct? And if so. why such a difference?
Comment: This is correct for trombonists reading in bass clef and playing in orchestras. In Brassbands trombonists read the same way and with the same consciousness as trumpeters: They think they play C.
Comment: That's more clear! I was really confused by this "the C of orchestra pitch is position 5"... yes I also call the closed position "1", hence the C at the 6th position. FYI, at least in France and Spain **every** trombonist I've ever seen (in brassband, bigband, orchestra, symphonic, street music,...), all read music in C. So I wouldn't say "Some trombonists - who are aware of this - can read music in C notation". For me it's just the standard and *normal* way to do.
Comment: Sorry, I thought I had read here from you or someone else closed position = 0 and trying to adapt to this I used the wrong number. But I must have been wrong!
Answer: I am not a professional musician, I just want to add something to the previous answers as a (tenor - B♭) saxophone player who deals with brass sections (trombones and trumpets mainly) reasonably frequently. My interpretation might be contrary to official and semi-official guidelines for brass/woodwind sections (I have no formal training or relevant degrees).
The trombone is (kind of) like a fretless guitar. You do not have any keys, so "by definition" your instrument cannot be a transposing one. The sole purpose of making trumpets and saxophones transposing instruments is to have the fingerings identical if one switches from, say, an alto saxophone (E♭) to a tenor (B♭). The fingerings for saxophones are not linear (except for specifically-made linear-fingering instruments) and would pose a big problem for someone switching from one instrument to another within the same "family" had they not been transposed.
As far as my understanding goes with trombones, the "key" they are in, as other respondents have stated, refers to the note sounding when in "zero" (or "null") state. The only way you can really relate to most other musicians is by stating your instrument's "normal" (non-altissimo) range (keep in mind that some systems refer to the first octave as the 0 octave, and some others - 1; it's very similar in the programming world, where some languages start indices at 1 as opposed to the more "regular" 0).
Where I am, I mostly see trombone parts written in the bass clef, concert pitch, and the parts for trumpet and saxophone are written in "concert pitch" tuned to their respective instrument. So, to give you an example, if the trombone score is in C, my (B♭ saxophone) will be in D.
To sum it up, I do not consider trombone to be a transposing instrument, because it has no keys (tone holes) and functions similar to a fretless string instrument in that respect.
P.S. Languages can be very misleading. With the musical language specifically, you will often find that the same words and phrases can refer to completely different or unrelated things. Even tempo markings for classical music have to be interpreted differently depending on where they stem from. I think this is such a case. If English (or German) is not your first language, in my opinion, you will often find it difficult to understand what the hell is going on. I have studied under 3 different notation systems (4 if you take into account British English having weird names for note durations, like "hemisemidemiquaver", which is like an STD to someone who has previous experience of learning Latin and Ancient Greek).
Don't give up and develop a healthy understanding of spoken language differences and how they relate to the underlying mathematics and physics of music. If you have previous experience with natural sciences, you will also know that different countries use different common symbolics to denote the same things. It's the same with music. Treat it as another human language.
Update: following the guitar analogy, you can think of your instrument as being "tuned" to a particular note (except you can't change it by turning pegs). A guitar doesn't suddenly become a "D" instrument if you change its tuning from EADGBE (regular) to DADGBE (dropped D) - it continues to play in the same key.
Answer: The "C" in the trombone description doesn't refer to a note on the scale. Instead, it's an abbreviation of the phrase "concert pitch". The statement "trombone is a C instrument" can be translated to "trombone is a concert pitch instrument". It is also true that a concert pitched instrument plays a C pitch when the note on the staff is in the C position. On the other hand, a transposing instrument will play some other pitch when the note on the staff is in the C position.
Comment: If the "C" stands for "concert pitch", then what does the "B flat" stand for in "B flat trumpet"?


Next.js gives missing script on all npm run commands

Question: I am creating a Next.js project as I follow along in a Udemy class. I have the following package.json
{
  "name": "nextjsdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.0.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}

My directory structure is as follows below.

npm install --save next react react-dom

When I run the command
npm run dev

I receive the error:
npm ERR! missing script: dev

I receive a similar error on npm run build as well.
What am I doing incorrectly?
Thanks,
Edit 1
The only way I could get this to work was to downgrade next to V4.2.3. This seems strange that the latest version does not work.
Comment: I couldn't think of any possible defect where `npm` wont be able to see an existing script. it also didn't make sense the downgrading `next`'s version solved this, I've just created a new project with the same `package.js` you have and it worked as expected.
Comment: what `npm` version do u have? `npm --v`
Comment: npm version 6.4.1
Comment: Are you running the script from the root of the project?
Comment: I did run the script from the root of the project
Comment: Like @SultanH. , I was able to get it to work properly too.  Must be an environment issue?
Comment: I will try it again from an empty directory - very strange
Comment: was you able to figure this out?!
Comment: It worked when I followed the setup on https://github.com/zeit/next.js/#setup. No idea why it didn't work in following along with the course. Perhaps it was the nested index files though that really does not make sense. Thanks for everyone's help.
Answer: The problem might be your file structure. Try and check if you are in the same folder that holds the package.json file. A common mistake is to have a parent folder (say user/next-demo) that then holds a child folder with your nextJs project (say user/next-demo/next-demo) and then trying to run the next scripts in the parent folder.
Comment: that is true, when you create your app you should change your directory to the directory of the created app, it is mentionned in documentation


Cygwin error when doing if...then...fi - Bash script

Question: I just started bash shell programming. I have installed Cygwin on my Windows 7 computer. I started writing a script using this tutorial.  My script requires an argument to be passed to it, if it doesn't it should display an error message. This is the code directly from the tutorial and the same one in my code:
[ $# -eq 0 ] && { echo "usage: someArgument";  exit 1; }

When I do the following:
sh ./myscript.sh

it gives me this error:
-bash: /home/Me/myscript.sh: line 5: syntax error: unexpected end of file

"Unexpected end of file" means I have missed a fi or done, etc. somewhere.
I double-checked my code, but found nothing. Plus, when I comment out the line the script works perfectly fine.
I tried using a if...then...fi:
if [ $# -eq 0 ]
then
    echo "usage: someArgument"
    exit 1;
fi

but to no avail!
Please help, it's been stumping me.
Comment: Consider providing an exact script reproducing your problem. It is not clear where your line "5" is.
Comment: @torrentialcoding I am using Notepad++. I just noticed in the bottom right corner the words change from Dos/Windows to UNIX when I run dos2unix on the script (see my answer).
Comment: @Java I believe Notepad++ allows you to save a file in Unix mode. This will save you an extra step of having to run the dos2unix tool to make your scripts usable.
Comment: @torrentialcoding Yeah it does. You can go to Edit>EOL Conversion>UNIX Format, or set as default under Peferences. That's good news :)
Answer: Probably you have \r or some other invisible symbols in the script. Please add set -x to the beginning of the script to switch debug on and run script once again.
Answer: Sorry for the trouble. I did some research on the invisible symbols mentioned by Igor. You have to run dos2unix in Cygwin which solved it for me. Dos-type files have \r\n instead of \n and some other stuff which makes Cygwin confused.
This:
$ dos2unix ./myscript.sh
$ sh ./myscript.sh

works correctly.
Answer: As an alternative, you can use bash parameter expansion to test for an unset variable. With no positional parameters, $1 will be unset:
: ${1?"usage: someArgument"}

The : command is a null-op, serving as a hook to expand its argument, which is $1. If $1 is unset, the word following the ? will undergo some expansion and be printed to standard error, after which a non-interactive shell will exit.
(This isn't a solution to your DOS line-ending problem, but just another approach to enforcing that a variable is set.)


LDAP userPassword only works with plaintext

Question: I have setup openLDAP server on an ubuntu machine.  I am trying to test user authentication, but am running into a problem.  If, in ldap, the userPassword contains a plaintext password, authentication works just fine.  However, if I set the value of userPassword to be a hashed password (like sha256), the authentication fails.  Do I need to tell openLDAP that I am using sha somewhere?
FYI, I am using openLDAP and Apache Directory Studio to interact with it.  I am testing authentication by trying to bind using a php script.
Answer: According to the FAQ, OpenLDAP releases prior to 2.4.32 do not support SHA-2 algorithms including SHA256. 2.4.32 and later releases need to be built with contrib/slapo-pw-sha2 to support SHA-2. You can use SHA-1 or Salted SHA-1 out of the box. Please see http://www.openldap.org/faq/index.cgi?file=1467 and http://www.openldap.org/doc/admin24/security.html#Password+Storage for more.


Como faço para trazer os cpfs iguais de outras tabelas?

Question: Bom dia, gostaria dessa ajuda.
Tenho uma tabela de "INSCRIÇÃO" onde a mesma possui 2 chaves estrangeiras (CAND_SQ e CANDPL_SQ).
Ambas as chaves estrangeiras possuem um campo CPF.
Gostaria de saber como eu trago os cpfs que são iguais dentro da inscrição.
Ou seja, atualmente tenho uma INSCRIÇÃO onde pode ser feita de duas maneiras diferentes. Inscrição Regular e Inscrição Atraso.
Quando eu for fazer a Inscrição Atraso, caso eu já tenha feito a Inscrição Regular não poderei fazer a Inscrição Atraso.
Comment: Afinal você utiliza o MySQL ou Microsoft SQL Server? Você quer dizer que o conteúdo dos campos CAND_SQ e CANDPL_SQ são unicamente CPF's e quer saber quais se repetem na tabela INSCRIÇÃO?
Comment: É porque eu posso dar o select tanto no MySQL quanto SQL Server, aqui.
Exato, quero saber quais se repetem na tabela INSCRIÇÃO.
Comment: Pesquise pela cláusula HAVING que deve atender a suas necessidades. Como não entendi como está organizada sua tabela não posso chutar um comando SQL.
Answer: Para ver quais CPFs se repetem:
Select t.cpf
from tabelaComCampoCAND_SQ t
inner join tabelaComCampoCANDPL_SQ t2 on t1.cpf = t2.cpf

Mas se a necessidade é só uma validação antes de fazer inscrição atraso, basta vc consultar na tabela de inscrição regular se o CPF já existe:
Select 1
from tabelaComCampoCAND_SQ t
WHERE t.cpf = (valorCpf)


Toggle display of an an element when you click on another element

Question: I have a p element and a hidden pre element. I want to make it so that when you click on a p element with (for example) id/class = "p1", it changes the display of the pre element with (for example) id/class = "pre1".
This is my javascript code :
var p = 1;
setInterval(function() {
   if(p <= document.querySelectorAll(".show").length) {
      document.getElementById("display-pre"+p).onclick = function() {
         console.log(p);
         if(document.getElementById("display-pre-a"+p).style.display == '') {
            document.getElementById("display-pre-a"+p).style.display = 'block';
         } else if(document.getElementById("display-pre-a"+p).style.display == 'block') {
            document.getElementById("display-pre-a"+p).style.display = 'none';
         }
      };
      p++;
      if(p > document.querySelectorAll(".show").length) {p = 1;}
   }
}, 100);

This code kind of works but not really. It sometimes changes other elements and sometimes does nothing.
This is my full javascript code : https://pastebin.com/wEwdKKLy
This is my html :

    <input type="text" id="search"/>
    <button type="submit" onclick="query()">Submit</button>
    <button type="submit" onclick="newInput()">New</button>
    <button type="submit" onclick="remove()">Delete</button>
    <button type="submit" onclick="deleteAll()">Delete All</button>

Test-a

Test-b

Test-ba

TEST-SHOW

Note : elements with class "show" have display none
I tried doing this with jquery but I'm just began learning jquery yesterday and it didn't work (I had the same problem as this).
Jquery code I tried : https://pastebin.com/cBisCmEZ
Thank you for your help.
Comment: Why are you setting onclick handlers inside a setInterval, especially at 100 ms interval at that?
Comment: I was thinking that it would basically test if the user has clicked on the p element 10 times per second.
Answer: Here is the solution for you

$("p[data-id]").on("click", function() {
  var idFound = $(this).data("id");

  $("[data-pre='"+ idFound +"']").toggleClass("show");

});
pre {
  display:none;
}

.show {
display:block;
}

This is the paragraph

This is the pre

I recommend using a button element for anything you click so that it stays accessible.


Creating a node with PHP cURL client returns 401 error - X-CSRF token always empty

Question: A recent update to Services and Drupal requires a csrf token, and it broke the PHP cURL client samples.
I am trying the sample code for Services to:

Create a node here https://drupal.org/node/1334758
Log in a user here https://drupal.org/node/1491754

It fails with 401 error. <code>$csrf_token</code> is always empty for me, so that should be the problem, but I am not sure how to return it with cURL. Any tips?
Answer: I fixed the DrupalREST class by Randall Kent here https://github.com/RandallKent/DrupalREST.PHP/issues/2


How to convert spark rdd to a numpy array?

Question: I have read textFile using spark context, test file is a csv file. Below testRdd is the similar format as my rdd.
testRdd = [[1.0,2.0,3.0,4.0,5.0,6.0,7.0],
[0.0,0.1,0.3,0.4,0.5,0.6,0.7],[1.1,1.2,1.3,1.4,1.5,1.6,1.7]]

I want to convert the the above rdd into a numpy array, So I can feed the numpy array into my machine learning model.
when I tried the following
 feature_vector = numpy.array(testRDD).astype(numpy.float32)

It gives me the below TypeError:
TypeError: float() argument must be a string or a number

How Should I covert the spark rdd into a numpy array.
Answer:
You'll have to collect the data to your local machine before calling numpy.array:
import numpy as np

a = np.array(testRdd.collect())
print(a)
#array([[ 1. ,  2. ,  3. ,  4. ,  5. ,  6. ,  7. ],
#       [ 0. ,  0.1,  0.3,  0.4,  0.5,  0.6,  0.7],
#       [ 1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7]])

Or if you want each row as a separate array:
b = testRdd.map(np.array).collect()
print(b)
#[array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.]),
# array([ 0. ,  0.1,  0.3,  0.4,  0.5,  0.6,  0.7]),
# array([ 1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7])]

Comment: Is there a way to do this without collect()?
Comment: It doesn't make sense to do it without `collect` - you can't have a spark dataframe with a column of numpy arrays. What are you trying to do?
Comment: I'm about to post this as a separate question - but I want to train a distributed deep learning model with horovod which doesn't accept dataframe or rdds, only nparrays. I want to write a udf which will use worker memory to convert the dataframe column to nparray in small batches. My starting point is a massive spark dataframe that cannot be collected in driver
Comment: @maverik in that case, do the conversion to numpy array in the `udf`. That's essentially what happens in `testRdd.map(np.array)` (I know that's an `rdd`, but you can make a parallel between `rdd.map` and a `udf`)
Comment: Posted: https://stackoverflow.com/questions/60441853/spark-dataframe-to-numpy-array-via-udf-or-without-collecting-to-driver
Answer: I had the same problem and collect() is not very efficient.
For me writing multiple numpy files on the executors worked pretty well, and loading multiple files using numpy is no problem. The number of resulting files equals the number of partitions.
In my case I had to put the files into hdfs as I have no access to the executor nodes:
from pyspark.sql.types import *
from pyspark.sql.functions import spark_partition_id

def write_numy(list):
  import numpy as np
  from pyspark.taskcontext import TaskContext
  import os

  ctx = TaskContext()
  id = ctx.partitionId()

  local_path = "/tmp/test"+str(id)+".npy"
  hdfs_dest_path = "/tmp/test/"
  np.save(local_path, np.array(list))
  os.system("hadoop fs -put "+local_path+" "+hdfs_dest_path)

schema = StructType([ StructField("ID", IntegerType()), StructField("TS", ArrayType( IntegerType()) )])
data = spark.createDataFrame(spark.sparkContext.parallelize(range(1, 1999)).map(lambda x: (x, range(1, 100)) ),schema)

data.rdd.foreachPartition(write_numy)

Comment: This is a very good solution to allow spark to write numpy files in a distributed manner.
Answer: My best shot at this would be:
import pandas
arr = rdd.toDF().toPandas().values

The rdd needs to be converted to a dataframe, the dataframe rendered as pandas, and then the underlying values (numpy arrays) exposed from there.
Edit -- You said you don't like that so have you tried just doing a map? Like so:
arr = np.array()
rdd.map(lambda x: np.append(arr, x))

You should include everything you tried in your question.
Comment: I don't want convert rdd into dataframe, I tried this solution, it takes enormous amounts of time showing nothing in my machine. So, is there any other solution?
Comment: @VamsiNimmala I made an edit to try a different approach


Error when playing AudioFile with Agora in Unity3d on iOS

Question: audio file plays on windows, but will not play on iOS. Tried .wav and .mp3 as well as a URL to a .mp3 file
<code>2020-08-06 16:40:18.336561-0500 Dev[6676:1857168] ExtAudioFile.cpp:192:Open: about to throw 'wht?': open audio file
2020-08-06 16:40:18.336920-0500 Dev[6676:1857168] [avae]            AVAEInternal.h:109   [AVAudioFile.mm:134:AVAudioFileImpl: (ExtAudioFileOpenURL((CFURLRef)fileURL, &_extAudioFile)): error 2003334207
2020-08-06 16:40:18.337266-0500 Dev[6676:1857168] ExtAudioFile.cpp:192:Open: about to throw 'wht?': open audio file
2020-08-06 16:40:18.337668-0500 Dev[6676:1857168] [avae]            AVAEInternal.h:109   [AVAudioFile.mm:134:AVAudioFileImpl: (ExtAudioFileOpenURL((CFURLRef)fileURL, &_extAudioFile)): error 2003334207
</code>
Answer: I was able to reproduce this problem.  It is because the file path you provide.  In Unity, you should place your audio file in StreamingAssets folder, and pass the file path Application.streamingAssetsPath + "/filename" to the PlayEffect call.


Email file using grails export plugin

Question: Currently I am using the export plugin to create an excel file on the fly on the server and then sending it to the browser via response.outputstream (done by the export plugin). Instead, what I want it to create the excel file and once done, email it to the user. Assuming I have the email can someone show me some sample code?
I looked into the export plugin code and it looks like it writes to the response output stream. Can I somehow read from this output stream, create a file, not store it to disc and just email it instead?
Answer: Export plugin can create file in server as well.
File exportOutput = new File("/home/mkb/test.csv")
def exportOutputStream = new FileOutputStream(exportOutput)
exportService.export('csv', exportOutputStream, User.list(), fields, labels, formatters, parameters)

and once you got the file then you can easily email it using grails mail plugin as an attachment.
Comment: should be marked as the right answer. The export method only need the outupstream, it can be from httpresponse or from a File
Answer: You want to use the attach(String fileName, String contentType, InputStreamSource source) method in the Grails Mail DSL.  This allows you to do everything in memory without writing a file to disc.
import org.springframework.core.io.ByteArrayResource
...

OutputStream outputStream = new ByteArrayOutputStream()
exportService.export(type, outputStream, objects, fields, labels, formatters, parameters)
InputStreamSource inputStream = new ByteArrayResource(outputStream.bytes)  //copy output stream to input stream

sendMail {
   mutipart true
   to "firstname.lastname@example.com"
   attach "yourfile.txt", "text/plain", inputStream
}

More info here.
Hope that helps!

Email file using grails export plugin


$A= \{w \in \{a, b\}^∗ \mid \text{length of $a \leqslant 5$ and length of $b \leqslant 20$}\}$

Question: I came across this proof-question to check the regularity of the following language:
$A= \{w \in \{a, b\}^∗ \mid  \text{length of $a \leqslant 5$ and length of $b \leqslant 20$}\}$
I tried first checking its regularity with pumping lemma to see whether it satisfies the conditions or not, but got stuck at pumping it because of the length limit of a's and b's. I am not sure how I can further proceed with this question.
Any help would be greatly appreciated.
Thank you!
Answer: If you have a word on the alphabet $\{a,b\}$ with at most $m$ occurrences of $a$ and at most $n$ occurrences of $b$, then the length of your word is at most $m + n$, right? Consequently, your language is finite and hence regular.


How can I override a module-defined view and export to code?

Question: I'm using nrembrowser to provide a media library and allow users to insert media via a wysiwyg interface. The module provides its own view which I've altered. I keep my views in code (using features) but I don't know any way to override an existing module-defined view via code (ie something similar to strongarm, but instead of overriding a variable, it's overriding a view). I've solved the problem by using a nrembrowser hook to change the view to my custom one, but I'd be interested in knowing if I could've overridden the module's default view in some way.
Answer: Using hook_views_default_views_alter(). There's a page on this on drupal.org. As far as I know there's no way to have features automatically export an overridden view and put it in a hook_views_default_views_alter(), and it looks like there's actually an issue with using features together with this hook.


How to pass variables from .env or docker-compose.yaml file to nginx server file

Question: I have a docker-compose.yaml file and a .env file. If I declare a variable in the env file, I can access it in docker-compose. So, this is good.
But, I would like to change nginx's default.conf properties, namely the server_name = xxx to be generated from the value I provide in the env.
So, my env looks like this (only sharing a portion)
#.env
NGINX_SERVER_NAME=dev.example

In docker-compose I mention this variable here:
nginx:
  container_name: ${APP_NAME}-server
  environment:
    - SERVER_NAME=${NGINX_SERVER_NAME}

And in default.conf I simple call the variable like this:
server_name ${SERVER_NAME};

I am expecting the default.conf to contain server_name dev.example but it contains the token i.e. ${SERVER_NAME}
How can I achieve what I am looking for?
Thanks
Answer: this seems ok to me. try to use quote around your env variable in compose file.
nginx:
  container_name: ${APP_NAME}-server
  environment:
    - SERVER_NAME="${NGINX_SERVER_NAME}"

or try to write your env variable like this.
nginx:
  container_name: ${APP_NAME}-server
  environment:
    SERVER_NAME: "${NGINX_SERVER_NAME}"


Question on number theory

Question: If a²+(5/2)b²+c²= 2ab+bc+ca then a+2b+2c equals what? I am unable to think how to solve it.. Please help
Comment: One trivial solution is $a=b=c=0$  The question is if there are others.  Why or why not?
Answer: Hint:$(a-2b)^2+(b-c)^2+(c-a)^2=0$
Comment: How did u get this?
Comment: @danny, by completing the squares

Question on number theory


How do I modify the output of iframes generated by Media oEmbed module?

Question: I'm trying to add a title attribute to all iframes outputted by the D7 media_oembed module with Youtube videos, but can't find the write entry point for it. There aren't any templates with the raw structure to override.
Can someone point me to the right place please?
Comment: Can you specify where are the iframes you're referring to? The media module, by itself, stores/display media files local to the Drupal installation.
Comment: I've updated the op.
Answer: The HTML is being generated by the YouTube oEmbed API.
If you inspect the themes/media-oembed.tpl.php template & the theme preprocess include themes/media_oembed.theme.inc, you can see that  media_oembed_get_data() looks up the plugin which pulls the data from the API. In the returned data, the html element is used to fill the $content variable in the template.
The module provides a few different means to hook into retrieval/process/display of the data:

hook_media_oembed_request_alter($parameters, $plugin, $url) can be evoked to alter data before plugin retrieval.
hook_media_oembed_response_alter($embed) can be evoked to alter data after plugin retrieval.
hook_preprocess_media_oembed(&$variables) can be evoked before processing the template for display.

Whatever means you use, it looks like you'll need to manipulate the HTML string directly to add the title element to your output.


How to set boolean flag based on multiple property selections?

Question: Overview:
I've bound the IsEnabled property of a button to a bool flag in it's related view model.
In the current UI setup the IsValidTagRequest should be set to true if all three properties have a selection, i.e RaisePropertyChanged() has fired in each setter.
What I did try is setting the private bool _isValidTagRequest to true after the RaisePropertyChanged() of each of the required properties - RegNumber, SelectedZone, SelectedParkDuration.
But this scenario doesn't account for all three properties having a value selected to enable the button.
Question:
Does anyone know how I can check that multiple properties have been changed before enabling a bool property to true?
The bool proeprty is defined as follows, followed by each of the required properties to be changed before IsEnabled is set to true:
    private bool isValidTagRequest = false;
    public bool IsValidTagRequest
    {
        get { return isValidTagRequest; }
        set
        {
           if (value != isValidTagRequest)
           {
                isValidTagRequest = value;
                RaisePropertyChanged("IsValidTagRequest");
           }

        }

    }

Three properties - RegNumber, SelectedZone, SelectedParkDuration:
    private string _regNumber;
    public string RegNumber
    {
        get
        {
            return this._regNumber;
        }

        set
        {
            if (_regNumber != value)
            {
                _regNumber = value;
                RaisePropertyChanged("RegNumber");
            }
        }
    }

    private ZoneInfo _selectedZone;
    public ZoneInfo SelectedZone
    {
        get
        {
            return this._selectedZone;
        }

        set
        {
            if (_selectedZone != value)
            {
                _selectedZone = value;
                RaisePropertyChanged("SelectedZone");
            }
        }
    }

    private TimeSpan? _selectedParkDuration = TimeSpan.Parse("00:00");
    public TimeSpan? SelectedParkDuration
    {
        get
        {
            return this._selectedParkDuration;
        }

        set
        {
            if (_selectedParkDuration != value)
            {
                _selectedParkDuration = value;
                RaisePropertyChanged("SelectedParkDuration");
            }
        }
    }

And for context, the binding in XAML is defined as follows:
<Button Grid.Row="3"
                    Grid.Column="1"
                    Width="200"
                    Height="100"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Bottom"
                    Command="{Binding TagRequestCommand}"
                    Content="Send"
                    IsEnabled="{Binding IsValidTagRequest,
                                        Mode=TwoWay}"
                    Style="{StaticResource CustomButtonStyle}" />

Answer: For example, you could call RaisePropertyChanged("IsValidTagRequest"); at the end of each setter of your 3 properties.
So when one of theses properties are set, the binding of IsValidTag would be reevaluated.
Though you should update the code of the getter of "IsValidTagRequest" to return the combination of the 3 properties, something like:
public bool IsValidTagRequest
{
    get { return SelectedParkDuration != null && SelectedZone != 0 & RegNumber != "" };
}

Please mark as answer if that helps, thank you
Stéphanie


Docker selenium 2.53 cannot override maxInstances and maxSession with env variables

Question: so I have the following docker compose config:
  selenium-hub:
    image: selenium/hub:2.53.1
    environment:
      - GRID_BROWSER_TIMEOUT=30000

  chrome:
    image: selenium/node-chrome-debug:2.53.1
    volumes:
      - /dev/shm:/dev/shm # Mitigates the Chromium issue described at https://code.google.com/p/chromium/issues/detail?id=519952
    environment:
      - NODE_MAX_INSTANCES=4
      - NODE_MAX_SESSION=4

  firefox:
    image: selenium/node-firefox-debug:2.53.1
    environment:
      - FIREFOX_VERSION=45.8.0
      - NODE_MAX_INSTANCES=4
      - NODE_MAX_SESSION=4

Even though I override NODE_MAX_INSTANCES and NODE_MAX_SESSION I still see
maxSession=1 and maxInstances=1 in /opt/selenium/config.json, so the question is that what could be the issue here as mostly it is the same config as in official selenium docker wiki ?
Answer: Seems like I found the answer here
Copy from maintainer's comment:

that functionality was released first in 2.53.1-americium. when
  releasing americium, we didn't have the fleshed out release process,
  so the image version you have "2.53.1" doesn't have that functionality
  to add "NODE_MAX_INSTANCES" and such. You can get this functionality
  by using the version 2.53.1-americium or 2.53.1-beryllium whichever
  you wish.


Wrong predictions for weekend, but good predictions for weekdays

Question: I have a set of 3 years of daily data. I saw weekly and annual seasonality in the data so I used msts time series and tbats (from the forecast package in R) to fit the best fitted model.
The predicted values for weekdays are with 5% of the actual data but it has very off predictions for weekend. I did not expect that as I included daily seasonality in a week (different weekday and weekend patterns) in my time series which I though will consider the seasonality correctly. I wonder if anybody have any idea whats going wrong with my data.
I also used ts with single seasonality of frequency 7 and again used tbats to fit a model. Th new model has better predictions for weekend but worse predictions for weekday. I also tried auto.arima (also from the forecast package) but as I have a huge number of data points, arima was not able to find a good model.
Comment: There's unlikely to be enough information here for anyone to identify what the problem might be. I'd start with a plot of your data, or at least part of it, as well as corresponding fitted values (that still won't be sufficient, but it may give some clues or enable people to suggest some things to try)
Comment: why don't you provide the data via dropbox
Comment: Can you tell us more about the data?
Comment: Well you didn't mention that until now (the shipments part). Can you more mathematically define how you handled the seasonality patterns to help us understand what might have gone wrong?
Comment: I used msts command in r by including seasonality of 7 for weekly seasonality and 365.25 for annually seasonality. Is that what you meant?
Comment: https://www.dropbox.com/business/business-free-trial?_tk=sem_goog_b&_kw=dropbox|e&_net=g&_ad=35064061902|1t1&_camp=sem_google_b_dropbox_us-english&gclid=CIOmmbjN_MACFaUF7AodgSMASw is the site to obtain access to dropbox
Answer: Some exploratory data analysis:
In summarizing your data at the monthly level, I noticed you have couple of issues going on in your data.

In the test period data which begins at January 2010 there is a
significant "bending upwards" of trend.
In addition I also see there is a high degree of variability in
seasonality, so you might want to apply an appropriate
transformation using box-cox transformation.

Coming back to the first part of the issue, before using an extrapolation method such as ARIMA or exponential smoothing or fixated on data mining/dredging, I would recommend to find out "why" the trend changed direction and went upwards. Unless you know the "why" part of this trend change, no matter what method you use, it is going to be impossible to improve accuracy or build better forecast. As noted in answer to your earlier question, the only way to build good forecasts for your problem is to systematically adjust the forecast from an extrapolative method using a well structured judgement or use an analogous time series top forecast time series. You could also use an ensemble of judgemental forecasting and extrapolative methods. Using univariate extrapolative method alone on a non-experimental data such as yours bound to produce poor predictions. It is important to do some initial  data analysis before fixating on methods and techniques, it might go a long way in improving predictions. Also, using a low frequency data such as rolling the daily data to monthly data and doing data visualization also is very helpful to better understand the data and ultimately better predictions.
Hopefully this analysis provided you some directions for future research.
I have to agree with Whuber, that only way to assess predictive performance of an extrapolation method is using hold out set. Simplest is the single origin forecast,If you have enough resources then I would do rolling forecast testing or cross-validation or jackknifing such as the one suggested by @Irishstat. See the link below for some nice blog post by Rob Hyndman on how to do this for time series data.
http://robjhyndman.com/hyndsight/tscvexample/
http://robjhyndman.com/hyndsight/rolling-forecasts/
I'm also curious to know why you would need a daily forecast for 1 year. In practice based on my own experience, you would use low frequency data (such as monthly/weekly) to do a full year forecast for planning purpose and use high frequency data such a hourly/daily to do a  very very short term forecast. When I mean very very short term, update and revise forecast every month. As an example, If I had your data (assuming you want to forecast for 2010), I would predict full year 2010 data using monthly data, and just produce daily forecast for January 2010. By this use you could get the bests of both worlds by have low frequency (less noise) and high frequency (daily data) forecasts. Once you have Jan 2010 data, you could produce daily forecast for February and keep producing and updating the daily forecast. You could repeat this for every month as the new data arrives. In addition you could also reconcile the monthly and daily forecast.
Comment: Box-Cox transformations should be based upon the linkage between the error variance and the expected value NOT the variance of the original series.. Also your remarks about forecasting out 366 values and measuring accuracy for 366 values echoes my comments above. It is not naive to do this but simply inappropriate,in my opinion.
Comment: As noted in my post, single origin forecast evaluation is one of the several options you could also do cross validation or rolling forecast evaluation. Out of curiosity, does Autobox provides multiple origin forecast evaluation ?
Comment: AUTOBOX does not do this automatically but it does allow the user the repetitive usage of a model from multiple origins.
Comment: @forecaster thank you for your discussion. I dont need a full year forecast and Im only looking for weekly forecasts. I only used one year ahead as a test data set. I should mention that not all the time, integrating the observed data for January 2010 to the historic data will improve forecasts for Februray. I did an experiment and compared the errors for februray forecast without adding new observed data and February forecast by including January data. Surprisingly, it makes my predictions worse. This statement does not work for all data sets as I tested.
Answer: You data https://www.autobox.com/FATEME/TestData.xlsx is here . I suggest other readers take the data and try to analyze it. On first view the 1096 historical daily values appear to have a large number of "outliers". These unusual values are in effect mostly usual as certain holidays have a significant effect. The problem you are having has to with your design matrix. You assume that the effect is day-of-the-week vs weekend. This is wrong because each day has it's own effect and certainly the 5 work days are not equal and the two weekend days are not equal in their importance. There have been major shifts in the days-of-the=week effects. Furthermore specific days-of-the-month and specific months of the year are very important in addition to Friday before Holidays impacts. Next there is a visually obvious level shift ( on or about  1/27/09 ) in your data that needs to be accounted for such that the final model coefficients are robust and meaningful.
Using AUTOBOX (a piece of software available from http://www.autobox.com/cms/ which I have helped develop) in a totally automatic fashion a model containing both deterministic effects and memory (ARIMA) was forged.
Attached is the equation (in two parts)
 and . A test for the sufficiency of a model is the ACF of the errors suggests randomness. Following is the Forecast plot.. I have added a representative screen shot of the forecasts presented in tabular fashion (forecasts then lower limit then upper limit).
With apologies in advance the 1096 values were able to be characterized with 58 statistically significant coefficients.
The summary statistics from the model are as follows
EDIT: I have added the 366 forecasts from 1 origin 12/31/2009 https://www.autobox.com/FATEME/AB50PRO.123
Comment: That blue background screenshot is very difficult to read (at least for me it kind hurts the eyes). Another advice is to make your code's output pictures clickable so one can increase and visualize them with a greater size. If you are interested, [here](http://meta.stackexchange.com/questions/238476/is-there-a-way-to-include-a-picture-that-gets-bigger-when-clicked-on) is the post which explains how to do it.
Comment: This is impressive (+1). Since you have challenged others to analyze these data you need to report the performance of your forecasts on the test dataset, which has been supplied in the spreadsheet specifically to evaluate competing models. I suspect an approach that extends your technology to generalized linear models ought to work even better, because these data could fruitfully be conceived of as realizations of a Poisson process (in which the underlying mean process is of the form you software currently handles). Do you test the homoscedasticity of the residuals?
Comment: It's going too far to accuse the OP of naiveté when you do not know their objectives, especially the time horizon they must use for predictions.  It would be fair, though, for you to posit specific purposes or contexts and then propose (and apply) reasonable methods of using the held-out data for assessing the accuracy of forecasts.
Comment: My problem is that measuring forecast accuracy for the next 366 values from 1 origin is a sample of 1 . I
Comment: My problem is that measuring forecast accuracy for the next 366 values from 1 and only 1 origin is a sample of 1. If one brought in the next value (1/1/2010) and obtained a new set of forecasts for the remaining 365 values a second/different estimate of accuracy could be computed etc..... In general one has to specify the number of values to be used to measure accuracy and then do so from many origins. It is very naive to measure accuracy for daily data for a holdout period of 366 days. I would suggest a 30 day out holdout from 336 origins could be appropriate BUT a lot of work for this task.
Comment: AUTOBOX tests the homoscedastic assumption via the procedures described in Tsay http://www.unc.edu/~jbhill/tsay.pdf.
Comment: ok I meant that in my opinion it is a stretch for "anybody" to use daily data to predict out 366 days and/or to measure accuracy for that length of time as forecasts can be readily updated as new daily data becomes available. Monthly data/predictions are more appropriate for a 366 period out horizon . I did not mean to accuse the specific OP of anything in particular . I was making a generalization based upon a long consulting history in this arena.


Normal prior for Binomial likelihood

Question: Pardon my ignorance, i am new to Bayesian Analysis.
I am trying to use Normal prior for a binomial likelihood,  which of these are most likely candidates        ( $\bar{x} $, $ \mu $, $ \sigma $ ) for prior and most likely candidates for constants ? Please advise.
Comment: It seems to me like your question does not make much sense as it stands now. Perhaps you'd benefit from reading introductory chapters/papers to the Bayesian approach.
Comment: $\bar{x}$ is not a parameter of the normal distribution (it's the maximum-likelihood estimate of $\mu$)
Answer: If the likelihood follows a binomial distribution, your conjugate prior is the beta distribution. Please check this great answer on the intuition of beta distribution.
After reading that answer, note that Beta(a, b) distribution can be approximated by the Normal distribution when a and b are sufficiently large.
You can play with a Beta distribtuion on this link. As you incraese a and b, the pdf looks more and more like the normal distribution.

Normal prior for Binomial likelihood


How to interpret hazard ratios of Cox output?

Question: I'm really struggling to understand how to interpret my R outputs in terms of   hazards ratios. I have ran a Cox proportional hazard regression to compare survival between 2 treatment groups (neutron and photon therapy) and I have adjusted for the biological site of cancer:
neutron$site <- factor(neutron$site, levels = c("Cervix", "Rectum", "Bladder", "Prostate")).

Regression:
cox2 <- coxph(Surv(stime, death)~treatment + site, data = neutron)

and finally the output:
exp(coef) exp(-coef) lower .95 upper .95
treatmentPhotons    0.7051     1.4183    0.4712     1.055
siteRectum          1.9813     0.5047    1.0837     3.622
siteBladder         1.8913     0.5287    1.0482     3.412
siteProstate        0.8243     1.2132    0.2690     2.525

How would these values be interpreted relative to the baseline?
Comment: By baseline, do you mean reference category? or baseline hazard?
Comment: Sorry, i guess i mean the baseline hazard? I just included the code for the reference so you could get an idea of what I was trying to do.
Comment: oh in that case I'm not really sure. I assumed you wanted to interpret the hazard ratio between your levels and the reference category.
Comment: Okay so how would I do that?
Comment: ok I'm typing that up now. I hope it's what you mean. well, we'll see.
Answer: A hazard rate is the chances of the event happening, and the hazard ratio is simply the ratio of the two rates between two levels of a predictor. Or between a unit increase if its a continuous predictor. It lets us compare what happens to the chances of the event happening when you move between one level and another level.
Ok, now to your output.
Your baseline is the label that is not there. So, treatment photons is being compared to treatment neutrons. Your 4 levels of cancer location are all being (individually) compared to cervix.
The first column exp(coef) is literally the hazard ratio comparing the level listed to the reference(baseline) level. So having photon treatment reduces the hazard ratio by 30% compared to having neutron treatment. i.e. the chances of the event happening is 30% less when having photon treatments compared to neutron treatments.
Having cancer in the rectum increases the hazard ratio by 98% compared to having it in your cervix. i.e. It basically doubles the chances of the event happening (compared to the other group). Having it in the bladder increases it by 90% compared to having it in your cervix, and so on for the other levels of location.
These percentages is literally just the difference between the number and 1, because 1 is when a ratio is perfectly balanced; there is no difference between the two parts being compared. If the hazard ratio is, for example, 0.6 then i say 1-0.6=0.4, so the hazard ratio decreased by 40%, if it's 1.6 then i say 1.6-1=0.6, so the hazard ratio increased by 60%.
The column exp(-coef) is just the hazard ratio going the other way. Having cancer in your cervix decreases the hazard ratio by 50% compared to having it in your rectum. This might sound confusing but they're just mirror opposites of each other, you've just swapped the numerator on the ratio. i.e. 1/1.98=0.5, 1.98/1=1.98.
The last two columns are the upper and lower confidence intervals for your estimate.
I hope this is what you're after and I haven't completely missed the point. Sorry if i have.