How do you implement type-specific functionality when using polymorphism does NOT make sense?

Question: A common red flag that an OOP language is not being leveraged properly looks like this:
if (typeof(x) == T1)
{
    DoSomethingWithT1(x);
}
else if (typeof(x) == T2)
{
    DoSomethingWithT2(x);
}

The standard "fix" for such design issues is to make T1 and T2 both share an interface, either through inheritance of a base type or implementation of a common interface (in languages that support it); for example, in C# a solution might be:
public interface IT
{
    void DoSomething();
}

However, sometimes you want to implement functionality that differs based on the type of an object but that functionality does not belong within that object's type; thus polymorphism seems the wrong way to go.
For example, consider the case of a UI that provides a view of a given clump of data. Supposing this view is capable of rendering various layouts and controls depending on the type of data being presented, how would you implement this type-specific rendering without a bunch of if/else statements?
For reasons that I hope are obvious, putting the rendering logic in the type itself strikes me as a very bad decision in this case. On the other hand, without coupling the type of data object to its visual presentation I have a hard time seeing how the if/else scenario is avoided.
Here's a concrete example: I work on a trading application which utilizes many different pricing models for various market products. These different models are represented by types inheriting from a common PricingModel base; and each type is associated with a completely different set of parameters. When the user wants to view the parameters for a particular pricing model (for a particular product), currently these are displayed by a form which detects the type of the model and displays an appropriate set of controls. My question is how this could be implemented more elegantly than it is currently (with a big if/else block).
I realize this probably seems like a very basic question; it's just one of those gaps in my knowledge (of solid OOP principles? design patterns? common sense?) that I figured it's about time to fix.
Answer: We are injecting (Spring.Net) such functionality into dictionaries by type.
IDictionary<Type, IBlahImplementor> blahImplementors;

blahImplementors[thingy.GetType()].Do(thingy);

This dictionary could be managed by a kind of repository which provides the functionality.
As an implementation detail, the implementor usually knows the type it depends on an can provide it itself:
interface IBlahImplementor
{
  Type ForType { get; }

  void Do(object thingy);
}

Then it is added to the dictionary like this:
IEnumerably<IBlahImplementor> blahImplementors;
foreach (var implementor in blahImplementors)
{
  blahImplementors.Add(implementor.ForType, implementor);
}

Remark: IMHO, it is very important to understand that some things do NOT belong into a class, even if providing subtype-specific implementations would make life much easier.

Edit: Finally understood your concrete example.
It is actually about instancing the right UI control to show the pricing models parameters. It should be possible with the pattern I described above. If you don't have a single UI control for a pricing model, you either create it or you write a UI configurer or something like this which sets up the required controls.
interface IPricingModelUiConfigurer
{
  Type PricingModelType { get; }
  void SetupUi(Control parent, IPricingModel model);
}

Answer: What you described is pretty much exactly the use case for the Visitor Pattern.
EDIT: For your concrete example, you could apply the visitor pattern like this:
// interface used to add external functionality to pricing models
public interface PricingModelVisitor {
    void visitPricingModel1(PricingModel1 m);
    void visitPricingModel2(PricingModel2 m);
    ...
}
// your existing base-class, with added abstract accept() method to accept a visitor
public abstract class PricingModelBase {
    public abstract void accept(PricingModelVisitor v);
    ...
}
// concrete implementations of the PricingModelBase implement accept() by calling the
// appropriate method on the visitor, passing themselves as the argument
public class PricingModel1 : PricingModelBase {
    public void accept(PricingModelVisitor v) { v.visitPricingModel1(this); }
    ...
}
public class PricingModel2 : PricingModel {
    public void accept(PricingModelVisitor v) { v.visitPricingModel2(this); }
    ...
}
// concrete implementation of the visitor interface, in this case with the new
// functionality of adding the appropriate controls to a parent control
public class ParameterGuiVisitor : PricingModelVisitor {
    private Control _parent;
    public ParameterGuiVisitor(Control parent) { _parent = parent; }
    visitPricingModel1(PricingModel1 m) {
        // add controls to _parent for PricingModel1
    }
    visitPricingModel2(PricingModel2 m) {
        // add controls to _parent for PricingModel1
    }
}

now, instead of using a big if-else block when you need to display the edit-controls for the parameters of a specific subtype of PricingModelVisitor, you can simply call
somePricingModel.accept(new ParameterGuiVisitor(parentControl))

and it will populate the appropriate GUI for you.
Comment: Visitor is probably not flexible enough. You can't add visited types dynamically. You only can dynamically add implementations of visitors.
Comment: What do you mean by "adding visited types dynamically"? The visitor pattern easily allows you to add new types by simply adding a new method to the visitor interface that deals with this new type. This will then at compile-time force you to update all existing visitor implementations to appropriately handle this new type, something that might be easily overlooked with a dictionary-based solution.
Comment: Sometimes it needs injecting, easy registering of types, adding types at runtime, adding types which are not known by the assembly which specifies the visitor interface etc. I don't say that dynamic is better then static, I just say that it is *probably not flexible enough* for the problem described here.
Comment: "Sometimes it needs ..." - none of which was mentioned in the question.
Answer: you can use common interface approach as you describe and  Command pattern to trigger methods with "functionality does not belong within that object's type". I think this won't break solid OOP principles.


Can I call a stored procedure in a cfloop and output dynamic out-parameters in Coldfusion?

Question: Last question for tonight, still using Coldfusion8 and MySQL.
I have a table with products, each with Price A, B and C. I need to retrieve the min and max values for A,B,C across all prices (A_min, A_max, B_min, B_max, C_min, C_max)
I thought I would create a stored procedure and loop through A,B,C like so:
  <cfloop list="A,B,C" index="what" delimiters=",">
    <cfstoredproc procedure="proc_search_select_minmax" datasource="dtb">
        <cfprocparam type="in" value="#what#" cfsqltype="cf_sql_varchar" maxlength="15">
        <cfprocparam type="in" value="#variables.xxx#" cfsqltype="cf_sql_varchar" maxlength="13">
        <cfprocparam type="in" value="#variables.yyy#" cfsqltype="cf_sql_varchar" maxlength="13">
        <cfprocparam type="in" value="#variables.zzz#" cfsqltype="cf_sql_text" maxlength="4">
        <cfprocparam type="out" cfsqltype="cf_sql_decimal" variable="#what#_min">
        <cfprocparam type="out" cfsqltype="cf_sql_decimal" variable="#what#_max">
     </cfstoredproc>
  </cfloop>

So the idea was to run this three times for A,B and C and get variables A_min, A_max, B_min... out of the loop.
But I'm having trouble with my out-parameters, which inside MySQL, I'm declaring like:
 CREATE ... PROCEDURE `proc_search_select_minmax`(..., OUT `outputMin` DECIMAL(12,2), OUT `outputMax` DECIMAL(12,2))

 ....
 SET outputMin = min(what);
 SET outputMax = max(what);

Coldfusion error says:
Error Executing Database Query
@
<cfprocparam type="out" cfsqltype="cf_sql_decimal" variable="#what#_min">
<cfprocparam type="out" cfsqltype="cf_sql_decimal" variable="#what#_max">

Questions:
Do I have to give my out parameters the same name as inside MySQL or is the correct order enough?
More importantly, can I set output variables dynamically like this? If not, are there any other ways except calling the stored procedure three separate times?
Comment: Do you get the same error if you remove #what# from the variable?  You might not be able to have a CF variable inside this CF Tag
Comment: mh. Same error. I read [this](http://www.bennadel.com/blog/152-Dynamic-ColdFusion-Variables-Via-Quoted-Naming.htm?&_=0.7007155815319436#comments_40124) and thought maybe I could use this inside a stored-proc, too
Comment: Need to recheck, what's happening in MySQL.
Answer: I never liked the variable return way of doing this. Useful but often difficult (depends on order etc).
I have 2 suggestions for you.
First, make the output a data set. In your stored procedure create a temp table (#myMinMax or whatever) with 2 columns minimum and maximum - populate the table with an insert and then select it out returning it as a <cfstoredprocresult..>
Secondly I would probably create a stored proc that does the looping and returns a whole dataset with a "type" column ... so you would end up with a dataset having type (as in A) minimum (as in 10) and maximum (as in 100) ... one row for A, one for B and one for C. A single connection to the datasource could return this dataset for you - avoiding 3 (or more) DB calls.
Comment: ok. Good tips. So I'm looping inside MySQL? Never done that. I'll both suggestions. Thanks so far!
Comment: Agree on type="out" variables. Never succeeded in getting these to work!
Comment: did just that. I have a small error left in "my SQL", so if you want to have a look: http://stackoverflow.com/questions/11062812/how-to-return-a-mysql-temporary-table-and-not-its-individual-entries-as-resultse
Answer: In SQL Server, we set our variables with the @ sign in the dbvarname attribute.
<cfprocparam cfsqltype="cf_sql_integer"
    value="#LOCAL.User_ID#"
    dbvarname="@User_ID">

Give that a try.
UPDATE ~ I just checked the CF docs, the advice above won't help you
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_p-q_14.html
Changed the dbvarname attribute behavior: it is now ignored for all drivers. ColdFusion uses JDBC 2.2 and does not support named parameters.
Comment: @Leigh, I corrected my answer 10 seconds before you got me. :)
Comment: let me give MySQL Debugger another run. Must have missed something.
Comment: @EvikJames - Yeah, I saw it .. just *after* I hit submit ;-) (Edit: I tried to delete the then redundant correction before you saw it, but I am too slow :)
Answer: I agree with Mark about output parameters. For a single value, you could go either way. But beyond that it is simpler to just return a resultset.

Error Executing Database Query

That said - your code works fine with the sample procedure below in CF8/MySQL5. Based on the partial error message, I suspect the real problem is a syntax error in your procedure. Did you test it directly in your database?
<cfloop>
    <cfstoredproc ...>
        ....
    </cfstoredproc>
</cfloop>
<cfoutput>
    #a_min# #a_max#

    #b_min# #b_max#

    #c_min# #c_max#

</cfoutput>

CREATE PROCEDURE `test`.`proc_search_select_minmax` (
     what varchar(50)
     , xxx varchar(50)
     , yyy varchar(50)
     , zzz varchar(50)
     , OUT outputMin decimal(12,2)
     , OUT outputMax decimal(12,2)
 )
BEGIN

      SET outputMin = 1;
      SET outputMax = 20;
END


failed to resolve: com.google.android.gms: play-services-games: 6.5+

Question: This project has been working for weeks. Yesterday, Android Studio pulled in some updates, and now gradle cannot find my play-services files. It has literally stopped building with no changes to the project - I didn't think this would happen with a gradle-based project.
gradle sync error
When I click on "Install Repository and sync project", another window opens with the message:
Ignoring unknown package filter 'extra-google-m2repository'Warning: The package filter removed all packages. There is nothing to install.
         Please consider trying to update again without a package filter.
Here is my gradle file:
<code>apply plugin: 'android-library'

repositories {
    mavenCentral()
}

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:20.0.+'
    compile 'com.android.support:support-v4:20.0.+'
    compile 'com.google.android.gms:play-services-games:6.5+'
    compile 'com.google.android.gms:play-services-plus:6.5+'
    compile 'com.google.android.gms:play-services-appstate:6.5+'
}

