Google searching requires captcha when using proxy server

Question: We currently have a Squid Proxy server setup on our network, a high school. We are sending all traffic from student devices (iPads) through the proxy, both internally and externally. Traffic gets sent to our Firewall, and then from there, passed on to the proxy server. The proxy server then sends the traffic through our internet filter, which is also at the Firewall level.
The setup seems to work fine for all websites, except Google. When Google searching, I am redirected to ipv4.google.com when we are required to enter a CAPTCHA to continue searching. Google thinks that there is unusual activity when going through the proxy server.
Is there a way around this? Is there a better way to do our proxy so that Google doesn't see it as unusual activity? Another option would maybe be to not have any traffic from Google go through our proxy, but I'm not sure how to do this.
Any help would be appreciated.
Thanks!
Comment: It's good that it is only once per session. That means Google isn't punishing legitimate users from your IP, as soon as it has the information to distinguish them from whatever traffic from your IP, it finds suspicious. But Google shouldn't be able to tell if the device has been sleeping between two requests. Are you sure it isn't connected to how much time has past rather than whether the device has been sleeping?
Comment: How frequently does each individual device see the captcha?
Comment: It seems to be only once per session. If they put the device to sleep and get back on, it asks for the captcha again.
Comment: You are right, I'm not sure exactly what factor is causing the device to have to enter the captcha again. It very well could be time, we will have to do some more testing to find out.
Answer: How to use the proxy for everything but Google
If you are hijacking the traffic to send it through a "transparent" proxy, then you could configure the device doing the hijacking to not hijack the IP ranges known to belong to Google. Then those requests won't go through the proxy.
If you are rather relying on a web proxy auto detection script, then you can update the script to consider the hostname before deciding on whether to use a proxy or direct connection.
However if those requests end up all going through a single NAT instead of all through a single proxy, Google may never know the difference. It would still see all the same requests coming from a single IP, which may look equally suspicious if done through NAT or proxy.
It may be the only way you could get a separate IP for each device is by using IPv6. Luckily Google supports IPv6, so if you do get IPv6 on your network, Google will be able to tell the difference between requests from different devices.
Other approaches
There may be a single or a few devices on your network, which are flooding Google with abusive requests. Try to track down the devices doing the most requests to Google, and figure out if they are legitimate. If you have a few machines infected by botnets, then cleaning them might solve the problem.
You could also double check if your proxy is sending all information to Google, which could help Google identify clients. If Google can tell which requests came from which device, they might only block the abuse devices and not everything going through your proxy. For http you could ensure all requests to Google get an X-Forwarded-For header. It might be Google would entirely ignore that header, you can really only find out by trying.
If the requests are done over https there is not much you can do. You can't help Google identify individual clients, and you can't figure out what requests are performed, only the volume. However the volume of requests might be enough to identify if there are any abusive devices on your network.
Answer: Google normally doesn't allow proxies to be used for searching as it may impact their search results, I have tried it on several occasions but the same result.
This can be due to the reason that proxies may affect the ranking positions on SERP(s) or maybe they want that everybody should come direct without hiding oneself.
Answer: Google switched all their http traffic to https.  What this means is that the X-Forwarded-For entry cannot be modified by a proxy server unless the proxy server is performing a Man In the Middle https interception and producing an unauthorized certificate claiming to be *.google.com.
Believing that Google would trust an ip-address listed in the X-Forwarded-For: header is not a bot is crazy.  Any bot coder could simply code their bot to use a random ip-address in the X-Forwarded-For header and Google would just trust it was not a bot.
Believing that Google would trust that some proxy server that is hijacking the https session and spoofing the ssl/tls certificate is a trustworthy enough to say they are not a bot is crazy.
Has anyone actually demonstrated in 2015 that the Google Captcha stops happening after hijacking the https, inserting an X-Forwarded-For header, and spoofing the ssl/tls certificate?
Comment: There is a huge difference between trusting a header and using the header as a signal to identify bots. I do not know exactly which signals Google use to identify bots. But I am pretty sure Google tries to use all useful signals. And Google could very well have the data needed to evaluate the usefulness of using X-Forwarded-For as such a signal. I am not going to create a bot to hammer Google with abusive requests in order to find out whether Google would use the X-Forwarded-For header to distinguish between the bot and legitimate requests.


HTML: Button that links to a .html file

Question: I'm trying to make a button that links to a file (spaceRace.html), but I don't know how I would get the button to link to the file.
Please tell me what I should put in the button code.
<button type="button" onclick="">1 Player Mode</button>

Any help would be highly appreciated,
Comment: What exactly does "links to a file" mean?
Comment: By clicking on the button, the webpage will change into the other webpage (which is a .html file)
Comment: Try a link `<a href...` change the styling if you need it to look like a button
Comment: khakiout: I think that is explaining how to make a button link to a WEBPAGE. I want mine to link to a .html file
Answer:

