Does 68–95–99.7 rule apply to skewed distributions as well and are they statistically correct?

Question: I am not much familiar with statistics, but for my current simulation, I am using it to analyze my results from Monte-Carlo simulation.
I understand the 68–95–99.7 rule. However, I want to confirm (and if any reference please) if the same rule applies to the Skewed curves as well. Please see the attached diagram. In figure 2 (For Access link), can I implement the 68–95–99.7 rule to find where does 95% data lies, and will it be statistically correct?
Answer: No, the rule is specific to normal distributions and need not apply to any non-normal distribution, skewed or otherwise. Consider for example the uniform distribution on $[0, 1]$. The SD is $\frac{1}{\sqrt{12}}$, or about .29. Only about 58% of the mass of this distribution is within 1 SD of the mean (0.5).
Comment: Yes, your interpretation is correct.  This is meant to be general guidance, not a precise quantitative prediction.  After all, even random samples from Normal distributions rarely exhibit exactly these ratios, either.  A more elaborate way to state this rule might be "When you are looking at data, in many cases about two-thirds of the values will be within one SD of their mean, about 19/20s will be within two SDs, and virtually all will be within three SDs." Of course there are exceptions: and they are readily identified because they obviously depart from this description!
Comment: Then how can I find 95% data categories in the skewed curve?
Comment: It can also be applied approximately to bell-shape/ mound-shaped symmetric distributions that are close to normal
Comment: @Kashan , are you familiar with quantiles or percentiles?  These could be used to identify the values that encapsulate 95% of the data.  It would require a little cleverness to get the mean in the middle of the spread --- instead of the median --- if that's your goal.
Comment: @Sal Mangiafico:  Yes I am a bit familiar with percentiles. I do not want mean in the middle of the spread. All I want is 95% interval for the Skewed distribution of attached figure. I will appreciate if you can elaborate a bit on this? Meanwhile, since the other two results I have are normal distribution, I have found 95% interval quite easily. I want to stick to it for the skewed graph as well. I will look into percentiles as you mentioned.
Comment: @Kashan , for a given data set, there are many ranges that encapsulate 95% of the data.  For example, there's the lowest 95% of data, the highest 95% of data, 95% of data with the median in the center,  95% of data with the mean in the center, and many others.
Comment: I am looking for highest 95% of data (I think it will make 5th percentile, right). I have reposted this question here: https://stats.stackexchange.com/questions/349811/in-a-left-skewed-distribution-how-can-the-range-where-95-data-lies
Comment: With substantial backing from teachers of statistics, I beg to differ with this opinion. Although the 68-95-99.7 rule of thumb is derived from the Normal distribution, and there are datasets and distributions that depart substantially from it, in practice it applies to a great deal of distributions and data, including strongly non-normal ones. It is definitely intended to apply beyond situations where the data are supposed to have a Normal distribution. For the distributions displayed in the question, this rule should offer reasonable guidance. Nobody would use it to obtain an exact solution.
Comment: @whuber I was under the impression that the 68-95-99.7 rule says that .68 of the mass of the distribution (exact to the nearest hundredth) lies within 1 SD of the mean, and so on. This clearly need not be true for non-normal distributions. If the rule says something more sophisticated, or more vague, I'm not sure what it is.
Comment: You appear to be committing a logical fallacy.  The 68-95-99.7 rule holds for far more than Normal distributions (albeit not all of them).  Observing that it does not hold for some distributions does not contradict this fact.  The primary assertion of your answer--namely, that this rule holds *only* for Normal distributions--is incorrect.
Comment: @whuber I said that the rule "need not apply to any non-normal distribution". No doubt you can construct non-normal distributions where it holds, but normality is what guarantees it. If there is a more general and useful condition than normality that suffices to make the rule work, then I don't know what it is.
Comment: The entire point to this rule of thumb is that it applies to many distributions, not just Normal ones.  Unless your data are extremely long tailed or extremely skewed, it tends to work surprisingly well.  The reason is that even with skewed distributions, the loss or gain of some probability between $-1$ and $0$ sds from the mean is nearly compensated by a counterbalancing gain or loss of probability between $0$ and $1$ sds.
Comment: @whuber It sounds like you're saying both that it applies in more general conditions than normality, and that its statement is less specific than "exactly .68 (to the nearest hundredth) of the mass is within 1 SD of the mean", etc. Again, in that case, I don't know what exactly the condition or statement would be.


Taylor's inequality question

Question:
Totally don't know how to go about doing this. Any help/insight would be appreciated.
Comment: It could be that I'm over thinking this...
Comment: Did you try, using the Taylor series for $f(x)=e^x$?
Comment: Expand using Taylor polynomials. Apply your version of Taylor's theorem. Conclude the answer. This is a question designed to test your comprehension, so it's good for you to spend the time to really understand it.
Comment: I'm still confused. I looked up the taylor expansion of $e^x$ but I don't get what to do with it given the interval. I haven't done any calculus in a long time and I'm very rusty.
Answer: They just want you to use Taylor-Lagrange inequality :
$$\forall x \in I, \left|f(x)-g(x)\right| \leq M \frac{\left|x\right|^{5}}{5!}$$
Where $M=e^{10}$ is I guess sufficient. (Notice how the RHS is a monomial with $a = \frac{e^{10}}{120} \in \mathbb{R}$ and $k=5\geq0$)

Taylor's inequality question


Dot products, cross product, and the (1,2) tensor

Question: How is the cross product a (1,2) tensor? If you do not mind, explain the question in terms of multilinear functions.  Wiki's answer confused me.
Answer: If $V$ is a vector space, a $(1,2)$ tensor is a trilinear map $T:V^*\times V \times V \to \Bbb R$. It may be naturally identified with a map $\widetilde{T}:V\times V\to V$ via the relation $$T(\alpha,v,w) = \alpha(\widetilde{T}(v,w)).$$So, $(1,2)$-tensors can be seen as $V$-valued $(0,2)$-tensors. This is precisely what the cross product is, for $V =\Bbb R^3$, a bilinear map $\times:\Bbb R^3\times \Bbb R^3\to \Bbb R^3$.
Comment: Thank you for your timely response.  Is tilde T bilinear in character?
Comment: Yes, that goes without saying.


How do I check if two arrays are equal in Zig?

Question: If I have two arrays of the same length -- for example, two [32]u8 --, how can I compare them?
Answer: The answer is: just loop through all their values and check if they are equal.
There is a method that does specifically this in the standard library: std.mem.eql.
var array1: [32]u8 = undefined;
var array2: [32]u8 = undefined;
if (std.mem.eql(u8, array1, array2)) {
  std.debug.print("they are equal!\n", .{});
}

There are also other functions in that same module that may be useful, such as std.mem.startsWith.
Comment: worth pointing out though that looping and checking for equality and using `std.mem.eql` are _not_ equivalent. This works for primitive types, but as soon as you have e.g. structs with padding or anything else which has a notion of equality other than "identical bit patterns" this won't work anymore.


What is the intuitive explanation and derivation of Mallows's $C_p$ statistic (model selection)?