android {
    compileSdkVersion 20
    buildToolsVersion '20'
}
</code>
Looking in my SDK manager, both "Google Repository" and "Android Support Repository" are installed.
SDK manager screen shot
It is possible that I have two different SDK's, but not sure how to tell if I do, and not sure how to remove the extra one if this is the issue.
Comment: Try by removing "+" and add the latest version. For example                         compile 'com.google.android.gms:play-services-games:8.4.89 '
Answer: Removing the "+" and specifying the specific version allows me to build again. I'm actually using 6.5.87, as 8.4.0 caused some other issue.
Comment: i think the problem is not with the version of play services and it might be caused by something else..


Difference between Chow test and F test

Question: I have the following model:
$Y_i=\beta_0 + \beta_1 X_i + \beta_2 D_i + \beta_3 (D_i*X_i) + \epsilon_i$
where $D_i$ is a dummy variable
I want to understand if it is desirable do keep the variable $D_i$ inside the model (if it has an effect on the $y$)
I would do the following test on parameters: $H_0: \beta_2= \beta_3=0$ vs $H_1$: at least one is not $0$
If I accept $H_0$, I remove $D_i$ from my model.
The test I just mentioned, is a test on a group of parameters (test F). Is it in some way different from the Chow test?
In other words, after doing the test previously mentioned, it is important to consider also the chow test? it would give me other / different information?
Comment: Hi: Here's an intro to the Chow-test. Note that the standard F-test in OLS regression is very different from the Chow test so I wouldn't try to relate them.. The only similarity is that you also look up the critical value using the F-distribution when making the decision in the Chow -test. https://www.statisticshowto.com/chow-test/
Comment: Look at [these](http://home.iitk.ac.in/~shalab/econometrics/Chapter12-Econometrics-TestsforStructuralChangeandStability.pdf) lecture notes, there you could find derivation of Chow test from the F test statistics.
Comment: Ok probably I asked the question in a wrong way. Focus on the last part: I mentioned a test in my test: if I accept H0, I remove Di from the model. If I accept, instead, the H0 of the Chow Test, the conclusion is the same ( I remove Di from the model ) or the conclusion is another one? (practically speaking) @mlofton
Comment: What you wrote may be an alternative formulation for how to do the Chow-test. I'm not familiar with that formulation but , according to the link I sent , you don't need a $D_{i}$. You just do two different regressions, calculate the statistic and compare it to the critical value. The result tells whether the coefficients are the same over the two periods. If they are, then one concludes that there is no structural change.
Answer:
The test I just mentioned, is a test on a group of parameters (test
F). Is it in some way different from the Chow test?

What you describe is precisely the Chow test. Indeed the Chow test can be viewed as an a particular case of usual F-test.
However, stating that I suppose that your dummy split the data around a relevant date, it is not a good idea to say something like "... [dummy] has an effect on $y$". What you are interested in is the presence of break in the data. The formalization of break is in the null hypothesis. Dummies are only auxiliary variables.

Difference between Chow test and F test


Expected index of a random element in a list of expected length 1+\alpha

Question: I have a list $l$ with $E(|l|)=1+\alpha$, where $\alpha>0$.
I choose a random element uniformly from $l$ and want to know what is the expectation of the index of this element in the list.
If $\alpha$ is an integer this question is simple, as I need to calculate $(1+2+...(1+\alpha))/(1+\alpha)=(2+\alpha)/2$. Is there a simple reasoning for calculating the expectation in the case that alpha is not an integer?
Comment: You would get the same result.  It is an application of the law of total expectation.
Answer: The answer is exactly the same for non-integer $\alpha$.
If $L$ is the length of the list and $X$ is the index, then $X|L\sim\mathrm{Unif}[1,L]$ and we know that $\mathbb{E}(X|L)=(1+L)/2$.
Iterating expectations gives $\mathbb{E}(X)=(1+\mathbb{E}(L))/2=(\alpha+2)/2$, as in your solution.


Explain why: $(1+\sin x+\cos x)^2=2(1+\cos x)(1+\sin x)$

Question: How can I prove that: $$(1+\sin x+\cos x)^2=2(1+\cos x)(1+\sin x)$$
I've started like this:
$$(1+\sin x+\cos x)^2=((1+\sin x)+\cos x)^2=(1+\sin x)^2+\cos^2x+2(1+\sin x)\cos x$$
Comment: You can prove any polynomial identity in $\sin(x)$ and $\cos(x)$ mechanically by substituting $\sin(x)=\frac{2t}{1+t^2}$  and $\cos(x)=\frac{1-t^2}{1+t^2}$ and simplifying. Here the $t$ is $\tan(x/2)$. With this technique these problems about proving trigonometric identities will not bother you any more.
Answer: To achieve your goal, you want to factor out $(1+\sin x)$:
$(1+\sin x)^2+\cos^2x+2(1+\sin x)\cos x=$
$(1+\sin x)^2 + (1-\sin^2x)+2(1+\sin x)\cos x=$
$\big[(1+\sin x)+(1-\sin x)+2\cos x\big](1+\sin x)=$
$[2+2\cos x](1+\sin x)=2(1+\cos x)(1+\sin x).$
Answer: \begin{aligned}
(1+\sin x+\cos x)^{2}=& 1+\sin ^{2} x+\cos ^{2} x+2 \sin x+2 \cos x \\
&+2 \sin x \cos x \\
=& 2+2 \sin x+2 \cos x+2 \sin x \cos x \\
=& 2(1+\sin x)(1+\cos x) .
\end{aligned}
Answer: Just continue expanding like you have, to obtain $$1 + \sin^2(x) + 2\sin(x) + \cos^2(x) + 2\cos(x) + 2\sin(x)\cos(x),$$ which then beomes $$2 + 2\sin(x) + 2\cos(x) + 2\sin(x)\cos(x).$$ From there, factor out the two and notice that $1 + a + b + ab = (1+a)(1+b)$.


Finding the number of solutions of a system of equations in Macaulay 2

Question: I just started working with Macaulay 2 and need some help. I need to find the number of solutions of a system of equations. I am having difficulty imputing this into the software so please be specific with the commands.
Say we have the following equations
$$u_{12}+u_{13}+u_{14} =  \beta (x_1 x_2+x_1 x_3+x_1x_4)  $$
$$u_{12}+u_{23}+u_{24} =  \beta (x_2 x_1+x_2 x_3+x_2x_4)  $$
$$u_{13}+u_{23}+u_{34} =  \beta (x_3 x_1+x_3 x_2+x_3x_4)  $$
$$u_{14}+u_{24}+u_{34} =  \beta (x_4 x_1+x_4 x_2+x_4x_3)  $$
Where we want to find the $u$'s. In fact we do know both $\beta$ and all the $x$'s. The $\beta = u_{12}+u_{13}+u_{14}+u{23}+u_{24}+u_{34}$ and say the $x_i=i$
Sorry to be asking for this I just am having hard time, programming. I was thinking if I define a variety in the polynomial ring in terms of the u's and then look at the ideal defined by the variety and then intersect it with the polynomial ring and take the degree of that
what i did is define QQ[x_1,x_2,x_3,x_4] then I made my matrix M to be the same as the one in the solution then I did the gens gb minors(4,M). From that I got the attached polynomials. Then I defined an ideal generated by those polynomials and took the degree of it
Answer: Your equation is a linear system of four equations on the $u$ with coefficients which are polynomials in the $x$s. The transposed matrix of coefficients is
$$\small
\left(
\begin{array}{cccc}
 -x_1 x_2-x_1 x_3-x_1 x_4+1 & -x_1 x_2-x_3 x_2-x_4 x_2+1 & -x_1 x_3-x_2 x_3-x_4 x_3 & -x_1 x_4-x_2
   x_4-x_3 x_4 \\
 -x_1 x_2-x_1 x_3-x_1 x_4+1 & -x_1 x_2-x_3 x_2-x_4 x_2 & -x_1 x_3-x_2 x_3-x_4 x_3+1 & -x_1 x_4-x_2
   x_4-x_3 x_4 \\
 -x_1 x_2-x_1 x_3-x_1 x_4+1 & -x_1 x_2-x_3 x_2-x_4 x_2 & -x_1 x_3-x_2 x_3-x_4 x_3 & -x_1 x_4-x_2
   x_4-x_3 x_4+1 \\
 -x_1 x_2-x_1 x_3-x_1 x_4 & -x_1 x_2-x_3 x_2-x_4 x_2+1 & -x_1 x_3-x_2 x_3-x_4 x_3+1 & -x_1 x_4-x_2
   x_4-x_3 x_4 \\
 -x_1 x_2-x_1 x_3-x_1 x_4 & -x_1 x_2-x_3 x_2-x_4 x_2+1 & -x_1 x_3-x_2 x_3-x_4 x_3 & -x_1 x_4-x_2
   x_4-x_3 x_4+1 \\
 -x_1 x_2-x_1 x_3-x_1 x_4 & -x_1 x_2-x_3 x_2-x_4 x_2 & -x_1 x_3-x_2 x_3-x_4 x_3+1 & -x_1 x_4-x_2
   x_4-x_3 x_4+1
\end{array}
\right).
$$
If you compute all the $4\times 4$ minors and then a Groebner basis for the ideal they generate, you find that it is generated by the single polynomial $$x_1 x_2+x_3 x_2+x_4 x_2+x_1 x_3+x_1 x_4+x_3 x_4-1.$$
This means that the rank of the system is four if this polynomial does not vanish, and then the set of $u$s solving the original system form a subspace of dimension $2$ in, say, $\mathbb C^6$.
On the other hand, computing a Groebner basis for the ideal generated by the determinants of all $3\times 3$ minors shows that it is generated by $1$, that is, for all possible values of $x$s the rank is at least $3$. So when the poynomial above vanishes, the set of solutions is a subspace of dimensio $3$.
In any case, whatever the $x$s aare, there are infinitely many solutions.
I did the computation in Mathematica, rather than in M2, only because it is what I have at hand right now:
us = u @@@ Subsets[Range[4], {2}];
xs = x /@ Range[4];
beta = Total[us];
equation[i_] := Sum[
    u @@ Sort[{i, j}] - beta x[i] x[j],
    {j, Complement[Range[4], {i}]}];
matrix = Table[Coefficient[equation[i], v], {i, 4}, {v, us}];
GroebnerBasis[Minors[matrix, 4], xs]

{-1 + x[1] x[2] + x[1] x[3] + x[2] x[3] + x[1] x[4] + x[2] x[4] + x[3] x[4]}

GroebnerBasis[Minors[matrix, 3], xs]

{1}

In Macaulay you have to construct the ring with
R = QQ[x_1,x_2,x_3,x_4]

then construct the matrix of coefficients, call it m and then say
gens gb minors(4, m)

to get a Groebner basis for the ideal generated by the minors of size 4.
Comment: Okay I did what you said, I got a gb basis for the minors and got 5 polynomials out of this. Now to find the number of solutions I enter the x's?  (Also thank you this is very helpful)
Comment: I suggest you edit your question and explain in detail what you did and what you got. As I wrote above, the ideal generated by the $4\times 4$ minors has a Groebner basis with *one* element, so I don't know what five polynomials you got!


AWS: When I tried to update a item in dynamodb the following error appears The provided key element does not match the schema

Question: When I tried to update a item in dynamodb the following error appears:
<code>var docClient = new AWS.DynamoDB.DocumentClient();

function updateItem() {
    var table = "Bicycle";

    var params = {
        TableName:table,
        Key:{
            warrantyDate: "2018/10/23",
            warrantyStatus: "Active"
        },
        UpdateExpression: "set warrantyStatus = :r",
        ExpressionAttributeValues:{
            ":r":"Inactive"
        },
        ReturnValues:"UPDATED_NEW"
    };

    docClient.update(params, function(err, data) {
        if (err) {
            alert("Unable to update item");
             alert(err);
        } else {
            alert("UpdateItem succeeded");
        }
    });
}
</code>
when I call this function I received this exception:
ValidationException: The provided key element does not match the schema
how can i fix this?
Answer: The problem is that you KEY attribute value does not match your primary partition key on your dynamodb table.
When updating an item, you need to specify the single key that maps to your primary key on the dynamodb table. There should only be one attribute in the Key field. You are trying to find a key that is both the warrantyDate and warrantyStatus. Make sure you're specifying the correct key that maps to your dynamodb configuration.
If you're trying to update multiple items, you need to use another function, as doClient.update() only updates a single row that matches your key to the primary index on the table.


Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?

Question: I have a written a simple GRPC server and a client to call the server (both in Go). Please tell me if using golang/protobuf/struct is the best way to send a dynamic JSON with GRPC.
In the example below, earlier I was creating Details as a map[string]interface{} and serializing it. Then I was sending it in protoMessage as bytes and was de-serializing the message on the server side.
Is it the best/efficient way to do it or should I define Details as a struct in my proto file?
Below is User.proto file
syntax = "proto3";
package messages;
import "google/protobuf/struct.proto";

service UserService {
    rpc SendJson (SendJsonRequest) returns (SendJsonResponse) {}
}

message SendJsonRequest {
    string UserID = 1;
    google.protobuf.Struct Details = 2;
}

message SendJsonResponse {
    string Response = 1;
}

Below is client.go file
package main
import (
    "context"
    "flag"
    pb "grpc-test/messages/pb"
    "log"
    "google.golang.org/grpc"
)

func main() {
    var serverAddr = flag.String("server_addr", "localhost:5001", "The server address in the format of host:port")
    opts := []grpc.DialOption{grpc.WithInsecure()}
    conn, err := grpc.Dial(*serverAddr, opts...)
    if err != nil {
        log.Fatalf("did not connect: %s", err)
    }
    defer conn.Close()

    userClient := pb.NewUserServiceClient(conn)
    ctx := context.Background()

    sendJson(userClient, ctx)
}

func sendJson(userClient pb.UserServiceClient, ctx context.Context) {
    var item = &structpb.Struct{
        Fields: map[string]*structpb.Value{
            "name": &structpb.Value{
                Kind: &structpb.Value_StringValue{
                    StringValue: "Anuj",
                },
            },
            "age": &structpb.Value{
                Kind: &structpb.Value_StringValue{
                    StringValue: "Anuj",
                },
            },
        },
    }

    userGetRequest := &pb.SendJsonRequest{
        UserID: "A123",
        Details: item,
    }

    res, err := userClient.SendJson(ctx, userGetRequest)
}

Comment: see https://blog.envoyproxy.io/dynamic-extensibility-and-protocol-buffers-dcd0bf0b8801
Answer: Based on this proto file.
syntax = "proto3";
package messages;
import "google/protobuf/struct.proto";

service UserService {
    rpc SendJson (SendJsonRequest) returns (SendJsonResponse) {}
}

message SendJsonRequest {
    string UserID = 1;
    google.protobuf.Struct Details = 2;
}

message SendJsonResponse {
    string Response = 1;
}

I think it is a good solution to use the google.protobuf.Struct type.
The folks with their answers, helped me a lot at the beginning, so I would like to say thanks for your work! :) I really appreciate both solutions! :)
On the other hand, I think I found a better one to produce these kinds of Structs.
Anuj's Solution
This is a little bit overcomplicated but it can work.
var item = &structpb.Struct{
    Fields: map[string]*structpb.Value{
        "name": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "Anuj",
            },
        },
        "age": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "Anuj",
            },
        },
    },
}