<input type = "button" style = "color:red; height:100px;width:125px; font-size:10px;font-family:'COMIC SANS MS' " value = "1 Player Mode"/>
Comment: is there a way I can change the height and width of the button? Also, how do I change the font? How do I change the button text's color and font size?
Comment: @htmlKid Use `CSS`, in this case i used `inline CSS`
Comment: Thanks, but how do I change the font of the button to something like Comic Sans?
Comment: font-family attribute,`font-family:'COMIC SANS MS'`
Comment: @htmlKid you can get all the CSS Attributes [here](http://www.w3schools.com/cssref/)

HTML: Button that links to a .html file


Why if we use independence and factorization, we cannot represent every joint distribution? (rigorous argument needed)

Question: I was reading Koller's Probabilistic Graphical models book and it says something like this:

Let $P(x_i) = \theta_i$.
Define:
$$P(x_1, \ldots , x_n) = \prod_{i=1}^n \theta_i$$
This representation is limited, and there are many distribution that
  we cannot capture by choosing values for $\theta_i, \ldots, \theta_n$.
  This fact is obvious not only from intuition, but also from a somewhat
  more formal perspective. The space of all join distributions is a $2^n - 1$
  dimensional subspace of $\mathbb{R}^{2^n}$ - the set $\{ (p_1, \ldots , p_{2^n}) \in \mathbb{R}^{2^n} : p_1 + \cdots + p_{2^n} = 1 \}$ . On
  the other hand, the space of all joint distributions specified in a
  facorized way as in equation above, is an n-dimensional manifold in
  $\mathbb{R}^{2^n}$

The thing that confuses me about this sentence is the last sentence:

On the other hand, the space of all joint distributions specified in a
    facorized way as in equation above, is an n-dimensional manifold in
    $\mathbb{R}^{2^n}$

I do not understand what it means that the factorized version is an n-dimensional manifold in $\mathbb{R}^{2^n}$. I don't know if its the wording or I don't know what manifold means in this context (not sure if a description of a set would make the point more clear). But, the thing is that the set that it wrote initially describing a joint distribution made sense and I understand it (I think). Its just saying it can pick any vector in $\mathbb{R}^{2^n}$ that satisfies the normalization condition. However, I fail to understand rigorously what the limitation of the factorization version is.
Answer: Some pieces of information are missing in the OP, and the notation is not very formal, however I think it is possible to reverse-engineer what's happening.
You seem to have $n$ random variables each of which takes values over $\{0,1\}$, or alternatively you have $n$ probability distributions on $\{0,1\}$ given by $\theta_1,\dots,\theta_n$. Each such distribution is completely characterized by $q_i := \theta_i(1)$ since $\theta_i(0) = 1-q_i$ in such case. Now, we are interested in considering  a (joint) distribution $\theta$ over $\{0,1\}^n$. This set has $2^n$ points, so any joint distribution $\theta$ can be characterized as a $[0,1]^n\subseteq \Bbb R^n$ vector $p = (p_0,\dots,p_{2^n-1})$ satisfying
$$
  \sum_{j=0}^{2^n-1}p_j = 1. \tag{1}
$$
The equation $(1)$ defines the $(2^n-1)$-dimensional manifold in $\Bbb R$, each point on which represent a single joint distribution. Among such joint distributions, there are factorized (or product) distributions given by $\theta = \theta_1\otimes \theta_2\otimes\dots\otimes\theta_n$. Each such product distribution is determined uniquely by a sequence of $\theta_i$'s, and as we remember each $\theta_i$ is uniquely determined by a single real number $q_i$. As a result, each factorized joint distribution $\theta$ is uniquely determined by a collection of $n$ real numbers, which suggests why is that an $n$-dimensional manifold. In particular, if $[j]_i$ denotes the $i$-th coordinate of the binary representation of $j = 0,1,\dots,2^n-1$ then
$$
  p_j = \prod_{i=1}^n \theta_i([j]_i) = \prod_{i=1}^n\left(q_i\cdot[j]_i + (1-q_i)(1 -[j]_i)\right).
$$
Comment: Well, it was not clear what are the ranges of $x_i$'s but I guess that $\{0,1\}$ is the natural choice. Just tell me whether you understand my answer whenever you'll get time to read it.
Comment: the part I am not sure about your answer is, what part of it implies that the factorized version of the distribution is limited and that there are many distributions we cannot capture? @Ilya
Comment: I realized I forgot to read ur answer, I sincerly apologize. I will get around it this weekend and post follow ups as soon as I have some. Thanks and srry.


AWS inbound rules not working for security group

Question: I'm trying to enable port 8080 between a pair of servers running in different availability zones (but the same region) on AWS.
I created a security group, added port 8080 as the port, and added the ID of the security group as the source. I then added this security group to both of the servers.
I am unable to connect from one machine to the other on port 8080, if I change the source to allow all, then I am able to connect.
Have I missed a step? It doesn't matter which group ID I use as the source, I still can't access without leaving it wide open. Is there perhaps another port that needs to be opened to service HTTP requests? The connection isn't refused, it just times out.
Comment: Do you have anything listening on port 8080 on the servers? Try running netstat -tulnp | grep 8080 (is this a Linux box?) Also, if your trying to make an outbound connection from point A -> B on AWS, you need to make sure that 8080 is open for outbound connnections.
Comment: @ryekayo, there is something listening - if I make the source "from anywhere" I can connect
Comment: Ok so what about the source SG? Does that have 8080 open as well?
Comment: Are the two servers inside the same VPC? Or are they in different VPCs?
Comment: @MattHouser the same VPC
Comment: @ryekayo the security group has an outbound rules set to all ports and all destinations
Comment: I'm not sure if it makes any difference, but I am using elastic IP's
Answer: Assuming Server A is trying to ping Server B and Server B's security group grants inbound access from Server A's security group...
You need to make sure Server A is pinging Server B via Server B's Private DNS Address (or Private IP Address) instead of Server B's public (or elastic) address.
According to the documentation:

Incoming traffic is allowed based on the private IP addresses of the instances that are associated with the source security group (and not the public IP or Elastic IP addresses).

If you select an instance from the Instances page on the EC2 Dashboard you can see the instance's public and private addresses.
Answer: This sounds like a problem with ephemeral ports. It working when you open all ports is the main reason I think this.
Short version: when a computer connects to a port on another computer, it chooses a random port as the "source" port. This port has to be unblocked on the destination computer to allow traffic to return to it.
Read up on the ephemeral port range on your operating system - it varies, but 49152 to 65535 is standard. Open 8080 and that port range. If it works, leave them open, it's generally safe. The main thing is to ensure privileged ports (below 1000) are protected.
It's probably not applicable in this case, but when you have connectivity problems you should generally check Network ACLs.
Comment: The default egress on the Security groups, at least in the console, is to allow all ports, so unless he does have specific outbound rules on the sec group it should work, given that port 8080 is open on inbound. NACL are a different story.
Comment: @strongjz you're right about the default, but given the information we have I think this is a reasonable theory. I'm happy to be proven wrong, but it's worth considering. It's easy to verify, let's wait to see what happens if Zack tries it.
Comment: @Tim unfortunately all the outbound ports are open, and this problem is still continuing
Comment: Can you please screenshot the security group settings and include in your question. Obfuscate anything you don't want to share.


Dagger 2 doesn't provide my class as singleton, why?

Question: I have a class:
public class MyFactory {
    public MyFactory() {
    }

}

My Dagger module:
@Module
public class MyModule {
    @Provides
    @Singleton
    public MyFactory provideMyFactory() {
        return new MyFactory();
    }
}

My component:
@Singleton
@MyScope
@Component(modules = MyModule.class)
public interface MyComponent {
    MyFactory getMyFactory();
}

My Scope:
@Scope
@Retention(RetentionPolicy.CLASS)
public @interface MyScope {
}

I expect MyFactory instance being provided by Dagger2 is a singleton however, it is not. I tried to call following code in two places of my project:
MyFactory factory = DaggerMyComponent.builder()
                .build()
                .getMyFactory();
Logcat.d("tag", "factory = " + factory);

My log shows me :
factory = :com.my.app.MyFactory@eaa9330
factory = :com.my.app.MyFactory@8bd552e

As you can see, they are two instances. So, My questions are:
Question 1. In above case, why Dagger doesn't provide MyFactory as a singleton??
Question 2. With my above code, does everytime calling DaggerMyComponent.builder().build(); create a new instance of MyComponent?
Question 3. Dagger also allow developer's class instance to be injectable by place a @Inject annotation in constructor without bothering having the module:
public class MyFactory {
    @Inject
    public MyFactory() {
    }
}

developer can use it just by @Inject MyFactory factory;
In this case, how to make MyFactory singleton with Dagger 2?
Comment: Because you're creating a new component each time.
Answer: Scopes are per component. If you create multiple components then you create multiple objects. @Singleton is no exception.
// same component
DaggerMyComponent firstComponent = DaggerMyComponent.builder().build();

firstComponent.getMyFactory() == firstComponent.getMyFactory(); // true

// second component
DaggerMyComponent secondComponent = DaggerMyComponent.builder().build();

firstComponent.getMyFactory() == secondComponent.getMyFactory(); // false

You will have to keep the component instances and reuse them, or you will always create new references. E.g. A common way is to place the @Singleton AppComponent within your Application and grab it from there when needed.

In this case, how to make MyFactory singleton with Dagger 2?

With constructor injection you just add the scope to the top of the class.
@Singleton // place scope _on_ the class
public class MyFactory {
  @Inject
  public MyFactory() {
  }
}

Comment: Do you mean everytime I call `DaggerMyComponent.builder().build();` it creates a new instance of `MyComponent`? If so, is there a way to make component singleton?
Comment: What about my question 3?
Comment: @Leem.fin Yes, it will always recreate the component with everything in it. There is no "true" singleton with Dagger. You should keep your Singleton scoped component in your Application and reuse it from there. I'd advise against storing it in a static variable. I updated the answer to reflect the question


Can anyone help me identify this sound my guitar is making?

Question: My guitar has this weird reverberating sound after I strum a chord? Is this normal?
Comment: I can hear a steady 'whistle' three or four octaves above the root note. Is this what you mean? It can be heard on its own just after the last chord dies out. Sounds like an amplifier resonance. It shouldn't be there. It might be just a teaspoon ratting in a mug near the mic, but if it's always there then something is wrong. .  .
Comment: I can't notice anything particularly abnormal. It's slightly out of tune maybe? Or do you mean the low notes being a bit muddy when they sound together? Is the same problem with all chords - if you play barre chords higher up the neck, or other kinds of voicings/fingerings?
Comment: It's the reverberating sound that lingers after a strum. It's the sound a cymbal makes when you drop it on the ground and it rolls around before falling flat. Same across the neck. Doesn't what chord I play. Idk maybe it's normal.
Comment: It sounds normal to me.
Comment: Is your guitar acoustic?  It should "reverb".
Comment: Electric. Just wanted to make sure because I don't hear this sound when I hear recordings of other people. Wonder why that is
Comment: @alliang if you are playing through an amp, you might have a slight bit of reverb dialed in on the amp.  You should be able to change that with the knobs on your amplifier.
Answer: Yes. Normal.
What you're hearing is the peaks and valleys of the sound waves misaligning. If your guitar is slightly out of tune and you play the same "note" in two locations (like "A" on your open "A string" + "A" at the 5th fret of your "E string") you will hear this wobble more clearly. Some may also describe it as a Leslie effect (rotating speaker cabinet). As you re-tune the strings more accurately, you'll notice the wobbles / reverberations start to align until they effectively disappear.
Unfortunately due to the nature of Equal Temperament and the guitar, some chords will do this more than others, even when you are "in tune."  But there's nothing wrong with your instrument. In fact, some find this sound is desirable :)


Proving $f(x,y)$ is not Lipschitz but still has a unique solution to initial value problem

Question: Consider $g:\mathbb R\to\mathbb R$ defined by $g(y)=1+\sqrt |y|$. Let $h:\mathbb R\to \mathbb R$ be a continous function such that $h(x)\neq 0$ for all $x\neq 0$. I'm asked to prove the following:

Prove the function $f(x,y)=\frac {h(x)}{g(y)}$ is not Lipschitz respect to $y$ around the origin.
Prove the initial value problem associated with $(0,0)$ has a unique solution. Find the solution in the case $h(x)=1$.

The first point is clear since $\partial f(x,y)/\partial y \to \infty $ as $y\to 0$. My problem lies on the second point. My only tool for proving uniqueness is the Picard theorem but $f(x,y)$ is not Lipschitz so I don't know how to tackle this problem. I tried using the method of separating variables but don't really know if it ensures uniqueness. Any help is appreciated.
Answer: You can use the method of separating the variables.
Namely, let
$$
G(y) := \int_0^y g(\xi)\, d\xi,\quad y\in\mathbb{R},
\qquad
H(x) := \int_0^x h(s)\, ds, \quad x\in\mathbb{R}.
$$
Since $G'(y) = g(y) \geq 1$ for every $y$, the function $G$ is strictly monotone increasing and $\text{Im}(G) = G(\mathbb{R}) = \mathbb{R}$, hence $G$ is bijective with inverse $G^{-1} \colon \mathbb{R}\to \mathbb{R}$.
Moreover, any solution $y(x)$ of the Cauchy problem satisfies the implicit relation
$G(y(x)) = H(x)$,
at least for those values of $x$ satisfying $H(x) \in \text{Im} G$.
Since $\text{Im} G = \mathbb{R}$, the implicit relation gives a unique solution $y(x) = G^{-1}(H(x))$ defined for all $x\in\mathbb{R}$.
Comment: If my $f(x,y)= x|y|$ and initial condition is $y(0)=0$. Then i should get a unique solution for $\mathbb{R}$. Isn't it?
Comment: Yes, that's correct. (And your unique solution is easily found.)


Generalization of binomial distribution?

Question: I know that you can approximate the normal distribution with the binomial distribution.
One sample would be to flip $N$ coins, count how many heads, and increment the count in a bucket of a histogram for that many heads.
If you do enough samples, and as $N$ approaches infinity, you'll get a normal distribution.
My question is: What happens where instead of using a 2 sided coin, you use an $M$ sided die?
Does this still approach a normal distribution? Or is it a different type of distribution?
Edit: From observation it seems like adding more sides to the dice ($M$ increases) that you get a taller "triangular" distribution, but if you add more rolls ($N$ increases) that the distribution becomes more normal / gaussian.
Comment: Depending on what you're counting, you'll get a normal or multivariate normal distribution. See https://en.wikipedia.org/wiki/Central_limit_theorem.
Answer: Rolling a $M$-sided die would give you a multinoulli or categorical distribution, and is specified by a probability vector $\vec{p}$ of length $M$ where the $i$-th element is the probability you get side $i$. The number of times you got each side in of $n$ rolls which are i.i.d. would follow a multinomial distribution with parameters $n, \vec{p}$.

Central limit theorems are statements that say that averages of random variables converge in distribution to a Gaussian distribution. The basic statment is that if $\{X_i\}$ are i.i.d. with mean $\mu$ and variance $\sigma^2$, then $\frac{\sum_{i=1}^n (X_i - \mu)}{\sigma\sqrt{n}} \to N(0,1)$ in distribution, i.e. $\lim_{n \to \infty} P(\frac{\sum_{i=1}^n (X_i - \mu)}{\sigma \sqrt{n}} \leq c) = P(N(0,1) \leq c)$ where N(0,1) denotes a Gaussian with mean zero and variance 1. You can extend this to vectors.  Central limit theorems tend to hold in a fairly wide set of cases and are a workhorse in probability/statistics (without them, and laws of large numbers, nothing would get done).
A Binomial(n,p) distribution has the distribution of a sum of n i.i.d. Bernoulli(p) random variables. Say $\{X_i\}$ is i.i.d. Bernoulli(p). So, by the usual basic central limit theorem, $\frac{\sum_{i=1}^n (X_i-p) }{\sqrt{np(1-p)}}$ converges in distribution to a Gaussian with mean $0$ and variance $1$.  That is, $\lim_{n \to \infty} P( \frac{\sum_{i=1}^n (X_i-p) }{\sqrt{np(1-p)}} \leq c) = P(N(0,1) \leq c)$.

Note that things don't always converge to
Gaussian distributions -- for example, if you have a sequence of Binomial$(n,p_n)$ distribution, and take the limit as $n\to \infty$ where $n p_n = \lambda$, the convergence in distribution is to a Poisson($\lambda$) distribution (the so called, law of rare events).

For more details, you can look at papers like
 Morris, Carl. Central Limit Theorems for Multinomial Sums. Ann. Statist. 3 (1975), no. 1, 165--188, which considers the case of averaging multi-sided die rolls.
The interplay between the number of sides (the length of $\vec{p}$), probability of sides ($\vec{p}$) and number of rolls (samples, $n$) can change the limiting distribution, just as in the Binomial case above.
Comment: Thanks batman. Also, much better than superman's explanation!
Comment: Hey there Batman.  I now realize I was a little ambiguous.  I'm summing the value of the dice rolls.  Does that make a difference or narrow down what kind of distribution it is?  If i rolled ten 3 sided dice and summed them, and made a histogram of the results of doing that 1000 times, I don't believe that would be a trinomial distribution.  Or would it?
Comment: Well, if the dies were fair, the sum of ten 3 sided die rolls would follow a discrete analogue of the Irwin-hall distribution. Say $X_i$ is the sum of ten 3 sided die rolls, and you do this $n$ times i.i.d.; Let $\mu$ be the mean of $X_i$ (which is 10 times the one die mean), and $\sigma^2$ be the variance of $X_i$ (which is 100 times the one die variance). Then, $\frac{\sum_{i=1}^n (X_i - \mu_i)}{\sigma \sqrt{n}}$ converges in distribution to a standard normal by the Central Limit Theorem.


Feature importance for random forest classification of a sample

Question: This is a cross post from : https://datascience.stackexchange.com/questions/8208/feature-importance-for-random-forest-classification-of-a-sample
Using a random forest is it possible to determine which features were the driving features to classify a specific sample as class A?
I know I can ask which features are more important to perform classification of ANY sample, but can I ask this for a specific sample? E.g. Why was sample 1 classified as A? Which of its features were much more like class A than class B?
Does it even make sense to ask this question of a random forest?
Bonus points on how to do it with sklearn in python :)
Answer: Variable importance accounts for the increase in out-of-bag cross-validated prediction error. It would be possible but not meaningful to account for the change of prediction error by one sample only. As one sample only can be correctly or wrongly predicted, such a term would be very unstable and crude.
You could check out 'local variable importance', 'partial dependence plots' or 'feature contributions'. Here's an example from my package forestFloor using feature contributions. Each plot shows the change of predicted class probability as function each variable. For the iris data set, there no strong variable interactions. Therefore, the model structure can be boiled down to a 2D visualization. The R-sqaured terms quantifies how much the model structure deviates from this main effect only interpretation/visualization.
<code>library(forestFloor)
library(randomForest)
data(iris)
X = iris[,!names(iris) %in% "Species"]
Y = iris[,"Species"]