Question: $$C_p = \frac{SS_E(p)}{\hat{\sigma}^2} - 2 + 2p $$
Here is the formula of Mallows's $C_p$ statistic, wher $SSe_p$ is residuals sum of square, $\hat\sigma^2$ is estimated variance of residuals, $n$ - number of observations and $p$ - number of predictors in model.
Questions: How can we intuitively understand and explain this statistic? Why does (from an intuitive point of view) it take such a form?
And what is the interpretation of the statistic? What does the output value mean? How can we interpret the result?
Comment: My understanding is that Cp's primary use is as a criterion for variable selection. SAS is one of the few software packages that recommends this statistic. Otherwise, I don't anyone who relies on it. Your question is clear but my question is, why waste time trying to understand it? Use another tool or approach for variable selection that is much clearer and more readily explained, e.g., the Lasso.
Comment: @DJohnson maybe you are right, but additional knowledge doesn't hurt:)
But thank you for your comment!
Answer: Suppose we are working with a linear model $Y = X\beta + \varepsilon$ for $\varepsilon \sim \mathcal N(X\beta, \sigma^2 I)$. Then (up to a constant) the log likelihood $l$ of $\beta$ is given by
$$
-2 \times l(\beta, \sigma^2 | Y) = \frac{1}{\sigma^2}|| Y - X\beta||^2.
$$
Recall the definition of the AIC:
$$
AIC(\hat \beta, \hat \sigma^2) = -2 l(\hat \beta, \hat \sigma^2 | y) + 2 p
$$
where $p$ is the dimension of our model.
We have that
$$
C_p = \frac{1}{\hat \sigma^2} ||Y - X\hat \beta||^2 + 2p - 2
$$
so we can see that the AIC and $C_p$ differ only by a constant, therefore their respective argminima are the same. As @DJohnson mentioned in the comments, $C_p$ is only ever really used for variable selection, i.e. we care about its argmin rather than its actual values. This means that (for this particular model, at least) we can interpret argminima of $C_p$ in terms of the argminima of the AIC and there's a whole body of work on that. See here or here, for instance.
In effect, I'm completely echoing DJohnson's comment that this isn't a particularly useful statistic and there's no point in wasting time trying to understand it by itself. I advocate for framing it in terms of AIC, which is definitely worth understanding (even if you don't like it or use it), and then putting your mental effort there (and on related *IC things like BIC, AICc, and etc).


What's the significance of the Church-Turing Thesis?

Question: My understanding is that the thesis is essentially a definition of the term "computable" to mean something that is computable on a Turing Machine.
Is this really all there is to it? If so, what makes this definition so important? What makes this definition so significant as to warrant having it's own name?
In most other branches of mathematics, a definition is an important part of the scaffolding, but not a result onto itself. In the case of the Church Turing Thesis, it seems like there must be more, but all I can see is the definition.
So, what is the significance of the Church-Turing Thesis?
Comment: Not exactly ... The rigorous definition of *Turing machine* gives as the precise mathematical concept of "Turing computable". The same for the many other equivalent definitions : recursive function, etc. It is quite obvious that any Turing computable fucntion or relation is intuitively effectively (i.e.mechanically) computableThe Church-Turing thesis is the "unprovable" assertion that all functions intuitively computable are Turing computable, i.e. that the mathematically rigorous def of Tuting computability (and its equivalents) exhasut the intuitive content of "mechanically" computable.
Comment: As far as I can see, the thesis is not importand because of its definition, but because it provides a bridge between the real world, where functions are effectively computable or not, and the theoretical world of mathematics, in which we have a strict definition of what "computable" means.
Answer: The answer from user73985 explains the content of the Church-Turing thesis, but I'd like to add a few words about its value; why do we want it.
The first benefit that we get from this thesis is that it lets us connect formal mathematical theorems to real-world issues of computability. For example, the theorem that the word problem for groups is Turing-undecidable has the real-world interpretation that no algorithm can solve all instance of the word problem.
The second benefit is in mathematics itself, specifically in computability theory.  Published proofs that something is Turing-computable almost never proceed by exhibiting a Turing-machine program, or indeed a program in any actual computing language.  Sometimes, if the matter is simple enough, they provide some sort of pseudo-code.  Most often, though, they merely give an informal description of an algorithm.  It is left to the reader to see that this actually does give an algorithm (in the intuitive sense) and therefore, by the Church-Turing thesis, could be simulated by a Turing machine. The usual situation is that, although experts in Turing-machine programming would (if they existed) be able to routinely convert the intuitive algorithm into a Turing machine program, the program would be too large and complicated to be worth writing down.
Comment: Isn't this a bit of a tautology? you can't *prove* the thesis, since the informal notion of computability isn't well defined without the thesis. Then, you use the thesis to "bridge" between the formal and the informal, even though you don't actually know the bridge exists!
Comment: @nbubis I"ll go out on a limb and say that I do know the bridge exists, i.e., I do know that the Church-Turing thesis is true.  Of course, as you said, I can't prove that mathematically, since it involves the non-mathematical notion of intuitive computability.  But I know lots of things that I can't prove mathematically, for example, the fact that I'm typing this comment.  There is, of course, an issue about the use of such non-mathematical knowledge in a mathematical proof; hence the last sentence in my answer: You could give a mathematical proof instead, but it would be messy.
Answer: The idea is that we have an informal notion of "computable" - that is, "something that can be computed". (This is explicitly not a precise definition). We also have a formal definition of "computable", that is, "computable by a Turing machine". The Church-Turing thesis is that these two notions coincide, that is, anything that "should" be computable is in fact computable by a Turing machine. (It's pretty clear that anything that is computable by a Turing machine is computable in the more informal sense).
Put another way, the Church-Turing thesis says that "computable by a Turing machine" is a correct definition of "computable".
Comment: One might add that another reason why we can believe that "computable by a Turing machine" is the correct definition of "computable", because "GOTO" and "WHILE" computabilities are equivalent to Turing-computability. So three different approaches lead to the same kind of computability, which is why we can believe that they describe the "correct" definition of computability.


Colocar marcadores do tipo disc ou circle ou square não funciona

Question: Fiz isso

             @mainItem.ShoppingCartMessage

Acontece que o texto que está em @mainItem.ShoppingCartMessage não vem com aquela "bolinha" ou "quadradinho" na frente. O que está acontecendo?
Está assim

Observe pela imagem, que mesmo sem texto o square ou disc fica aparecendo e antes da linha vertical e meu código agora, para essa imagem está assim, tentando não imprimir o square num texto vazio

        @if (!string.IsNullOrEmpty(mainItem.ShoppingCartMessage))
        {

                @mainItem.ShoppingCartMessage

         }

Só não entendo porque que o saquare está fora da table, conforme imagem, aplicando o código acima. Com o código acima eliminei o square quando o mainItem for null ou vazio, agora só preciso entender o porque que o square ou disc está fora da table
Comment: porque não se pode colocar uma lista dentro de uma linha (tr), coloque dentro da td que vai funcionar
Comment: @RicardoPontual, então fiz conforme o sua sugestão e não funcionou também. O que acho estranho que a  não reconhece o type. Ele aceita typeof, mas não type. `

                                                    @mainItem.ShoppingCartMessage

   `
Comment: Fazendo assim: `` eu consigo, porém há uma linha vertical(limitando a tr) e o texto fica dentro dessa linha, mas o square fica fora.
Comment: Resolvi o problema do vazio. A questão toda é que o disc fica fora da linha, conforme imagem e o texto dentro. Para colocar o disc dentro, eu tenho que setar a Margin, mas não gostaria disso. O que tenho que fazer?
Comment: tranquilo, mas novamente, a tr não foi feita pra fazer layout com uma lista, aninhado logo abaixo da tr deve ser um td ou th, se precisa de uma linha para um layout deveria usar um elemento como div com o display como inline ou inline-block
Answer: Veja o código que colocou no comentário:

 @mainItem.ShoppingCartMessage

 @mainItem.ShoppingCartMessage

Aparece perfeitamente, usando a lista no lugar certo (dentro da td) aparece certo
Comment: Não consegui colocando na tag ``. Só funciona na  e com `style="list-style: square"`. Com apenas type="square" ou "disc", não funciona
Comment: Com esse código: `

           @if (!string.IsNullOrEmpty(mainItem.ShoppingCartMessage))
           {

                   @mainItem.ShoppingCartMessage

            }

` e o square continua fora dos limites da table
Comment: Se eu coloco a margin-left da lista para 15 ou mais px, aí o disc ou square fica ok, mas não gostaria de fixar manualmente com valor em pixels, devido a diversos browsers usados pelos clientes, poderia dar "tilt". Alguém tem alguma sugestão?


A bicentric quadrilateral $ABCD$

Question: A bicentric quadrilateral $ABCD$ is inscribed in the circle $k_1(O_1;R)$ and circumscribes the circle $k_2(O_2;r)$. Let $K$ be the intersection point of the diagonals $AC$ and $BD$. Prove that $V, O_1$ and $O_2$ are collinear points.

I chose a point on the circumcircle, constructed from it a tangent to the incircle, found the other intersection point of the tangent with circumcircle, and repeated the process until the quadrilateral closures. The distance between the centers of the in- and circumcircle is a function of their radii. Fuss' theorem gives a relation between the inradius $r$, the circumradius $R$ and the distance $x$ between the incenter $O_2$ and the circumcenter $O_1$, for any bicentric quadrilateral.
Answer: Let $\alpha,\beta,\gamma,\delta$ be the angles at vertices $A,B,C,D$, respectively. Without loss of generality we can assume that the angles $\alpha,\beta$ are acute. In this case both circumcenter $O$ and incenter $I$ lie inside $\triangle ABK$, where $K$ is the intersection point of the diagonals.
We have:
$$\angle BID=2\pi-\frac12\beta-\gamma-\frac12\delta=\frac\pi2+\alpha,
\quad \angle BOD=2\alpha.$$
Let $\rho(P,P_1P_2)$ denote the distance of a point $P$ to a line drawn through the points $P_1$ and $P_2$. Then
$$
\frac{\rho(O,BD)}{\rho(I,BD)}=\frac{A_{BOD}}{A_{BID}}
=\frac{OB\cdot OD\cdot\sin(\angle BOD)}{IB\cdot ID\cdot\sin(\angle BID)}
=\frac{R^2\sin2\alpha}{\frac{r}{\sin\frac\beta2}\frac{r}{\sin\frac\delta2}\sin\left(\frac\pi2+\alpha\right)}=\frac{R^2}{r^2}\sin\alpha\sin\beta.\tag1
$$
The same result will be obtained for the ratio of the distances to the diagonal $AC$. Thus:
$$
\frac{\rho(O,BD)}{\rho(I,BD)}=\frac{\rho(O,AC)}{\rho(I,AC)}\iff
\frac{\rho(O,AC)}{\rho(O,BD)}=\frac{\rho(I,AC)}{\rho(I,BD)},
$$
which means that the points $K,I,O$ are collinear. As a side result we obtain:
$$\begin{align}
\frac{KO}{KI}&=\frac{R^2}{r^2}\sin\alpha\sin\beta\\
&=\frac{(ab+cd)(ac+bd)(ad+bc)}{16\,abcd}\frac{(a+c)(b+d)}{abcd}\frac{2\sqrt{abcd}}{ad+bc}\frac{2\sqrt{abcd}}{ab+cd}\\
&=\frac{(ac+bd)(a+c)(b+d)}{4abcd},\tag2
\end{align}
$$
where formulas from wikipedia page were used to express the radii and angles via the sides of the quadrilateral.
Comment: Thank you for the response! I saw this solution in a Russian journal. I haven't studied trigonometry. I am not sure I understand what we are trying to prove. What is the idea?
Comment: The idea behind the proof is the following. You probably know that if the cartesian coordinates of two points satisfy the relation $$\frac{y_1}{x_1}=\frac{y_2}{x_2}$$ the points $(x_1,y_1)$ and $(x_2,y_2)$ lie on the line which goes through the origin of the coordinates. The same is valid for skew coordinate systems. In this case the axes are the diagonals $AC$ and $BD$ and their intersection point $K$ is the origin of the coordinates. The essential point in the expression (1) is the symmetry between  the angles $\alpha$ and $\beta$.

A bicentric quadrilateral $ABCD$


Closed subset of quasi-separated space is quasi-separated?

Question: Is every closed subset of quasi-separated space quasi-separated?
A topological space is called quasi-separated if the intersection of two quasi-compact opens is quasi-compact. Here quasi-compact means every open cover has a finite subcover.
Answer: Let $X$ be a space with the following property: each point has a n.h. basis consisting of quasi-compact opens.
Then (since any closed subset of a quasi-compact set is quasi-compact), we deduce that any closed subset $Z$ of $X$ inherits this property.
Furthermore, one easily sees that any quasi-compact open subset $V$ of $Z$ may be written in the form $V = U \cap Z,$ where $U$ is a quasi-compact open subset of $X$.   (Without making our initial assumption on $X$, this property need not hold; e.g. consider a compact subset $Z$ of $X = \mathbb R^n$.)
Suppose now that $X$ is also quasi-separated, and let $Z$ be a closed subset of $X$.  If $V_1$ and $V_2$ are two quasi-compact open subsets of $Z$, we may write $V_i = U_i \cap Z$, where $U_i$ is quasi-compact open in $X$.  Then $U_1 \cap U_2$ is quasi-compact by assumption, and so $V_1 \cap V_2 = U_1 \cap U_2 \cap Z$ is also quasi-compact; hence $Z$ is quasi-separated.
(I'm not sure what's true if we don't make the additional assumption on $X$; have you looked in the topology section of the Stacks Project?)


.NET Core + Visual Studio Code - Organização da estrutura

Question: Tenho aqui comigo algumas dúvidas sobre o desenvolvimento de aplicações em .NET Core usando o Visual Studio Code:

Como é criado um projeto base, como por exemplo uma "blank solution", igual no Visual Studio?
Como é feito a organização de um projeto .NET Core que segue alguns ou todos os conceitos de DDD. Como se faz essa divisão, por DLL's ?
Voltando a primeira questão, é necessário criar uma solução em branco para que possamos organizar melhor o projeto ?
Answer: Acredito que consigo responder todas as suas perguntas com um exemplo, mas posso te adiantar que voce vai passar a utilizar a linha de comando, ao invés de realizar todas as operações como é no Visual Studio.
Veja alguns comandos:
dotnet new sln # Cria a solution do seu projeto
dotnet new [template_name] -o [output path] # Cria o seu projeto
dotnet sln [sln_name] add [csproj_name] # Adiciona o seu projeto a solution criada.

Apenas para exemplificar os comandos acima:
dotnet new sln
mkdir src
dotnet new classlib -o src\ProjetoExemplo.Core\
dotnet sln ProjetoExemplo.sln add src\ProjetoExemplo.Core\ProjetoExemplo.Core.csproj

Com isso voce consegue compilar os seus projetos separadamente e voce consegue abrir a sua pasta principal do projeto no Visual Studio Code.
Voce pode obter maiores detalhes sobre organização do projeto .net core com uma série de posts do Scott Allen
Comment: Fala Nicolas, muito obrigado por responder. Vou testar agora mesmo!
Comment: Nicolas, testei aqui e acho que consegui executar tudo certinho. Uma outra coisa. é normal a solução ficar por ultimo no projeto ?
segue o print: https://imgur.com/7lAFUsn
Comment: Hiroyuki, isso é normal, porque o VS code ordena pelas pastas e depois os arquivos, você pode alterar esta ordenação.
Dentro do VS Code, nas suas configurações, procure por "explorer.sortOrder", você consegue deixar a propriedade Files First habilitada, com isso a sua *.sln ficará antes das pastas. Veja [ref](https://stackoverflow.com/questions/40920775/how-can-i-change-the-file-sorting-of-vs-code)


Finding the conditional probability.

Question: Question:
There are $50$ students in a computer room. $36$ students work on tablets, and $20$ students work on laptops. There are $12$ students who work on none. A teacher chooses a student randomly. What is the probability of this student not working on laptop, given that she has worked on a tablet?
Solution:
n(only laptop) = $2$
n(only tablet) = $18$
n(both laptop and tablet) = $18$
n(neither) = $12$
P(not laptop given tablet has been used) = $\frac{P(\text{not laptop and tablet})}{P(\text{tablet})}$
P(not laptop) = $\frac{30}{50}$
P(tablet) = $\frac{36}{50}$
Therefore, P(not laptop given tablet has been used) should be $\frac{3}{5}$, but the answer in my textbook shows that it is $\frac{1}{2}$. How to do to get this answer?
Comment: P(tablet-and-not-laptop)=P(only-tablet)=18/50
Comment: Did you divide by $P(\text{tablet})$?
Answer: The counting is correct. However, you need to write what these probabilities are.
You have $\mathbb{P}[\text{not laptop} \wedge \text{tablet}] = \mathbb{P}[\text{only tablet}] = n(\text{only tablet}) / 50 = 18/50$.
Next, you need to find $\mathbb{P}[\text{tablet}]$ which is simply $n(\text{tablet})/50 = 36/50$.
Dividing both probabilities gives you $\mathbb{P}[\text{not laptop} \vert \text{tablet}] = 1/2$
Comment: You mean that it is $\frac{\frac{18}{50}}{\frac{36}{50}}$, which simplifies to $1/2$.
Comment: Thanks for your answer.

Finding the conditional probability.


Custom framework using SpriteKit - asset files not loaded

Question: I created a cocoa touch framework project, which uses SpriteKit and includes image assets. (It's a framework because the idea is to create a mini game that I can add to different apps).
I am testing it with a sample project that uses this framework.
My problem is at runtime - when I create a sprite with an image I get an error:
SKTexture: Error loading image resource XXXXX
I am using SKSpriteNode(imageNamed:"XXXXXX").
the images are in the bundle of the framework in a folder. I tried also putting them in an asset catalog. nothing works.
Any ideas what the problem is?
Comment: I tried creating a UIImage with and image from the framework and it worked because I used:
UIImage(named:in:compatibleWith:) and gave it Bundle(for: type(of: self)).
I Wish there was some way to pass the framework bundle when creating SKSprite or SKTexture
Answer: Well since you can get the desired asset from the framework as a UIImage, couldn't you just
<code>let image = UIImage(named: "image", in: type(of: self), compatibleWith: nil)
let texture = SKTexture(image: image)
let sprite = SKSpriteNode(texture: texture)
</code>
Comment: Yes, I actually did that in order for things to work, but I think it's performance consuming and very bad practice. isn't it?


Ordering By a Decimal / String in MySQL

Question: I'm trying to make a string ordering in CakePHP but I've some mistakes with this. I've strings like C.110, C.100.1, ..., C.100.8.
When I try to order using:
ORDER BY CAST(plane_accounts.code AS DECIMAL(10,5))

MySQL returns me some like:
C.110
C.110.8
C.110.1
C.100.2

Someone know how to resolve this? Thank's for help.
Comment: This looks like a SQL problem, could you post the full query?
Comment: Is there any reason you can't just use ORDER BY (plane_accounts.code)?  Also, this appears to have nothing to do with CakePHP - just a MySQL question.  If you get the MySQL working, THEN ask about CakePHP if you  don't understand how to implement.
Answer: There is no need to cast it, a plain ASC sort on the code field should just work:
$this->PlaneAccount->find('all', array(
    'order' => array(
        'PlaneAccount.code' => 'ASC'
    )
));

Or in plain MySQL syntax:
SELECT `code` FROM `plane_accounts` ORDER BY `code` ASC;

Comment: Hey everybody, hold on. I know how to do this using CakePHP and obviously I tried to do this using just `ORDER BY plane_accounts.code`.

But... when I do this the return was:
`5, A, B, B.100, C.110, C.110.1, C.110.10, C.110.11, C.110.2, C.110.3`
Can you see now the problem? I try to use CAST to correctly order this strings.
Comment: That still doesn't change anything. The data you mentioned above will still be put in that order if you just do a plain ASC order on the code field. Otherwise, you should be more clear on what order you get now and what you would expect.
Comment: Flávio Ricardo - what's the problem with that order?  It looks correct.  Per Oldskool, post what you're getting AND what you're hoping for - that will help a LOT in getting you the answer you're hoping for.

Ordering By a Decimal / String in MySQL


Influence of radius in neighborhood function of SOM

Question: Reference document: here
In section 3.3 of the referenced document, discussion regarding neighborhood function in SOM is provided. What I am not being able to understand is what influence radius has on the neighborhood function since I do not see it being used in the actual function formula. In the first screenshot below, different neighborhood functions are shown, and in the second screenshot, the images of different neighborhood functions with different radius values are shown. Could anyone please help me understand how they are related?

Looking at how the step/bubble function is formulated and drawn, my guess is that $\sigma$(k) is the radius. Is my guess correct?
Answer: Yes, $(k)$ is the radius at step $k$.
I'd say this is the reference that will give the most assistance. The article above provides a good summary of Kohonen's work (and extends it to a new dataset); more details are here.
Kohonen, T. MATLAB Implementations and Applications of the Self-Organizing Map. Unigrafia Oy, Helsinki, Finland, 2014.
See p. 48 for a different representation of the four neighbourhood functions:

case 'bubble', H = (Ud<=radius(t));
case 'gaussian', H = exp(-Ud/(2*radius(t)));
case 'cutgauss', H = exp(-Ud/(2radius(t))) . (Ud<=radius(t));
case 'ep', H = (1-Ud/radius(t)) .* (Ud<=radius(t));
Comment: Thank you @Tom Anderson!


UIStackView hiding views and unsatisfiable layout on rotation

Question: I have a view controller in which I would like to hide certain subviews, labels, etc., depending on what the trait collection is. For example, I have labels on the side I want to hide when compact horizontally, and labels on the top and bottom I want to hide when compact vertically.
Because I want to hide whole sections of the interface, it sounds like a UIStackView would make this easier. Likewise, I'm trying to do as much as I can within Interface Builder / Xcode (9.1 9B55) rather than in code, to try and keep it simple.
The main element of the design is a chess board, which:

Is always aspect ratio 1:1
Is as large as possible within the view

Then labels and other items around it I want to move and hide based on the current trait collection.
I have begun by building a horizontal stack view, alignment, and distribution set to "Fill." Within it are two items, the boardView (purple) and labelView (yellow).
The labelView has a couple of labels in it, with constraints set within the view itself for the layout of these labels.
The boardView has a constraint of aspect ratio 1:1 (@1000):

I set the following constraints for the Stack View, pinning it to the superview (except for the bottom):

Safe Area.trailing = Stack View.trailing(@1000)
Safe Area.leading = Stack View.leading (@1000)
Safe Area.top = Stack View.top(@1000)
Safe Area.bottom >= Stack View.bottom(@1000)

I set these constraints to insure the boardView never overflows the superview:

boardView.width <= Safe Area.width (@1000)
boardView.height <= Safe Area.height (@1000)

And then I set these constraints at a lower priority so that, if possible, the width or height will expand to fill the superview (but not overflow, since these are a lower priority than above):

boardView.width = Safe Area.width (@250)
boardView.height = Safe Area.height (@250)

This all seems to work great. No errors within Xcode and the app behaves as I would expect, in portrait and landscape (these screenshots from iPhone 8 simulator):

The problem comes when I try to hide the right view. I'm trying to do this by hiding the nameView when we are in regular mode vertically. I select nameView, click the + next to the Installed checkbox, select hR:

And then uncheck the Installed box for hR:

This looks great within Xcode. No errors and IB seems to be showing all the views as I would expect in both landscape and portrait (where the name labels are hidden):

So far, so good. In fact, when I run it, it looks just as we would expect, initially. If we start the simulator in the landscape, it looks good:

If we start the simulator in portrait, it looks good:

So what's the problem? Well, as soon as we rotate from portrait to landscape, the layout is completely wrong:

At the same time, we get in console a LayoutConstraints error:
<code>2017-12-03 19:25:55.710381-0600 TestLayoutSIngleView[31439:3231004] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fixes it.
(
    "<NSLayoutConstraint:0x60400009b8a0 UIView:0x7fe920603e90.width == UIView:0x7fe920603e90.height   (active)>",
    "<NSLayoutConstraint:0x60000009ced0 UIStackView:0x7fe92050bd70.leading == UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x60000009d100 UIStackView:0x7fe92050bd70.top == UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide'.top   (active)>",
    "<NSLayoutConstraint:0x60000009d150 UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide'.trailing == UIStackView:0x7fe92050bd70.trailing   (active)>",
    "<NSLayoutConstraint:0x60000009d1a0 UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide'.bottom >= UIStackView:0x7fe92050bd70.bottom   (active)>",
    "<NSLayoutConstraint:0x60000009e5a0 'UISV-canvas-connection' UIStackView:0x7fe92050bd70.leading == UIView:0x7fe920603e90.leading   (active)>",
    "<NSLayoutConstraint:0x60000009ce30 'UISV-canvas-connection' UIStackView:0x7fe92050bd70.top == UIView:0x7fe920603e90.top   (active)>",
    "<NSLayoutConstraint:0x60000009e5f0 'UISV-canvas-connection' V:[UIView:0x7fe920603e90]-(0)-|   (active, names: '|':UIStackView:0x7fe92050bd70 )>",
    "<NSLayoutConstraint:0x60000009cde0 'UISV-canvas-connection' H:[UIView:0x7fe920603e90]-(0)-|   (active, names: '|':UIStackView:0x7fe92050bd70 )>",
    "<NSLayoutConstraint:0x60000009e7d0 'UIView-Encapsulated-Layout-Height' UIView:0x7fe92050b8f0.height == 375   (active)>",
    "<NSLayoutConstraint:0x60000009e780 'UIView-Encapsulated-Layout-Width' UIView:0x7fe92050b8f0.width == 667   (active)>",
    "<NSLayoutConstraint:0x60000009d060 'UIViewSafeAreaLayoutGuide-bottom' V:[UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide']-(0)-|   (active, names: '|':UIView:0x7fe92050b8f0 )>",
    "<NSLayoutConstraint:0x60000009d010 'UIViewSafeAreaLayoutGuide-left' H:|-(0)-[UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide'](LTR)   (active, names: '|':UIView:0x7fe92050b8f0 )>",
    "<NSLayoutConstraint:0x60000009d0b0 'UIViewSafeAreaLayoutGuide-right' H:[UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide']-(0)-|(LTR)   (active, names: '|':UIView:0x7fe92050b8f0 )>",
    "<NSLayoutConstraint:0x60000009cfc0 'UIViewSafeAreaLayoutGuide-top' V:|-(0)-[UILayoutGuide:0x6000001b5d20'UIViewSafeAreaLayoutGuide']   (active, names: '|':UIView:0x7fe92050b8f0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60400009b8a0 UIView:0x7fe920603e90.width == UIView:0x7fe920603e90.height   (active)>
</code>
I like the idea of using UIStackView to make Auto Layout and hiding views easier. But if what I see in Xcode doesn't work when compiled and run, it seems like this is going to be tricky.
What am I doing wrong (or am I running into a Xcode bug)?
I created a GitHub project which demonstrates the above:
https://github.com/johnstewart/TestLayoutSIngleView
Edit.... It occurs to me as I've finished writing all of the above, that if we were to hide this view in landscape mode, the layout wouldn't be satisfiable... but I'm not hiding this view in landscape, only portrait. For some reason, iOS is making the change to the layout BEFORE the rotation.
If I set the priority of this from 1000 to 750:

Safe Area.trailing = Stack View.trailing(@1000)

... I don't get any auto layout errors on the console. However, the landscape view once rotated doesn't at all have things in the right place.
It's as if the stack view immediately is shrunk on beginning the rotation from portrait to landscape, and leaving the stack view in that shrunken state upon completion of the rotation, even though there is now plenty of room for it:

I sincerely hope I'm missing something obvious here... else I don't see how un-installing views based on trait collections with UIStackView is at all feasible; this seems like a straightforward example (and it is; I've got a lot more stuff to add!)
Edit:
The WWDC video where I saw this technique is from WWDC2017, Auto Layout Techniques in Interface Builder (https://developer.apple.com/videos/play/wwdc2017/412/). The demo for this begins at 29:00.
I was incorrect, however, that it was the "Installed" property that was being used for this. As the accepted answer indicates, "Hidden" was the way to do it.
Comment: Update 20171205 - Updated to Xcode 9.2 (9C40b) and it's the same behaviour.
Answer: I think you can achieve what you want without 'installed' property:
just set 'hidden' for portrait mode:
Comment: And I'll say this technique, which had me excited when I initially saw this demo, seems to be limited in usefulness... when I use it to hide the items in the stack view, including all subviews, etc., I get all sorts of missing constraints errors for these *hidden* items. UIStackView doesn't seem to be handling removing these from the auto layout process as implied in the video. Maybe it'd work for a super-simple design, but I fail to see how this will work for any actual app.
Comment: I've been trying to play with this a bit, and it's not truly solving my problem. When you make the nameView hidden on hR, you get errors on constraints for the items within nameView. You can make them hidden as well, but this doesn't seem to scale if the layout is more complex than this (very minimalized) example.
Comment: Problem with `installed` property is that after 'uninstalling' controller can't get `leftView`. It was removed from superview and controller couldn't load it from xib because it happens only on the start of vc lifecycle.
Solution is use outlets to `leftView` and `stackView` and call `[self.stackView removeArrangedSubview:self.leftView];` and `[self.stackView addArrangedSubview:self.leftView];` in `viewWillTransitionToSize:withTransitionCoordinator:` method depending on the screen orientation.
Comment: I *swear* I saw this "installed" trick to hiding a piece of a UIStackView in a WWDC video sometime, which is why I thought this was the "Apple way" of dealing with removing views in IB. I've been going through all the WWDC videos I can find that reference stack view, but so far I'm not finding it.
Comment: I found it, WWDC 2017, Auto Layout Techniques in Interface Builder, beginning at 29:00. And you're right, Josshad. The property he was using to hide things based on size class was, indeed, "hidden" and not "installed". The hidden property keeps the included views still within the arrange subviews of the UIStackView, it seems. Marking yours as the answer, and I apologize for not giving your answer the bounty before it expired.
Comment: This has been a major issue in my personal app, to the point where it (among other issues) has kept me from being able to release my redesign for years. And what do you know, this simple and obvious fix made everything work perfectly. Kudos!


Error creating window handle before window loads

Question: I have a large windows forms program with a lot of controls. The first window I see when I run it is the Login screen, it only has a combobox, button, textbox and a few labels. When I press the button it loads Form1. Form1, on load automatically creates an instance of Game, which it minimizes and embeds Game into Form1 using this code:
Game.Location = new Point(146, 6);
Game.TopLevel = false;
Game.Visible = true;
Game.BringToFront();
Game.FormBorderStyle = FormBorderStyle.None;
Controls.Add(Game);

I get the

"Error creating window handle"

error on this line (for some reason it's not on the window create line):
this.timer.Interval = 10;

Please help, others have said that this is to do with too many windows, but there I've tried deleting windows in project and I get the same error.
Answer: This question appears to already be answered:
Error creating window handle

You're getting the error because your program is creating too many
handles. The windows handle limit for your application is 10,000
handles. You'll need to find the memory leak.

Make sure you are calling Dispose() on forms after you close them and are done, or declare the Form inside using clauses:
using(Form mainForm = new Form())
{
    mainForm.Show();
}

Process Explorer or the Windows Task Manager allows you to look at the GDI Objects, Handles, Threads and USER objects. You will have to do to the details tab and select those columns to be viewed (Right click on columns->Select Columns). Look for a large number of GDI Objects to confirm the windows handle limit is indeed the problem.
Are you disposing the login form? You mention you have a-lot of controls, any way you can limit those, such as using a label and an array of text to display something instead of a bunch of labels or a grid of textboxes or the like.
An example of a memory profiler you could use would be the .Net Memory Profiler.
(Update 3/30/16)
Revising the information you have provided me, three things have occurred to me:

Unregistering events
If you are dynamically creating and then removing Controls on your forms, you must ensure to unregister any event handlers from every event you have previously registered with this control. If you don't, the event handler will hold a reference to the control and be prevented from being eligible for garbage collection (along with the GDI/USER objects), even if you call Dispose! They will remain held until you Dispose the parent Form.

Timer (and other, not-UI) events
The code in the Timer's tick event handler method (and any its calls) will be running on a separate thread that IS NOT the UI thread. If you need to access ANY of the UI properties, members, or methods, you must switch the thread context back to the UI thread, or else this can raise all kinds of funky exceptions. Also, if your creating UI objects (Controls) from a non UI thread, it creates MORE GUI/USER handles where it otherwise might have not. You do this by calling the Form's or Control's Invoke method and do your UI manipulation inside an anonymous method or pass its a delegate to the UI manipulation code. If you also call that method directly from any UI object, you might want to check Control.InvokeRequired to avoid the costly Invoke method which uses locks.

AppDomain.FirstChanceException
If all else fails, and you still don't know why you are getting the exception, heres a clever little trick that I have used to find VERY obscure or difficult-to-find bugs: Register an event handler with the AppDomain.FirstChanceException event, and put a breakpoint in the handler's method body. That way, the very next time an Exception is thrown, your code will get 'first chance' to handle it, and you will hit that breakpoint in the FirstChanceException handler method I just mentioned. From here, you can open up the call stack window and see the stack trace from where the exception is being thrown. This includes exceptions that are originating from native or .net APIs. Normally, this information is hidden from you, because the call stack get cleared before handing off the exception to your code, where you catch it.
Comment: I just added a using statement to the button event in Login, still happening. How would I go about finding a memory leak exactly?
Comment: @DenverP. I edited my answer above to answer your question in the comments.
Comment: @DenverP. Hey, I just wanted to follow up with you to see if you ever found a solution to your problem? I also noticed that you have not selected a best answer, and would like to encourage you to please to so. Remember, you can change the selected answer at any time, should someone come along and provide a better answer. In selecting an answer, also you provide yourself reputation as well. Furthermore, I have up-voted your question, in hopes that it will draw more eyes to your issue.
Comment: @DenverP.  Also I have updated my answer with some other things I thought it could likely be, after re-reading your description of your problem.
Answer: Just wanted to share that I got this error right at the start of our Desktop app, directly when loading the very first Form on startup. It turned out someone had configured compatibility mode 'Windows 95' on the startup executable. This appearently results in the exact same 'Error creating window handle'. Setting compatibility on the .exe remains, even after deploying a new .exe. I just hope that sharing this prevents others from wasting as much time as I did.


Fatal error: Class 'Conexao' not found in C:\xampp\htdocs\home.php on line 5

Question: Estou tendo este problemna de conexão com o banco
PHP:
$i = new Conexao();

$f = $imv['imovel_id'];

$i->ExecSQL("select * from imoveis_fotos where foto_imovel = '$f' limit 1");

$foto = $i->ListarDados();

PHP Conexão:
class Conexao {

private $host;
private $user;
private $senha;
private $bd;
private $link;
public  $query;
public  $lista;

//private $tabela;

/**
 *funcao construtora que inicia o link caso esteja null
 */
function __construct() {
    if ($this->link == NULL):

        $this->getConexao();

    endif;

}

/*
 *faz a conexao caso não tenha valores no LINK
 */
public function getConexao() {
    $this->host = 'localhost';
    $this->user = 'root';
    $this->senha = '';
    $this->bd = 'imoveis';

    $this->link = mysql_connect($this->host, $this->user, $this->senha) or die('Erro de conexão');
    mysql_select_db($this->bd, $this->link);
    mysql_set_charset('UTF8', $this->link);
}

PHP Config:
<?php

function __autoload($class) {

$arquivo = "{$_SERVER['DOCUMENT_ROOT']}/app/{$class}.class.php";

if (file_exists($arquivo)):
    //require_once (Config.php);
    require_once ($arquivo);
else:
    die("
Erro algum arquivo esta faltando
");

endif;

Comment: Qual a versão php?
Comment: Versão 5.6.8 do PHP
Comment: Evite utilizar `mysql` pois está obsoleto, utilize `mysqli` ou `PDO`, aparentemente está tentado incluir a classe `Conexao` que está em `C:\xampp\htdocs\home.php`. Qual o diretorio que está o arquivo `Conexao`? Em `app` msm?
Comment: Sim, esta em Conexao
Comment: Acho que você não me entendeu... O arquivo `Conexao` está em qual pasta (diretório), esse erro está dando porque o `include` ou `require` está errado, precisa apontar para o local correto do arquivo.
Comment: C:\xampp\htdocs\app\Conexao.class.php
Comment: Então o problema está no `__autoload`, que não está funcionando corretamente. Faz `echo $_SERVER['DOCUMENT_ROOT']` e veja o q ele mostra, normalmente `DOCUMENT_ROOT` traz até a raiz do projeto que no seu caso é `app`. Ou seja, `C:\xampp\htdocs\app`, então como vc escreveu `/app/{$class}.class.php`, o link para o arquivo ficou  `C:/xampp/htdocs/app/app/{$class}.class.php`
Comment: Muito obrigada.
Comment: Funcionou? Se sim, vou transformar o comentário em resposta e vc deixa com o simbolo de melhor resposta (verde).
Answer: Então o problema está no __autoload, que não está funcionando corretamente. Faz echo $_SERVER['DOCUMENT_ROOT'] e veja o q ele mostra, normalmente DOCUMENT_ROOT traz até a raiz do projeto que no seu caso é app. Ou seja, C:\xampp\htdocs\app, então como vc escreveu /app/{$class}.class.php, o link para o arquivo ficou C:/xampp/htdocs/app/app/{$class}.class.php


How to Read particular sector of a disk using ATA command?

Question: I want to read a particular sector(MBR Sector) of a disk using ATA  commands in vc++. I am new to VC++ so i am facing a problem when sending command to disk using DeviceIoControl. I am providing a code that i am using to read out a sector using command Read Sector(s)(0x20).
  BOOL status = FALSE;
 PATA_PASS_THROUGH_EX pATAData;
DWORD dataSize = sizeof(ATA_PASS_THROUGH_EX) + 512;
BYTE Buffer[sizeof(ATA_PASS_THROUGH_EX) + 512];
DWORD bytescopied = 0;

    pATAData = (ATA_PASS_THROUGH_EX*)Buffer;

    ZeroMemory(pATAData,dataSize); // clears the buffer

    pATAData->Length = sizeof(ATA_PASS_THROUGH_EX);
    pATAData->DataBufferOffset = sizeof(ATA_PASS_THROUGH_EX);
    pATAData->DataTransferLength = 512;
    pATAData->TimeOutValue = 2;

    pATAData->CurrentTaskFile[1] = 0x01;
    pATAData->CurrentTaskFile[2] = 0x00;
    pATAData->CurrentTaskFile[3] = 0x00;
    pATAData->CurrentTaskFile[4] = 0x00;
    pATAData->AtaFlags =ATA_FLAGS_DATA_IN;

    pATAData->CurrentTaskFile[6] = 0x20; // command Read Sector(s)(0x20)
    /* sends the command to the device, **hDevice** is device handle*/
    status = DeviceIoControl(hDevice, IOCTL_ATA_PASS_THROUGH, pATAData, dataSize,Buffer, dataSize, &bytescopied, NULL );

I can't undersatnd that what's wrong in this code and what i am missing here, but it is not working.
What i am missing here ?  If there is a problem with parametres of PATA_PASS_THROUGH_EX structure than tell how to read first sector(MBR).
Comment: Did you call GetLastError to see why it failed?
Comment: Why does this have the `qt` tag? You may get better help with other tags such as: `device`,  `hard-drive` or `sata`. Also, what is the error you get?
Comment: Not sure if this applies since you don't show the code for opening the device, but you might take a look anyway.  http://stackoverflow.com/questions/3362037/problem-reading-mbr-with-deviceiocontrol-function
Comment: Yes i call GetLastError. It give an error ERROR_INVALID_PARAMETER (0x57). But i can't understand which parameter is wrong. Actually I am new to windows progarmming.
Comment: Tags fixed to match code.
Comment: Thanks @RetiredNinja for your help. I read your link but it give partition info only, actually i want to read a complete sector or multiple sectors. Actually i have to do both read/write with ATA commands.
Comment: I don't see any obvious errors in the code. (1) Have you tried making your buffer cache align? (2) Have you tried a more basic command, such as IDENTIFY_DEVICE (ECh)?
Answer: Thankyou everyone for your help. I got the solution. A little bit thing that i have not noticed. That is Ata Flags. I have to send multiple flags. Eg.
pATAData->ataFlags = ATA_FLAGS_48BIT_COMMAND | ATA_FLAGS_DRDY_REQUIRED | ATA_FLAGS_DATA_IN

and also send the ATA command Opcode in PreviousTaskFile[6]  also.
And the few things to be noticed is
What is the block size of the HDD?  It could be more than 512 bytes, especially if it is a large disk like(1TB...4TB). As such, you'll need to adjust the sizes accordingly.    You can see what the size is by doing the EC identify ATA command, and then look at the resulting data structure.
Answer: Thanks for your help guys. I got the solution. I was not assigning the Device Handle in CurrentTaskFile.
pATAData->CurrentTaskFile[5] = (UCHAR)hDevice;

But IDENTIFY_DEVICE(ECh) command was sending succesfully without this. I don't know it's right or wrong but this is working.
Comment: Now i can read sectors, but now i have to read large storage disk(upto 4 TB). Can anyone help me how to send details in CurrentTaskFile[]  to read a large space disk. Because CurrentTaskFile[] is UCHAR type array. If i want to read last sector from a 1 TB disk .
Comment: You need to use the extended commands (EXT) along with the PreviousTaskFile[]
Comment: Regarding the CurrentTaskFile[5] aka the "Device" register. The old ATA spec reserved bit 6 of this register for "LBA mode". This means you should set this bit to enable "LBA mode", and clear it to use "CHS mode". To keep things simple, just always use LBA mode by setting this register to 0x40. The reason why the IDENTIFY_DEVICE command works is because it doesn't access any sectors, so it doesn't care about LBA or CHS mode.
Comment: THanks @tchau.dev . Your last two comments is very helpfull to me. Yes i have to use the extended commands (EXT) along with the PreviousTaskFile[] for large disk.
Answer: Thanks guys for your help. After a long discussion i find that i have to send extended commands for large disk. But now i am sending Read Sector(s) Ext(0x24 oppcode) command.
BOOL status = FALSE;
PATA_PASS_THROUGH_EX pATAData;
DWORD dataSize = sizeof(ATA_PASS_THROUGH_EX) + 512;
BYTE Buffer[sizeof(ATA_PASS_THROUGH_EX) + 512];
DWORD bytescopied = 0;

pATAData = (ATA_PASS_THROUGH_EX*)Buffer;

ZeroMemory(pATAData,dataSize); // clears the buffer

pATAData->Length = sizeof(ATA_PASS_THROUGH_EX);
pATAData->DataBufferOffset = sizeof(ATA_PASS_THROUGH_EX);
pATAData->DataTransferLength = 512;
pATAData->TimeOutValue = 2;

pATAData->CurrentTaskFile[0] = 0x00;
pATAData->CurrentTaskFile[1] = 0x01;
pATAData->CurrentTaskFile[2] = 0x01;
pATAData->CurrentTaskFile[3] = 0x00;
pATAData->CurrentTaskFile[4] = 0x00;
pATAData->CurrentTaskFile[5] = 0x40;
pATAData->CurrentTaskFile[7]=  0x00;
pATAData->AtaFlags =ATA_FLAGS_48BIT_COMMAND;

pATAData->PreviousTaskFile[0] = 0x00;
pATAData->PreviousTaskFile[1] = 0x00;
pATAData->PreviousTaskFile[2] = 0x00;
pATAData->PreviousTaskFile[3] = 0x00;
pATAData->PreviousTaskFile[4] = 0x00;
pATAData->PreviousTaskFile[5] = 0x04;
pATAData->PreviousTaskFile[7]=  0x00;

pATAData->CurrentTaskFile[6] = 0x24; // command Read Sector(s) Ext(0x24)
/* sends the command to the device, **hDevice** is device handle*/
status = DeviceIoControl(hDevice, IOCTL_ATA_PASS_THROUGH, pATAData, dataSize,Buffer, dataSize, &bytescopied, NULL );

But here is the same problem. command executed successfully but it does not read any sector. I am unable to find any error.
Comment: There are 2 types of errors you need to take into consideration when using DeviceIoControl. (1) The first is from DeviceIoControl telling you if the command was sent successfully to the device. (2) The second is from the device it self. In this case, a SATA or PATA drive. Every command will return a status indicating if the command is successful or not. This will be in the "Status" register (CurrentTaskFile[7]) and the "Error" register (CurrentTaskFile[0]). The "Status" register tells you if there is an error, and the "Error" register will tell you the type of error.
Comment: I got none of the above errors. Everything looks like ok but no buffer is read from drive. The "Status" register (CurrentTaskFile[7]  and  "Error" register (CurrentTaskFile[0]) both are zero. GetLastError() retruns code(0x57)(ERROR_INVALID_PARAMETER). DeviceIoControl returns TRUE but output buffer is empty. The lpBytesReturned parameter's value is 40(exactly the size of PATA_PASS_THROUGH_EX structure) it means no data is read from the drive.
Comment: Error register can be zero, but the Status register should at least have the "Device Ready" bit set to one (bit 6). Don't trust the DeviceIoControl() return status. It looks like GetLastError() is telling the truth.
Comment: Correction on my part, the "Status" register should be the same as the "Command" register, which is CurrentTaskFile[6].
Comment: No error no result, what should i do. The "Status" register (CurrentTaskFile[7] and "Error" register (CurrentTaskFile[0]) both are zero. Only two registers  "Command" register is 0x58, and "Device" register is 0xE0 has any  returned value that is not helping. What should i do.
Comment: Are you still stuck on this? If so, you can send me the code, and I'll test it out.
Comment: Thanks @tchau.dev . Now its working. But here is a problem, does not pass >256 sector count transfer length (ATA 48-bit is capable to transfer upto 65536 sectors). I have used all commands Read Sector(s), Read Multiple. I am not able to make a transfer more than 256 sectors in one time. For 256 sectors working but if i send 257 or more than DeviceIOControl returns 0.   Do you know any thing about this.
Comment: Yeah it's a limitation. Not sure why, but the only way around it is to send ReadFile and WriteFile. The problem with this is the fact that you can't send the specific read write command that you want.
Comment: Any idea to overcome this limitation. Any alternative. why can we use full capacity of ATA 48-bit commands(ATA 48-bit is capable to transfer upto 65536 sectors). Only ATA i have to use. Thanks @tchau.dev.
Comment: The limitation is at the kernel level. Most companies write their own driver to overcome this limitation. You can do the same. That said, I wouldn't recommend it unless you really know what you're doing, or know someone who does.
Comment: @Sam Sam, what was the reason for your error in this code? how did you fix it?


Perdi a codificação do projeto

Question: Eu instalei o eclipse no meu computador Windows e baixei meu projeto pra dar continuidade ao mesmo, não havia percebido antes, mas na tela que trabalho, quando fui me deparar com um erro percebi que os caracteres estavam assim:
@Size(max = 20, message = "Máximo de 20 caracteres permitidos.")

Sendo que no notebook não está e nem no github. Isso aconteceu no meu computador, alguém sabe se isso é opção do eclipse para que eu possa corrigir?
Comment: Verifica o encode do arquivo. Eh possível que tenha mudado.altera pra utf-8
Answer: Você provavelmente precisa mudar as configurações de encoding do Workspace, segundo essa resposta aqui: https://stackoverflow.com/a/22100912/3473971
Vá em

Windows -> Preferences, then under General -> Workspace

Espero que resolva seu problema!
Comment: Obrigado, era isso.

Perdi a codificação do projeto


What's the correct way to learn tremolo?

Question: In classical guitar, we have tremolo. But I see, most people do it not making any clean sound, they still have the sound of string muted with the right hand (the left hand is okay).
What's the correct way to learn it? So, we can produce clean sound and do it as fast as we should.
Comment: Are we talking classical trem or flamenco trem?
Comment: @NeilMeyer I think flamenco and classical tremolo is the same.
Answer: There are a number of pieces in the classical music repertoire that were specifically written to help learners develop their tremolo technique.
Note: Be absolutely sure to use the correct right-hand fingers in learning tremolo.
Carcassi's 25 Etudes, which are in the public domain and can be found in PDF version online, has several pieces which, if sufficiently developed, can be played in a performance. Off of the top of my head, Etude 7 and Etude 13 both emphasize tremolo.
As for the right-hand, the fingers chosen will depend on the player and the number of notes in the tremolo. A three-note tremolo might consist of a-m-i, i-m-a or even m-a-i. A four note tremolo would probably be a-m-i-a. In my experience, as long as the method of executing the technique is mechanically sound, there may be several equally viable alternatives and the best approach is to choose one and master it thoroughly.
Comment: I want to second @Kirk's suggestion to try pinky-ring-middle-index. For a continuous four-note tremolo, this pattern is mechanically very good, but may be difficult to master.
Answer: For right hand tremolo, there is no reason to damp or mute the string. I don't actually know of any pieces where you would do this.
You have a range of options - but the most common these days is to use tirando strokes to pluck, which will definitely not lead to any muting. Even apoyando shouldn't.
So typically, you would use tirando or apoyando with i and p, m, i and p or even a, m, i and p in order to time your tremolo. Your right hand should be arched so your fingers approach the strings almost at a 90 degree angle - no part of your right hand should be resting on the strings.
Answer: +1 for the Carcassi Method. My teacher recommended that as well. As for tremolo picking, try this experiment: make a fist. In what order did you close your fingers? Pinky first? Index last? Then thumb? Probably. (That's how I do it.) Consequently, I found it easier to tremolo pick in the same order.
For instance, in Leyenda, I would first use p-i, then p-m-i, and finally p-a-m-i. As I recall, I would begin with p-i with rest strokes, and then switch to free strokes for the m-i and a-m-i tremolo picking. (Free strokes should eliminate any muting problems from other digits.) Of course, your experience may vary. Do what works for you.
Comment: No, the thumb is not included in the tremolo. I've included that above to illustrate the picking sequence; the tremolo (a-m-i) alternates with the bass (p). In Leyenda, the theme is repeated first with single notes, then two-note tremolo, and finally three-note tremolo -- all in alternation with the bass.
Comment: P being pulgar - thumb, are you saying thumb/index for a two digit tremolo?


Value cannot be null. (Parameter 'builder') .net core 6

Question: Olá, estou tentando utilizar o EF no .NET CORE 6.0, porém está a apresentar um erro de "Value cannot be null. (Parameter 'builder')" ao tentar adicionar uma nova migration "Add-Migration", o código funciona em .net core 5.0, houve mudanças para o 6.0?
Como podemos ajustar para que isso funcione?
Essa é minha DB Context
public IDbConnection Connection => Database.GetDbConnection();
    public ApplicationDbContext (DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<LoginModel> Logins { get; set; }
    public DbSet<Carro> Carros { get; set; }
    public DbSet<CarteiraVirtual> CarteirasVirtuais { get; set; }
    public DbSet<Estacionamento> Estacionamentos { get; set; }
    public DbSet<Reserva> Reservas { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.ApplyConfiguration(new CarroMap());
        builder.ApplyConfiguration(new CarteiraMap());
        builder.ApplyConfiguration(new EstacionamentoMap());
        builder.ApplyConfiguration(new ReservaMap());

        base.OnModelCreating(builder);
    }

Meu Program.cs:
    var connectionString = builder.Configuration.GetConnectionString("Estacionamento");

builder.Services.AddDbContext<ApplicationDbContext>(x =>
    x.UseSqlServer(connectionString));
var app = builder.Build();

Answer: Blz?
Eu passei pelo mesmo problema que você e passei horas para encontrar o erro e a solução.
Um dos motivos pelo qual esse erro está ocorrendo é nos relacionamentos entre os objetos.
Por exemplo:

Isso aconteceu comigo e as pessoas podem pensar "Como não viu esse erro?!!!"
Ocorre que esse é apenas um exemplo simples. Quando a aplicação está com diversas classes, a coisa complica um pouco.
Dica:
Quando você tenta adicionar um novo migration e ocorre esse erro, o Package Manager Console informa quais objetos estão com problema e precisam ser revistos.
Adaptei um dos meus erros abaixo para você entender que há dicas na saída dos erros.
There are multiple relationships between 'Carro' and 'Reserva' without configured foreign key properties. This will cause Entity Framework to create shadow properties on 'Carro' with names dependent on the discovery order. Consider configuring the foreign key properties using the [ForeignKey] attribute or in 'OnModelCreating'.


Rewriting git history to make crlf consistent

Question: I have a git repository that has a fine variation of LF and CRLF files.
Before making a possible switch, I want to rewrite commits where the parent and the current commit have different LR/CRLF encodings.
So I tried the following "one-liner" (slightly edited) where I try to run todos if the parent version of a file contains a CR.
$ git filter-branch --tree-filter '
  echo
  P=$GIT_COMMIT^;
  FILES=$(git diff --name-only $P);
  for a in $FILES; do
     if ! git cat-file -e $P:$a; then echo "no parent"; continue; fi;
     if git show $:$a | grep -qUP '\r'; then
        echo "parent is dos";
        todos $a;
     else
        echo "parent is unix";
        fromdos $a;
     fi;
  done' 23498f..HEAD

It doesn't work. Can anyone spot the error or give a solution to this problem?
Answer: I am answering my own question.  The bug in my original solution is that the FILES set is wrong because the diff is not taken between the rewritten parent and the current commit, but between the original parent and the current commit.
When traversing a set of commits like this, the files that need to be changed isn't the set of files touched by a commit, but also the set of files where some parent commit messed up the line endings.
This means that I don't get the correct set of files.  There is a map function provided to filter-branch expressions that can transform an "original" rev to the rewritten rev.  When I use that function, it works correctly.
The resulting "one-liner" looks like this:
$ git filter-branch -f --tree-filter '
    echo "\n $GIT_COMMIT";
    P=$(git rev-parse $GIT_COMMIT^);
    echo $P;
    P=$(map $P);
    echo $P;
    git cat-file commit $GIT_COMMIT;
    FILES=$(git diff --name-only $GIT_COMMIT $P);
    echo "FILES:\n$FILES";
    for a in $FILES; do
        git cat-file -e $P:$a > /dev/null 2>&1 || continue;
        if git show $P:$a | grep -qUP '\r'; then
           echo "parent is dos $a";
           todos $a;
        else
           echo "parent is unix $a";
           fromdos $a;
        fi;
    done;
    git add $FILES;' a6d9e..HEAD

Most of the aI don't think the last 'git add $FILES' is needed, but that is the command that I used, and I don't want to provide an incorrect answer.
Note: It should also be possible to define FILES=$(git diff --name-only a6d9e HEAD) and thus use a fixed set when traversing the commits. That is probably much simpler, but I didn't do that.
Answer: Do you really want to re-write history?
Using the built in configuration option helps to make these things transparent.  I have done something similar to this, and for the last few years, working with people on Windows, Mac and Linux systems have yet to have a problem with line endings.
Look at Dealing With Line Endings from GitHub.
Here is what they have to say about configuration files:

Here's an example .gitattributes file, you can use it as a template for all your repositories:

# Set default behaviour, in case users don't have core.autocrlf set.
* text=auto

# Explicitly declare text files we want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary The advantage of this is that your end of line configuration now travels with your repository and you don't need to worry about whether or not collaborators have the proper global settings.

They go on to talk about what you can do if you have a current repository, and need to apply these settings to it.
Re-normalizing a repository

After you've set the core.autocrlf option and committed a
  .gitattributes file, you may find that git wants to commit files that
  you've not modified. This is because git wants to normalize the line
  endings for you. The best way to do this is wipe out your working tree
  (all the files except the .git directory) and then restore them. Make
  sure you've committed any work before you do this, or it will be lost.

git rm --cached -r .
# Remove everything from the index.

git reset --hard
# Write both the index and working directory from git's database.

git add .
# Prepare to make a commit by staging all the files that will get normalized.
# This is your chance to inspect which files were never normalized. You should
# get lots of messages like: "warning: CRLF will be replaced by LF in file."

git commit -m "Normalize line endings"
# Commit

Comment: My issue is that I *already* have commits that have changed the line ending of files. I don't want that right now.  I found a solution that I am satisfied with that I am adding as an answer.
Comment: That is what the second part of this answer is supposed to address.  When you have a history and need to apply the settings.  Glad you found a solution!


AngularJS e backend Java

Question: Olá,
Estou deixando de utilizar o framework JSF para iniciar a utilização de AngularJS. Gostaria de saber se alguém possuí um exemplo de integração entre o AngularJS com Back-end Java, para que eu possa ver o funcionamento da passagem de parâmetro do Front-end para o Back-end e a gravação no banco de dados MySql. Pode ser exemplo de um crud qualquer ou login com Spring ou Jax-RS, pesquisei na internet mas a maioria dos exemplos são muito extensos, confusos ou está faltando classe.
Alguém possuí um código no github para entendimento de processo entre o AngularJS e o Back-end?
Desde já agradeço.
Comment: da uma olhada http://uaihebert.com/aplicacao-web-completa-angular-twitter-bootstrap-spring-mvc-data-e-security/  bem completo
Comment: Se está começando agora sugiro usar o Angular2 com uma api REST no backEnd
Answer: Esse guia é bem simples e explicativo pra mostrar o Spring MVC com o AngularJS, porém ele não tem a conexão com o banco.
Esse guia possui conexão com o banco, mas é um pouco menos explicativo na parte do Angular, mas junto com o guia anterior acredito que é um bom kick-off.
Este outro guia também é bem legal, não é tão simples mas ta bem bacana. Ele usa o MySql, Angular e o Spring MVC.
Comment: Beleza, eu tinha visto o uaihebert que o Otto aconselhou acima mas achei meio confuso, mas com os 2 primeiros links da sua resposta descritos aqui ficou mais claro a compreensão do processo. Valeu gente.

AngularJS e backend Java


IPv6 nameservers but no AAAA record?

Question: I'm trying to understand the network I'm part of. It has a couple thousand computers and the backbone routers are supposed to be IPv6, but the firewalls are not, thus there is a hypothetical IPv6 capability, but no routing is possible. I talked to a network admin and he said it had something to do with the firewalls not being IPv6 capable or not routing as fast with IPv6. Does anyone know what firewalls (I don't know anything more specific than that) can have to do with a local network and IPv6?
When I dig the domain of my organization (when I'm in the local network), I get DNS records which also include AAAA records for the nameservers (I don't see these AAAA records when I google the DNS records for the site). But there is no IPv6 routing possible and the host itself does not have a AAAA records. Do you know what are things organizations need to do to migrate their servers to IPv6? Do you need to change any hardware to make this possible if the routers already support IPv6?
Answer: IPv6 is an entirely different IP stack from IPv4.  Various things are simpler in IPv6 than IPv4, and vice versa.
IPv6 has a site local address space which has been deprecated.  I think this was intended to be similar the private address spaces in IPv4.
Many ISPs do not yet support IPv6 so tunneling may be required.  A lot of older (not necessarily that old) equipment is not capable of working with IPv6.  This may include some (a few, many, most, or all) of the routers your organization uses.
Many networks will have internal firewalls between various segments.  If these firewalls are not IPv6 capable any inter-segment IPv6 routing would need to be tunneled.
If the routers do support IPv6 internal routing within firewalled segments should be possible.  However, device discovery will likely depend on DNS or other host registries.  Finding unregistered hosts in an IPv6 network can be much more difficult with IPv6 than it is with IPv4 where range scans are practical.

IPv6 nameservers but no AAAA record?


paperclip uploading muliple images, renaming the name"avatar"

Question: I have installed paperclip for my ruby on rails project. But I cant upload multiple images.
I have two different fields where I want to upload images for eg logo and picture.
Can I change the name "avatar" to indicate the name of the field?? Is it possible?
Comment: possible duplicate of [Uploading multiple files with paperclip](http://stackoverflow.com/questions/11605787/uploading-multiple-files-with-paperclip)
Comment: does it work for single image upload?
Answer: Yes it is possible.
If you want to change "avatar" to "logo" using below command
rails g paperclip modalname logo

where logo is your field name.
I hope you understand and may be it solve your problem.
Answer: It sounds like you need some ideas to work with Rails & Paperclip:

Paperclip
Handles a file attachment & sends the data to your DB
- Creates DB entries:
your_definition_file_name
your_definition_content_type
your_definition_file_size
your_definition_uploaded_at

- Handles Objects called _your_definition
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
    has_attached_file :your_definition
end

Paperclip basically acts like a bridge between your db & your files -- meaning you just have to keep the object name consistent to get it to work

Code
If you have two fields (logo & picture), you'll need to declare them in your attachment model, pass their params, and add the columns in your table:
#app/controllers/attachments_controller.rb
def create
    @attachment = Attachment.new(attachment_params)
    @attachment.save
end

private

def attachment_params
    params.require(:attachment).permit(:logo, :picture)
end

#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
    has_attached_file :logo
    has_attached_file :picture
end

#db/migrate
def change
     add_attachment :attachments, :logo
end

attachments
id | logo_file_name | logo_content_type | logo_file_size | logo_uploaded_at | picture_file_name | picture_content_type | picture_file_size | picture_uploaded_at | created_at | updated_at

Recommendation
The above code is not very DRY
I would recommend using a type attribute in your attachment model, setting the type each time you upload
This way, you can call the attachment as image or similar, uploading with the extra para of type each time:
#app/controllers/attachments_controller.rb
def create
    @attachment = Attachment.new(attachment_params)
    @attachment.save
end

private

def attachment_params
    params.require(:attachment).permit(:image, :type)
end

#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
    has_attached_file :image
end

#db/migrate
def change
     add_attachment :attachments, :logo
end

attachments
id | image_file_name | image_content_type | image_file_size | image_uploaded_at | type | created_at | updated_at


Express dynamic route's get added to static routes middleware stack

Question: I am defining static & dynamic routes in Express, and I have built a generic responder to send response to client. The responder is global to all routes and thus added at the end.
However, when I define static routes, matching dynamic routes' middlewares get added to the stack before the responder.
To illustrate:
server.get('/hello/test', function(req, res, next) {
    console.log('/hello/test');
    next();
});
server.get('/hello/:page', function(req, res, next) {
    console.log('/hello/:page');
    next();
});
server.use(function(req, res, next) {
    res.status(200).send('test');
});

Calling curl localhost:3000/hello/test will console.log both '/hello/test' and '/hello/:page' before the responder middleware gets called. I only want the first matching routes middleware to be called.
Is there anyway to prevent this behaviour?
Comment: have you tried removing ´next();´ from the first route?
--> http://expressjs.com/api.html#app.METHOD
Comment: @John how would i reach the responder middleware without next()?
Answer: The method next() is passing the control to the next handler.
You could solve your issue just removing the next() call from your routes, and putting the middleware into a function:
server.get('/hello/test', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/test');
});
server.get('/hello/test_b', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/test_b');
});
server.get('/hello/:page', myMiddleware(req, res, next), function(req, res) {
    console.log('/hello/:page');
});
server.get('*', myMiddleware(req, res, next), function (req, res) {
    res.type('txt').send('Not found');
});

function myMiddleware(req, res, next) {
    console.Log("in midleware")
    next();
}


Engineering notation algorithm, i.e. 1000 -> 1k, 0.001 -> 1m

Question: I had to come up with a simple algorithm on a low powered embedded system, because dividing numbers by 1000s to get the wanted digits (first three basically) caused a loss in precision in the floating point operations. 10 million became 9.8M for example.
Here is my basic algorithm to get 1.00k from 1000:

Take first 3 digits

100

Find magnitude by division, and subtract from integer length (digits)

4 - 3 = 1

Divide by appropriate power of 10:

100 / 10^(3-1) = 1.00, and with magnitude known (3=k), get 1.00k.

An issue is I want to do this for numbers below 1 as well.
The first thought was inverse would work, because 1/1000 = 0.001 (k->m) but I seem to have been mistaken as the magnitude could be different on the inverted number from the non-inverse.
Is there a clever algorithm to do this?
My current code (if it needs explanation, ask) to deal with the above was this:
for (;value >= 1000*1000; value /= 1000) //until <condition>; do <condition>
    magnitude+=3;
if (value >= 1000)
    magnitude+=3;
    diff = digitcount(value) - magnitude;
    return firstthree(value) / 10^(3-diff);

I tried a for loop with value < 1; value *= 1000 but the result was something like 100m 10m 1000u 100u 10u 1000n (relying on inverse to get magnitude), or 0.1u, 0.01u, 0.001u (firstthree() fails here ovviously) which is not the autoranging I am looking for of course.
I expect maybe if magnitude below 1 can be found, I can then multiply by thousands until I have a number above 1?
Comment: The arithmetic in that system is very strange. Getting the first three digits intact is the most important part. Yor code confuses me, your *magnitude* variable is acumulative, but your *value* variable gets constantly decreased.Not to risk precision, I would just read the specs  and do a hardcoded, bitwise conversion.
Answer: Look up scaled arithmetic. This was popular in FORTH (a lightweight language that was popular in underpowered embedded systems, with integer arithmetic only).


How to solve the given initial-value problem?

Question: Solve the given problem which the input function $g(x)$ is discontinuous?
$y''+4y = g(x)$, $y(0) = 1$, $y'(0) = 2$, where
$$g(x) = \begin{cases} \sin x, & 0\leq x\leq\frac{\pi}{2}\\
0,& x>\frac{\pi}{2} \end{cases}$$
And the given answer is,
$$y = \begin{cases} \cos 2x+\frac56\sin2x+\frac13\sin x, & 0\leq x\leq\frac{\pi}{2}\\
\frac23\cos 2x+\frac56\sin2x,& x>\frac{\pi}{2} \end{cases}$$
Comment: @user84275: Have you learned Laplace Transforms?
Comment: Solve it on $[0,\,\pi/2]$ first by the standard method. That gives you boundary conditions for the second part, on the interval $[\pi/2,\,\infty)$.
Comment: @Amzoti, this should be done without using Laplace.
Answer: Note: It is best to use Laplace Transforms for these sorts of problems and this is where the LT shows it's usefulness, but that is not allowed, so we will use undetermined coefficients instead.
We are given:
$\tag 1 y''+4y = g(x), y(0) = 1, y'(0) = 2$
where
$$g(x) = \begin{cases} \sin x, & 0\leq x\leq\frac{\pi}{2}\\
0,& x>\frac{\pi}{2} \end{cases}$$
The approach will be as mentioned by D.F. in comments, we are going to solve for the lower interval and use that result to solve the upper interval (in essence, we are solving two ODEs).
We start out by finding the homogeneous solution to $(1)$, so we have:
$$m^2 + 4 = 0 \rightarrow m_{1,2} = \pm 2i$$
This gives us:
$$y_h = c_1 \cos 2x + c_2 \sin 2x$$
Next, we will solve for the particular solution, so we guess at a solution of the form:
$$y_p = a \cos x + b \sin x$$
To solve for the constants, $a$ and $b$, we substitute back into $(1)$, yielding:
$-a \cos x - b \sin x + 4a \cos x + 4b \sin x = \sin  x$
This yields $a = 0$ and $b = \dfrac{1}{3}$.
So, we can write our solution as: $y = y_h + y_p = c_1 \cos 2x + c_2 \sin 2x + \dfrac{1}{3} \sin x$
Using the IC's, we solve for $c_1$ and $c_2$, yielding $c_1 = 1, c_2 = \dfrac{5}{6}$, so we have:
$$\tag 2 y(x) = \cos 2x + \dfrac{5}{6} \sin 2x + \dfrac{1}{3} \sin x, 0 \le x \le \dfrac{\pi}{2}$$
Next, we want to solve for the upper upper half of the range, so we have, $y'' + 4y = 0$, but we need ICs. We will use $(2)$ to generate an IC at $\dfrac{\pi}{2}$ (do you know what allows us to do this and why it is useful to do so?).
So, using $(2)$, we get $y\left(\dfrac{\pi}{2}\right) = -\dfrac{2}{3}$ and $y'\left(\dfrac{\pi}{2}\right) = -\dfrac{5}{3}$.
We have our solution for $(2)$ from earlier as: $y = c_1 \cos 2x + c_2 \sin 2x$
Using these new ICs, we arrive at, $c_1 = \dfrac{2}{3}, c_2 = \dfrac{5}{6}$, so:
$$\tag 3 y(x) = \dfrac{2}{3} \cos 2x + \dfrac{5}{6} \sin 2x, x \gt \dfrac{\pi}{2}$$
Using $(2)$ and $(3)$, the solution can be written as:
$$y(x) = \begin{cases} \cos 2x + \dfrac{5}{6} \sin 2x + \dfrac{1}{3} \sin x, & 0\leq x\leq\frac{\pi}{2}\\
\dfrac{2}{3} \cos 2x + \dfrac{5}{6} \sin 2x,& x>\frac{\pi}{2} \end{cases}$$
Comment: @Amzoti I don't really know what allow us to generate an IC at π/2. :/
Comment: @user84275: Since we have a piecewise function, where do they meet? They meet at $\frac{\pi}{2}$ and we would like for them to be continuous and have nice, smooth, continuous properties there. So, since we fully solved for the first part of the DEQ and it was valid at $\pi/2$, why not use the value of that function and its derivative at the point so the two are well behaved. Clear now?
Comment: @Amzoti very clear. thanks a lot..
Answer: First let $g(x)=\sin(x)$.
$$
\begin{align*}
y'' + 4y &= \sin(x)
\end{align*}
$$
Applying the Laplace transform to both sides gives
\begin{align*}
s^2Y(s)-s-2+4Y(s) &= \dfrac{1}{s^2+1}\\
Y(s)(s^2+4) &= \dfrac{1}{s^2+1}+s+2\\
Y(s) &= \dfrac{1}{(s^2+1)(s^2+4)}+\dfrac{s}{s^2+4}+\dfrac{2}{s^2+4}\\
\end{align*}
Via partial fraction decomposition we get
\begin{align*}
Y(s) &= \dfrac{1}{3(s^2+1)}-\dfrac{1}{3(s^2+4)}+\dfrac{s}{s^2+4}+\dfrac{2}{s^2+4}\\
\end{align*}
Thus the inverse Laplace transform gives the desired solution:
$$y(x) = \frac{1}{3}\sin(x) - \frac{5}{6}\sin(2x)+\cos(2x)$$
For $g(x)=0$, we have
$$\begin{align*}y'' + 4y &= 0\\
\end{align*}$$
Let us make the ansatz that $y(x)=e^{\lambda x}$. Thus,
$$\begin{align*}
\lambda^2e^{\lambda x} + 4e^{\lambda x} &= 0\\
\lambda^2 + 4 &= 0\\
\end{align*}$$
Hence $\lambda = \pm 2i$, and the general solution is:
$$\begin{align*}
y(x) &= c_1 e^{2ix} + c_2e^{-2ix}\\
&=c_1(\cos(2x)+i\sin(x))+c_2(\cos(2x)-i\sin(2x))\\
&=(c_1+c_2)\cos(2x)+i(c_1-c_2)\sin(2x)\\
&=k_1\cos(2x)+k_2\sin(2x)
\end{align*}$$
where the last line simply redefines our constants, since they are already arbitrary. To satisfy initial conditions, $k_1=k_2=1$, which gives the specific solution
$$ y(x) = \cos(2x)+\sin(2x) $$
In conclusion, the piecewise function is
$$y(x) =
  \begin{cases}
   \frac{1}{3}\sin(x) - \frac{5}{6}\sin(2x)+\cos(2x) & \text{if } 0 \leq x \leq \frac{\pi}{2} \\
   \cos(2x)+\sin(2x)       & \text{if } x > \frac{\pi}{2}
  \end{cases}$$
Comment: Ah, I just saw your most recent comment above regarding not using Laplace transforms... :\


How to share resources between unit test and instrumentation test in android?

Question: I'm following this post, http://blog.danlew.net/2015/11/02/sharing-code-between-unit-tests-and-instrumentation-tests-on-android/, to share code, but how to share an asset?, like a fixture file?, I want to mock an api response, so I have a JSON file to do it, but I try this: https://gist.github.com/nebiros/91a68aaf6995fa635507
In Unit Test, this works:
ClassLoader.getSystemResourceAsStream("some_response.json");

but in Android Intrumentation Tests, it doesn't, where can I put those fixture files?.
Comment: Any solution? I am facing the same issue
Comment: @Nazneen I post the solution I found.
Answer: I found this way, to share fixture files from test to androidTest:

Add your fixture files to the resources folder of your test one, here: src/test/resources.
Add test resources folder to androidTest, resources.srcDirs += ['src/test/resources'], here's an example:
android {
    sourceSets {
        String sharedTestJavaDir = 'src/sharedTest/java'

        test {
            java.srcDirs += [sharedTestJavaDir]
        }

        androidTest {
            java.srcDirs += [sharedTestJavaDir]
            resources.srcDirs += ['src/test/resources']
        }
    }
}

Access fixture files from your androidTest env this way: this.getClass().getClassLoader().getResourceAsStream(filename);


What does Page Content contain in Panels Everywhere when site template is enabled?

Question: Panels Everywhere (PE) configuration allows a site template to be used to "wrap" any page in a panels display.
If I edit the content of this panel, for example like this:

does it mean that any (I mean all) other page will be crammed in the Page Content item defined in the template?
In other words:

Are pages always inserted in the template's page content?
Is there anything else than pages ever ending in the template's page content? If yes, what and when?
Answer: A page panel will be placed where the main page content is located.  The page panel will be displayed only when the conditions of its Selection rules and Contexts are satisfied.  You can define alternatives by creating multiple variants for the panel and modifying the settings to meet your needs.  Panels will search through the variants and go with the first variant that meets the criteria so the order you place the variants in may matter.  Using Panels Everywhere, you would set the overall layout for your site pages in variants to the default site panel.  The various page panels would then be displayed in the regions as defined for them.
You can also create mini-panels and view content panes which act similar to blocks except that, like page panels, you can define selection rules and contexts for them and place them anywhere else on the default panel variants you desire.  So you can provide content related to your main content based upon the context (users, tax terms, field settings etc.) that apply to the main content display.
I'm not sure if I've fully answered your question.  What do you want to achieve in your site setup?
Comment: I want to define a general header and footer + left and right column to all my website pages. So, the answers to my questions would be i) Yes and ii) No. Correct?


What's the mathematical representation of shifting of an array?

Question: Consider 5x1 matrix, for example
A = \begin{bmatrix}1\\2\\3\\4\\5\end{bmatrix}
I want to shift each element down by one position and bring the last element to the first position.
B = \begin{bmatrix}5\\1\\2\\3\\4\end{bmatrix}
How can this operation be represented as a generalised mathematical expression?
Thanks in advance SEmath!
Answer: The representation of this shift is simply the $5\times 5$ matrix
$$
M = \pmatrix{0&0&0&0&1\\1&0&0&0&0\\0&1&0&0&0\\0&0&1&0&0\\0&0&0&1&0}
$$
where, if you have your array $A$ stored as a column vector, then the shifted array is equal to $B = MA$.
In general, any permutation of elements in an array can be represented by a matrix which has a single $1$ in each row and in each column, and $0$ otherwise. For this reason, such matrices are called permutation matrices.
Answer: This operation can be represented as multiplication by a matrix that selects the appropriate rows of the vector. Here are some general principles that you can use to construct such "selector" matrices:

The rows of the matrix product $AB$ are linear combinations of the rows of $B$ with coefficients given by the corresponding row of $A$. Similarly, the columns are linear combinations of the columns of $A$, with coefficients taken from the corresponding column of $B$.
As a result, left-multiplying a matrix $B$ by a row of the identity matrix picks out the corresponding row of $B$ and right-multiplying by a column of the identity matrix picks out the corresponding column.

You want to shuffle the rows of the vector, so you'll be left-multiplying by some matrix $M$. The first row of the result needs to be the last row of the vector, so the first row of $M$ is $\begin{bmatrix}0&0&0&0&1\end{bmatrix}$, which is the last row of the $5\times5$ identity matrix. Similarly, the second row of the result should be the first row of the input, so the second row of $M$ is $\begin{bmatrix}1&0&0&0&0\end{bmatrix}$. Continuing in this fashion, you will end up with $$M = \begin{bmatrix}0&0&0&0&1 \\ 1&0&0&0&0 \\ 0&1&0&0&0 \\ 0&0&1&0&0 \\ 0&0&0&1&0 \end{bmatrix}.$$ A matrix like this that produces a permutation of the rows or columns of another matrix is known as a permutation matrix, but using the principles above you can also represent other operations that select parts of matrices as matrix multiplications.


Dropdown not working in Contact Form 7

Question: I have added a contact form using the plugin contact form 7 with drop-down area.
http://www.edsys.in/contact/ 1
The trial software field has the dropdown.But it s not displayin properly.
T searched over net and applied the following css:
select {
    background: transparent;
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 0;
    height: 34px;
    -webkit-appearance: none;
}

...but it didnt work.
I need something like this: http://www.zebraprintandcopy.com/upload-file/
When I checked the source code, I couldn't find any helpful styles.
Thanks in advance!!
edit:
This is the code I have added for the dropdown in the form:

Trial Software Of :
[select* dropdown multiple "test1" "test2" "test3" "test4"]

Comment: Show us the code you are using to create the field in CF7. Remove "multiple" from the code
Answer: Remove multiple from your select box code.
Answer: I think you have to uncheck the option "Allow multiple answers" when you create the field. Or you can remove the "multiple" option from the tag.
Answer: You need to remove the multiple option from the form, in the Admin.
Right now, you likely have something like:
[select your-select multiple "test1" "test2" "test3" "test4"]

Read the docs for full details.
Answer: Your code should look like the following with "multiple" removed.

Trial Software Of :
[select* dropdown "test1" "test2" "test3" "test4"]

Dropdown not working in Contact Form 7


PHP Array merge with keys match

Question: Having Two arrays need to Merge two arrays with matching their keys and rest should be empty. I have tried array_merge, array_diff, array_fill but nothing helped iam bit newbie, Thanks in advance.
Array one
Array
    (
        [5] => PHM
        [4] => ODM
        [3] => N
        [6] => M9
        [10] => RDM9
    )

array 2
 Array
  (
    [0] => 01
    [1] => 02
    [2] => 03
    [3] => 04
    [4] => 05
    [5] => 06
    [6] => 07
    [7] => 08
    [8] => 09
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 13
   )

Final Output
Array
  (
    [0] => null
    [1] => null
    [2] => null
    [3] => N
    [4] => ODM
    [5] => PHM
    [6] => M9
    [7] => null
    [8] => null
    [9] => null
    [10] => RDM9
    [11] =>  null
    [12] => null
   )

Comment: What was the output when using `array_merge` ?
Comment: Yeah, it's no use to tell readers which things you've tried, without telling them why those things didn't work.
Comment: why would you want `null` for the other array values?
Comment: need to display in a table as null,
Answer: Make array with all nulls from the 2nd array and replace by values from the 1st array
$arr2 = array_fill_keys(array_flip($arr2), null);
$new = array_replace($arr2, $arr1);
print_r($new);

Comment: Glad that could help.
Comment: I'm affraid there is one problem, what if we have key '20' in first array but not in second? it will appear in the final array as filled
Comment: @ConstantineUA Yes. But we need to ask OP is it correct result or not
Answer: You can pass array 2 to a foreach loop and use an if/else statment to check if the key of array 2 exists in array 1, if so set the value of element $output[$key] to NULL, else assign the value as $arr1[key]
   foreach ($arr2 as $key=> $value){
       $output[$key]=(!array_key_exists($key, $arr1)) ? NULL : $arr1[$key];
    }
    var_dump($output);

Comment: It's not my downvote, but think that due to `global $arr1;`
Comment: anyone care to explain what was the downvote for? while it might not be the fastest solution, it does fulfil the requirement, no??
Comment: foreach doesn't change variable scope unlike a function.
Comment: @spalsh58 Yes, you are absolutely right. I must have done something stupid when I tested it in a rush to lead me into thinking it won't work without the global declaration. Now with a more clear head, that line is redundant. Thank you so much, I've learned something from this. Appreciated.
Comment: Could you please elaborate more your answer adding a little more description about the solution you provide?
Comment: @abarisone if key x doesn't exist in $arr1, then set the value of element $output[x] as NULL, else the value of element $output[x] equals to the value of element$arr1[x], x is the key of the (key, value) pair of the foreach loop (x is $key of the $key=>$value pair). In other word the above is looped for every (key, value) pair of $arr2 to create a new array $output. Since it is a simple question I thought the code is self explanatory, thus didn't include comments. P.S I usually do include code comments in more complex solution.Just used ternary operator for a shorthand if/else that's all
Comment: @SML and for god's sake, please do put spaces when using ternary operators, otherwise it's just like a pile of dust being thrown in one's eyes
Comment: @OliverMaksimovic is this what you meant?
Comment: @SML yes :D also, brackets around `!array_key_exists()` are redundant :P Sorry, it's stronger than me >.<
Comment: @OliverMaksimovic Yes, that I am aware of, that's personal habitat, I usually put brackets as visual aid around any statement that starts with the not operator !. I hope that's not considered bad practice.

PHP Array merge with keys match


Bluetooth Enable Disable ADB command and Opening Android Activity with Android Driver not working in Some Android 7 devices

Question: Result: Parcel(
  0x00000000: ffffffff 0000006e 0065004e 00640065 '....n...N.e.e.d.'
  0x00000010: 00420020 0055004c 00540045 004f004f ' .B.L.U.E.T.O.O.'
  0x00000020: 00480054 00410020 004d0044 004e0049 'T.H. .A.D.M.I.N.'
  0x00000030: 00700020 00720065 0069006d 00730073 ' .p.e.r.m.i.s.s.'
  0x00000040: 006f0069 003a006e 004e0020 00690065 'i.o.n.:. .N.e.i.'
  0x00000050: 00680074 00720065 00750020 00650073 't.h.e.r. .u.s.e.'
  0x00000060: 00200072 00300032 00300030 006e0020 'r. .126.96.36.199. .n.'
  0x00000070: 0072006f 00630020 00720075 00650072 'o.r. .c.u.r.r.e.'
  0x00000080: 0074006e 00700020 006f0072 00650063 'n.t. .p.r.o.c.e.'
  0x00000090: 00730073 00680020 00730061 00610020 's.s. .h.a.s. .a.'
  0x000000a0: 0064006e 006f0072 00640069 0070002e 'n.d.r.o.i.d...p.'
  0x000000b0: 00720065 0069006d 00730073 006f0069 'e.r.m.i.s.s.i.o.'
  0x000000c0: 002e006e 004c0042 00450055 004f0054 'n...B.L.U.E.T.O.'
  0x000000d0: 0054004f 005f0048 00440041 0049004d 'O.T.H._.A.D.M.I.'
  0x000000e0: 002e004e 00000000                   'N.......        ')

While running the following ADB Command, the above error thrown in CLI.
Enable:

adb shell service call bluetooth_manager 6

Disable:

adb shell service call bluetooth_manager 9

Also tried with the appium android driver activity, Nearly the same permission issue in Samsung Galaxy Note 8 (7.1.1), Samsung Galaxy Note 2 (7.0). But both activity and ADB command works fine in Samsung Galaxy S7 edge (7.0).
Android driver activity error:
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Error occured while starting App. Original error: Error executing adbExec. Original error: 'Command '/home/user/Android/Sdk/platform-tools/adb -P 5037 -s 83f0374b42535532 shell am start -W -n com.android.settings/com.android.settings.bluetooth.BluetoothSettings -S -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -f 0x10200000' exited with code 1'; Stderr: 'java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.settings/.bluetooth.BluetoothSettings launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } } from null (pid=24744, uid=2000) requires android.permission.BLUETOOTH_ADMIN
    at android.os.Parcel.readException(Parcel.java:1693)
    at android.os.Parcel.readException(Parcel.java:1646)
    at android.app.ActivityManagerProxy.startActivityAndWait(ActivityManagerNative.java:3646)
    at com.android.commands.am.Am.runStart(Am.java:658)
    at com.android.commands.am.Am.onRun(Am.java:392)
    at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)
    at com.android.commands.am.Am.main(Am.java:125)
    at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
    at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:301)'; Code: '1' (WARNING: The server did not provide any stacktrace information)

Any solutions would be appreciated.
Comment: Any one know about this issue and solution for this?
Answer: the problem that you had faced because that you run your command without root permission.
run this command if your phone is already rooted :
adb root

after :
adb shell service call bluetooth_manager 6