Luke's Solution
This is a shorter one but still require more conversion than necessary. map[string]interface{} -> bytes -> Struct
m := map[string]interface{}{
  "foo":"bar",
  "baz":123,
}
b, err := json.Marshal(m)
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)

The solution from my perspective
My solution will use the official functions from the structpb package which is pretty well documented and user friendly.
Documentation: https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb
For example, this code creates a *structpb.Struct via the function that was designed to do this.
m := map[string]interface{}{
    "name": "Anuj",
    "age":  23,
}

details, err := structpb.NewStruct(m) // Check to rules below to avoid errors
if err != nil {
    panic(err)
}

userGetRequest := &pb.SendJsonRequest{
    UserID: "A123",
    Details: details,
}

One of the most important thing, that we should keep in mind when we are building Struct from a map[string]interface{} is this:
https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb#NewValue
// NewValue constructs a Value from a general-purpose Go interface.
//
//  ╔════════════════════════╤════════════════════════════════════════════╗
//  ║ Go type                │ Conversion                                 ║
//  ╠════════════════════════╪════════════════════════════════════════════╣
//  ║ nil                    │ stored as NullValue                        ║
//  ║ bool                   │ stored as BoolValue                        ║
//  ║ int, int32, int64      │ stored as NumberValue                      ║
//  ║ uint, uint32, uint64   │ stored as NumberValue                      ║
//  ║ float32, float64       │ stored as NumberValue                      ║
//  ║ string                 │ stored as StringValue; must be valid UTF-8 ║
//  ║ []byte                 │ stored as StringValue; base64-encoded      ║
//  ║ map[string]interface{} │ stored as StructValue                      ║
//  ║ []interface{}          │ stored as ListValue                        ║
//  ╚════════════════════════╧════════════════════════════════════════════╝
//
// When converting an int64 or uint64 to a NumberValue, numeric precision loss
// is possible since they are stored as a float64.

For example, if you would like to produce a Struct that has a string list in its JSON form, you should create the following map[string]interface{}
m := map[string]interface{}{
    "name": "Anuj",
    "age":  23,
    "cars": []interface{}{
        "Toyota",
        "Honda",
        "Dodge",
    }
}

Sorry for the long post, I hope it makes your work easier with proto3 and Go! :)
Answer: I ended up using a two-step conversion with protojson, from map to json to struct:
m := map[string]interface{}{
  "foo":"bar",
  "baz":123,
}
b, err := json.Marshal(m)
s := &structpb.Struct{}
err = protojson.Unmarshal(b, s)

I don't find it elegant but could not really find any official documentation of how to do this differently. I also prefer to produce structures using "official" functions rather than trying to build a structure myself.
Answer: If you have JSON data already, you could also choose to encode it as a string field.  Otherwise, using a google.protobuf.Struct seems pretty reasonable, and you should be able to use jsonpb to convert between the Struct and JSON easily on the client and server.
Comment: Any example on how to use `jsobpb` to a protot struct type would be helful
Comment: @Arajit 1) struct -> []byte // using json.Unmarshal. 2) proto struct -> []byte // using jsonpb package; bts:= buffers.NewBuffer(nil) jsonpb.Unmarshaler{}.Marshal(bts, yourProto). 3) []byte -> proto struct // using jsonpb package; jsonpb.Unmarshal(bytes.NewBuffer(bts), &protoStruct{})
Answer: Don't use dynamic json. It means you have to write custom encoders for golang, it's brutal don't do it.


MS Dynamics programming environment

Question: Is it possible to setup MS Dynamics programming/development environment on single PC for self-study purposes for free? How to setup?
Answer: You can set a trial version of CRM Dynamics Online for 30 days. Check here. After set the trial download the training kit and sdk to study.
Answer: Yes it is, but strictly speaking the product itself is its own development environment. Setup info is to be found on the Microsoft Dynamics site:
https://www.microsoft.com/en-gb/dynamics/crm-free-trial-overview.aspx

MS Dynamics programming environment


Is it possible to compute $\int_{-\infty}^\infty {x \sin x\over x^4+1}dx$ without using complex analysis?

Question:
$$\int_{-\infty}^\infty {x\sin x\over x^4+1}dx$$