rf = randomForest(X,Y,
                  keep.forest=TRUE, #mandatory for classification
                  replace=FALSE,    #if TRUE use trimTrees::cinbag, not randomForest
                  keep.inbag=TRUE,  #mandatory always for forestFloor
                  sampsize =15 )    #optional:smaller trees smoother model structure

ff = forestFloor(rf.fit  = rf,           # mandatory
                 X       = X,            # mandatory
                 calc_np = "sad monkey", # this input takes no effect for classification
                 binary_reg = FALSE)     # can change two class classification to regression
# Thus cannot be TRUE for IRIS (three class)

plot(ff,plot_GOF=TRUE,cex=.7,
     colLists=list(c("#FF0000A5"),
                   c("#00FF0050"),
                   c("#0000FF35")))
</code>
Comment: For anyone interested, I found this implementation with some of these things for sklearn:  http://blog.datadive.net/random-forest-interpretation-with-scikit-learn/

It needs the dev version of sklearn (0.17)
Comment: Thanks for your description, example, and terminology.  It's amazing how much easier it is to find information when you know the jargon :)


Prove that $ A^n := \{ a^n : a \in A \}$ and $A_n := \{ g: g \in A : g^n = 1 \} $ are characteristic subgroups of $A$.

Question: The Statement of the Problem:
Let $A$ be an abelian group and $n$ a positive integer. Prove that
$$ A^n := \{ a^n : a \in A \} $$
$$ \text{and} $$
$$ A_n := \{ g: g \in A : g^n = 1 \} $$
are characteristic subgroups of $A$.
Where I Am:
So, it looks like what I want to show is that $\forall \phi \in \text{Auto}(A), \phi (A^n) = A^n$. If I understand correctly, the case of inner automorphisms is clear:
$$ \phi _ a (a^n) = aa^na^{-1} = aa^{-1}a^n = a^n .$$
But, is there some way to represent an arbitrary automorphism and just "check" it? Or is this not as simple as I've hoped (or even simpler!)?
EDIT: I've got an idea for the first one, but I don't think it's correct...
$a^n = aaa...a$, i.e., the product of $n$ $a$'s. Now, because $\phi$ is a homomorphism:
$$ \phi (a^n) = \phi (aaa...a) = \phi(a)\phi(a)\phi(a)...\phi(a). $$
And because $\phi$ is bijective:
$$ \phi^{-1}[\phi(a)\phi(a)\phi(a)...\phi(a)] = aaa...a = a^n. $$
Q.E.D?
Comment: It's trivially true of inner automorphisms: There's only the identity, for abelian groups! But yes, just pick a "generic automorphism" (i.e., bijection $\varphi :A \to A$ satisfying $\varphi(xy) = \varphi(x)\varphi(y)$), and see what happens.
Comment: @pjs36 Ah. Ok. Well, I worked it for a bit and added an edit. I'm not too confident in it, though...
Answer: I think it's easier (algebraically) than you're making it, but we have to think more if we want less algebra. I think you have the big idea, but I wouldn't say it's entirely airtight $\ddot\smile$.
At least, I think the big idea of yours is that $\phi(a^n) \in A^n$, so $\phi(A^n) \subseteq A^n$. Mentioning this would be good: "Since $\phi(a) \in A$, we have that $\phi(a^n) = \phi(a)^n \in A^n$," for example.
I'm not sure you showed the reverse containment though, this is where the commentary is really important. To show that $A^n \subseteq \phi(A^n)$, show that every $a^n$ can be written as an image under $\phi$ of some $n$th power: $$a^n = \phi\big(\underbrace{\phi^{-1}(a)^n}_{\in A^n}\big) \in \phi(A^n).$$ But that was super confusing for me to figure out exactly what needed written down!

An alternative:
You already showed that $\phi(a^n) = \phi(a)^n$, and I would use that.
So, if $A^n = \{a^n : a \in A\}$, we have
\begin{align*}
\phi(A^n)
&= \{\phi(a^n) : a \in A\} \tag{definition of image} \\
&= \{\phi(a)^n: a \in A\} \tag{property of homomorphisms}\\
&= A^n
\end{align*}
where the latest equality is simply because $\phi: A \to A$ is a bijection; we have $$A = \{a: a \in A\} = \{\phi(a): a \in A\},$$
and so $\{\phi(a)^n : a \in A\}$ must be $\{a^n : a \in A\}$, just a bit "mixed up" perhaps (as $a$ runs through $A,\ \phi(a)$ does too).


What are all the cases in which BFS and DFS produce the same tree on a graph?

Question: I want to know what are the cases in which BFS and DFS produce the same tree from a graph rooted at any node. I know one of the cases is when the graph is already a tree. Is this the only case?
Is it dependent on the way you choose the neighbors of a node? What are some ways that the order of picking the neighbors will make it the same?
Answer: First, before delving into a direct answer to the question, I want to take a slight moment to explain DFS and BFS. This is for anyone reading who may not know what "breadth first search" and "depth first search" are.
DFS: Depth-First Search is a tree-traversal algorithm that starts at a root node and explores as far along as possible for each branch before backtracking.
BFS: Breadth-First Search is a tree traversal algorithm that starts at a root node and explores all vertices at the current depth-level before moving on to explore the vertices at the next depth level. This is a top-down approach to create a tree.
Now, onto the question.

I know one of the cases is when the graph is already a tree. Is this the only case?

You are correct in saying this is one of the cases where BFS and DFS of a graph produce the same tree. To be more explicitly clear, when you state that the graph is already a tree, you're hopefully referring to a graph that has one of the three following properties:

A graph with a maximum breadth of 1
A graph that resembles a singly linked list
When you state the tree has to be the same, if isomorphic trees are regarded to as
the "same" by your definition, then any graph that is already a tree (which may also be what you're referring to in your question) will produce the "same" tree for BFS and DFS. Of course, there must be no cycles within the tree, or the graph will result in different outcomes for BFS and DFS.

In all three of these instances, the DFS and BFS of the tree will be the same given that you start at the same proper root node for both traversals. These are the only cases that I know of. However, in some instances, there are other means of obtaining the same tree for DFS and BFS traversal of a given graph if you have the freedom to determine the order you can select "neighbors" of a given node. This leads to the second half of your question...

Is it dependent on the way you choose the neighbors of a node? What are some ways that the order of picking the neighbors will make it the same?

Yes, it is dependent (if this question means what I really think it means), because if you have the freedom for this, then there are instances in which the order of picking neighbors will make it the same. For example, having a tree in which there is at most only one child that also has children, you can obtain the same BFS and DFS by traversing the nodes without children first in the DFS traversal of the graph.
Hopefully this information helps.


Linear regression with multiple observations for each input point: WLS approach

Question: Consider a dataset $X, y$ where each $y$ is distinct, but many of the rows of $X$ are repeated.
Suppose that there are indices $\{ i_j: j = 1  \dots J \}$ such that the consecutive rows $X_{i_j}=X_{i_j+1} \dots = X_{i_{j+1}-1}$ are all identical.
Will I get the same result if I work with a reduced dataset $\tilde{X} = ( X_{i_j} : j = 1 \dots J)$ and $\tilde{y} = \left( \frac{1}{n_j}\sum_{k=i_j}^{i_{j+1}-1} y_k : j = 1 \dots J\right)$ where $n_j = i_{j+1}-i_{j}$ and use WLS with weights $w = (n_j: j = 1 \dots J)$?
Here's a "proof":
The gradients (score function) are the same for both regressions:
$$ 2X'(X\beta - y) = 2\tilde{X}' W (\tilde{X} \beta - \tilde{y})$$
where $W = \mathrm{diag}(w)$.
Is the above correct?
If so, is there a name for this?
Answer: I worked out the answer.
Let $J$ be the number of unique $x$ observations, $n_j$ the number of times observation $x_j$ is repeated and $\{y_{j,i} : 1 \le i \le n_j \}$ the corresponding $y$ observations.
For a regression model $y = f(x, \beta) + \varepsilon$ the loss is given by
$$
\begin{aligned}
\sum_{j=1}^J \sum_{i=1}^{n_J} \left( y_{j,i} - f(x_j, \beta) \right)^2
&= \sum_{j=1}^J \sum_{i=1}^{n_J} \left( y_{j,i} -  \overline{y}_j + \overline{y}_j - f(x_j, \beta) \right)^2 \\
&= \sum_{j=1}^J \sum_{i=1}^{n_J} \left( y_{j,i} -  \overline{y}_j \right)^2 + \left( \overline{y}_j - f(x_j, \beta) \right)^2 + 2 \left( y_{j,i} -  \overline{y}_j \right)\left( \overline{y}_j - f(x_j, \beta) \right) \\
&= \sum_{j=1}^J \sum_{i=1}^{n_J} \left( y_{j,i} -  \overline{y}_j \right)^2 + \sum_{j=1}^J \sum_{i=1}^{n_J} \left( \overline{y}_j - f(x_j, \beta) \right)^2 \\
\end{aligned}
$$
The first term doesn't depend on $\beta$, which concludes the proof that the $\beta$s are the same.
The estimates of the residual variance will obviously differ between the two methods.


Proof involving multivariable chain rule

Question: Let the three-variable function f be differentiable and satisfy $$f(t\vec{x})) = t^{p}f(\vec{x}) $$ for all $ x \in \mathbb{R}^{3} $ and $ t \in \mathbb{R}$.
Prove that $$ \vec{x} \cdot \nabla{f(\vec{x})} = pf(\vec{x})$$ for all $\vec{x} \in \mathbb{R}^{3}$
I tried using a substitution $\vec{v} = t\vec{x}$ and then differentiating both sides of the function with respect to t to get $$\frac{d}{dt}f(\vec{v}) = pt^{p-1}f(\vec{x}) $$ Then the left side by the chain rule..
$$=\frac{\partial f}{\partial v_i}\frac{dv_i}{dt}  =  \frac{\partial f}{\partial v_i}x_i =\frac{\partial f}{\partial x_i}\frac{d x_i}{d v_j}x_j= \frac{\partial f}{\partial x_i}\frac{1}{t}x_i=\frac{1}{t}\nabla f\cdot \vec{x}$$
Now plugging this back in doesn't quite give the right expression:
$$ \nabla f(\vec{x})\cdot \vec{x} = p\cdot t^pf(\vec{x})$$
Answer: Your problem is that your partial differentation by $t$ was not executed correctly.
By the chain rule, $\frac{\partial}{\partial t}f(t\overrightarrow{x})$ is the fourth entry of the $1$-by-$4$ matrix $$D(f\circ g)(\overrightarrow{x},t)=\nabla f(t\overrightarrow{x})Dg(\overrightarrow{x},t)$$ where $g(\overrightarrow{x},t):=t\overrightarrow{x}$. Elementary computation shows that the rightmost column of $Dg(\overrightarrow{x},t)$ is $(x,y,z)^{T}$.  Thus, $$\frac{\partial}{\partial t}f(t\overrightarrow{x})=\nabla f(t\overrightarrow{x})\cdot \overrightarrow{x}$$ and hence, $$\nabla f(\overrightarrow{x})\cdot \overrightarrow{x}=\frac{\partial}{\partial t}|_{t=1}f(t\overrightarrow{x})=\frac{\partial}{\partial t}|_{t=1}(t^{p}f(\overrightarrow{x}))|_{t=1}=(pt^{p-1}f(\overrightarrow{x}))|_{t=1}=pf(\overrightarrow{x})$$
This completes the proof.  The problem that you had was that you shouldn't use the power rule when computing the derivative of $f(v)$ with respect to $t$.


How to add CSS to the module?

Question: I am very new to Drupal. I have an html form and I want to create a module that take the html of the form and create a table in the database and saves the form values in database.
what i have done i have created a form with form api (with buildForm method) my form is being rendered and i have converted it into Twig template (it is being shown in twig template), but first my CSS is not getting loaded.
My library file: mymodulename.libraries.yml
bootstrap:
  version: 1.x
  css:
    css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

global-components:
  Version: 1.x
  css:
    css/baselayout.css: {}
    css/form.css: {}
    css/wisdom.css: {}

  js:
    js/jquery.smartmenus.min.js: {}
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Comment: I removed the second unrelated question (about database input), please ask separate questions separately, after researching yourself first. Thanks!
Answer: CSS lives one level further down in a libraries file; under system, module or theme. e.g.:
bootstrap:
  version: 1.x
  css:
    theme:
      css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Comment: i tried this also
Comment: That's the answer to your question (_how to add css to module in drupal 8_), beyond that I'm not sure what you mean
Comment: hi Clive please help me how to pass action attribute in twig form.

How to add CSS to the module?


Using python to control a phone with bluetooth

Question: I would like to know if there are any API's for python to programmatically control a phone, like starting and ending calls, but also to record conversations.
I would also like to use the Headphones and Mic of the computer to talk over the phone.
Any info would be great, I tried googling for something, but nothing useful came up.
Comment: you've been a touch vague - is there any more detail you can provide?
Answer: Be careful when using PyBluez! The results will actually depend on the BT-USB dongle you are using. Depending on the hardware(the BT chip in there), PyBluez will use one or another BT stack - for example there was one from WIDCOMM. Results will vary, as PyBluez is actually wrapping around those stacks - all of which are far from complete.
So, when you have a working project, be sure to know what actual BT stack you were using :)
For Python audio stuff, you could try this.
Comment: One thing to remember, since the Pybluez library is so underdeveloped, and will not work with most BT Dongle drivers, it is a good idea to never actually install the drivers! **Try to make BT dongles install with standard MS Windows drivers!!! **
Answer:
PyBluez is an effort to create python wrappers around system Bluetooth resources to allow Python developers to easily and quickly create Bluetooth applications.

Unfortunately I've not found a page dedicated to its features, but it could be a good starting point, whether everything you need is in its feature set, or if you could build your application upon it by extending it.
http://code.google.com/p/pybluez/
Comment: Thanks! I also found this neat guide from nokia:
http://www.developer.nokia.com/Community/Wiki/How_to_send_AT_commands_and_Dial_with_Python_and_Bluetooth
It explains alot about making calls using pybluez

Now the next problem will be to use the speakers and mic from the computer to conversate :)


Inherit copy constructor

Question: Say I have a class A, which provide a copy constructor (accepting another A).
I then have a derived class B of A, which does not provide a copy constructor.
Can I inherit the copy constructor of A into B, alike what's possible for non-copy constructors?
Note: B does not have any state, except the state contained in A.
Comment: The copy constructor is not inherited via the *constructor inheritance* C++11 feature. However, the compiler is able to provide a ("custom") copy constructor for the derived class under some conditions. Please add a code sample or further details.
Answer: If you don't need any special behaviour in addition to what the base class's copy constructor provides, you should be fine with simply telling the compiler to use the default copy constructor, which will invoke the base classes copy constructor
#include <iostream>

class A {
public:
    int a;
    A()=default;
    A(const A& other) {
        std::cout << "Class A copy constructor called" << std::endl;
        a = other.a;
    }

};

class B: public A {
public :
    int b;
    B() = default;
    B(const B& other) = default;
};

int main() {
    B b1;
    b1.a = 1;
    b1.b = 2;

    B b2(b1);

    std::cout << b2.a << " - " << b2.b << std::endl;
}

Output:
Class A copy constructor called
1 - 2

EDIT:
In order to answer your exact question: I believe that the using directive makes all base class constructors visible in the derived class. I'm personally not too fond of this behavior, so I prefer using the default constructors instead of the using directive, but that's just me.

Inherit copy constructor


Find image of complex set:

Question: Find image of set:
$$ \{ z \in C : 0 \le Im (z), 0 \le Re(z) \}$$ and $$f(z)=\frac{i-z}{i+z}$$
I caclulate $ w=\frac{i-z}{i+z} $ and then $z=\frac{i(1-w)}{w+1}$ and don't know what to do next... I will be grateful for any help
Comment: Probably easiest to start with if you work with the Cartesian representation. Write $z = x + iy$ and then rationalize the denominator.
Comment: I did it and I have something like this: $z= \frac{i(1-x)+y}{x+iy+1}$ and I don't know what to do next...
Comment: Look at the images of $[0,\infty)$ and $i[0,\infty)$.
Answer: In your rearranged form for $z$, write $w=u+iv$. Multiply top and bottom of the fraction by the conjugate of the denominator so that you can identify the real and imaginary parts of $z$ in terms of $u$ and $v$. Now you can apply the inequality conditions given in the question, giving you inequalities for $u$ and $v$. You will end up with a region in the complex plane.
Answer: $f(ri) = {1 +r \over 1-r}$, hence $\{f(ri)\}_{r \ge 0} = (-1,1]$.
$f(r) = {(1-r^2)+2r i \over 1+r^2}$, from which we see that $|f(r)| = 1$, and
$\{f(ri)\}_{r \ge 0} = \{z | |z|=1, \operatorname{im}z >0 \} \cup \{1\}$.
$f(\infty) = -1$.
$f(1+i) = {-1+2i \over 5}$, so we can see that the image of the set (including
$f(\infty)$) is $\{ z \in B(0,1) | \operatorname{im}z \ge 0 \}$.

Find image of complex set:


Where to look for a forum thread in database?

Question: In Drupal 6 forum, a user reported that her thread has suddenly disappeared.
I am wondering in which database table should I look for the thread, and what might be the cause?
Answer: I don't know how 6 version works with forum (because I've never used 6v), but in d7 forum is actually is a node (threads are node types). I thinks you can search for forum table which holds the nids of threads and node and node_type tables for actually for that nodes and thread type...
To find the node by Title:
Open your PhpMyAdmin from browser -> select your db -> open 'node' table -> switch to SQL tab -> SELECT * FROM node WHERE title = "YOUR TITLE"
EDIT:
threads are taxonomies, not node types (based on comment of Mohammad Ali Akbari)
Comment: As I know threads are taxonomies and topics are nodes.
Comment: The only thing that I know of the missed thread is the title. How should I query it?
Comment: Open your PhpMyAdmin from browser -> select your db -> open 'node' table -> switch to SQL tab -> SELECT * FROM `node` WHERE title = "YOUR TITLE"
Comment: @MohammadAliAkbari Sorry, you're right absolutely. Thanks for the clarification.
Comment: @xurshid29. You were right. I could find the topic using this qurey:  select * from node where title like "%The lost topic title%" ; Please add this to that I can accpet your answer


Probability in a range

Question: Suppose $0 \leq z \leq 20 $
What is the probability that $10 \leq z \leq 15$?  $z$ is a real number.
Don't tell me the answer. It is my homework, but I missed my class so I don't know how to do it. Please guide me.
Comment: The question as it stands is meaningless.  Just telling me the range of values $z$ can take doesn't tell me the *distribution* of $z$.  For instance, $z$ could be $0$ with probability $1$.  Then we have $0\leq z\leq20$, and the probability that $10\leq z\leq15$ is $0$.  On the other hand, $z$ could be uniquely $10$ with probability $1$.  Then the probability that $10\leq z\leq15$ is $1$.  I imagine you mean that $z$ is uniformly distributed in the interval $[0,20]$.  Then the answer is -----------
Answer: Think about it geometrically. You are picking a random point on the line:

+--------------------+
0                    20

and you want the probability that the point you pick is in a specific region on this line:

          10    15
          |     |
+---------=======----+
0                    20
Comment: So we're just assuming all variables are uniformly distributed now?
Comment: @ChrisEagle Yes, that was my assumption. I will change/delete this answer if the OP indicates that this is not the case.

Probability in a range


Clustering of large, heavy-tailed dataset

Question: I have a dataset of 130k internet users characterized by 4 variables describing users' number of sessions, locations visited, avg data download and session time aggregated from four months of activity.
Dataset is very heavy-tailed. For example third of users logged only once during four months, whereas six users had more than 1000 sessions.
I wanted to come up with a simple classification of users, preferably with indication of the most appropriate number of clusters.
Is there anything you could recommend as a solution?
Comment: I don't see why you want to cluster your users without any subjective input (I refer to a comment you made @reed), you said you want "the most appropriate number of clusters", but unfortunatly you don't have a clear objective, if you want to cluster your population to show something particular, you should tell us what you want to show ? If you want statistic (the data) to tell you what you want to show this is another problem :)
Comment: @robin: thanks for comment. i haven't seen much research in this area and the input from data provider was minimal [so far they were not interested/capable of investigating it further]. after initial exploration of data it was quite clear for me that there are couple of distinctive patterns [examples being 'heavy downloaders' in just a few locations or 'frequent hoppers' with lots of small sessions in large number of locations].
my goal at this stage was to try to use data itself to tell me how can i divide it best and minimize subjective input.
Answer: You could of for a supervised self-organizing map (e.g. with kohonen package for R), and use the login frequency as dependent variable. That way, the clustering will focus on separating the frequent visitors from the rare visitors. By plotting the number of users on each map unit, you may get an idea in clusters present in your data.
Because SOMs are non-linear mapping methods, this approach is particularly interesting for tailed data.
Comment: Thanks Egon. SOM approach might be very interesting indeed. Will have a look at it.
Answer: K-Means clustering should work well for this type of problem.  However, it does require that you specify the number of clusters in advance.
Given the nature of this data, however, you may be able to work with a hierarchical clustering algorithm instead.  Since all 4 variables are most likely fairly highly correlated, you can most likely break out clusters, and stop when you reach a small enough distance between clusters.  This may be a much simpler approach in this specific case, and allows you to determine "how many clusters" by just stopping as soon as you've broken your set into fine enough clusters.
Comment: Thanks Reed. k-means is definitely a way to go and I explored several solutions. However I am trying to go for a solution without subjective decision of the number of clusters.   Hierarchical approach on the other hand produced huge classification and again it was hard for me to specify where to stop.
Answer: You might consider transforming (perhaps a log) the positively skewed variables.
If after exploring various clustering algorithms you find that the four variables simply reflect varying intensity levels of usage, you might think about a theoretically based classification. Presumably this classification is going to be used for a purpose and that purpose could drive meaningful cut points on one or more of the variables.
Comment: Thanks Jeromy. I explored several possible transformations of data using Stata's gladder function for the ladder of powers.

Teoreically based solution will be one way to go, but before that I wanted to check for the data driven solution.
Answer: This is problem with clustering, you can't tell what is considered a cluster. I would see what is the reason behind clustering users, specify my threshold value, and use hierarchical clustering.
In my experience, one has to set either the number of cluster needed, or the threshold value (the distance value that binds two data point together).


MER - Modelo entidade e relacionamento

Question: Gostaria de saber se meu MER está correto e se é possível faze um relacionamento N:N entre animais e agendamentos.
Especificações que eu criei para o sistema:
Informatizar os agendamentos de um banho e tosa, envolvendo os clientes, atendentes, animais, solicitação de agendamentos, agendamentos, serviços.

O sistema permitirá o cliente se cadastrar no sistema;
O sistema permitirá o cliente cadastrar seus animais no sistema;
O sistema permitirá o cliente escolher qual atendente ele irá fazer o serviço;
O sistema permitirá o cliente fazer solicitações de agendamentos;
O sistema permitirá o atendente aprovar ou cancelar as solicitações;
O sistema permitirá o atendente cadastrar novos serviços;
O sistema permitirá o cliente fazer a solicitação de agendamento com busca do animal em casa;
O sistema permitirá parametrizar o horario de disponibilidade do atendente;
O sistema permitirá parametrizar o horario de disponiblidade do banho e tosa;
Answer: Isso depende muito do fluxo de informações/regras de negócio de sua aplicação. Por exemplo, caso necessário mais de um endereço, poderia haver a tabela endereço e cliente separadas. No geral (com exceções), toda informação que se repete deve haver uma tabela específica e ser "laçada" com um ID referente.
Para um relacionamento N:N para animais e agendamentos, talvez a inclusão de uma tabela com as colunas ID - ID_ANIMAL - ID_AGENDAMENTO resolveria seu problema.
Recomento haver um histórico de serviços para os animais e a possibilidade de cadastro de mais de um serviço para determinado animal.
Comment: A questão das relações que usei para as tabelas você consideraria coerente?
Comment: Eu criaria a tabela endereços e depois a de cidades. Na tabela de atendente colocaria mais dados sobre o mesmo. Fora isso à principio está tudo ok. Mas como falei, o contexto das regras de negócio/necessidades influencia muito na modelagem de uma base de dados.
Comment: Ok, muito obrigado!

MER - Modelo entidade e relacionamento


Understanding the complex world of midi controllers, DAWs and live playing: what software should I use?

Question: So here's the scenario:
I play drums and mallets (marimba, vibes, etc.) and currently own a drumkit and a 4.3 octave padouk marimba. However, I'm looking into buying a Pearl MalletSTATION. The versatility of it is very attractive, being able to play all those percussion instruments on this one thing. I'm also quite interesting in jamming by building up some layers/loops; such as playing a bass marimba line, drums, chords on vibe and finally play solos on xylophone for example. On the other hand, I regularly help out small town orchestras with their melodic percussion and they usually don't have the right instruments (vibes, tubular bells etc.) so hooking the malletstation up to a PA would be very useful.
For context: I'm a software developer by profession. I use linux (ubuntu) or otherwise Windows if necessary for better software. MIDI is not an entirely strange concept to me, but DAWs mostly are (used cubase years ago but it looked like a maze to me). I read that Mainstage is good at this, but it's not for windows/linux and that ableton live can do this, but I'm not sure if it's overcomplicated. And to get mallet samples I need the suite version of the software voor €599...
So the question is: what is the most straightforward setup for me that I can use to play the malletstation at home but also bring to performances?
Edit:
a clearer overview of what I basically want to do, preferably as many of these as possible through programmable buttons on the midi-controllers:

plug midi-controller into laptop
choose an instrument
hit record
play some notes
hit stop so it starts looping those measures
change instrument
hit record again etc. (or play without recording)
Comment: If you say so I believe you, but I had no clue what a rack module is (just googled it) and would prefer not to invest in more hardware. Also, to be able to use any midi-hardware I need a midi-expander for the malletstation since by default it only outputs midi over USB
Comment: If you spend some time you can roll your own, the midi specification is not super long and at least Windows have built in midi api. Not sure if you can use plugins and soundfonts with it though...
Comment: What do you mean Emil? Build my own midi-hardware? So far I've been using Ableton with very mixed results
Comment: I got the impression you wanted a software which could record midi into tracks easily, and possibly play it back. I have only converted touchpad to realtime playback so I am not an expert but it is certainly not impossible to make your own if you are a programmer.
Comment: Oh I see you are a professional musician, you probably don't want to waste time making your own in that case.
Comment: Hey Emil, definitely not a professional musician, though yeah I earn some small money with it. To elaborate: I bought a MalletSTATION a while ago and use it with a novation launchpad mini. But I did have to write my own plugin to get some of my setup working. That pluging didn't work with the latest ableton though, so I don't have a perfect setup currently. But also haven't played much because of work ;-)
Answer: I don't own any instruments, synthesizers, or physical plugins, so I can't help you with that.
As for DAW, most have a high learning curve and the difference is hardly noticeable if you're a beginner. However, it is extremely recommended to own a professional DAW if you plan on composing or mixing. It is not worth saving your money on free DAWs like Audacity, GarageBand, the ones you find on AppStore, or rent in on a browser.
The main decision on which DAW to own depends on if you're on Windows or Mac. FL Studio is great for Windows and is beginner-friendly. If you're on Mac, I hear good things from Logic Pro or Cubase.
Most of the main challenge in maneuvering the DAW is on the plugins itself, not the DAW's interface. It is important for your DAW to be able to support important 3rd party plugins such as Kontakt Player, Serum, or certain special slicers or voice harmonizers.
Some awesome and super professional plugins for voicing, orchestration, or beat making seem to be exclusive to certain DAWs. If any of those were your purpose, be sure to check out if your DAW supports making certain genres of music/sounds.
If you are still unsure, just get either and expand your knowledge from that platform. Most of us get our current expertise and career that way anyway, by jumping in after enough time of fiddling and not over analyzing.
Comment: Just want to add (as it has been forgot here ;) ) that, if you are on GNU/Linux, Ardour is a very good choice, especially these last years. It is free, or very cheap, and interface well with the plugins you can find on GNU/Linux like Calf Plugins.
Comment: Thanks both for your suggestions. I'd like to add though that recording/composing/mixing is not my goal. The goal is looping my plays on top of eachother live (so without creating new tracks with mouse/keyboard preferably) and just playing the instrument. So isn't a DAW over-featured? I basically just want to:
- hit record
- play some notes
- hit stop so it starts looping those measures
- change instrument
- hit record again etc. (or play without recording)
I'll add this info to the question
Comment: Again, on GNU/Linux ;) I would advice the fantastic sooperlooper which is much more suited for looping purposes and which can be completely controlled by MIDI, for instance a foot controller.


admin theme changes to default at editing page, Themekey module

Question: Using the ThemeKey module, I have changed the theme of user role (EDITOR) to Administration theme. So, when the user of this role logs in, he gets admin theme.
It works find but when he edit something the theme changes back to default. I want to have admin theme, even at editing pages for this user role. Please suggest.
Answer: I found the solution for this. I had to deselect the administration theme when editing or creating content, in admin/appearance.


C# - Specifying type parameters of super-class in sub-classes?

Question: I am trying to do the following in C#.
public class Parent<T> where T : Parent<???>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