By using things like Feynman's trick (Differentiating under the integral sign) or other high school level calculus concepts? I do not know things like residue theorem.
Comment: @R_Berger I would have considered a function $f(t) = \int_{0}^{\infty} e^{-tx}\frac{\sin x }{x} \text{d}x$, from that 2f(0) = I and evaluate f'(t).. Something like this https://www.youtube.com/watch?v=s1zhYD4x6mY
Comment: You can use or prove the Fourier inversion theorem.
Comment: I don't see a "high school level" way to do even $\int_{-\infty}^{\infty} sin(x)/x dx$. You can check the methods how to solve that, to see how Fourier inversion would work on a simpler example.
Comment: Maybe nice to know if you would also like to see it answered using other real methods.
Answer: We have
$$ \int_{\mathbb{R}}\frac{x\sin x}{x^4+1}\,dx= \frac{1}{2\sqrt{2}}\int_{\mathbb{R}}\sin(x)\left[\frac{1}{x^2-x\sqrt{2}+1}-\frac{1}{x^2+x\sqrt{2}+1}\right]\,dx $$
by partial fraction decomposition. On the other hand
$$ \int_{\mathbb{R}}\frac{\sin x}{x^2-x\sqrt{2}+1}\,dx = \int_{\mathbb{R}}\frac{\sin\left(x+\frac{1}{\sqrt{2}}\right)}{x^2+\frac{1}{2}}\,dx $$
$$ \int_{\mathbb{R}}\frac{\sin x}{x^2+x\sqrt{2}+1}\,dx = \int_{\mathbb{R}}\frac{\sin\left(x-\frac{1}{\sqrt{2}}\right)}{x^2+\frac{1}{2}}\,dx $$
so the whole problem boils down to evaluating
$$ \int_{\mathbb{R}}\frac{\cos(x)}{x^2+\frac{1}{2}}\,dx=2\int_{0}^{+\infty}\frac{\cos(x)}{x^2+\frac{1}{2}}\color{red}{=}{\pi \sqrt{2}\, e^{-\frac{1}{\sqrt{2}}}}.$$
The last identity can be proved through the Laplace transform, the Fourier transform, Feynman's trick, ordinary differential equations, the residue theorem or the known relation between the Cauchy distribution and the Laplace distribution. A slick way is to notice that by integration by parts
$$ \frac{1}{x^2+\frac{1}{2}}=\int_{0}^{+\infty} \cos(xz) \sqrt{2} e^{-\frac{z}{\sqrt{2}}}\,dz = \int_{0}^{+\infty} \frac{\sin(xz)}{x}\,e^{-\frac{z}{\sqrt{2}}}\,dz $$
holds, then to apply Fubini's theorem to a double integral, recalling that for any $z\geq 0$
$$ \int_{0}^{+\infty}\frac{\sin(xz)\cos(x)}{x}\,dx = \left\{\begin{array}{rcl}0&\text{if}& z<1\\\frac{\pi}{4}&\text{if}&z=1\\\frac{\pi}{2}&\text{if}&z>1.\end{array}\right.$$
Comment: Yooo I was just writing this in full details!! Nicely done!
Comment: I also replicated the same computation, not knowing this approach is already done. Nice job! (+1)
Answer: The same answer as @JackD'Aurizio with slightly more details. I was doing this after he sent his answer so I finish anyway.
Let $\alpha=\frac{1}{2\sqrt[]{2}}$. After partial fraction decomposition we get:
\begin{align}
\int^\infty_{-\infty}\frac{x\sin(x)}{x^4+1}\,dx=-\alpha\int^\infty_{-\infty}\frac{\sin(x)}{x^2+\sqrt[]{2}x+1}\,dx+\alpha\int^\infty_{-\infty}\frac{\sin(x)}{x^2-\sqrt[]{2}x+1}\,dx
\end{align}
Now define:
\begin{align}
I:=\int^\infty_{-\infty}\frac{\sin(x)}{x^2+\sqrt[]{2}x+1}\,dx,\ \ \ \ J:=\int^\infty_{-\infty}\frac{\sin(x)}{x^2-\sqrt[]{2}x+1}\,dx
\end{align}
First we do $I$. Completing the squares in the denominator yields:
\begin{align}
I=\int^\infty_{-\infty}\frac{\sin(x)}{(x+\frac{\sqrt[]{2}}{2})^2+\frac{1}{2}}\,dx
\end{align}
Substitute $u=x+\frac{\sqrt[]{2}}{2}$ and use the formula for $\sin(x+y)$:
\begin{align}
I&=\int^\infty_{-\infty}\frac{\sin\left(u-\frac{\sqrt[]{2}}{2}\right)}{u^2+\frac{1}{2}}\,du\\& = \int^\infty_{-\infty}\frac{\sin\left(u\right)\cos\left(-\frac{\sqrt[]{2}}{2}\right)}{u^2+1}\,du+\int^\infty_{-\infty}\frac{\cos(u)\sin\left(-\frac{\sqrt[]{2}}{2}\right)}{u^2+\frac{1}{2}}\,du\\
 \end{align}
The integral with $\sin(u)$ is convergent and the ingerand is an odd function, so it vanishes. Now we get:
\begin{align}
I=\sin\left(-\frac{\sqrt[]{2}}{2}\right)\int^\infty_{-\infty}\frac{\cos(u)}{u^2+\frac{1}{2}}\,du
\end{align}
This integral can be done with the explicitly mentioned trick by you, namely Feynman's trick. It is done nicely with full details by user Mark Viola in this answer.
So we get:
\begin{align}
I=\sin\left(-\frac{\sqrt[]{2}}{2}\right) \frac{\pi\sqrt[]{2}}{e^{1/\sqrt[]{2}}}=-\sin\left(\frac{\sqrt[]{2}}{2}\right) \frac{\pi\sqrt[]{2}}{e^{1/\sqrt[]{2}}}
\end{align}
The same can be done for $J$ (do it yourself!). We get:
\begin{align}
J=\sin\left(\frac{\sqrt[]{2}}{2}\right)\frac{\pi\sqrt[]{2}}{e^{1/\sqrt[]{2}}}
\end{align}
Finally we get:

\begin{align}
\int^\infty_{-\infty}\frac{x\sin(x)}{x^4+1}\,dx = \frac{\pi}{e^{1/\sqrt[]{2}}}\sin\left(\frac{\sqrt[]{2}}{2}\right)
\end{align}
Answer: Just using basic integration methods.
Let us call $a,b,c,d$ the roots of $x^4+1=0$. Then using partial fraction decomposition
$$\frac x{x^4+1}=\frac{a}{(a-b) (a-c) (a-d) (x-a)}+\frac{b}{(b-a) (b-c) (b-d) (x-b)}+\frac{c}{(c-a)
   (c-b) (c-d) (x-c)}+\frac{d}{(d-a) (d-b) (d-c) (x-d)}$$ which makes that we are left with four integrals looking like
$$I_r=\int \frac{\sin(x)}{x-r}\,dx=\int \frac{\sin(y+r)}{y}\,dy=\cos(r)\int \frac{\sin(y)}{y}\,dy+\sin(r)\int \frac{\cos(y)}{y}\,dy$$ that is to say
$$I_r=\cos (r)\, \text{Si}(y)+ \sin (r)\,\text{Ci}(y)$$ where appear sine and cosine integrals.
For sure, now the problem is to recombine all of that (tedious work) and replace $a,b,c,d$ by the roots of unity and finally integrate between the bounds. I let you the pleasure of doing it.
By the end, you should arrive to
$$\int_{-\infty}^\infty {x\sin x\over x^4+1}\,dx=\pi \,e^{-\frac{1}{\sqrt{2}}} \,  \sin \left(\frac{1}{\sqrt{2}}\right)$$
Comment: The sine integral is a special function (cannot be evaluated). What we want is evaluate $\int_{-\infty}^\infty \frac{\sin(x)}{x-r}dx$ for $r \not \in \mathbb{R}$. How would you do it, and why don't you mention it
Comment: Knowing the value of $\int_{-\infty}^\infty \frac{\sin(y)}{y}\,dy$ and $PV.\int_{-\infty}^\infty \frac{\cos(y)}{y}\,dy$ doesn't help for $\int_{-\infty}^\infty \frac{\sin(x)}{x+i}dx$.
Comment: @reuns. I started my answer with *Just using basic integration methods*. For sure this involves sine and cosine integrals the values of which being known at infinity.  This method has been widely used for years in my research group. Nevertheless, I delete my answer and let you posting an answer using one of the many other possibilities.
Comment: Dear @ClaudeLeibovici, I undeleted your answer since it seems to be useful. Perhaps you can add some detail if necessary. :)
Comment: @PedroTamaroff. Thank you for doing it.
Comment: The main problem is that for $r \in \mathbb{C}$, $\int \frac{\sin(x)}{x-r}\,dx=\int \frac{\sin(y+r)}{y}\,dy=\cos(r)\int \frac{\sin(y)}{y}\,dy+\sin(r)\int \frac{\cos(y)}{y}\,dy$ is not true in real analysis, and in complex analysis it is not quite true neither because of the integration constants
Comment: @Claude Leibovici $\int_{-\infty}^\infty \frac{\cos(y)}{y}\,dy=0$ not $-i\pi$.


Add browser name to the json result produced by cucumber java

Question: Is there a way to add the browser name as a additional field to the json result produced by cucumber java using selenium.
Answer: Sure.  Cosider the following:
<code>import cucumber.api.Scenario;

public class MyStepdefs {
    private Scenario scenario;
    private WebDriver driver;

    @Before
    public void before(Scenario scenario) {
        this.scenario = scenario;
        driver = new FirefoxDriver();
    }

    @Given("^I have (\\d+) cukes in my belly$")
    public void cukes_in_my_belly(int cukes) {
         Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
         String browsername = cap.getBrowserName();
         scenario.write("Browser is " + browsername + "\n");
    }
}
</code>
You can read the official post here
EDIT
The json part is controlled by your cucumber options.
<code>@CucumberOptions(plugin = {"pretty", "json:target2/cucumber.json"}, ...)
</code>
Comment: Not really the exact answer that Connor was asking for, but close.
Comment: @djangofan How so?


is there a maximum size limit on the root drive while creating a new EC2 instance?

Question: say, if I setup a windows server 2012 instance, is there a maximum size limit on the C drive?
Comment: This question appears to be off-topic because it is a question for Amazon.
Answer:
With Amazon EBS, you can...Create storage volumes up to 1 TB in size and attach them as devices on EC2 instances.

Source.
Comment: looks like the concept of root drives and file systems simply don't apply for EBS - which is great. thanks for your clear answer and the source.


What is the maximum runs allowed to take by running between the wickets?

Question: What is the maximum number of runs allowed to take by running between the wickets per ball including overthrows in international cricket?
If a batsman doubted that he or his partner didn't get reach any of the runs, are they allowed to run more than the maximum number?
Answer: There is no limit to the amount of runs that can be scored off a single ball. Any runs scored as a result of fielding side's overthrows will get added. You can read a bit more about this on Wikipedia's article about overthrows.
If in the case of a ball being lost in the field (in high grass or something similar), the fielding side can invoke Law 20, which will award the batting side all the runs they scored from running between the wickets.


Import Specification Error

Question: I keep getting an import error when trying to bring in a text file through VBA.  All other files are working fine.  It keeps saying the text file does not exist.  Any ideas?
My code looks like this:
<code>Const cstrFolderE = "\\Data\Business Objects\tblSCFLAGCHECKER.txt"

        If FSO.FileExists(cstrFolderE) Then
           DoCmd.TransferText acImportFixed, "tblSCFLAGCHECKER", "tblSCFLAG_CHECKER", cstrFolderE, True
        End If
</code>
Answer: I hadn't named my import spec correctly. All sorted now.

Import Specification Error


How to pass argument from a class to another file

Question: I m trying to pass from file_a the argument 'a' to file_b. So how can I get this variable in file_b
(page file_a.py)
class try():
    def pass_this():
        a = 7
(page file_b.py)
from file_a import try

And also if anyone can explain me if I can do it without using the class(if is it possible) it would help me
Comment: Python's basic organization is based on modules and packages, not on files.
Answer: In file_a.py
You can just create a variable named a
a = 7
and in file_b.py, import this variable like:
from file_a import a
If 'a' is a class property or in some functions or methods use global key word
def myFunc():
       global a
        a = 7

Answer: Can you just set a as a global?
(page file_a.py)
a = 7

(page file_b.py)
from file_a import a


Generating Multivariate Uniform Distribution in R

Question: Let $d$ a positive integer How to generate a sample of $n$ random variables with a multivariate uniform distribution on the cube $[a,b]^d$ in R?
I don't know what to do. I know that I need a covariance matrix for the random vectors that I will generate...
Comment: Why do you think you need a covariance matrix?
Comment: If your real task is about discovering the covariance matrix, by using trials, then you may be interested in a direct analytical solution: the variance-covariance matrix for a uniform variable, in Euclidean space, on the cube $[a,b]^d$ is $$cov(x_i,x_j) = \frac{1}{12}(a-b)^2 \cdot \mathbf{I}$$
Answer: It depends a little bit on the terminology, but usually multivariate uniform refers to a distribution where every point in $[a,b]^d$ is equally likely. Hence, the dimensions are independent, and you can draw uniformly between $[a,b]$ d times individually to get a sample from the multivariate uniform.
If you don't want the dimensions to be independent, it might be worth looking into Copulas
Answer: Following up on Sam's answer:
samps <- replicate(n, runif(d,a,b)) # draw samples
cov(t(samps))  # get the sample covariance matrix

Answer: Following up on the second part Sam's answer:
library(copula)
set.seed(2019)
d <- 2
n <- 1000

indep.cop <- indepCopula(d)
sample    <- rCopula(n, indep.cop)
chisq.test(sample)

#        Pearson's Chi-squared test

# data:  sample
# X-squared = 362.15, df = 1998, p-value = 1

# Warning message:
# In chisq.test(sample) : Chi-squared approximation may be incorrect

Because the p-value is 1, it's not unreasonable to assume that the dimensions are independent.
Comment: @RichardHardy, yes. Fixed


Need modified Euler's method equation to approximate exact solution of initial value problem.

Question: I am asked to solve the following problem.
Use Euler's modified method to solve the initial value problem
$\frac{dx}{dt} =\frac{1+x^2}{t} ,1\le t \le4, x(1)=0$
The step size is not given here.
Now, I can solve this using Euler's method but I am not able to find the formula for modified one in the mentioned textbook. So, I need the method here.
I need to use the following as textbook:
Brain Bradie, A friendly Introduction to Numerical Analysis (Pearson)
Comment: If we have an ODE $\frac{dx}{dt} = f(t,x)$ then IIRC the modified Euler's method says that $x_{n+1} = x_n + \frac{h}{2}\left[ f(t_n, x_n) + f(t_{n+1}, x_{n} + h f(t_n, x_n))\right]$ where $h = \Delta t$ is the step-size.
Comment: Can you post picture or source from where you got this method please.
Comment: It's from memory so I can't guarantee that this is the same method your book calls Euler's modified method. However if we do a simple [Google Search](https://www.google.co.uk/search?q=modified+eulers+methods&ie=utf-8&oe=utf-8&client=firefox-b-ab&gfe_rd=cr&ei=7jgrWMPDHdD38AevrbHYCA) then the three top hits all agree with this defintion.
Comment: Yes, now I got the method in textbook under the heading "The most common second-order Runge-Kutta methods"
Answer: You can find the method under the name Heuns's method, also as (explicit) trapezoidal method.
<code>k1 = h*f( t  , x    )
k2 = h*f( t+h, x+k1 )

y += 0.5 * ( k1 + k2 )
</code>


Password protect wired LAN?