How can I do it?
Comment: @geeko - No, it works fine. It'll compile and allow you to define `class Child : Parent` the way you've asked for.
Comment: Do you just need `class Parent where T : Parent`?
Comment: Isnt the Definition of Parent incomplete when you are trying to use it?
Comment: @Enigmativity this is recursive, it does not work.
Comment: @PrateekShrivastava How do you suggest to refactor the code? Any workarounds?
Comment: @Enigmativity fantastic. Is there also a way to force the subclass to pass itself as the type parameter?
Comment: @geeko - No, c# does not have this type constraint. I've mentioned it in my answer.
Comment: This is know as the [Curiously Recurring Template Pattern](https://ericlippert.com/2011/02/02/curiouser-and-curiouser/)
Answer: This works fine:
public class Parent<T> where T : Parent<T>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

Do be careful with this as c# does not enforce a true Parent/Child relationship. For example, given the above code, it is also legal for me to then do this:
public class Stranger : Parent<Child>
{
}

If you write unit tests then it's worth writing a type checker that looks for this mispattern.
Comment: Very interesting -- I've been using this pattern for a long time and I never thought that it could be misused like this. Thanks!


Is there a command in SQL to select 2 or more matches in a list?

Question: I'm looking a a few tables for job postings that I am wanting to filter. One of the tables is the "master" table, which is one-to-one has information including the job id, location, and salary. The other table is a "tags" table that is a one-to-many table that has several "tags" (such as education, experience, soft skills, and hard skills) associated with it. Note that there are millions of job id's and therefore even more tags.
"master" table
╔══════╦═══════════╦════════╦
║ id   ║  location ║salary  ║
╠══════╬═══════════╬════════╬
║  zy3 ║ CA        ║100,000 ║
║  w1e ║ TX        ║150,000 ║
║  sr2 ║ UT        ║200,000 ║
║  hi9 ║ NY        ║130,000 ║
╚══════╩═══════════╩════════╩

"tags" table
╔══════╦════════╦
║ id   ║  tag   ║
╠══════╬════════╬
║  zy3 ║ Python ║
║  zy3 ║ Hadoop ║
║  zy3 ║ master ║
║  w1e ║ Hadoop ║
║  w1e ║ BS     ║
║  w1e ║ junior ║
║  sr2 ║ Hadoop ║
║  sr2 ║ Tech   ║
║  sr2 ║ Stats  ║
║  hi9 ║ Java   ║
║  hi9 ║ Spark  ║
║  hi9 ║ GCP    ║
║  hi9 ║ MS     ║
╚══════╩════════╩

I am wanting to subset the "Master" table to include only the roles which, for example, includes two or more of the following tags:
Python, Hadoop, Java, Spark
So then the new master table would look like:
╔══════╦═══════════╦════════╦
║ id   ║  location ║salary  ║
╠══════╬═══════════╬════════╬
║  zy3 ║ CA        ║100,000 ║
║  hi9 ║ NY        ║130,000 ║
╚══════╩═══════════╩════════╩

I am considering introducing another table which would have a list of different tags I would accept.
To an extent, I've been able to hard-code a solution, but it's really computationally demanding, especially since I am working with millions of rows and sometimes there are many potential tags I would match with (in this case, it was just four tags of interest). Below is the code I have used.
select * from master t0
where (select count(id) from
((select id from master t1 where t1.id=t0.id and exists (select 1 from tags t2 where t1.id=t2.id and t2.tag='Python'))
union
(select id from master t1 where t1.id=t0.id and exists (select 1 from tags t2 where t1.id=t2.id and t2.tag='Hadoop'))
union
(select id from master t1 where t1.id=t0.id and exists (select 1 from tags t2 where t1.id=t2.id and t2.tag='Java'))
union
(select id from master t1 where t1.id=t0.id and exists (select 1 from tags t2 where t1.id=t2.id and t2.tag='Spark'))) tx)
>=2;

Comment: [How to create table in SO questions?](https://meta.stackoverflow.com/q/277716/62576)
Answer: You don't need a UNION, just use WHERE tag in (<list of specified tags>). Then join that with the master table.
SELECT m.*
FROM master AS m
JOIN (
    SELECT id
    FROM tags
    WHERE tag in ('python', 'hadoop', 'java', 'spark')
    GROUP BY id
    HAVING COUNT(*) >= 2
) AS t ON m.id = t.id

Comment: Excellent! Thank you.


Nodes appearing but when clicked "page not found"

Question: I recently migrated a site and some nodes don't appear in the content list but they do appear in Views I've created. When they're clicked however (example.com/node/123) it just returns a Page not found.
The node is in the database, both in the node table and the node_revisions as well as the relevent CCK tables.
What could possibly be causing this?
Comment: Do you use i18n? There is similar situation when someone create a node in one language, but the administration theme language is another.
Comment: If I do use it, what can be done to fix this?
Comment: I am having the same issue. The odd thing is that I didn't perform any action at all before the problem happened. Perhaps the hosting server did an update that messed up Drupal; I'm currently hosted by Dreamhost. Do you have the same hosting provider?
Comment: No, I host it myself.
Comment: Try re-saving the problem nodes.  I have the same issue after I migrated some content over (although we're on D7...).  Some pages would give 404 even though I see them in the system and they're published.
Comment: Having the same problem. Cannot figure what's wrong.
Answer: I had this problem, it only affected certain nodes. When investigated in db all values corresponded between node and node revisions tables so I initially assumed it wasn't related to values in those tables.
Checked url_alias table and all seemed well there too, site is multilingual so checked the variables table for discrepancies between multilingual paths auto values for custom content types and all was also well. Rebuilding the menu router didn't help either. I already tried resetting all node access permissions as suggested here. Honestly I was just about out of ideas, then thankfully I came across this post :D
The problem had come from where i had imported some node content from a custom module i wrote to ingest nodes from xml (which worked fine) but since the import was done the user account which had done the import had been removed. This meant all the multilingual imported nodes were still linked to that, now non-existent user account's uid.
A simple sql query in phpmyadmin set all my nodes to be owned by admin (uid:1)
UPDATE node set uid = 1;
UPDATE node_revisions set uid = 1;
This fixed my perplexing issue. I propose a patch so that if a user account is removed Drupal optionally checks all nodes belonging to that user and updates them to uid: 1 so nodes added by a deleted user account aren't suddenly inaccessible to the rest of the site including uid 1 (admin).
This was frustrating as a sensible sort would naturally assume that uid 1 will always have view/edit access to any node content on the site regardless of if it is, disabled, enabled or added by some mugwump.
I wish you good Drupaling!
Comment: I have had the same problem, deleting a user associated with a node made the node completely inaccessible. Thank you!
Answer: In most of the cases this is a conflict with permissions, so go to admin/content/node-settings/rebuild and rebuild the permissions.
This happens when you test some access modules and they're not correctly uninstalled, also take notice that views not always uses the same permissions this is why you can see your node in views but not in node/123.
Also if you don't have any access module installed and the rebuild doesn't work, have a look in your database and execute the following queries:
TRUNCATE TABLE node_access;
INSERT INTO node_access VALUES (0, 0, 'all', 1, 0, 0);

This should also fix it.
You can try to install Devel and use the Devel Node Access module shiped with it on the node to analyze the problem.
Comment: @Karl you tag it migration, did you move your site to another server ? Is the .htaccess still there ? Have you rebuild the menu ? Can you try to run update.php, see http://drupal.org/node/262892
Comment: I would love to be able to say that that fixed it, but it didn't. Useful to know though.
Comment: @Karl can you try with devel node access to see if something weird is occuring ? Also in admin (uid 1) there's no problem right ?
Comment: @Karl what's inside the node_access table ?
Comment: The node access module won't show anything in a Page not found page. It doesn't matter what user I'm using, it's all the same. I'm normally logged in as admin.
Comment: @Karl, yes you're right and usually permission problems generate an "Access denied", sorry for giving you false hopes...
Comment: Nope, that unfortunately didn't work either. Thanks so much though :)
Answer: It could be the database doesn't contain anymore the information about the account used to create the node.
Answer:
What you need to do is go to www.yourdomain.tld/admin/structure/pages ensure that these are all disabled and then the problem should be resolved unless you've deleted critical system files that Drupal requires in that case go and re-download the distribution of Drupal and then upload to your host and extract files then move them to overwrite the current ones that are there.


I can't add to cart without HTTPS enabled

Question: I have a Nginx server with Varnish that runs a Drupal Commerce website. The Add to Cart button doesn't work on a session without HTTPS.
I'd really appreciate any help.
Answer: The problem is that the Commerce Cart module requires a valid session or a logged-in user. The site security settings prevented sessions being sent out to HTTP requests.
While the OP solved this problem via PHP.ini, there are other valid solutions:

Require all users to use HTTPS
Avoid the cart is shown to anonymous users


Web API não retorna JSON

Question: fiz uma web api c# onde por padrão retorna xml, tentei de vários métodos da internet transformar esse retorno para json mas quando faço uma requisição continua vindo em xml, alguém poderia ajudar?
método que apresenta o resultado:
 // GET: api/OINV/5
    [ResponseType(typeof(OINV))]
    public IHttpActionResult GetOINV(int id)
    {
        OINV oINV = db.OINV.Find(id);
        if (oINV == null)
        {
            return NotFound();
        }

        return Ok(oINV);
    }

webapiconfig.cs
 public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Web API routes
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }

Comment: Posta o método que retorna o valor
Comment: Onde há algum retorno aí?
Comment: Olá Leandro, obrigado por responder, estarei editando e colocando o retorno
Comment: Apresente o método que está retornando o xml
Comment: @LeandroAngelo alterado leandro, de uma olhada.
Comment: Tentou invés de `text/html` por `application/json`?
Comment: já @Barbetta, ele até carrega em json mas em 1 segundo pisca e volta pra xml, bem estranho.
Comment: `[Produces("application/json")]` antes a declaração da sua classe de controller já não resolve?
Comment: @LeandroAngelo tentei aqui mas da erro de namespace could not be found
Comment: Ok... de que versão você está falando e de qual classe a sua controller está herdando
Comment: @LeandroAngelo web api entity framework, criei a controller com entity framework, o db também
Comment: controller com entity framework? desculpe nunca ouvi falar disso
Comment: Isso, clico com o botão direito na pasta controller > add>controller dai seleciono de qual tabela do banco criar. Ele cria o crud sozinho
Comment: ok.... mas a controller não herda do entity framework, certo? e quanto a versão, eu me refiro a do asp.net
Comment: Bom, estou longe do pc agr mas amanhã posso trazer essa informação
Comment: Bom dia, @LeandroAngelo versão 4.6.1
Answer: Na verdade não tem com o que se preocupar, a ASP.NET Web API 2 com o Framework 4.X vai serializar as respostas tanto como XML, quanto JSON de acordo com o que for definido na requisição. Não deveria se preocupar em como esse conteúdo está aparecendo no browser porque o Web API não é apresentar o conteúdo para a leitura de um usuário, mas sim servir de interface para a comunicação entre aplicações.
Documentação Microsoft
Ou seja por padrão ele já está atendendo os clients que pretentendem desserializar o conteúdo tanto em XML quanto JSON. Mas, se você quer restringir a sua aplicação para retornar apenas no formato JSON você pode fazer como sugerido pelo @Barbetta e remover o MediaType do xml da lista da formatadores.
Agora, se a questão é apenas para você visualizar os dados no browser para testes e "documentação" você pode implementar recursos que são especializados para isso, como o Swagger.
Mas o que eu realmente recomendaria, uma vez que está começando uma aplicação nova, seria já trabalhar com a versão do ASP.Net Core que só vai lhe trazer benefícios (tutorial).
Veja o exemplo abaixo:
Comment: Olá Leandro! Muito obrigado pela resposta e explicação, realmente não sabia que não teria problema no retorno. Agradeço também pelas dicas passadas!
Answer: Uma opção é remover o SupportedMediaType XML
public static void Register(HttpConfiguration config)
{
    //Outras Configurações
    config.Formatters.XmlFormatter.SupportedMediaTypes
        .Remove(config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"));
}

Comment: Não deu certo também amigo.
Answer: Tente adicionar as seguintes linhas ao método Register:
 config.Formatters.Clear();
 config.Formatters.Add(new JsonMediaTypeFormatter());

Vi um cara com o mesmo problema aqui no stackoverflow e ele fez isso: How do I get ASP.NET Web API to return JSON instead of XML using Chrome?
Ele apaga todos os formatadores da web api e em seguida adiciona o suporte para formatação em json
Comment: Olá Michael, infelizmente não deu certo.

Web API não retorna JSON


Combining semantic segmentation with image classification (FCN + CNN)

Question: I am currently working on a project that involves classifying each image as Good/Bad/Failed. We have a working convolutional neural network approach that works decent.
I also have trained a Fully convolutional neural network to do segmentation. THe labels for the segmentation are the actual objects in the image. So the FCN can tell me which pixels are what. Part of segmentation is identifying damaged areas which contribute to the good/bad/failed criteria.
My questions is what is best way to create a classifier that basically segments the image (tells me what and where everything is) but also put a single meta-class on top of that. Given that I have segmentation labels and full image classification images (not the same images though). Is there a way to train a single network to do both?
I do not know the relationship between damaged areas and Bad/Failed criteria besides that if an image contains damage it is not good. Beyond that I do not know. It may be as simple as damage > Threshold -> Failed but I doubt it is that easy.
I am using Caffe for everything
Answer: Yes, I suggest you stack the output of segmentation network with the input image, doing any resizing necessary, and then another CNN on top which performs the final classification. This way, the classification makes use of the segmentation performed by the FCN to help it predict.
Comment: It doesn't seem like you'd need a second CNN necessarily. For example, if the segmentation is done by a U-Net, there's an downsample and and upsample piece for segmentation, but one should be able to classify the entire image based on the results of in-between pooling layers (probably those just from the down-sampler actually).


Passar parâmetro para rota no javascript em laravel

Question: Boa tarde, tenho uma dúvida sobre parâmetros em laravel que não achei no site, tenho uma rota como esta:
Route::get('busca/{id}', 'MatriculasController@busca');

que passa um parâmetro para um método no controller do laravel.

Minha dúvida é no javascript como coloco o parâmetro na rota?
Comment: Alguém pode me ajudar nessa dúvida por favor?
Comment: Depende, pois terá que enviar uma requisição via ajax para ter o retorno do json.

Há três formas nativas de se trabalhar com o javascript no laravel "dependendo da versão", são eles  javascript puro "vanilla js", jquery e vue.js
Answer: Consegui resolver, segue o código caso alguém esteja com esse mesmo problema:
  $(document).ready(function () {
        fetch_customer_data();

     function fetch_customer_data(query = '')
     {
      $.ajax({
       url:"{{ route('live_search.action') }}",
       method:'GET',
       data:{query:query},
       dataType:'json',
       success:function(data)
       {
        $('tbody').html(data.table_data);
        $('#total_records').text(data.total_data);
       }
      });
     }

     $(document).on('keyup', '#search', function(){
      var query = $(this).val();
      fetch_customer_data(query);
     });
     });

No controller simplesmente chama assim:
$query = $request->get('query');

Resumindo no parâmetro data do ajax/jquery se define o parametro do método no controller. abç.


Proportions test in R

Question: I am interested in assessing if my proportion is significant.  I have no clue what to do and how to do it. I use R for programming.
I have list of genes (200) that are involved in a particular process and I call this as a ProcSet.   From an independent experiment I found that out of 10,000 genes, 1500 are significant and I call these 1500 genes as ResultSet.
The intersection of ResultSet and ProcSet are 80 genes.
That means 40% of ProcSet are significant.
How do I calculate that 40% is significant and more than I expect by chance given ResultSet and 10,000 genes I evaluated in the experiment?
What I have:
n = 200 (ProcSet)
p = 0.4

N = 1500  (ResultSet)

N1 =10,000

Pn = 0.15

What kind of test will help me know that 0.4 is significant given 0.15? Any suggestions will greatly help me.
Comment: Of the 160 in the Procset not in the Resultset, none of them were statistically significant?
Answer: If the experiments generating ProcSet and ResultSet are genuinely independent, you can use the  "test of equal or given proportions".  Try ?prop.test in R for details.

Proportions test in R


Como implementar funcionalidades customizadas em um model no .NET?

Question: Eu precisei implementar algumas funcionalidades no model users mas como vocês podem ver logo no início esta classe é gerada automaticamente pela Entity, então sempre que eu atualizar ou recriar o model as funcionalidades customizadas serão perdidas.
Exemplo de uma implementação customizada feito no model users:
public string full_name
{
    get
    {
        return this.first_name + ' ' + this.last_name;
    }
}

Há alguma forma de sobrescrever o model para manter estas funcionalidades customizadas sem que sejam sobrescrevidas sempre que eu atualizar / recriar o model?
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace E_Learning.Models
{
    using System;
    using System.Collections.Generic;
    using E_Learning.Helpers;

    public partial class users
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public users()
        {
            this.updated_at = DateTime.Now;
            this.created_at = DateTime.Now;

            this.signatures = new HashSet<signatures>();
            this.testimonials = new HashSet<testimonials>();
        }

        public int id { get; set; }
        public string identity_ { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string email { get; set; }
        public string telephone { get; set; }
        public string password { get; set; }
        public Nullable<System.DateTime> birthday { get; set; }
        public Nullable<int> sexuality { get; set; }
        public string remember_token { get; set; }
        public System.DateTime updated_at { get; set; }
        public System.DateTime created_at { get; set; }
        public Nullable<byte> status { get; set; }
        public string handle { get; set; }

        public string setHandle ()
        {
            return Slugify.Make(this.first_name + ' ' + this.last_name);
        }

        public string full_name
        {
            get
            {
                return this.first_name + ' ' + this.last_name;
            }
        }

        private Nullable<int> age
        {
            get
            {
                DateTime now = DateTime.Today;

                if (this.birthday.HasValue)
                {
                    DateTime birthday = DateTime.Parse(this.birthday.ToString());
                    int age = now.Year - birthday.Year;

                    if (now < birthday.AddYears(age))
                        age--;

                    return age;
                }

                return null;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<signatures> signatures { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<testimonials> testimonials { get; set; }
    }
}

Print:
Answer: Um dos princípios de programação orientada à objetos, SOLID, é que um objeto deve ser fechado para manutenção, mas aberto para extensão.
Para adicionar funcionalidades em um objeto fechado para manutenção, basta estende-lo. Veja:
public static class UserExtensions
{
    public static string FullName(this User user) =>
         $"{user.first_name} {user.last_name}";
}

E depois basta consumir:
var usuario = new User { first_name = "Thiago", last_name = "Lunardi" };
Console.WriteLine( usuario.FullName() ); // Thiago Lunardi

Veja funcionando aqui.
Veja mais neste artigo sobre SOLID - OCP - Open/Closed Principles.
Answer: Isto já foi mais ou menos respondido em Como editar uma Partial Class?
As classes parciais existem justamente para este tipo de problema. Você cria as customizações em um arquivo separado que será compilado junto.
É claro que você não pode mexer em nada do arquivo gerado. Isto sempre será perdido quando atualizar o model. Tem que achar uma organização e até criar padrões de projeto para desacoplar uma parte da outra se tiver algumas coisas mais complexas para fazer (na maioria dos casos é só ter métodos simples mesmo).
Então crie um outro arquivo com class partial Users e faça o que precisar ali. Note que a classe já foi gerada com esta intenção.
Você não pode sobrepor uma propriedade existente. O que pode fazer é criar uma outra que chame a original criada pelo EF. Só a propriedade do EF será persistida, a sua será auxiliar. Pode não ser o ideal, mas até onde eu sei não tem outra forma. No seu exemplo, funcionará perfeitamente, FullName é uma ótima propriedade complementar para FirstName e LastName.
Dependendo do que for fazer pode adicionar complementos para o modelo gerado em uma classe de metadados. Não parece ser o que deseja, mas é uma alternativa em alguns casos.
No futuro talvez terá o supersedes ou algo do tipo. Acredito que ele seja feito sob medida para este problema. Então você poderá dizer na classe parcial que uma propriedade deve substituir a outra gerada na outra parte da classe, mais ou menos como se fosse um método virtual (claro que o mecanismo é bem mais simples e resolvido todo em compilação).
Um exemplo é o uso de eventos: Partial para separação de eventos e métodos. Exemplo com WPF: Centralizar (usar apenas um) um try-catch para toda aplicação WPF. Exemplo com ASP.NET: Erro ao adicionar valor do While no List<>
Pode ajudar: Criar método parcial (partial) no C#
Outra solução é adotar o Model First que acaba com este problema e é o futuro do EF, o presente no EF Core.
Answer: Para fazer isso, você pode criar um projeto de ViewModels na sua aplicação, e adicionar um metadata que associa ao seu Model do Entity. Exemplo:
namespace E_Learning.ViewModels
{
    [MetadataType(typeof(E_Learning.Models.users))]
    public partial class users
    {

    }
}

Referência: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx
Comment: Bom uso de classes `partial`. Porém, o *pattern* `ViewModel` não tem esse fim. Nesta [resposta](http://pt.stackoverflow.com/a/126551/3825) falo sobre o uso ideal dele.


Sets of Polynomial roots

Question: For a real number $k,$ let $A$ be the set of roots of $$x^2 + (k - 1) x - 2(k + 1) = 0,$$and let $B$ be the set of roots of $$(k - 1) x^2 + kx + 1 = 0.$$(These roots may be complex.) Find the number of values of $k$ so that $|A \cup B| = 3.$
I don't know how to start this. Can someone help?
Comment: The most straightforward approach would be to write the roots of each equation in terms of $k$ using the quadratic formula. From there you can handle all the situations that may lead to the desired condition $|A \cup B| = 3$.
Comment: If that union has three elements, then $|A\cap B|=1$. Therefore the two polynomials must have non-constant gcd but not be multiple of each other. Just do long division (divide the non-monic by the monic for convenience) and impose that the remainder divides them, but is non-zero.
Comment: @logarithm What if one of them has repeated roots?
Answer: The roots of the two equations are
$$\frac{1}{2}\left(-(k-1) \pm \sqrt{(k-1)^2 + 8 (k+1)}\right) = \frac{1}{2}(-(k-1) \pm (k+3)) = \{2, -(k+1)\}$$
$$\frac{1}{2(k-1)} \left(-k \pm \sqrt{k^2 - 4(k-1)}\right) = \frac{1}{2(k-1)}(-k \pm (k-2)) = \{-\frac{1}{k-1}, -1\}$$
so you want
$$\{2, -(k+1), -\frac{1}{k-1}, -1\}$$
to have cardinality $3$.
Answer: Hint: Observe that by the fundamental theorem of algebra, every polynomial of degree 2 has 2 roots. Therefore, if we have 2 polynomials of degree 2, we need one of them to have a root with multiplicity and not the other one. The quadratic formula will be useful here.
Edit: Matthew pointed out that it could be possible that they both have two roots, but one in common. I was mistaken.
Comment: Why couldn't each polynomial have two roots but they have one root in common?
Comment: They can. You are absolutely correct.

Sets of Polynomial roots


GuitarPro: Change to Eb, but keep notation in E

Question: I just downloaded GuitarPro 7.5.  I used to use GuitarPro quite a bit, but it's been a while.
I like to tune down and play in Eb.  I want to change a song to sound 1/2 step lower, but want to keep the notation and tab in original finger and original key.
Ie->Smoke on the Water in standard E tuning.
I want the key signature to remain the same (Bb major, for Smoke on the Water), or say I load a song that is in C. Drop the pitch to B, but I want the tab/score to remain in C.  Hope that makes sense
-> change pitch to E flat, but keep notation/tab as was originally
I read "real" music much better than I read tab, so I don't want to hide the score.
Hope that makes sense.  I used to do this all the time, but am having worst time trying to remember how I did this.
-->> It's easy to do in GuitarPro 6, but not GuitarPro 7.  Not sure why.
EDIT:
Here are a couple of screencaps.  First is a Steve Morse tune in A minor, w/ key in notation being C.  When I change the tuning to Eb it also changes the score so that there are accidentals. I've tried transposing 1/2 step, but this doesn't work. There has to be a way to manipulate the score w/o altering the pitch/tone that is played.
First pic:

And here is 2nd pic:

I want the musical notation to look like this but played w/ Eb tuning. This is score w/o the tab:

Hope that makes sense.  I want to be able to drop tone/pitch 1/2 step, but be able to keep the notation in original key.  I can't seem to manipulate the score w/o changing the actual pitch.  Hope that makes sense.
ps.  If you're wondering why?  I'm using an Ibanez w/ locking tuners.  It's tuned to Eb
Comment: I've voted to close this as a duplicate of a more recent Q&A. The newer post is more general, has the identical answer, and the answer is accepted.
Comment: Can you load your Guitar Pro file in TuxGuitar and see if you can transpose the file there? PS I like 1/2 step down and you can switch to standard fast with CAPO 1. TuxGuitar also shows the scales if you like to find chords etc. I like that software. Do all the notes show up sharped when you change the key. Example are the lower and higher octaves also sharped/or flattened I noticed a lot of sheet music will not show these expect for the sharps next to the staff.
Answer: You simply have to change the tuning for each instrument track in the "Track Inspector".
Hope this helps.
Answer: File -> Sheetstyle.
Ensure "Capo and shifted tunings impact standard notation" is unchecked. Then verify the key signature is correct.
That should fix it.
Note: I've been searching for years also, finally found it!
Answer: Now I don't know GuitarPro at all, so my answer is totally based on the pictures you supplied.
Take the last picture where you have written how you want it to look without the tab.
On the right side there are some options.
There is this option:
"Transposition tonality"
C played as C
Wouldn't all you need to do be to change that to:
C played as B
?
Comment: I tried that.  No go.  It brings the tonality down 1/2 step, necessitating all the accidentals.  It's easy to do in GuitarPro6. I suppose I'll do that sort of editing in GuitarPro6.  I'm liking 6 better than 7 so far.  If I wanted to just have a printout, "read-only" transcript I could just write it as usual, and play as usual w/ the Eb tuning.  But, to get sound I have to choose either play in E standard tuning, or have the mess to read.


How to play multiple audio files one by one in html 5?

Question: I would like to play multiple audio files one by one. I have read the same question, but I have found the links to the original answer not working and question unanswered.
Original answer
<audio id="mySound" controls><source src="http://www.hvalur.org/audio/uploaded_files/ds_umkomuleysi_0_0.mp3" type="audio/mpeg"></audio>

<audio id="mySound1" ><source src="http://www.hvalur.org/audio/uploaded_files/ds_ljosmyndavel_0_0.mp3" type="audio/mpeg"></audio>

I want the first sound started by the user action (pressing the play button) and then the following sound(s) playing one by one.
The usage of this example will be practising of understanding of the telephone numbers read by native speaker.
Answer: I would do something like that:
var mySound = document.getElementById("mySound");
var mySound1 = document.getElementById("mySound1");
var mySound2 = document.getElementById("mySound2");
var mySound3 = document.getElementById("mySound3");

var mySoundArray = [mySound, mySound1, mySound2, mySound3];
var mySoundArrayPos = 0;

var myButton = document.getElementById("myButton");
myButton.addEventListener("click", function(event) {
    mySound.play();
    mySoundArrayPos = 0;
    startSoundTimer();
});

const startSoundTimer = () => {
    var mySoundTimer = setInterval(() => {
        if (mySoundArray[mySoundArrayPos].currentTime >= mySoundArray[mySoundArrayPos].duration) {
            if (mySoundArrayPos < mySoundArray.length -1) {
                mySoundArrayPos += 1;
                mySoundArray[mySoundArrayPos].play();
            } else {
                clearInterval(mySoundTimer);
            }
        }
    }, 10);
};

I don't know if the 10ms are a bit too fast, but I think, it's legit.
Comment: I edited my answer. But again, this is really freestyle without testing. Drop another line, if it doesn't work.
Comment: Ah! I thought, you wanted to play it repeatetly. I adjused my answer again. Now it should stop after all sounds in the array were played.
Comment: Thank you for your answer. There are several issues. 1) first version with mySound.play(); worked. but 2) I would need more than 2 files to play one by one 3) it playes only once, later only the first audio 4) in audio player the length of the bar corresponds only to length of the first audio. Thank you
Comment: The bar indicating the length can be hidden (not an important issue)...
Comment: Thank you, it works by pressing the button (I have hided the controls), but it does not stop and repeats all the time.
Comment: Yes, it stops now, great. When I try to press the button again, it playes only first sound of that array...
Comment: I added `mySoundArrayPos = 0;` into the button click event. Try again...
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232559/discussion-between-kurt-lagerbier-and-chejnik).
Answer: Javascript
=============== `playaudio(i) {
    var thisme = this;
    var audio = new Audio(thisme.model.audioFiles[i].audioUrl);
    audio.play();
      audio.addEventListener("ended", function () {
        i = i + 1;
        console.log(i);
        if (i < thisme.model.audioFiles.length) {
          audio.src = thisme.model.audioFiles[i].audioUrl;
          audio.play();
        }
    }, false);
    }
  }`

HTML
====`

        `


PowerShell - Convert Word doc to PDF WITHOUT Com Object

Question: I haven't been able to find a solution yet.
Only solutions using Powershell please. How can a Word *.docx file be converted to a PDF *.pdf file please without using a COM object. This is to run on a virtual server via a Windows Task Schedule with 'Run whether user is logged on or not' option ticked which is why the current COM object solution is not working (if I instead tick 'Run only when user is logged on' it works but it is not a suitable option).
I found a PSWriteWord powershell module to do the search and replace portion of the code (word template to new word file) but it does not appear to support save as PDF. There is also a PSWritePDF module but again it does not appear to have this functionality.
<code>$filePath   = "C:\Temp6"
$origFile   = "$filePath\Template.docx"
$newFile    = "$filePath\ReplacedText.docx"

# Get the original document
$WordDocument = Get-WordDocument -FilePath $origFile

# Search and replace some text
ForEach ($Paragraph in $WordDocument.Paragraphs) {
    $Paragraph.ReplaceText('[given_name]','Jane')
    $Paragraph.ReplaceText('[surname]','Doe')
}

# Save as new document
Save-WordDocument -WordDocument $WordDocument -FilePath $newFile

# Quick check to confirm Word application is not left open
Get-Process -name WinWord -ErrorAction SilentlyContinue

# How to convert/save as PDF WITHOUT COM Object?
</code>
Thank you.
Comment: @ShellD As long as Word does not load a user interface, but does the conversion silently when called from the command line, there's a good chance it works.
Comment: Damn, that's too bad. You could try OpenOffice - maybe there is something of use in there.
Comment: https://superuser.com/questions/393118/how-to-convert-word-doc-to-pdf-from-windows-command-line
Comment: if you are  going to use docx to pdf ... you need an app or util that can do the converting. the _usual_ way is to use the COM interface ... and an account that is designed for that.
Comment: @Lee_Daily - The script I currently have uses a COM object however it needs to run as an admin user on a virtual server in a windows task scheduler when a user is NOT logged on. It wont work if I tick this option and we don't want the user to have to be constantly logged on, hence my post. I have tried the hack suggested by creating a 'desktop' directory in the userprofile folder but that didn't work unfortunately.
Comment: @Tomalak - thanks, I'll have a look, hopefully it works in a windows task schedule with the user logged off (unlike com objects)
Comment: @Tomalak - unfortunately none of them worked whilst 'user logged off'. A few worked whilst logged on but I can already do that & don't want to. Others I couldn't get to work & some required a printer to be installed.
Answer: Thanks @Tomalak, OpenOffice/LibreOffice did the trick, this works in a Windows Task Schedule with "Run whether user is logged on or not" ticked.
Thankfully my word document didn't have much in the way of formatting, as I have read multiple posts saying OpenOffice/LibreOffice conversion isn't suitable as it strips out some formatting.
<code># Set an alias for LibreOffice (OpenOffice)
Set-Alias -Name soffice "C:\Program Files\LibreOffice\program\soffice.exe"

# Export docx to pdf using LibreOffice (OpenOffice)
# Wait for the process to complete by using & and | Out-<StreamType>
& soffice --headless --convert-to pdf:writer_pdf_Export --outdir "$($filePath)" "$($newFile)" | Out-Null

# Remove the temporary word document
Remove-Item -Path $($newFile)
</code>