Question: The title is not a mistake, I really am talking about wired, not wireless.
Essentially, I was wondering if it was possible to password-protect a LAN wired network to enhance security and only allow computers knowing the password to join.
I thought about using MAC address filtering, but that is way too trivial to circumvent.
Any ideas?
Thanks!
Comment: There's some quite effective methods of Layer 2 security a lot more powerful that MAC address filtering, but they're generally quite expensive to implement.
Answer: 802.1x authentication will do what you're looking for. Your switches will need to support it and you'll need a RADIUS server (which isn't a big deal because there are Free and no-cost options for most mainstream operating systems). Depending on how you actually do the authentication (certificates deployed on client computers, username / password on the clients) you may have addt'l steps necessary (like deploying a PKI) to get 802.1x up and going.
If you're using a Microsoft server platform you can get some background from them here: http://technet.microsoft.com/en-us/library/cc753354(WS.10).aspx
Some Linux server background (as well as just good background about 802.1x) is available here: http://www.linux.org/docs/ldp/howto/8021X-HOWTO/index.html
Comment: a I fully agree this is most secure, but in terms of ease a captive portal is much better.
Comment: 802.1x isn't *that* difficult to get going w/ modern OS's and switches. My advice to the OP would be to take a little extra time and put together a solution that has some reasonable security behind it and that works well in his environment.
Comment: @even I fully agree 802.1x is great, but in certain cases captive portals might be better...
Comment: @jacob I disagree with the captive portal idea. With .1x one could use the switch extended capabilities like: make vlan assingments. This is a better security tool.
Answer: What you are looking for is called a captive portal.  You would have to look around to find one that works with the switches you use though.  Basically, all unauthenticated ports should be on their own isolated vlan.  Once someone authenticates on a port, it would be moved over to the normal vlan, and the traffic would work normally.

Password protect wired LAN?


Why is my girlfriend's flugelhorn a semitone lower than my bass?

Question: Firstly, I'll apologise in advance - I'm a self-taught rock 'musician' and I have virtually no knowledge of music theory (didn't stop me playing hundreds of gigs though!).
I have a four-string bass in standard tuning (EADG), and my girlfriend has a flugelhorn. I was trying to learn a piece of piano music on my bass, struggling to read sheet music. It's rather hard to play both the bass and the treble parts on a bass, so I asked my girlfriend to play the high part.
Playing the music as written, she appeared to be consistently a semitone lower. Perplexed, we tried getting her to play notes into a guitar tuner app on my phone, which suggested she was slightly sharper than a semitone lower than the note she thought she was playing.
I've read that the flugelhorn's fundamental pitch is B♭. Does this mean that what's written as a C in sheet music written for a flugelhorn is actually a B (ie a semitone lower than a C) for everyone else? Hence any music would need to be transposed a tone to be readable to her whilst in tune with everyone else? Is her flugelhorn just out of tune? Are all brass instruments built this way, or can you get flugelhorns/trumpets that are built with a fundamental pitch of C?
Comment: I want to go on record supporting the idea of a bass / flugelhorn duet. Also her instrument transposes (whole step) if she's only registering a semitone off then she's playing sharp, which is a separate issue. Trumpet, flugelhorn, baritone TC, French horn all transpose. Trombones and tubas are "non-C non-transposing instruments" if you want to get really nerdy.
Comment: @jjmusicnotes  Chuck Mangione
Comment: Recommendation: toss that "guitar tuner" app and install a chromatic tuner -- which will tell you if any standard (12-tone) pitch is in tune.
Answer: Welcome to the wonderful world of transposing instruments.
As you've identified, the factors at play here are:

The flugelhorn is indeed a transposing instrument, in Bb. That means it plays a tone (not semitone) lower than written. If you play a written C on a flugelhorn, it will really be a Bb.
The flugelhorn is a wind instrument, which will not play in tune by default. If at all.

So, she's probably playing the wrong note (she needs to transpose up a tone), and is also apparently playing very sharp. This may be a technique issue, or a broken instrument. The tuner may also be lying; it could be set for a capo, or just broken (much less likely).
I'd check this by playing a C on the flugelhorn. Your tuner should show a Bb.
Once that's sorted, you'll need to either transpose the music, or she'll need to learn to sight-transpose from concert pitch. Both are useful skills.
There are concert C brass instruments. They're comparatively rare, and have a tendency to be somewhat garbage. I should also mention that the trombone is often learnt as a concert pitch (C) instrument.
There are many other answers on this site about transposing instruments that may be of interest.
Comment: what do you mean when you say wind instruments "will not play in tune by default. If at all?" Wind instruments are played in tune by amateur and professional musicians all around the world every day.
Comment: @phoog Bb trombone parts are a brass band thing, which occasionally escape into concert band parts.
Comment: @Peter Probably my ongoing exposure to junior concert bands sneaking out again. They certainly don't play in tune without some practice, unlike, say, a piano. A number of specimens never seem to play in tune, but I think we can guess where that fault lies.
Comment: "the trombone is often learnt as a concert pitch (C) instrument": are trombone parts ever scored in a pitch other than concert pitch?  I've never seen such a thing, but I haven't seen many band scores.
Answer: Most wind instruments are fine-tuneable. They need to be so when they play with others, they can all play at the exact same pitch. Sounds like this flugel is a little off, and needs the fundamental B♭ adjusting. At least then it's not playing 'in the cracks'. There's also the probability that the player isn't playing some notes exactly in tune, even though the flugel itself might be.
As a transposing instrument, as so many brass instruments are (although C instruments exist), the music needs to be written just one tone higher than it comes out. Read a C note, blow and it sounds like a B♭ - 'cos it is.
You could, for the purposes of playing together, tune down your bass by one tone. It'll still play fine, and then you can read, correctly, the dots together. Or, you could compensate, and read the dots as if they were one tone down. Actually not that difficult. Or, as I did when learning the trumpet, read the dots one tone higher, thus playing in the key above that on the music. For a C note, read a D; for an F note, read G. That's actually a useful trick - it means you can play any old sheet music with everyone else without having a B♭ version of your own to rely on.
But the first thing is to get both instruments playing notes in tune with each other, not half a fret out, as it seems at the moment.
Answer: You are correct that the flugelhorn is in the key of Bb. So it should actually sound TWO semitones lower than your bass.
Instruments like this are called "transposing" instruments. Trumpet, tenor saxophone, clarinet, and soprano saxophone are also in the key of Bb. Bass, guitar, piano, flute, and most other brass instruments are in the key of C (which is usually called "concert pitch"). There are also instruments in other keys, like alto saxophone (in Eb) and "French" horn (in F).
To answer your last question, they do make trumpets in C, but the standard trumpet is in Bb.
Comment: Thanks for taking the time to answer, I've marked the other as correct as it's more expansive.
Answer: It is possible but unlikely that your girlfriend's flugelhorn is a very old one in Bflat but at A456. These were standard in British brass bands in the 1960s but most bands had converted to low pitch (A440) by the mid 1970s.
But this does not explain your tuner reading. It should read around 1.5 semitones flat for an A456 instrument.
Answer: Your question gets a bit confused between B and B♭, tones and semitones.
But, misprints apart, you're basically right.  Her instrument is going to sound a tone (two semitones) lower than written.
The basic trumpet is in B♭.   There are other sizes, including on in C, and the C trumpet is relatively common among professional players.  It has a brighter, more cutting sound which can be useful in the orchestra.
But the whole POINT of a flugelhorn is to be a mellow alternative to the trumpet.  I hesitate to say there's NEVER been a Flugel in C, but don't hold your breath waiting for one to come along!


Robust regression for heavy-tailed random design

Question: As far as I know, there are robust regression methods for outliers in response $Y$ and heavy-tailed error $\epsilon$. The settings for the design matrix (predictor) $X$ is either fixed design or sub-exponential like Normal distribution. What if the design matrix $X$ is random design and the distribution is heavy-tailed? Is there any advanced methods apart from truncation on $X$ or $\log X$?
Answer: One simple method would be to use the quantiles of $X$ rather than $X$ per se as predictor, e.g. adding a column which equals $1$ if $x_k$ is larger than the 90 quantile of $X$. This avoids truncation or arbitrarily changing the distribution of $X$.
Comment: Perhaps look here for a larger discussion: https://stats.stackexchange.com/questions/68834/what-is-the-benefit-of-breaking-up-a-continuous-predictor-variable
Comment: Is there any paper I can read more about this?
Answer: One method/idea is resistant regression. The idea is to order the squared residuals, rejecting some percent of the largest ones, and then minimize the sum of squared kept residuals. That is highly nonlinear and nonconvex, and one idea for the optimization is genetic algorithms.
One implementation is lqs in R package MASS, see the companion book by Venables & Ripley. For code example see How to get summary statistics from "resistant regression" - lqs - in R?
Answer: In Python, in scikit-learn there is also RANSACRegessor, and TheilSenRegressor. Both of them are robust to outliers in the design.


How to customize a link with a custom module?

Question: I installed the "Private Message" module on Drupal 8.
There is a link to send a message that I want to transform into a Bootstrap button.
How to customize a link on Drupal 8 ?
Here is the HTML code of the link :

Envoyer un message

The developer of "Private Message" gave me this code, but I do not know what to do with it.
I need to create a custom module or put it in my_theme.info.yml ?
function HOOK_node_view_alter(&$build) {
  $build['private_message_link']['#title'] = t('Click me. Click me now!');
}

The developer of the module wrote in a comment :
You can implement hook_ENTITY_TYPE_view_alter(). For example, if you are altering the link on the user profile you would implement hook_user_view_alter(). If you are altering the link on nodes, you would implement hook_node_view_alter(). If you are altering the link on comments, you would implement hook_ENTITY_TYPE_view_alter().

In this function, you can change the output of the link by altering $build['private_message_link'] as you see fit.

I created a custom module:
private_message_contact_button.module :
<?php

/**
 * @file
 * Hook implementations of private_message_contact_button module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function private_message_contact_button_node_view_alter(&$build) {
  $build['private_message_link']['class'] = array('button button--primary', 'btn');
}

The code works, but the button is not applied.
I want to add class btn btn-success
And I want to add an icon make awesome in front of the text
I have to put what as code ?
Answer: The CSS class is a sub-key of the #attributes of a render array like $build:
function private_message_contact_button_node_view_alter(&$build) {
  if (array_key_exists('private_message_link', $build)) {
    $build['private_message_link']['#attributes']['class'] = array('button button--primary', 'btn');
  }
}

Comment: Thank you, it works. Can you tell me how to add a font-awesome icon in front of the text? See the end of my question
Comment: I guess the simpliest way would be extending/overwriting the `#title` as suggested by the module author.
Comment: yes but I do not know how to insert do awesome in markup
Comment: I updated your answer. The icon is not rendered this way
Comment: Have you tried `$build['private_message_link']['#title'] = t(' Click me. Click me now!');`
Comment: OOOPS I forgot to clean the cache. The answer works


Trocar cor do item selecionado - select > option

Question: Tenho o seguinte select.

É possível trocar a cor azul dele para uma que eu queira aplicar, vermelho por exemplo?
Answer: Elementos SELECT são renderizados pelo sistema operacional, não HTML. Você não pode mudar essa cor azul, porque ela é padrão do SO.
"A alternativa é usar bibliotecas que customizam o select, geralmente transformado-os em dropdowns e outros (Exemplo: bootstrap select - silviomoreto.github.io/bootstrap-select)."
Mas voce pode mudar algumas coisas sem usar dropdowns:

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}
.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}
<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>
Comment: Entendi, Paulo. Obrigado pelo esclarecimento.
Comment: A alternativa é usar bibliotecas que customizam o `select`, geralmente transformado-os em `dropdowns` e outros (Exemplo: bootstrap select - http://silviomoreto.github.io/bootstrap-select/).
Comment: Eric, dá uma olhada no exemplo que eu coloquei, e veja algumas das mudanças que voce pode fazer.
Comment: Mas, perceba que o AZUL continua, porque ele é padrão do Sistema Operacional.
Comment: E obrigado, Eduardo, pela sugestão.


Sample variance formula vs. Population variance formula usage

Question: Just for sake of not having to write this equation out a few times, I will denote the residual sum of squares for a set of data points $X$ to be
$$
RSS= \sum_{x\in X} \left(x - \overline{x}\right)^2
$$
Now I understand that there are two different formulas for variance, with sample variance being defined as
$$
s^2 = \dfrac{RSS}{n-1}
$$
and population variance being
$$
\sigma^2 = \dfrac{RSS}{n}
$$
for $n$ data points.
Now I understand that we use the sample formula, as the population formula is a biased estimator for the true variance.
Now with that I was listening to one of my machine learning lectures and saw that my professor told us to calculate the variance for Naive Baysian classifier using the population formula since it is proven to be the Maximum Likelyhood Estimator for Gaussian Distribution variance. I also understood this proof, but I was confused about why we would select to use the formula for population variance on our sample when we know it is a biased estimator?
Anyone who could provide some insight would be appreciated!
Comment: What most people fail to understand about this topic is that the sample variance and the population variance estimator are two fundamentally different things. One is simply a measure of the spread of a finite, small sample, whereas the other is a Maximum Likelihood Estimator of a population parameter.
Comment: @K.defaoite I found that so confusing until I really broke it down. I think this really isn't taught even though the distinction is so obvious. And it's so important.
Answer:
For reasonably large n it is not going to make a significant difference.
The "sample variance" is not the best(optimal) estimator for the variance. The optimality criteria being MSE(Mean Square Error). The estimator with lower MSE
is considered to be better. It is more accurate.

Item 2 in the list requires more explanation. Let's denote
$$ \hat{[\sigma}^{*}]^2 = \frac{1}{k-1}\sum_k (x_k - \bar{x})^2 \tag{1} \label{1}$$
$$ \hat{\sigma}^2 = \frac{1}{k}\sum_k (x_k - \bar{x})^2 \tag{2} \label{2} $$
The MSE for $\eqref{1}$ is $e^{*} = E[(\hat{[\sigma}^{*}]^2 - \sigma^2)^2]$
The MSE for $\eqref{2}$ is $e = E[(\hat{\sigma}^2 - \sigma^2)^2]$
Where $\sigma^2$ is true variance.
It can be shown that $e^{*} > e$. Although $\eqref{2}$ is biased it has lower MSE.


Facebook Open Graph API Global Actions

Question: Is there a comprehensive list of all global actions? Is it just the watch/read/play/listen mentioned here: http://developers.facebook.com/docs/reference/plugins/activity2/
Answer: It seems that the Global Actions are like, watch, read, and play according to their developer docs at http://developers.facebook.com/docs/reference/plugins/activity/?refid=20&ref=pymk&ft=fbid.154475804670516&_fb_noscript=1
If you're using the JSDK, you don't include your app namespace when setting a "Global" action:
FB.api('/me/video.watches', 'post',
    {
        video : "LINK TO YOUR VIDEO META DATA",
    },
    function (respononse) {
        console.log(respononse);
    }
);

Facebook Open Graph API Global Actions


Asynchronous Remote WMI Calls C#

Question: I'm really struggling to get WMI data from a remote host in an asynchronous way. After a lot of research, I can't find any clear examples, Microsoft's documentation only has VB and C++ code and there are even articles explaining why it's a bad idea. I've come from PowerShell, with that I would just create a new runspace to get the information.
I currently have a WPF window that I want to remain responsive whilst querying the information before updating the window. I've currently only managed to use synchronous calls using CimSession.Create and QueryInstance.
I would really appreciate some help with this :)
Comment: Does this help? https://stackoverflow.com/questions/52159471/creating-async-selects-to-wmi-and-wait-to-their-completion
Comment: @Hintham I read that but it didn't make much sense. Do you know if there is a simpler example or something that I can build up from? I can't seem to find any tutorials either...
Answer: After proposing the same question to the MSDN forums, I got the correct answer and thought I would share it here as well :) I have put comments into the code to explain what is happening:
<code>//Used to define what is returned in the async results
public static CimAsyncMultipleResults<CimInstance> GetValues(CimSession _session)
{
    return _session.QueryInstancesAsync(@"root\cimv2", "WQL", "SELECT Username FROM Win32_ComputerSystem");
}

//This watches the async progress
class CimInstanceWatcher : IObserver<CimInstance>
{
    public void OnCompleted()
    {
        Console.WriteLine("Done");
    }

    public void OnError(Exception e)
    {
        Console.WriteLine("Error: " + e.Message);
    }

    public void OnNext (CimInstance value)
    {
        Console.WriteLine("Value: " + value);
    }
}

private static void Main()
{
    //Leaving cimsession creation as sync because is happens "instantly"
    CimSession Session = CimSession.Create("PC-NAME");
    //Creating a new watcher object
    var instanceObject = new CimInstanceWatcher();
    //Subscribing the watcher object to the async call
    GetValues(Session).Subscribe(instanceObject);
    Console.ReadLine();
}
</code>
Answer: You can use ORMi async methods to do async WMI work. For example:
<code>WMIHelper helper = new WMIHelper("root\\CimV2");
List<Processor> processors = await helper.QueryAsync<Processor>().ToList();
</code>
Comment: How would I use this in a distributed program though? wouldn't it need to be installed on ever machine?
Comment: No. Just make multiple connections. To do remote WMI work you will need a domain user.

Asynchronous Remote WMI Calls C#


Separate Bonferroni corrections for multiple categories

Question: I have a study in which we are looking at healthcare costs and utilization by patients with a disease vs. healthy controls (HC), as well as by different stratifications of disease (severity, comorbidities).
Summary of all comparisons are below:
Part 1. Healthcare costs

Inpatient: 1) Disease vs. HC, 2) mild Disease vs. HC, 3) severe Disease vs. HC, 4) Disease + 1 comorbidity vs. Disease alone, 5) Disease + 2 comorbidities vs. Disease alone, and 6) Disease + 3 comorbidities vs. Disease alone
Outpatient: same as above in inpatient
Emergency room: same comparisons as above
Pharmacy costs: same comparisons as above

Part 2. Healthcare utilizations

Disease vs. HC in odds of seeing 15 different types of specialty providers
Mild disease vs. HC in odds of seeing 15 different types of specialty providers
Severe disease vs. HC in odds of seeing 15 different types of specialty providers
Disease + 1 comorbidity vs. Disease alone in seeing 15 different types of specialty providers
Disease + 2 comorbiditeis vs. Disease alone in seeing 15 different types of specialty providers
Disease + 3 comorbidtiies vs. Disease alone in seeing 15 different types of specialty providers

If I were to use Bonferroni for multiple comparison correction, can I use the different categories to have separate Bonferroni corrections for each one?
In other words, for Part 1, can my Bonferroni p-value cut off be: 0.05/6 = 0.0083 for each of Inpatient, Outpatient, Emergency, and Pharmacy category? Or will it be 0.05/24 =0.002 lumping all the comparisons in the different categories together?
Similarly, for Part 2, can my Bonferroni p-value cut off be: 0.05/15 = 0.003 for each of the comparisons? Or will it be 0.05/90 = 0.0005??
Thanks in advance!
Comment: See https://stats.stackexchange.com/questions/120362/whats-wrong-with-bonferroni-adjustments/ for arguments against using the Bonferroni correction at all. The only good reason to use it is if people who have the power to stop you publishing want you to. If those people are ok with using categories in the way you suggest, go ahead.
Answer: Bonferroni and other multiple comparisons procedures are quite useful to keep researchers honest. It is easy to cherry-pick statistical results to get whatever conclusions you want, simply by taking advantage of randomness.
Sure, you can use separate groups, and this is commonly done, eg, in pharmaceutical studies. But such a data analysis plan must be pre-specified, otherwise, you run the risk of the same cherry-picking mistakes that Bonferroni and other multiple comparisons procedures aim to avoid. You also need to acknowledge that the maximum overall familywise type I error rate (FWER) is 0.10, not 0.05, when you have two separate families.
There are improvements that can be made over simple Bonferroni by incorporating dependencies, logical constraints, distributional characteristics (eg discreteness), and hierarchical structures, while still controlling the FWER.
You also might want to consider whether you would be satisfied by controlling the false discovery rate (FDR) instead of the FWER. You might just lump the entire set of comparisons into a single family in that case.


How can I use different types of repeats in my lead sheet?

Question: Happy Friday!
I'm trying to draft a lead sheet that captures the structure of a song I'm working on in a single page.  I just can't find a solution.  I hope to get better at notating repeats and creating lead sheets one day, but, for now, can you please assist?
The structure is as follows:
<code>ABCACBD
</code>
As you'll see in my attempted road map, I got stuck because I didn't accommodate the BC/CB switch in the body of the song.

Any input is appreciated!  Thank you!!
Comment: This is rather more complex than the linked question, and I think deserves an answer.   Here's a solution.  https://imgur.com/a/02uXipm  It also deserves a warning.   IF the lead sheet is purely for reference purposes, OK a complex repeat structure is acceptable.   But if there's any danger of musicians having to PLAY it - just don't.  Write it out.
Comment: Paper is cheap, rehearsal time is expensive. Write it out.
Comment: Although the linked question is not an exact duplicate to your form, the techniques in the answers will solve the problem.
Answer: This is rather more complex than the linked question, and I think deserves an answer. Here's a solution.
And here's an alternative solution.  Just notate each section once, in order ABCD.   Write over the top 'Play sections in this order: ABCACBD.'  Probably just as useful as a complex repeat structure.
(Those who use the score publisher Sibelius will recognise the two approaches.  Playback can be achieved with repeat barlines, DS al Coda instructions etc.  Or you can set up a manual playback map, instructing bars to be played in any arbitrary order.  Sometimes it's the only way.)
And my answer includes a warning. IF the lead sheet is purely for reference purposes, OK a complex repeat structure like this is acceptable. But if there's any danger of musicians having to READ and play it - just don't. Write it out.


How to figure out the smallest integral type that can represent a number, in compile time

Question: I need to figure out the smallest unsigned integral type that can represent a particular number, in compile time. Something like this...
//////////////////////////////////////////////////////////////////////////
template<size_t Bits>
struct uint_least{};

template<>
struct uint_least<8>{ typedef std::uint8_t type; };

template<>
struct uint_least<16>{ typedef std::uint16_t type; };

//////////////////////////////////////////////////////////////////////////
template<size_t max>
struct uint_least_bits
{
    static const size_t value = 14; // just a placeholder
};

//////////////////////////////////////////////////////////////////////////
template<size_t max>
class A
{
    typedef typename uint_least<uint_least_bits<max>::value>::type underlying_type;

    underlying_type m_X;
};

uint_least is meant to give you the smallest unsigned integral type that is at least Bits large and it should work for any value up to 64 (not just 8, 16, 32, 64 but also 1, 4, 13, etc).
uint_least_bits is meant to give you the minimum number of bits needed to represent max.

How can I implement uint_least?
How can I implement uint_least_bits?
What types should bits, min, and max be? If the answer is a template type, how can I guard against invalid input?

The exact structuring of the traits doesn't matter. Feel free to scrap what I provided. I just need to provide a number and get back the smallest unsigned integral type that can hold it.
Comment: Should `int_least_bits<255, 256>::value` be 1 or 9?
Comment: @KerrekSB: `decltype` won't give you the *smallest* type for values small enough to promote to `int`.  For example, `decltype(1)` is `int`, not one of the `char` types.
Comment: You could just use `decltype` on your integral constant.
Comment: @GManNickG Good question. I would say 9, however feel free to disagree and tell me why
Comment: @Dave: Because I can encode two integer values in just one bit, zero meaning the first, one meaning the second. Basically, is this: "what type can I use to encode the values in this" or "what type can I use that would allow me to directly assign it the literal values in this range"? The word "represent" in your question is what introduces this ambiguity.
Comment: @GManNickG Okay I'll change my wording then. Thanks
Answer: I did this just yesterday, what a coincidence. I'll leave it here, even though it's not exactly what you need(it fixes the best integral type thing anyway):
#include <type_traits>
#include <stdint.h>

template<size_t i>
struct best_type {
    typedef typename std::conditional<
        (i <= 8),
        uint8_t,
        typename std::conditional<
            (i <= 16),
            uint16_t,
            typename std::conditional<
                (i <= 32),
                uint32_t,
                uint64_t
            >::type
        >::type
    >::type type;
};

Then, you'd use it like this:
#include <type_traits>
#include <iostream>
#include <stdint.h>

template<size_t i>
struct best_type {
    typedef typename std::conditional<
        (i <= 8),
        uint8_t,
        typename std::conditional<
            (i <= 16),
            uint16_t,
            typename std::conditional<
                (i <= 32),
                uint32_t,
                uint64_t
            >::type
        >::type
    >::type type;
};

int main() {
    std::cout << sizeof(best_type<2>::type) << std::endl;
    std::cout << sizeof(best_type<8>::type) << std::endl;
    std::cout << sizeof(best_type<15>::type) << std::endl;
    std::cout << sizeof(best_type<17>::type) << std::endl;
}

Live demo, here.
Comment: +1 But I should get credit for using `constexpr` when the OP least expected it. :-)
Answer: If you've got constexpr, this will work:
#include <climits>
#include <cstdint>
#include <cstddef>

inline
constexpr
unsigned
clz(unsigned x)
{
    return x == 0 ? sizeof(x)*CHAR_BIT : x & 0x80000000 ? 0 : 1 + clz(x << 1);
}

inline
constexpr
unsigned
clp2(unsigned x)
{
    return x == 0 ? 0 : 1 << (sizeof(x)*CHAR_BIT - clz(x-1));
}

inline
constexpr
unsigned
at_least8(unsigned x)
{
    return x < 8 ? 8 : x;
}

template<size_t Bits>
struct uint_least{};

template<>
struct uint_least<8>{ typedef std::uint8_t type; };

template<>
struct uint_least<16>{ typedef std::uint16_t type; };

template<>
struct uint_least<32>{ typedef std::uint32_t type; };

template<>
struct uint_least<64>{ typedef std::uint64_t type; };

template<size_t max>
struct uint_least_bits
{
    static const size_t value = clp2(max);
};

template<size_t max>
class A
{
    typedef typename uint_least<at_least8(uint_least_bits<max>::value)>::type underlying_type;

    underlying_type m_X;
};

int main()
{
    A<3> a;
}

If you don't have constexpr, you could translate clp2 into a template meta-function (and that's left as an exercise for the reader :-)).
Oh, disclaimer:  Assumes a 32 bit unsigned.  That could be generalized too if needed.
Comment: Tell me if I'm wrong, but I think it's useless to precise `inline` when defining `constexpr` functions.
Comment: constexpr functions can still run at run time if called with non-constexpr arguments.
Comment: From the C++11 standard, section 7.1.5: `constexpr functions and constexpr constructors are implicitly inline`. Ok, that has nothing to do with the current problem. At least I've an answer for one question. Sorry for the trouble.


What are the URLs for devel generated images in CCK fields?

Question: I generated a few nodes with Devel. When I do a krumo($node), the CCK field consisting of an image, does not have a filename. $field_name['und'][0][filename] is a string of 0 characters. I only get this: $field_name['und'][0]['uri'] = public:///garbledImageName.tmp.png. How do I use this? What function does Drupal use, to convert this public:/// URI into a complete image path? And in the future, can I count on custom created modules to also have the 'uri' value?
Answer: Drupal uses the file_create_url() function for this:

Creates a web-accessible URL for a stream to an external or local file.

Code example:
$url = file_create_url($field_name['und'][0]['uri']);


Visual Studio 2013 não instala no windows 7

Question: Eu não consigo instalar o Visual Studio 2013 no Windows 7, sei que é possível pois na faculdade temos o Visual Studio instalados no Windows 7. Então não sei porque ele reclama da versão do Windows.
Comment: Você tem todas atualizações do Windows 7? Por exemplo o Windows 7 Service Pack 1? Ele é original? Você clicou no *link*? O que diz?
Comment: A julgar pela versão do Internet Explorer estar desatualizada, parece que seu sistema operacional realmente não possui todas as atualizações instaladas. Além dos riscos óbvios de segurança, isso pode ser a causa do seu problema, como o colega @bigown falou.
Comment: @William, você pode aceitar então a resposta dada pelo bigown, já que ela parece ter sido a solução para seu problema?
Answer: Muito provavelmente está faltando o Service Pack 1 no Windows 7, ou pode ser outra atualização dele. Tem que ter certeza que está tudo atualizado. Veja no link apresentado mais detalhes se isto não for o problema, mas provavelmente é.
Ele também fala em atualizar o IE, já para o 11. Não deixa uma máquina com coisas antigas deste jeito.
Requerimentos.
Comment: Vocês são os melhores, segui as dicas de vocês e consegui instalar o Visual Studio, era só instalar o service pack 1 do windows 7. Valeu galera!
Comment: @WilliamCaetano por favor marque a resposta como correta, isso pode ajudar outras pessoas com o mesmo problema. +1
Answer: Habilite o Windows Update com certeza o problema é esse para ativar o Windows Upadate no Windows 7 caso não saiba:

Painel de Controle > Windows Update > Alterar configurações > Instalar
  atualizações automaticamente (recomendado).
Answer: Atualize o IE para 10 ou 11(dependendo o que for pedido pela instalação).
Pois já passei por isso, e quando atualizei o IE.
Deu certo.


Tamanhos de divs ( Width e Height ) com posições Relativas e/ou Absolutas

Question: Estou tendo problemas ao posicionar items (div's), no caso, preciso que a primeira div, ocupe toda a altura e largura da tela, já as demais, ocupem apenas o padding que recebem e o tamanho do conteúdo de dentro dela (sem vazar conteúdo caso o mesmo seja maior, como por exemplo texto).
Como posso fazer usando position relative, e como posso fazer com absolute ?

As section's não podem se sobrepor

.main-content{
  width:100%;
  display:flex;
  flex-direction:column;
  padding:6px 0;
}
.section{
  position:relative;
  float:left;
  padding:6px;
  width:100%;
}

Comment: não entendi bem sua duvida, o conteúdo esta ultrapassando a div em que contem o conteudo ou esta ultrapassando o `main-content`?
Comment: A dúvida é como fazer, de forma que não ultrapasse, e que os outros `sections` sigam o fluxo sem se sobrepor, ta escrito ...
Comment: ultrapassar na horizontal ou na vertical? você pode colocar os dados que esta usando para ver como fica?
Comment: não ultrapassar na horizontal obviamente :D
Comment: Ta tudo ai, é apenas um exemplo pra ver como pode ser feito...
Comment: Ainda não está claro.
Comment: a div tem que ocupar 100% da altura e largura da página, e não pode sobrepor ou ser sobreposta por outras
Comment: huahuahua se ocupar 100% da pagina como não pode ser sobreposta por outras?
Comment: as outras são jogadas logo abaixo
Comment: no caso é o height da parte visivel da página, ocupando 100% dele e do width
Comment: tá muito enrolado, retirei a resposta. visite essa página Como fazer uma boa pergunta? http://pt.stackoverflow.com/help/how-to-ask
Comment: Faz uma imagem no photoshop ou paint ilustrando como você precisa que fique, senão fica difícil de entender.
Answer: Pra fazer com que as divs internas não vazem, tente utilizar *{box-sizing: border-box;} no CSS

* {
  box-sizing: border-box;
}
.main-content{
  width:100%;
  display:flex;
  flex-direction:column;
  padding:6px 0;
  background-color: red;
}
.section{
  position:relative;
  float:left;
  padding:6px;
  width:100%;
}
.section:nth-child(1) {
  background-color: blue;
}
.section:nth-child(2) {
  background-color: yellow;
}
.section:nth-child(3) {
  background-color: green;
}

E para manter o elemento com altura 100%, tente com jQuery

$(window).bind("load resize", function() {
 // Será executado quando o documento carregar
  //ou quando o usuário redimensionar a tela (zoom)

  // Caso utilize Navbar, dar o valor de sua altura + margem
  // Exemplo: Navbar possui 30px de largura + 10px de margin-bottom
  // topOffset = 40;
 topOffset = 0;
 height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height);

  // \/ Altura da página - valor da Navbar (topOffset)
 height = height - topOffset;
 if (height < 1) height = 1;
 if (height > topOffset) {
  $(".wrapper").css("min-height", (height) + "px");
    // /\ Elemento alvo
 }
});
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  background-color: red;
}

.wrapper {
  padding: 8px 4px;
  background-color: #fff;
  max-height: 35px;
}

  Wrapper aqui

Comment: Editado ;) tenta agora
Comment: mas e o height de 100% da visualização da tela ? :3


change dropdown content when checked

Question: I have made a way to present a droplist to end user and by default containing 4 items (value=a,value=b,value=c,value=d). When a user click on a checkbox the content of the droplist changes to only 2 items (value=a,value=b) IF unchecked returned to default state.
I achieve this way below using hiding div but wondering if a better different way using Jquery, I have searched and cant figure it out using let say if checked present these options else present default. Currently I have to work with 2 different dropdown which is awkward when passing values in a form.
THE CHECKBOX
 <input class="optionChoice" type="checkbox" id="optionChoice"         name="optionChoice" value="YES" onClick="if(this.c.........

IN MY PHP PAGE I HAVE 2 DIV WHERE ONE IS VISIBLE AND THE OTHER IS NOT ALL DEPENDS ON IF CHECKBOX CLICKED THEN MAKE ONE VISIBLE AND THE OTHER INVISIBLE VISVERSA.

               Service Type *

                <select name="serviceType" id="serviceType">
                     <option value="" label="-- Choose One --"> -- Choose One --</option>
                     <option value="A" label="A">A</option>
                      <option value="B" label="B">B</option>
                     <option value="C" label="C">C</option>
                      <option value="D" label="D">D</option>
                </select>

                    Service Type *

                     <select name="serviceType2" id="serviceType2">
                        <option value="" label="-- Choose One --"> -- Choose One --</option>
                         <option value="A" label="A">A</option>
                          <option value="B" label="B">B</option>
                      </select>

    script

        $(function() {
            enable_cbChoice();
            $("#optionChoice").click(enable_cbChoice);
        });
        function enable_cbChoice() {
            if (this.checked) {
                $("#test").hide();
                $("#test2").show();
            }
            else{
                $("#test").show();
                $("#test2").hide();
            }
        }

Answer: Try to just have one dropdown (id="serviceType") and then add or remove the options based on the state of the checkbox:
var detached;
$('#optionChoice').on('change', function() {
    var $el = $(this);

    if( $el.prop('checked') ) {
        detached = $('option[value="C"], option[value="D"]').detach();
    } else {
       $('#serviceType').append(detached);
    }
});

Working Fiddle: http://jsfiddle.net/jhummel/D43fh/
Comment: THis is amazing, its so simple I feel stupid. Thank You! I will apply this logic.
Answer: You can achieve this by detecting the state of the checkbox using javascript. I can show you the method using jquery. Then you can use the remove and append function of jquery to add and remove values from the dropdown. To achieve your problem, you can do something like this.
$('input[type="checkbox"]').click(function() {
    if( $(this).is(':checked') ) {
        $("#selectBox option[value='C']").remove();
        $("#selectBox option[value='D']").remove();
    } else {
        $('#selectBox').append('<option value="C">C</option>');
        $('#selectBox').append('<option value="D">D</option>');
    }
});

change dropdown content when checked


Why no mention of penalized regression techniques in Applied Logistic Regression, 3rd edition, by Hosmer, Lemeshow, and Sturdivant?

Question: Just ordered this textbook, and Wow, the complete omission of this subject from an otherwise excellent reference on logistic regression is a bit surprising. The 2nd edition was published in 2000 - there's been a lot of research into penalized regression techniques since then: for example, the lasso and elastic net.
I know this text is aimed at epidemiologists and public health specialists. Have researchers in these fields ignored any developments that smack of data mining?
Comment: Unless one of them has written or spoken about this (which I doubt), answers about why this decision was taken are likely to be largely speculation - highly plausible reasons might be given, but they'll almost certainly remain speculation.
Comment: Of course you can't cover everything; but in the 2nd edition the authors devoted a large part of one chapter to post-hoc variable selection techniques, including stepwise & best-subset methods (though they noted they were going out of fashion), & from what I can see on Google Books the coverage hasn't changed much in the 3rd edition. These techniques smack of data mining just as much as LASSO & elastic net do - so I agree that it's a rather surprising omission, but don't have any theories about it.
Comment: @RobertF: An ideal complement to *Applied Logistic Regression* IMO would be [Harrell (2002), *Regression Modelling Strategies*](http://www.springer.com/statistics/statistical+theory+and+methods/book/978-0-387-95232-1), in which penalized regression methods often take centre stage.
Comment: @Scortchi - Yes the methods described in the variable selection chapter seem outdated. I'm still glad I bought the book, not as a sole source for all things logistic regression but as a complimentary resource to other textbooks.
Answer: It is possible that there is a prejudice against anything that comes close to data mining, but there can also be good reasons for omitting this area. Without further information I would start with the assumption that there was a good reason. If you assume a good reason and there was actually a prejudice the debate starts as much more friendly and is likely to become much more productive than when you assume prejudice and there was actually a good reason.
Any textbook needs to make a selection on what it covers and what it does not cover. The fact that something has developed recently is on its own not a sufficient reason to include it. I use logistic regression a lot in my own research and I have never been in a situation where I needed the lasso or elastic nets. So if I were writing such a textbook, I would probably ignore that part too. This is not to say there is anything wrong with these techniques; they just weren't useful for the problems I wanted to solve.
Since different (sub-)disciplines tend to focus on different types of questions, it is not surprising that some techniques are less useful for that (sub-)discipline than others. This should translate to which topics are covered in textbooks aimed at different (sub-)disciplines.
Comment: Thanks for the insightful response Maarten. I get the impression the field of statistics is fracturing into many subfields which don't communicate with each other.


Postpaid license billing type does not work with Commerce Stripe

Question: This has been placed on https://www.drupal.org/node/2634778, but since there is no any reaction there yet I thought I'd have better chances here on Drupal Questions.
This has been tested well on a clean Drupal Commerce setup:
If a product configured with prepaid license billing type (see different billing types on https://www.drupal.org/node/2127603) is checked out, then everything works well - Drupal Commerce creates two orders: one already processed and one for the next billing period with the "Recurring: Open" status.
However, if a product with postpaid license billing type is checked out, then Drupal Commerce creates only one initial order that never recurs. What is interesting, if a postpaid product is checked out together with a prepaid product in a single order (just to get an order with "Recurring: Open" status created) and then if prepaid product gets cancelled, then the postpaid one keeps recurring successfully.
At the same time, if "Example payment" is used instead of "Commerce Stripe" as the payment method, then both pre and postpaid products recur without problems. Which makes me to believe that something in Commerce Stripe is not triggered when postpaid product is ordered.
Answer: This is just to let every one interested know, that Aviindub was kind enough to reply to my post on https://www.drupal.org/node/2634778#comment-10669204, after which I have re-installed everything from scratch once again, but in little bit different order, and postpaid orders started to recur too.


Is it against the rules to head the ball back to your goalie?

Question: While I was reading the Laws of the Game to look for an answer to another question, I came to read the following bit:

Cautions for unsporting behaviour There are different circumstances
  when a player must be cautioned for unsporting behaviour, e.g. if a
  player:

...
uses a deliberate trick while the ball is in play to pass the ball to
  his own goalkeeper with his head, chest, knee, etc. in order to
  circumvent the Law, irrespective of whether the goalkeeper touches the
  ball with his hands or not. The offence is committed by the player in
  attempting to circumvent both the letter and the spirit of Law 12 and
  play is restarted with an indirect free kick

This goes against all my knowledge of football, as it happens on a regular basis, as a matter of fact it's even a sign of a good defender to do this properly. Have I misunderstood something, or is this rule just not enforced on a regular basis?
Answer: You are misinterpreting the rule; you can pass the ball to your goalie using your head, chest or whatever. What you can't do, is to pass the ball using a trick, like for example the goalie gives the ball to a defender, and then the defender does some juggling to raise the ball,and head it back to the goalie.
But according to the rule, you could lift the ball to another player who can then pass it to the goalkeeper, and this is not illegal in the spirit of the law (since the law always refer to one player).
The ball can be passed to the goalie in the flow of the game with any legal body part, even with your feet, if that was not your intention (if you try to kick the ball and you miss it, or if you try to deflect it and it goes to your goal).
Read about this here
Comment: Ah ok, I think it's pretty vaguely put in the rulebook. Btw I did some small edits in your answer to clarify some bits, hope that's OK.
Answer: In 1992, FIFA introduced the Back-Pass rule in an attempt to speed up the game and reduce time wasting.
The Back-Pass rule prohibits goalkeepers from intentionally handling the ball if it has been deliberately played to them by a teammate, or from intentionally handling the ball when receiving directly from a throw-in.

According to the Laws of the Game, a goalkeeper cannot touch the ball
  with his hands after a teammate has deliberately kicked it to him. In
  this back-pass situation, the goalkeeper has two options: kick the
  ball to safety or don't touch it at all. The back-pass rule also
  applies to throw-ins – a goalie can't pick the ball up if a teammate
  throws it directly to him.
If a goalkeeper does handle the ball from a back-pass, the referee
  will blow his whistle and award an indirect free kick to the
  opposition. Worse still, your opponents will take the free kick from
  the spot where the goalkeeper handled the ball – even if it's just
  inches from your goal!
When Can a Goalie Pick Up a Back-Pass?
There are some very important exceptions to the back-pass rule. If a
  player passes the ball back to his goalkeeper using his head, chest or
  knee, the goalie can pick up the ball. The goalie can also pick up the
  ball if a teammate passes it to him by accident. For example, a
  defender might slice or scuff his clearance, accidentally kicking the
  ball towards the goalkeeper. In this case, the goalie can pick up the
  ball.

Sources: 1 2
Comment: This doesn't address the specific case asked about in the question.