SQLiteStudio tipos de dados

Question: Estou usando o SQLiteStudio para modelar uma base de dados. Na hora de criar os campos de uma tabela, reparei que ele dispõe de alguns tipos de dados que não aparecem na documentação do SQLite. Por exemplo, Na combobox onde escolhemos o tipo da coluna, ele tem: BOOLEAN, DOUBLE, procurei na documentação do SQLite e não encontrei esses tipos de dados.
Answer: A própria documentação informa que não possui boolean e informa que valores booleanos são guardados como int, sendo false = 0 e true = 1:

1.1 Boolean Datatype
SQLite does not have a separate Boolean storage class. Instead,
  Boolean values are stored as integers 0 (false) and 1 (true).

Daí, você trata na sua aplicação quando o valor deste campo for 0, é false e quando for 1, é true.
E quando ao double, você pode usar real, que é também a recomendação da documentação, conforme a tabela abaixo:

Referencias:
SQLite - Data Type
Datatypes In SQLite Version 3
Comment: @MatheusSaraiva na verdade sua pergunta não é essa que você pôs no comment. Mas se a intenção é que seja, você pode [edit] a pergunta e acrescentar esse complemento.
Comment: @MatheusSaraiva ele deve fazer as conversões conforme descrito na documentação, é interessante você verificar qual o tipo dos campos da tabela, provavelmente o que você selecionou boolean, ele criou como int, e o double deve estar como real.
Comment: @MatheusSaraiva Não dá para colocar um link direto, mas a frase está logo no início do item: `2.0 Type Affinity` :)
Comment: Opa, Diego.
Isso eu ja tinha visto. Minha pergunta é por que o [SQLiteStudio](http://sqlitestudio.pl/) permite criar colunas com esses tipos de dados se o SQLite não suporta.
[PRINTSCREEN](http://oi66.tinypic.com/2h68unr.jpg)
Comment: @MatheusSaraiva Na imagem da resposta, coluna do "meio", mostra o tipo de "afinidade" (`Affinity`) da coluna e se você consultar o link `SQLite - DataType` da resposta, lá explica o porquê: "aumentar a compatibilidade do SQLite com outros databases". Não é o SQLiteStudio quem "cria" esses tipos

SQLiteStudio tipos de dados


Composing Music- Interpretation

Question: When writing music, does one:

Let the musician interpret the music more (less dynamics, tempo markings, etc.), or
Let all musicians follow the same general interpretation (more dynamics, tempo markings, etc.)?

That is:
When I write music, writing using music software tends to become tedious.
I don't want to have to put markings everywhere to tell the musician to play exactly my way. However, if I don't put that many markings, no player will know the "real" way of playing my song.
This is my question. How do I write my songs then? Do I want musicians to play "my way", or their own way more?
Answer: I think this depends purely on you. If you want to write a song that you want to be played the way you hear it in your head, you have to add markings; otherwise, you can let the musicians play it the way they feel.
The latter would be really difficult in an orchestra; this is why the orchestra scores usually have a lot of markings, whilst the small ones can be more 'free'.
When I write music, usually I add a few markings as pointers, and leave the rest up to the musicians.
Comment: So your way is to let the musician interpret it more?
Comment: yes,unless I want a specific part to be played my way
Answer: Your score should ideally contain all of the information necessary for a professional musician to sightread the piece properly on the first try. By "properly," we just mean that they understand the basic techniques they need to execute to convey the idea of what you want. If you don't care what they do, then don't include markings! And to the contrary, there is always room for more nuanced interpretation with further rehearsal time. A crescendo means get louder, but doesn't necessarily say how loud or at what rate. A conductor can help communicate this (even when sightreading), as can feedback from the composer.
So to expand on the first point, your score is communication with the musicians. It tells them what they need to know. If you're writing a jazz chart, the musicians will automatically interpret certain rhythmic gestures with certain articulations -- this is true for any idiomatic music that fits into a well-known style. When you're making use of an idiomatic musical gesture, you may not need to include all the markings for a literal interpretation, but you should include markings that the musicians would expect to see, based on the rest of the published repertoire in the idiom.
In contrast, many composers are expressly focused on crafting a new style that doesn't fit into any existing idioms. This often means more ink on the score is used for markings than it is for noteheads! But if you find your digital entry of interpretive marks to be tedious, I would suggest that you may be missing some software usage patterns that could make your job easier. You shouldn't need to duplicate your efforts for music that is marked the same way in multiple staffs or multiple places--whenever I find myself doing this in Sibelius, I go looking for a shortcut or plugin, since something usually exists that I've been missing. (And if it's still bugging you, once you get rich and famous you can hire someone to typeset your scores for you!)
Comment: Basically, you're saying that new styles need more markings than others?
Comment: I'm saying that when you're doing something brand new, you need to effectively communicate that, so typically this will result in more markings. Unless, of course, the "new music" you produce is based on drones, or is chance music, or uses an alternate system of notation, or isn't notated at all!
Comment: This answer gives a more general answer than just a "do this" or "do that", which is the reason why I like it. However, when doing something brand-new, I'm assuming that one does not put too many markings to limit the musician's interpretation, but put enough so that it can be played correctly. Is that correct?
Comment: Well there's a funny thing that happens when the composer is still alive -- you can ask them how they want their piece to be played! The idea of "interpretation" largely comes from playing the music of dead people and _trying_ to figure out what they meant. The living composers I know have a crystal-clear picture of what they want their music to sound like, and so they work with their conductor and musicians to get that across as accurately as possible. Including markings just makes that job easier, more efficient, and saves rehearsal time.
Comment: By the same token, _over_-marking a piece can just confuse the musicians and conductor, so we always come back to the point of effective communication.
Answer: I have found (and have been taught) to include a lot of dynamics, articulations, slurs and markings.  If your music fits stylistically into well established genres, it probably requires fewer markings in order to get a good interpretation.  Conversely, if your music is less conventional, then the more information you give to the performer about what you had in mind, the better.
I agree that adding all these markings to a score is tedious.  And it can be very difficult to envision the most musical way to play the piece before rehearsals begin.  But when the markings are absent, I find that musicians end up asking what I want and writing down what I say anyway.  So I'd say putting it all down to begin with makes more sense and definitely makes the score look more professional.
Comment: So your way is to let the musician follow the composer's interpretations more?
Comment: More-or-less, I find that having a lot of markings doesn't necessarily limit the musicians' expressive boundaries, but rather helps them to more expressive/musical.  I think it gives them *more* to work with, not *less*.  In the absence of markings they will typically ask "what's the dynamic at m. 33?", etc.  It's as if they've been given an incomplete roadmap.
Comment: p.s.  It totally depends on what the music is, too.  Something simple for a soloist could just say "dolce" above it.  But complex ensemble passages should probably be marked-up or you'll spend all your rehearsal time deciding what should be short/long loud/soft and everyone will be writing it down in pencil on their part!

Composing Music- Interpretation


Write an equation that relates $\arg(z)$ to $\arg(1/z)$, $z\not = 0$

Question:
Write an equation that relates $\arg(z)$ to $\arg(1/z)$, $z\not = 0$.

I don't have a clear idea of how attack this type of exercise.
I know if $z=r(\cos\theta +i\sin\theta$) or equivalent to $z=x+iy$ then the $\arg(z)=\theta$ and we can calculate $\theta$ using the fact $\tan\theta=\frac{y}{x}\implies\theta=\tan^{-1}(\frac{y}{x})$ But, here I'm stuck. Can someone help me?
Answer: Write $z$ in the polar form as $z=re^{i\theta}$. Then $1/z=\frac{1}{r}e^{-i\theta}$. So $\arg(1/z)=-\arg(z)$.
Comment: Even for $z=-1$?
Comment: Yes, because $\arg(1/-1)=\arg(-1)=\pi=-\pi=-\arg(-1)$. The angles $\pi$ and $-\pi$ are equivalent. Although you do bring up a good point, which is that you may need to add or subtract $2\pi$ to get the argument in the usual range
Comment: Ah $\pi=-\pi$. You live and learn!
Answer: So if
$$z = r(\cos \theta + i \sin \theta)$$
what is the expression for $1/z$? You can use the usual trick for division by complex numbers: multiple numerator and denominator by the complex conjugate.
Now once you have an expression for $1/z$, you should be able to infer the correct angle.


How to set the spinner position to selected item from choice selected in different fragment

Question: Add color spinner
the update fragment
this is my first time asking a question and I am a new coder and been trying out android with kotlin and java. I have an app that allows a user to add an item of clothing the options are set up with spinners. The issue is when the user selects an item from the spinner it saves and when I want to update the values like the image shows the blue words saying brown is the option selected form the add clothing item spinner but the spinner is showing grey is there a way I can set the spinner to be on brown and not the default value.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Yes. You need to use the getItemAtPosition() method. From your user interface, the Object you are trying to retrieve is a String. So if you wrote your code in Java. Knowing you've used a TextView to display the selection
Java
<code>TextView clotheColor = findViewById(R.id.whatever_the_id_is);

String selectedColor = "";

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedColor = parent.getItemAtPosition(position).toString();
                Log.i(TAG, selectedColor);

                switch (selectedSpinnerItem) {
                    case "Brown":

                    case "Red":
                    case "Blue":
                        clotheColor.SetText(selectedColor);
                        break;
                    default:
                        Log.i(TAG, "");

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.i(TAG, "Nothing has been selected");
            }
        });
</code>
KOTLIN
You can convert the code to Kotlin from here. Read this.
How can I convert a part of Java source file to Kotlin?
Comment: okay thank you so will that set my spinner position to not be grey anymore and instead be the selected item in the new fragment
Comment: @johnsn Yes it will


Input value jQuery check length and value?

Question: I'm still stuck here when validating the value of the input. If the value is between 0.4 and 0.9 the input n2 will remove the read-only. On another hand where if value less than 0.4 or more than 0.9 it will show up modal dialog. My question here is to validate the value/length if the value key in by the user is not in decimal value? let say user insert value 1, then my jquery
won't firing out because my length is >=3.. if I put the length check > 1, then when user key the decimal value for example 0.5, the modal dialog
will pop out 3 times..  since my length value is >= 3.. if I remove the length checking, it will keep pop out the modal dialog whenever user key in value length that more than one.
My question is how to control such a situation if the valid range value is between 0.4 to 0.9, at the same time can checking value that not in decimal number as well? Is it possible?
<input type="text" class="form-control input-sm da" name="da" id="da" value="" autocomplete="off" />

Action
<input type="text" class="form-control input-sm cdaaction" name="cdaaction" id="cdaaction" value="" />

<input type="text" class="form-control input-sm n2" name="n2" id="n2" value="" autocomplete="off" readonly />

$(document).ready(function() {
            $(".da").keyup(function() {
            var dInput = $(this).val();

            if ($('.da').val().length >= 3)
            {
                if(dInput < 0.4 || dInput > 0.9)
                {
                    var mymodal = $('#mi-modal');
                    mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +'  ?');
                    mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
                    $("#mi-modal").modal('show');

                    $("#modal-btn-si").on("click", function(){
                    $("#mi-modal").modal('hide');
                    $('.actionDiv').show();
                    });

                    $("#modal-btn-no").on("click", function(){
                    $("#mi-modal").modal('hide');
                    $('.actionDiv').hide();
                    $("#da").focus();
                    });
                    $(".n2").attr('readonly', true);

                }
                else
                {
                    $(".n2").removeAttr("readonly");
                    $('.actionDiv').hide();
                }
            }

            });
        });

Comment: Do you inspect `dInput` to be a number? if so why not use `type="number"` on the input with the id `da`
Comment: actualy i got function that i not included here where that input only can key in numbering  `function isNumberKey(evt)
  {
   var charCode = (evt.which) ? evt.which : evt.keyCode;
   if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
   return false;

   return true;
  }` onkeypress="return isNumberKey(event)" at the input
Comment: @CarstenLøvboAndersen yes it allowed numbering only. the.i have own purpose to do so. actually at 1st attempt fill the input user might able to key in value within the range or not within range.. not wihin range means the value will be store as well.
Answer: Use parseFloat()
$(document).ready(function() {
        $(".da").keyup(function() {
        //var dInput = $(this).val();

        var val = parseFloat($(this).val());

            if (!isNaN(val) && (val < 0.4 || val > 0.9))
            //if(dInput < 0.4 || dInput > 0.9)
            {
                var mymodal = $('#mi-modal');
                mymodal.find('.modal-body').html('Is the value correct: '+ $('.da').val() +'  ?');
                mymodal.find('.modal-footer').html('<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button><button type="button" class="btn btn-primary" id="modal-btn-no">No</button>');
                $("#mi-modal").modal('show');

                $("#modal-btn-si").on("click", function(){
                $("#mi-modal").modal('hide');
                $('.actionDiv').show();
                });

                $("#modal-btn-no").on("click", function(){
                $("#mi-modal").modal('hide');
                $('.actionDiv').hide();
                $("#da").focus();
                });
                $(".n2").attr('readonly', true);

            }
            else
            {
                $(".n2").removeAttr("readonly");
                $('.actionDiv').hide();
            }
        }

        });
    });

Answer: You could consider triggering your code on blur(). When the user focusses out of the input box, you can check whether the inputted value is correct or not.
Furthermore, what Carsten said is true: Use type=number for your input and you won't need the check on the input length, just on the value.
Comment: the input have validation. 1st attempt if user input the value not within then range it will be able to be edited at the 2nd attempt where they able to edit. the purposse i disable the input so that the old input is remain there and the new input will be appear in the modal dialog and there user will key in the correct value in the modal dialog.


Coding repeated measures 2x2 ANOVA for aligned rank transformed data

Question: I'm using the following code to run a repeated measures 2x2 ANOVA after transforming my data using the art function from ARTool package for R using the following code:
m <- art(response ~ Factor1*Factor2 + Error(Subjects/(Factor1*Factor2)), data=myData)
and then
anova(m)
The art function performs alignment and ranking on the data. Does someone know if this is the correct way to account for repeated measures?
Answer: No, it is not the correct way,
according to the examples of the reference pdf the right way should be:
m <- art(response ~ Factor1*Factor2 + (1|Subjects), data=myData)

Just a hint, you also used the wrong line (/ instead of |)
Comment: The HigginsABC example on page 10 of the document you reference has an example with the `Error` notation, so it appears either notation is permissible.
Comment: The reference pdf says on page 4 that a repeated measures design should include an error term, "as in `y ~ a*b*c + Error(d)`," but to me it's not clear that the d in Error(d) is meant to be identical to the d in (1|d) recommended for mixed effect ANOVAs. I chose the error in the original post after reading this [link](https://www.r-bloggers.com/two-way-anova-with-repeated-measures/)


Solve the functional equation $f(x)f(1/x)=f(x+1/x)+1$, $f(1)=2$, where $f(x)$ is a polynomial.

Question: Solve the functional equation
$$f(x)f(1/x)=f(x+1/x)+1,\ f(1)=2,$$
where $f(x)$ is a polynomial.
It is easy to check that $f(x)=x+1$ is a solution. Are there any other solutions? My attempt is described as follows.
Since $f(x)$ is a polynomial, we can write it as $f(x)=\sum_{i=0}^n a_ix^i$, where $a_n\neq 0$. Substituting it into the functional equation, we have
$$
f(x)f(1/x)=\sum_{i=0}^n a_ix^i\sum_{j=0}^n a_jx^{-j}=\sum_{\ell=-n}^n \Bigg(\sum_{i=\max(0,\ell)}^{\min(n,n+\ell)} a_ia_{i-\ell}\Bigg) x^\ell $$
and
\begin{align}
f(x+1/x)+1&=\sum_{i=0}^n a_i(x+1/x)^i+1=\sum_{i=0}^n a_i\sum_{j=0}^i\binom{i}{j} x^{2j-i}+1\\
&=\sum_{\ell=-n}^n \Bigg(\sum_{\max(\ell,0)\leq j\leq \frac{n+\ell}{2}} a_{2j-\ell}\binom{2j-\ell}{j}\Bigg)x^{\ell}+1.
\end{align}
By comparing the coefficients of $x^\ell$ on both sides of the above two equations and noting that $f(1)=\sum_{i=0}^n a_i=2$, we can obtain a very complex system of equations of the coefficients $a_i$, $0\leq i\leq n$. For example, when $n=5$, the system of equations is of the form
\begin{align}
&a_0a_5=a_5,\\
&a_0a_4+a_1a_5=a_4,\\
&a_0a_3+a_1a_4+a_2a_5=a_3+5a_5,\\
&a_0a_2+a_1a_3+a_2a_4+a_3a_5=a_2+4a_4,\\
&a_0a_1+a_1a_2+a_2a_3+a_3a_4+a_4a_5=a_1+3a_3+10a_5,\\
&a_0^2+a_1^2+a_2^2+a_3^2+a_4^2+a_5^2=1+a_0+2a_2+6a_4,\\
&a_0+a_1+a_2+a_3+a_4+a_5=2.
\end{align}
Assuming that $a_5\neq 0$, it is not hard to show that the above system of equations has no solution. But for general case, I have no idea how to solve it or to show it has no solution. I wonder whether there is a clever approach which avoids this tedious computation?
Added. I would like to point out that the condition $f(1)=2$ imposes a strong restriction on the problem. For example, the polynomial $f(x)=1+(1-\sqrt{2})x^2$ satisfies the functional equation but does not satisfy the condition $f(1)=2$. It seems that this condition rules out many solutions.
Comment: Where did you find this problem?  Or did you create it?
Comment: Would it help to look at techniques for solving things like $f(x)f(y)=f(x+y)+1$ or $f(x)f(y)=f(x+y)+xy$? Your assumption is weaker (but implied by these when $y=1/x$), but maybe applying a technique for similar equations to your situation might yield ideas.
Comment: Just checked there is no other solution with real coefficients for $\deg f \leq 17$.
Comment: As far as I think, the predefined value for $f(1)$ is for us to consider a root of the polynomial rather than defining the polynomial fully, just let $a$ be a root and solve $1+1/x=a$ to get $x=\frac{1}{a-1}$so that $a$ is never $1$ and indeed it's given $1$ is not a zero of the polynomial.
Comment: We have $f(2)=3$.
Comment: @MichaelHoppe Yes, we have $f(2)=3$ by setting $x=1$ in the functional equation, but it seems to be hard to get the values of $f(x)$ at other numbers.
Comment: @Shamim I agree with you. The condition $f(1)=2$ seems to suggest us something. Should we solve $x+1/x=a$? as $1+1/x$ does not appear in the functional equation.
Comment: I am so sorry. I misread $x+1/x$ as $1+1/x$
Comment: Taking the derivative we have $f'(1)\cdot2+2\cdot f'(1)(-1)=f'(2)\cdot0$, i.e., $0=0$.
Comment: @XiangYu now the problem seems even harder, both sides are symmetric and thus manipulating will become harder, as I was expecting to do by considering a zero $a$ and defining $g(x)=f(x)+1$ and somehow showing $deg f=1$
Comment: Let $\deg(f)=n$, $a_n\neq0$ and $a_0$ are the leading coefficient and the constant term respectively. Then we get the polynomial identity $$X^nf(X)f(1/X)=X^nf(X+1/X)+X^n$$ comparing leading coefficients of both sides we get $$a_na_0=a_n$$ and hence $a_0=1$. This gives the important information that $0$ is not a root of $f$ with $f(0)=1$ and hence $f(X)\equiv Xh(X)+1$ for some polynomial $h$ with $\deg(h)=n-1$ and $h(1)=1$.
Comment: @ShubhrajitBhattacharya Actually, by comparing the coefficients of the term following the leading term, we have $a_0a_{n-1}+a_1a_n=a_{n-1}$. Since $a_0=1$ and $a_n\neq 0$, we get $a_1=0$. However, it seems that this technique is not sufficient to determine all the $a_i$.
Comment: We have
$$f(x) f(1/x) = f(x+1/x) + 1$$
$$\sum_0^n a_i x^i \sum_0^n a_i x^{-i} = \sum_0^n a_i(x+1/x)^i + 1 $$
Multiply with $x^n$ both sides
$$\sum_0^n a_i x^i \sum_0^n a_i x^{n-i} = \sum_0^n a_i (x^2+1)^i x^{n-i} + x^n $$
$$(a_nx^n + \cdots + a_0)(a_n + \cdots a_0x^n) = (a_n(x^2+1)^n + \cdots a_0 x^n ) + x^n$$
Sub $x=0$
$$a_0a_n = a_n \Rightarrow a_0 = 1 $$
Comment: $a_1=0$ does not support the fact that $f(X)=X+1$ is a valid solution if we take $n=1$.
Comment: @ShubhrajitBhattacharya I implicitly assumed that $n\geq 2$. When $n=1$, the equality should be $a_0 a_{n-1}+a_1a_n=a_{n-1}+1$ because now $2n-1=n$.
Comment: You are right, sorry:)
Comment: Looking at $\lim_{x\to0^+}$ of both sides informally gives $f(0)=1$ also, as $\lim_{x\to\infty}{f(x)\over f(x)+1}$ should be $1$.
Comment: Other factoids by looking at complex numbers: $f(x)\ge -1$ for $-2\le x\le 2$; $|f(i)|=\sqrt 2$; $|f(\frac12\pm i\frac{\sqrt 3}2)|=\sqrt3$
Comment: @BrianTung One of my students asked me this question in the class. I am not clear where it comes from.
Comment: an interesting problem definitely - there are polynomials with non-real coefficients that satisfy the functional equations already in degree $3$ and I think polynomials of any degree exist satisfying the functional equation (we have $a_0=1, a_1=0, a_2=n, n \ge 3$ for example and for low degree cases one can continue and get the next $a$'s - in degree $3$ already we have a quadratic for $a_3, a_3^2=-2$ and in degree $4$ various cases, however in all such I checked, the sum of the coefficients is far from $1$ so that condition is essential
Comment: One can let $a_3=-n+1-\sum_{j=4}^n a_k$ to force $f(1)=2$.
Comment: Furthermore $a_3=-a_{n-1}/a_n$.
Answer: Here is my solution that was found during an exam :
first let $Deg_p=n>2$ now let :
$$p(x)=\sum_{i=0}^n{a_ix^i}$$
so we have  :
$$p(x)p(\frac{1}{x})=\sum_{i=0}^n{a_ix^i}\sum_{i=0}^n{a_ix^{-i}}=1+\sum_{i=0}^n{a_i(x+\frac{1}{x})^i}$$
first we will look at the constant therm on the both side which is :
$$1+a_0=\sum_{i=0}^n{a_i^2}$$
now we will look at the term $x^n$ at both sides. which gives :
$$a_na_0=a_n$$
since $a_n$ can not be $0$ we must have $a_0=1$ , we rewrite the first condition as :
$$\sum_{i=1}^n{a_i^2}=1$$
now lets calculate the term $x^{n-1}$ on both side we have :
$$a_na_1+a_{n-1}=a_{n-1}$$
which gives $a_1=0$ now we look at the term $n-2$ :
$$a_na_2+a_{n-2}=na_n+a_{n-2}$$
so we have $a_2=n$ but this gives contradiction with the assumption that
$$\sum_{i=1}^n{a_i^2}=1 \ge a_2^2=n^2$$
so we have $n\le 2$ if $n=1$ then we clearly have
$p(1)=2,p(2)=3$ (from $x=1$) so we have $a_1+a_0=2,2a_1+a_0=3$ so $a_1=1,a_0=1$ and $p(x)=x+1$ which clearly works.
if $n=2$ remember we proved $a_1=0$ this also works for $n=2$ so we have
$$p(x)=ax^2+1$$
but since $p(1)=2$ we have $a=1$ bot the polynomial $p(x)=x^2+1$ doesn't work in the statement.
so we are done
Comment: I don't get it right: what do you mean by *constant term*?  That one containing no (trivial) power of $x$?  I agree, on the left hand side it's the sum of squares of the coefficients of $p$.  But on the right hand side some more terms will appear, namely in all $(x+1/x)^i$ where $i$ is even.  What am I missing?
Answer: Concerning the constant term
If the degree $n$ of $f$ is one, there's a unique solution satisfying the functional equation and $f(1)=2$.  For $n\in\{2,3\}$ several functions satisfy the functional equation but not $f(1)=2$.  From now on let $n\geq4$.
We already know that then $f$ has the form
$$f(x)=1+nx^2+\sum_{j=3}^n ajx^j.$$
The constant term of $f(x)f(1/x)$ is the sum of the squares of the coefficients of $f$.  The constant term of $f(x+1/x)$ arises when expanding $(x+1/x)^j$ for even $j$, that is
$$1+2n+\binom{4}{2}a_4+\binom{6}{3}a_6+\binom{8}{4}a_8+\cdots$$
Together with the functional equation we have
$$1^2+n^2+\sum_{j=3}^{n}a_j^{2}=1+2n+\binom{4}{2}a_4+\binom{6}{3}a_6+\binom{8}{4}a_8+\cdots+1.$$
You'll find functions satisfying this equation.  But the function must also satisfy $f(1)=2$, that is
$$1+n+\sum_{j=3}^{n}a_j=2\text{, that is }
\sum_{j=3}^{n}a_j=1-n.$$


Why can't my script find the files?

Question: I made a batch script that should echo the full path of all files with the .txt extension.
forfiles /m *.txt /c "echo @PATH"

When I run it, I get this error:
ERROR: The system cannot find the file specified.

What is the cause of this?
Comment: Could it just be that there are no `.txt` files in that directory?
Answer: Try this:
forfiles /m *.txt /c "cmd /c echo @PATH"

The problem is that echo is not a program in itself, but is a built-in command of the cmd program. So you have to execute cmd to use echo.

Why can't my script find the files?


Good metric to distinguish between fat tailed and narrow distribution

Question: Could anyone point me to a good metric to distinguish between the following distributions? One distribution seems to be exponential type whereas the other is fatter and sometimes also has a peak around 16Hz.
Type 1

Type 2

Given an unlabelled distribution, how to classify it as type 1 or type 2?
Comment: The main distinction I see between the two collections is that the first lot all look unimodal and the second lot all seem to have at least two modes, and often more. You might want to consider whether that's what you really need to identify.
Answer: It is unlikely that your histograms are going to be very helpful here.  To diagnose whether a distribution has "fat tails" you would usually construct a tail plot (see this related answer).  If you want to reduce that to a single metric then I would suggest conducting a weighted regression on the tails to estimate whether the tail behaviour is consistent with a power law, and if so, estimate the rate parameter in the power law.  Anything less than cubic decay indicates a "heavy tailed" distribution in the sense of having an infinite variance.
Answer: My eye says that Type 1 distribution has higher kurtosis (it seems more peaked while Type 2 more flat) and smaller variance. Maybe from just these values combined with the mode/mean/median you could determine the distribution type, but the other central moments could also be informative. I would recommend you to grow a decision tree using these as features and possibly than try other combinations of central moments and mode/mean/median as explanatory variables and see what works.


Is there anything like BizSpark for non software startups?

Question: I'm trying to figure out how to build a decent IT infrastructure for a new business on a budget and I was wondering if anyone has any tips or ideas on how to build a Windows IT infrastructure cheaply in a new business. I know for software startups there is BizSpark which basically gives the business keys to the kingdom, but I haven't found anything like that for traditional companies.
Answer: Look into Small Business Server 2008 (SBS 2008).  It gives you a ton of Microsoft software for very little startup costs including Exchange, SQL Server, ISA, etc.  It also allows you to run Windows Server on three servers (a lot more if you use Hyper-V to virtualize).
Answer: If you want to build IT infrastructure on a budget the first thing to do is to think long and hard about whether you really need Windows or not, and there are two parts to that question:

Do you need Windows on the servers?

are there any specialised windows-only services that you need to run, or do you just need the usual services like file & print sharing, tape backup, internet gateway/firewall, web server or web proxy, email, sql database, etc?
you can save yourself thousands of dollars per server by using linux (or freebsd or even opensolaris) based servers rather than windows.

Do you need Windows on the desktops?

are there any windows-only apps that your users will need, or do you just need the usual word-processing, spreadsheets, database, email and web browsing?  and if you only need one or two windows-only apps, will they run on Linux under Wine?
you can save yourself hundreds of dollars per machine by using a desktop-oriented linux distribution like Ubuntu.
or if only a few staff members need to use a windows-only app, you could still standardise on Ubuntu desktops and use VirtualBox to install Windows on their machines - greatly reducing the number of Windows and application licenses you have to buy.
Comment: How do you save hundreds of dollars per machine by using Linux over Windows?  When Windows is included with a PC purchase and you request a refund you usually get back $40-50 US.  The retail cost of Windows is not the same as using the OEM license that most people use.
Comment: i just read your other question - Solidworks wont run under Wine...but it would run under Virtualbox.  With careful choice of hardware (i.e. nvidia graphics cards), it can run with full 3d graphics capabilities and only 1-2% performance drop (not noticable by users - people just don't notice performance gains or losses of less than about 10%).  you wouldn't save as much money, though, if every desktop user needed Solidworks - you'd still need a Windows license for each workstation, so you'd only save on the other apps.
Comment: @mrdenny: Windows license + MS Office License + virus scanner license + licenses for other apps that have a free linux equivalent + licenses for various third-party utilities that just aren't needed or are included free with linux & linux apps (e.g. good PDF output drivers)
Answer: Also: If you're an IT company, you can join the Microsoft Partner Program and I think their Action Pack contains a bunch of licenses to everything you need for $300/yr.
Comment: That's a good option as well.  Not all the server's come with CALs though, so be careful on this one (also on the SBS option as well).  But if you can live within the limits of the action pack (we've used it to augment our other software we've paid for) the action pack is great.
Comment: Yep. You really can't beat the price. For most purposes, it's a great starting server environment in a box, and you can use the Open License program for the rest.


Why cant i see the string?

Question: I know this code is sloppy, but I'm wondering why when I'm using the ReadProcessMemory() function I can't see the string stored in the relevant address.
    //If the game window is open then this function grabs the process ID.
if(FinderCheck)
{
    DWORD procID;

    GetWindowThreadProcessId(hwnd, &procID);

    //All so access you can read and write to process memory.
    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,procID);

    if(procID = NULL)
    {
        cout << "Error: Failed to Obtain Process ID" << endl;
    }
    else
    {
        while(true)
        {

        //To read the process memory this line writes the memory data to buffer
        //Remember to change the address every time you boot the process or it will not work.
        ReadProcessMemory(handle, (PBYTE*)0xDC8F1AA904,&Cursor,sizeof(Cursor),0);
        cout << Cursor << endl;
        cout << "Test" << endl;

        Sleep(500);
        }
    }

Comment: I understand this is probably really sloppy code. I'm open to suggestions for improvements.
Comment: first suggestion: your paragraph is a wall of text. It's really tiresome to read. You should improve on that first.
Comment: After you fix the typo pointed out below, add error checking to all of the Windows functions you call. Right now if it doesn't work you'll have no idea why. You may also have more success asking for the actual permissions you need rather than PROCESS_ALL_ACCESS.
Comment: Turn on your compiler's warnings.  It would have caught the mistake that arorias pointed out.
Answer:     if(procID = NULL)

Sadly, this if statement will always evaluate to false, you are missing the second "=". This also means that from this point procID is NULL.
What about the rest of the code? Can you show us how the definition of the Cursor looks like and how do you implemented operator<<?
Comment: Hi. Welcome to SO. In the answer should really go just that: a answer. Requesting clarifications go in the comments. When you will have enough rep you will be able to post comments.

Why cant i see the string?


Is there any difference between racing driver and formula 1 driver?

Question: I want to know if is there any difference between a racing car driver and a formula one driver?
Have a look at the 2 images I have attached, both from Google.
Against the name of Massa there is formula 1 driver is written whereas racing driver is shown against Jules Bianchi.
So this was my doubt as if there is any difference between formula one driver or racing driver?
Comment: Could you define what you mean by "racing car driver"?
Comment: What are you even asking? There is difference between every Formula One drive. As a matter of fact between every human being. If you are asking whats the difference between Formula One "driving" & other race car "driving" than thats a different matter
Comment: Voting to close as unclear until some clarification is supplied.
Comment: The edit helps, but this is still off-topic as you're asking "What algorithm does Google use to determine the tag line for a person?" and that's nothing to do with sports per se.
Comment: I'm voting to close this question as off-topic because it is about Google's algorithms.
Answer: Those details from google are literally a collection of information that it pulls from various websites in which a user adds the information to describe them.
Example: Angelo is a gun-owner. The gun he owns is a .238 Summerfield Winchester. One site might put him as a "Gun-owner". This is equivalent of "racing driver". The other one might put him as a ".238 Summerfield Winchester" owner. This is the equivalent of "Formula 1 driver".


How do I programatically generate multiple "add to cart" forms on product display?

Question: I've got a matrix of 12 products, which can be added to the cart by users after selecting different term reference fields, which then select the appropriate product. This is shown on a product display.
However, I'd like to have multiple add-to-cart forms, each with a different line item selected on the product display field.
Basically, I've got a field collection, and I'd like to iterate through each of the field collection entities and display an add to cart form, with my full 12-product matrix of options, for each of these field collection items.
It would seem that I could get the add to cart field, all formatted, using
field_default_view($entity_type, $entity, $field, $instance, $langcode, $items, $display)

But I am currently on the node.tpl.php file, and I can't quite work out which entity objects are which to pass to this function. Nothing really resembles what I'm seeing passed to commerce_cart_field_formatter_view.
Am I thinking about this wrong? Is there a better way to accomplish this?
Answer: I implemented this through patching Commerce Add to Cart Extras. My patch can be found here: https://www.drupal.org/node/1836200
In brief, the line item type contains a reference to an entity, a field collection item, actually.
I used views to generate a list of products with an add to cart form using Commerce Add to Cart Extras, joining (by a views relationship) on my field tables that provide the reference which must be attached to the line item.
Next, I had to alter Commerce Add to Cart extras so that the views result containing my entity id which must be added to the line item will copy that id over to the line item when the line item is created.
In the end, I have a list of multiple instances of the same product with a quantity field and a single add to cart button. Each product has the entity which must be added to the line item. When one of those products is added to the cart, the entity id gets copied over to the line item.


Enviar select para impressão com php

Question: Preciso criar dinamicamente um tabela com "n" linhas e depois mandar essa tabela para impressão, mas não obtendo sucesso, a construção da tabela está assim:
    // laço para buscar e-mail e efetuar envio
foreach($checkboxes as $id) {

    // deletando registro do candidato
    mysql_select_db($database_conCurriculo, $conCurriculo);
    $query_rsRegistro = "SELECT * FROM candidato WHERE id_candidato = $id ";
    $rsRegistro = mysql_query($query_rsRegistro, $conCurriculo) or die(mysql_error());
    $row_rsRegistro = mysql_fetch_assoc($rsRegistro);
    $totalRows_rsRegistro = mysql_num_rows($rsRegistro);
    $status = $rsRegistro;

   $impressao =  "

            {$row_rsRegistro['nome']}
            implode('-', array_reverse(explode('-', {$row_rsRegistro['dt_nascimento']})));
            implode('-', array_reverse(explode('-',{$row_rsRegistro['dt_atualizacao']})));>
            {$row_rsRegistro['endereco']}; ?>
            {$row_rsRegistro['id_municipio']}; ?>
            {$row_rsRegistro['id_uf']}; ?>

";

} // fim do foreach

Como posso monta-la e mandar para impressão?
Comment: Como você pretende imprimir? A tabela é exibida em HTML e impressa? Você pretende gerar um PDF direto do PHP?
Comment: O que estou pretendendo fazer é gerar o html e enviar para impressão, como uma listagen.
Answer: Eu uso while para gerar o select dinamicamente, espero que o exemplo abaixo te ajude:
<?php
$select = pg_query($conexao, $sql->menu_logado($entidade));

echo "<select name=\"codseg\" onChange=\"document.forms['segmentos'].submit();\">";

echo "<option>SELECIONE</option>";

echo "<option value=''>TODOS</option>";

while ($segmento = pg_fetch_array($select)) {

    $cod = $segmento['segcodseg'];

    $descricao = str_replace("/", " / ", $segmento['segdesseg']);

    $c = '';

    if ($selecionado == $cod) {

        $c = ' SELECTED';

    }

    echo "<option value='".$cod."' $c>".$descricao."</option>";

}

echo "</select>";

Comment: Obrigado pelo script @Gustavo Emmel

Enviar select para impressão com php


Largest eigenvalue of the adjacency matrix of a graph

Question: Let $G$ be a connected graph with $n$ vertices and $m$ edges. Assume that $\lambda_1$ is the largest eigenvalue of adjacency matrix of $G$. I know that $\lambda_1\geq 2m/n$ with equality holding if and only if $G$ is a regular graph, but I cannot prove it. Could you please help me to prove it?
Comment: Hi mina. The site's guidelines require questions to contain some *context*, meaning some thoughts of your own to show that you've thought about the problem for yourself. Please edit your question with your thoughts on the problem, or the question may be down-voted and closed.
Comment: For example, could you show that if $G$ is a regular graph, then $2m/n$ is an eigenvalue of the adjacency matrix? Also, are you familiar with the [Gershgorin Circle Theorem](https://en.wikipedia.org/wiki/Gershgorin_circle_theorem)?
Comment: You may find some material on graphs looking for Erdös material. I would ask myself what does regular graphs are. I do not really know. :-P
Comment: Also, "I know but cannot prove" sounds like contradicting itself
Answer: HINT:
Let $A$ be the adjacency matrix matrix of the graph, $\lambda_1$ its largest eigenvalue. Then $\lambda_1 I - A$ is positive semi-definite. Now
the sum of entries of a positive semi-definite matrix is $\ge 0$. We conclude that
$$n \lambda_1 - 2 m \ge 0$$
Note that the sum of entries of $\lambda_1 I - A$ equals
$$\langle (\lambda_1 I - A) v , v\rangle$$
where $v = (1,\ldots, 1)$. If we have equality, $v$ must be in the kernel of $\lambda_1 I - A$.
Comment: I don't understand why your hint is useful. You basically say that $v = (1, \ldots ,1)$ is an eigenvector associated with $\lambda_1$, but how can we conclude that there are no other eigenvectors associated with $\lambda_1$ that are linearly independent with $v$?


sort objects in array with dynamic keys

Question: I am trying to sort an array of dynamic key / values (Object) based on a property in the object. Can someone please provide me an example of how to do this. Ill try to create a similar structure to my issue
Order Class:
export class order {
  id: number;
  productRank: number;
  productId: number;
  productName: string;
}

There is a storeOrders observable array of orders in my component
storeOrders$: Observable<Array<orders>>;

The key in the orders array is dynamically generated and is stored with the key/value containing  as key and order object as value
then the orders object for example is something like:
 let orders = {
12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt'},
23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne'},
67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }
 }

When i subscribe to this data, how can I iterate over the storeOrders array and sort items based on the productRank. I have been trying to get this right but was not able to get this working, can someone please point out how to iterate over dynamic keys in an array and do a sort based on a property in the value object? Thank you, your helps really appreciated!
Comment: your orders array is wrong. Simple you can't have key value pair in an array
Comment: @PratapA.K is right, are you sure `orders` isn't an object?
Answer: Your orders should be a object as below,
orders = {
    12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt' },
    23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne' },
    67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }
  };

you can form the values by using Object.values(orders)
I use sortBy from lodash library as I'm used to it and you get the sorted values as
console.log(sortBy(Object.values(orders),['productRank']));

Stackblitz
Comment: Using loadash is really not that useful here. Just `ordersValues = Object.values(orders); ordersValues.sort((o2, o1) => o2.productRank - o1.productRank);` should work out of the box.
Comment: @Jeto yes. I mentioned I'm used to `lodash` ! even array sort function should also work as you mentioned
Comment: @Aravind thanks for your help, I was struggling with this for a minute, esp iterating the dynamic keys was throwing me off
Answer: to order a dynamic array of keys/values you can do this :
example of array :
arr = [
{de : 'germany'},
{fr : 'france'},
{uk : 'united kingdom'},
{tn : 'tunisia'}
]

arr.sort((a, b) => {

      const a_key = Object.keys(a);
      const a_value = a[a_key];
      const b_key = Object.keys(b);
      const b_value = b[b_key];

      if (a_value == b_value) return 0;
      return a_value > b_value ? 1 : -1;
    });

that's all !

sort objects in array with dynamic keys


PRAW: How to mark_as_read() with just the message ID?

Question: I just have a list of messages IDs that I need to mark_as_read(), I don't need the message contents, just mark it as read.
Is it possible to mark them as read without fetching them first?
Answer: Super late reply, sorry. In case you are still looking, here you go:
You should be able to create a new instance of a message object. Like so:
import praw
reddit = praw.Reddit('Bot-name')
msgIDs = ['id1','id2','id3']
for id in msgIDs:
    temp = reddit.message('id')
    mark_as_read(temp)

If you have any further questions feel free to ask.


Report Builder 3.0 Cannot Connect to an HTTPS Hosted Report Server

Question: So we have a 2012 R2 SSRS server (a couple actually). We go to disable HTTP access on the Report Manager and Web Service URL. Everything is dandy until we try to open Report Builder and connect to the report server at https://server.domain.com/ReportServer. Its a no-go. We re-enable http on just the Web Service URL and then can connect to http://server.domain.com/ReportServer via Report Builder.
Our friend Google does not seem to know the answer. Hoping someone smarter might? Error message below.

I can confirm the server is up, the URL is correct (the https URL), and I have permission. Simply changing the https to http will allow the connection.
I have also reviewed the report server logs and found nothing of interest as it relates to this issue.
EDIT: We are in native mode.
Comment: I did find an answer, yes. There is a registry setting SchUseStrongCrypto that needs to be set for .Net. I'll post an answer soon (when I am at a computer again).
Answer: I figured this out after finding a laptop that Report Builder worked on and comparing against my machine where it didn't work. Digging through the registry and with the help of Google I finally found the following fix. A quick update to the registry, a reboot, and everything is working.
I imagine this is occurring because Report Builder was built on an older version of .NET that doesn't look for TLS 1.2 by default. So the registry entry tells .NET to give TLS 1.2 a try (I am sure it is more technical that that...).
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Comment: You good sir are a prince among men. Thought to myself it had to be 2.0 old as it was and was going to give up till you said it worked against 4.0
Comment: Glad I could be of assistance!


Two fields unique

Question: I have two fields in my model,
number and series, What I want is that these fields are not repeated among the other records, example R1: Series: A and number: 1, which does not allow these two records to be repeated in the future if it already exists
Comment: If a record would be created that duplicates those fields, what do you want to happen instead?
Comment: Hello, welcome! I think you'll get better answers if you post a [mcve].
Comment: I wish I could catch the error, stop the insertion and be able to show something in the template
Answer: Sounds like you want unique_together
Here is an example of what that model might look like:
<code>class Item(models.Model):
    series = models.CharField(max_length=5)
    number = models.IntegerField()

    class Meta(object):
        unique_together = "series", "number"
</code>

Two fields unique


What's the accepted way to add different prices to commerce products?

Question: The standard model for an e-commerce system is to have an RRP price and sale price (and when relevant a cost price).
I know there are product pricing rules to apply discounts, but this is a pretty un-intuitive solution as it requires the adding of a new rule for every single product that needs a discount.
Plus 'discount' isn't the right way to look at this particular situation conceptually in my opinion. I don't want the users to have to work out what the discount should be when all they want is to set a static 'special offer' price. It also doesn't make sense to refer to the cost price as a discount of any kind.
What I'd like to have is 2/3 (or as many as I want to be honest) different price fields on the product to represent the different prices. The system would then obviously display the correct price at the correct time based on some sort of rule.
I know I can just add new fields to the product bundle but their relationship to the overall price of the product will obviously not exist until "something" happens.
This seems like a pretty standard use case...has anyone come up with a good solution? Code and UI solutions both welcome.
Comment: I think your idea with custom product field is good. You can add "Special price" field and add Product Pricing Rule to set price to that field (if field is not empty).
Comment: just thinking out loud, so you want a field_collection of prices (where the colletion is like {a_price, type_of_price (an enumeration, taxonomy: rrp, cost, sale, etc)}. Then maybe you could create a Relation for your products, Product_Has_Realtime_Pricing_Type that lets you toggle per-product or with say VBO N kinds of products a value for Product_has_realtime_pricing_type that is a DELTA into the field_collection of prices ..... just some thoughts ...
Comment: @kalabro Thanks I didn't know it could be that easy, I'll give that a try
Comment: @tenken That sounds like it'd work but it might be a bit more complicated than I was hoping for. I'll give it a go though, cheers for the idea
Comment: @Clive So I will add an answer :)
Answer: As mentioned you can add new field to your product type:

Next enable commerce_product_pricing_ui module or just add new Rule on event "Calculating the sell price of a product". Rule looks like this (full size):

You can control the order of Product Pricing rules by Rules weight.
But I prefer to create field "Old price" (or "Common price") and to add simple description:

If you want to create special offer for this product, please, place new price in the Price field and move crossed out price to "Old price" field.

So, "Old price" is only for theming. It works for small commerce sites and I don't need any crazy Rules.
Comment: I went with the Rules method (it'll sit better with this particular client), thanks a lot for going into so much detail this helped a lot


fable: list of models to model function

Question: With fable I can do:
require(fable)
it <-  tsibbledata::global_economy %>%    filter(Country == "Italy")
fm <-  model(.data = it, ARIMA(log(GDP) ~ Population), ETS(log(GDP)))

I would like to be able to build the model list prior passing it to model(), something like:
mod_list <- list2(m1 = ARIMA(log(GDP) ~ Population), m2 = ETS(log(GDP)))
fm <- model(.data = it, mod_list)

I could not find a way of achieving this.
Any suggestions?
Something like:
map(mod_list, model, .data = it)

could be a starting point but not exactly what I would like to achieve
Thanks in advance for any help
Comment: If there were some data to work with and some `library` calls to load all needed packages then tested code might be forthcoming.
Answer: One method is to use purrr::imap.
purrr::imap(mod_list, ~fabletools(it, !!.y:= .x))

This will return a list of tsibble::mable objects. You can then use purrr::reduce and dplyr::left_join to reduce the the objects into a single mable by joining on the keyed variable in your tsibble which is presumably the variable Country.
purrr::imap(mod_list, ~fabletools(it, !!.y:= .x)) %>%
    purrr::reduce(dplyr::left_join, by = "Country")

The double exclamation mark is used to unquote .y (otherwise it would not pass the name from the list) and the := is required to name the variable when programming with tidyverse.
For further info see What is the R assignment operator := for? and ??imap in the R help pages.
Comment: More efficient code:
it %>% fable tools::model(!!!purrr:map(.x = mod_list, .f = function(x) x))
https://community.rstudio.com/t/list-of-models-to-model-function/63191/4

fable: list of models to model function


EntityFramework 5.0 with CastleWindsor

Question: As EF 5.0 is already having UnitOfWork pattern implemented so I want to it instead of creating my own IUnitOfWork classes for maintaining transactions. But most of the examples I found on internet are using Separate UnitOfWork instead of EF directly.
I'm trying to implement this using IoC (castle windsor). Could you please provide some samples or direction on implementing this.
Thanks in advance
Sai
Answer: You didn't provide any details about your current Windsor setup or what UoW looks like in EF5 (I don't use it), but based on this [1] it appears they have an IUnitOfWork interface implemented on their db context class.  So this appears to be pretty straightforward to leverage in a dependency injection pattern driven by Windsor.  You'll first want to register the IUnitOfWork interface and implementation with the container.  There's a variety of ways to register components in Windsor.  I prefer installers [2]... so you'll end up with something like this:
public class YourInstaller : IWindsorInstaller
{
   public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      container.Register(Component.For<IUnitOfWork>().ImplementedBy<YourDbContext>());
   }
}

Then you have this injected into your application's services in some fashion such as:
public class YourService
{
    public YourService(IUnitOfWork uow)
    {
       // rock out
    }
}

[1] http://dumians.wordpress.com/2013/04/13/how-to-use-repository-and-unit-of-work-patterns-with-entity-framework/
[2] http://docs.castleproject.org/Default.aspx?Page=Installers&NS=Windsor&AspxAutoDetectCookieSupport=1
Comment: Thanks Kellyb, I have a backend SQL Server, so If I do the container.Register with IUnitOfwork for my dbContext will it work? BTW I will be following Database first approach.

EntityFramework 5.0 with CastleWindsor


knockout Validation: Any option to apply the errorElementClass to parent of input?

Question: Does the Knockout validation plugin have any option to apply the error class to the parent or parent's-parent of the input in error?  If not can anybody suggest an approach to modify knockout validation to do this?
Please see the following fiddle for an example of what I'm trying to achieve.  Out of the box knockout validation sets the class of the input, but I want it to instead set the class of the containing control-group:
http://jsfiddle.net/fbA4m/1/
View

Clear the field and tab out of it to "see" the current behaviour - error class is added directly to the input by knockout validation. But I want to add class "error" to control-group containing the input instead of directly to the input.

Field

<input type="text" data-bind="value: testField" class="">

    <button data-bind="click: setErrorOnControlGroup">Click to see desired effect</button>

Javascript
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    decorateElement: true,
    errorClass: 'error',
    insertMessages: false,
    parseInputAttributes: true,
    messageTemplate: null
});

var viewModel = {
    testField: ko.observable("123").extend({required: true}),
    setErrorOnControlGroup: function() {
        $("input.error").removeClass("error");
        $(".control-group").addClass("error");
    }
};

ko.applyBindings(viewModel);

Stylesheet (Illustrative only - I shouldn't need this because I want to the use the twitter bootstrap styles)
/*NOTE: This is not actually the style I want, it just illustrates the default behaviour of knockout validation*/
input.error {
    background-color: #aaffaa;
}

I ask because I'm using twitter bootstrap styling and it uses the input's parent control-group element to style "error" inputs.
Comment: Can you put together a small working example, which shows what you are trying achieve?
Comment: Alright I'll see if I can put together a fiddle for it.
Comment: jsfiddle and "sample" code added
Answer: I tweaked mutex's fiddle to achieve the effect.   http://jsfiddle.net/3vGVC/9/.  There's room for improvement though, perhaps so that one could specify the css class to apply. Here's the bindingHandler, which can be applied to the container.
ko.bindingHandlers.validationElement = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var valueIsValid = valueAccessor().isValid();
    if(!valueIsValid) {
        $(element).addClass("error");
    }
    else {
        $(element).removeClass("error");
    }
}

}
Answer: You could write your own binding.
Have a look at the source of the validationElement binding in knockout-validation's source.
Comment: Did you do that? care to share the code if you did? - I need to do exactly the same.


Getting Screen width and height in Android

Question: I am using this code to get my screen width and height and send my button to a random position on the screen but sometimes my button is completely off-screen. I don't believe that the resolution my code gets me is the true res.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float height = displayMetrics.heightPixels;
float width = displayMetrics.widthPixels;

float maxX = width;
float maxY = height;
float minX = width/10;
float minY = height/15;

Random rand = new Random();

float finalX = rand.nextFloat() * abs(maxX - minX);
float finalY = rand.nextFloat() * abs(maxY - minY);

_height.setText("Current Y: " + String.valueOf(finalY));
_width.setText("Current X: " + String.valueOf(finalX));
max_height.setText("Max height: " + String.valueOf(height));
max_width.setText("Max width: " + String.valueOf(width));
btnClick.setX(finalX);
btnClick.setY(finalY);
btnClick.setVisibility(View.VISIBLE);

Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
app:layout_constraintRight_toRightOf="@+id/width"
tools:context="com.jamblatech.clicker.MainActivity"
tools:layout_editor_absoluteY="81dp">

<Button
    android:id="@+id/buttonEnd"
    android:layout_width="363dp"
    android:layout_height="572dp"
    android:background="@android:color/transparent"
    android:onClick=""
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

<TextView
    android:id="@+id/textViewCount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/zero"
    android:textColor="@color/colorAccent"
    android:textSize="36sp"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.03" />

<TextView
    android:id="@+id/timerView"
    android:layout_width="185dp"
    android:layout_height="41dp"
    android:text="@string/zero"
    android:textAlignment="center"
    android:textSize="24sp"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.937" />

<Button
    android:id="@+id/buttonClick"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginTop="200dp"
    android:background="@drawable/clickbutton"
    android:text="@string/Click"
    android:textSize="24sp"
    android:visibility="invisible"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textViewCount" />

<Button
    android:id="@+id/buttonReplay"
    android:layout_width="221dp"
    android:layout_height="103dp"
    android:text="@string/Replay"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.503"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/buttonBack"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Back"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.674" />

<TextView
    android:id="@+id/highScore"
    android:layout_width="261dp"
    android:layout_height="107dp"
    android:textAlignment="center"
    android:textColor="@android:color/holo_purple"
    android:textSize="30sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.149" />

<TextView
    android:id="@+id/height"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Test"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.029" />

<TextView
    android:id="@+id/width"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Test"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

<TextView
    android:id="@+id/maxheight"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Test"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.06" />

<TextView
    android:id="@+id/maxwidth"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Test"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.09" />

<TextView
    android:id="@+id/testTExt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Test"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

<TextView
    android:id="@+id/startTimerText"
    android:layout_width="134dp"
    android:layout_height="95dp"
    android:text="@string/Test_number"
    android:textAlignment="center"
    android:textColor="@android:color/holo_green_dark"
    android:textSize="60sp"
    android:visibility="visible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.54" />
    </android.support.constraint.ConstraintLayout>

Here are 2 pictures displaying my problem:

Button slightly on-screen:

Button completely off-screen:
Comment: Can you share your xml file also?
Comment: Don't replace ConstraintLayout, simply learn how to use it. The problem you're having is unrelated. You need to translate the button in the layout by modifying the layout parameters.
Comment: I have added the XML :)
Comment: Try replacing the ConstraintLayout with a RelativeLayout
Answer: What you can do is:
you already have randomly generated x and y,
 x + button.getWidth() to it and check if it is less than screen width if yes your x is well in bound if no regerenate your random x and y, similary if x is in bound do it for y and check y + button.getHeight() is less than screen height it will do.


Starting activities on tab click

Question: I have 3 tabs which show different content on click. I want them to open certain activities on click. These activities are nothing but database reports which just need to be displayed. I used web view and works fine on emulator with API level 11 but gives an error saying Web page not found on my device which is API level 10. Also, The tabs display data only after clicking on other tabs and coming back to the first.
Is there a way I can start the activities directly instead of using web view?
Any help is appreciated.
xml:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <TabHost
       android:id="@+id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/linearLayout1"
        android:orientation="vertical"
        >
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" ></TabWidget>
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/tabs1"
            android:orientation="vertical"
            >
            <WebView
                android:id="@+id/txtGetFuelInfo"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Get info from Database" />
                <TextView
android:id="@+id/txtGetFuel"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"/>
        </LinearLayout>
        <LinearLayout
              android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/tabs2"
            android:orientation="vertical"
            >

          <WebView
                android:id="@+id/txtMainGetInfo"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Get info from Database"/>
<TextView
                android:id="@+id/txtGetMain"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"/>

        </LinearLayout>

        <LinearLayout
             android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/tabs3"
            android:orientation="vertical"
            >
            <WebView
                android:id="@+id/txtSpareGetInfo"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Get info from Database"/>
<TextView
android:id="@+id/txtGetspare"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"/>

        </LinearLayout>
    </FrameLayout>
    </LinearLayout>
   </TabHost>
</LinearLayout>

Class :
public class DetailsTabs extends Activity
{
    TabSpec tspec;
    FuelStoredInfo  fuelInfo;
    WebView fuelView,mainView,sparesView;
    TextView tvFuel, tvMain, tvSpares;
    WebSettings fuelSetting, mainSetting, spareSetting;
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detailstabs);

        fuelView = (WebView)findViewById(R.id.txtGetFuelInfo);
        mainView = (WebView)findViewById(R.id.txtMainGetInfo);
        sparesView = (WebView)findViewById(R.id.txtSpareGetInfo);

        //tvFuel = (TextView)findViewById(R.id.totalFuelId);
        //tvMain = (TextView)findViewById(R.id.totalmainId);
        //tvSpares = (TextView)findViewById(R.id.totalspareId);

        fuelInfo = new FuelStoredInfo(this);
        fuelInfo.open();

        TabHost th = (TabHost)findViewById(R.id.tabhost);
        th.setup();

        // Fuel Expense tab
        tspec = th.newTabSpec("Tag 1");

        tspec.setContent(R.id.tabs1);
        tspec.setIndicator("Fuel"+"\n"+"Expense");
        String Data = fuelInfo.getData();
           double fuelTotal  =fuelInfo.getTotalFuel();
        fuelSetting = fuelView.getSettings();
        fuelSetting.setDefaultFontSize(10);
        //tvFuel.setText("Total fuel expense : Rs. "+ String.valueOf(fuelTotal));
        fuelView.loadData(Data,"text/html",null);
        th.addTab(tspec);

        //Maintenance Expense tab
        tspec = th.newTabSpec("Tag 2");
        tspec.setContent(R.id.tabs2);
        tspec.setIndicator("Maintenance"+"\n"+"Expense");
        mainSetting = mainView.getSettings();
        mainSetting.setDefaultFontSize(10);
        String mainData = fuelInfo.getMainData();
        double mainTotal  =fuelInfo.getTotalMain();
        tvMain.setText("Total maintenance expense : Rs. "+ String.valueOf(mainTotal));
        mainView.loadData(mainData,"text/html",null);

        th.addTab(tspec);

        //Spares Expense tab
        tspec = th.newTabSpec("Tag 3");

        tspec.setContent(R.id.tabs3);
        tspec.setIndicator("Spares"+"\n"+"Expense");
        spareSetting = sparesView.getSettings();
        spareSetting.setDefaultFontSize(10);
        String sparesData= fuelInfo.getSpareData();
        double spareTotal = fuelInfo.getTotalSpares();
        tvSpares.setText("Total spares expense : Rs."+ String.valueOf(spareTotal));
        sparesView.loadData(sparesData,"text/html",null);

        th.addTab(tspec);

        fuelInfo.close();

    }

}

Comment: Tabhost is depreated so better use fragments.
Answer: TabHost is deprecated so why don't you use ActionBar ?
Any way..I think you should use TabHost something like this
Resources ressources = getResources();
    TabHost tabHost = getTabHost();

    // Android tab
    Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
    TabSpec tabSpecAndroid = tabHost
      .newTabSpec("Android")
      .setIndicator("", ressources.getDrawable(R.drawable.icon_android_config))
      .setContent(intentAndroid);

There is a good tutorial for this TabHost Example
Answer: Try this
    tabHost = (TabHost) findViewById(android.R.id.tabhost);

    TabSpec Spec = null;
    Spec = tabHost.newTabSpec("home");
    Spec.setIndicator("Home", getResources().getDrawable(R.drawable.ic_tab_home));
    Spec.setContent(new Intent(this, MainList.class));
    tabHost.addTab(Spec);

    Spec = tabHost.newTabSpec("recent");
    Spec.setIndicator("Recent", getResources().getDrawable(R.drawable.ic_tab_recent));
    Spec.setContent(new Intent(this, Recent.class));
    tabHost.addTab(Spec);

    Spec = tabHost.newTabSpec("setting");
    Spec.setIndicator("Setting", getResources().getDrawable(R.drawable.ic_tab_setting));
    Spec.setContent(new Intent(this, Setting.class));
    tabHost.addTab(Spec);

    tabHost.getTabWidget().setCurrentTab(0);

Starting activities on tab click


How to reference an exception class in Python?

Question: I want to catch a GPSException thrown by the gpxpy library.
try:
    gpx = gpxpy.parse(open(filepath))
except GPXException:
    print "GPXException for %s." % filepath

Since I am new to Python I do not understand how one would reference the exception via namespace such as gpxpy.gpx.GPSException or an import statement such as ..
import gpxpy
import gpxpy.gpx
import gpxpy.gpx.GPSException

Answer: You need to reference the exception correctly.
Either import the exception directly into your module, or use the full reference:
import gpxpy.gpx

try:
    # ...
except gpxpy.gpx.GPSException:
    # ...

or
from gpxpy.gpx import GPSException

try:
    # ...
except GPSException:
    # ...

Comment: Is there an advantage to using one method over the other?
Comment: @StevenVascellaro: ['import module' vs. 'from module import function'](//softwareengineering.stackexchange.com/q/187403)


Tangent at average of two roots of cubic with one real and two complex roots

Question: I was able to easily prove that the tangent at the average of two roots of a real cubic polynomial passed through the third root of the function. But I have only done this for functions with three distinct real roots using $y = (x-a) (x-b) (x-c)$ as the function.
I calculated the derivative of the function in terms of ($x$= midpoint of $a$ and $b$) and then just subbed in ($x = c$) in the equation of the tangent that I worked out to prove this conjecture.
BUT!!
Now, I am trying to prove the same for cubics with one real and two complex roots.
I am using $y = (x -d) (x-(a+bi) (x- (a-bi))$ where $d$ is the one real root.
So far, I have found the derivative of this to be
\begin{align}
dy/dx &= 2(x-d)(x-a) + (x-a-bi) (x-a+bi)\\
      &= 2(x-d)(x-a) + x^2 + a^2 - bi^2\\
      &= 2(x-a) (x-d) (x^2 + a^2 + b^2)
\end{align}
The average of the two roots I have used is $((a+bi/2) + (a - bi/2))/2 = a$
I have already proved it for this average of roots!
But!!
I also tried the other possible average of roots $((d + a +bi)/2)$
where the Point of contact I used is $((a+bi+d)/2), -((a+bi-d)/2)^3$
Why is that the equation of the tangent I worked out for this second possible pair of roots using ($m =ystep/xstep$)  is not equalling zero when I sub in the third root into the equation of tangent I am getting??
Maybe I have calculated some things wrong?
Can you please help me prove the conjecture?
Plus, another mini question:
Can cubic polynomials be non-real? because when we say all cubic polynomials must have at least one real root, it implies that the cubic is real.
So can I say that a cubic with an imaginary coefficient is non-real?
I won't try to prove this conjecture for non-real cubics though.
Can you please help me?!
I would really appreciate even a bit of help
Sorry and Thanks!! =)
Answer: To the last question, traditionally if one does not qualify the coefficients directly or from context, rational or integer coefficients are assumed, so the polynomial is a real function.
The calculations for the case with complex roots should be the same as with the real roots, just take $b,c$ complex instead of real, with $c=\bar b$.
$f(x)=(x-a)(x-b)(x-c)$, $f'(x)=(x-a)(x-b)+(x-a)(x-c)+(x-b)(x-c)$, the tangent at $x_0=\frac12(a+b)$ is
$$
t(x)=f(x_0)+(x-x_0)f'(x_0)=(x_0-a)(x_0-b)(x_0-c)+(x-x_0)(x_0-a)(x_0-b)
=(x-c)(x_0-a)(x_0-b)
$$
so it has a root at $x=c$.
However, you would get the third root more quickly by using that $-(a+b+c)$ is the quadratic coefficient of the polynomial.
Comment: LutzL, Thankyou. I really appreciate your help with this. Just another
Answer: A real cubic polynomial with one real and two complex roots is of the form
$$f(x)=(x-\alpha)\bigl((x-m)^2+\beta^2\bigr)\ .$$
One computes $f(m)=(m-\alpha)\beta^2$ and $f'(m)=1\cdot\beta^2+(m-\alpha)\cdot 0=\beta^2$; therefore the tangent in question is the line $\ell$ with the equation
$$\ell:\qquad y=(m-\alpha)\beta^2+\beta^2(x-m)\ .$$
This line passes through the point $(\alpha,0)$.


Como colocar um ID numa variável? ASP.NET MVC

Question: Atualmente tenho uma view em que uma Tabela(Encomendas) está a ser carregada outra tabela(Cores)
Pretendo que dentro de cada encomenda seja lista a cor que tenha o mesmo ID que a encomenda.
Minhas Tabelas:
public partial class Programa
{
    public int ID_Programa { get; set; }
    [System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public Nullable<System.DateTime> Data_Registo { get; set; }
    public string Num_Encomenda { get; set; }
 }

public partial class Programa_Cor
{
    public int ID_Programa { get; set; }
    public string Cor { get; set; }
}

Para usar os dois modelos numa unica view criei esta class
public class EncomendaViewModel
{
    public IEnumerable<Programa> Programas { get; set; }
    public IEnumerable<Programa_Cor> ProgramasCor { get; set; }
}

O que me pareceu más lógico foi associar um variável ao campo ID_Programa e comparar com ID_Programa da tabela Programas_Cor, mas é listado todas as cores por encomenda e não somente as que tem o mesmo ID.
Meu Controlador:
var cor = color.Where(x => id.Contains(x.ID_Programa)).ToList()

        var tables = new EncomendaViewModel
        {
            Programas = embOpen.ToList(),
            ProgramasCor = cor.ToList(),
        };

Agradeço a quem me possa ajudar!
---------------------Update-----------------------------
Minha View

@foreach (var programa in Model.Programas)
{

            Artigo: @programa.Cod_Artigo

            Modelo: @programa.Modelo

            Nº Encomenda: @programa.Num_Encomenda

            Ref.Cliente: @programa.Ref_Cliente)

                @foreach (var programa_Cor in Model.ProgramasCor)
                {

                            @programa_Cor.Cor)

                }

}

neste momento tenho as cores que estão carregadas são de apenas um id para teste, pois carrega mesma cor em todas as Encomendas
Comment: Sua modelagem tá um pouco estranha e a pergunta não foi específica o suficiente. Porém: acredito que você tenha um problema na sua modelagem. Pelo que eu entendi, o correto aí seria mudar a tabela de "ProgramaCor" para apenas "Cor" e na tabela "Programa" colocar uma chave estrangeira referenciando a tabela "Cor". Sendo assim, cada programa possuiria uma cor.
Comment: Da forma como está não faz sentido ter uma classe `Programa_Cor`, apenas uma propriedade `Cor` na classe programa
Comment: vou colocar a minha view em cima para compreenderem melhor o meu projeto
Answer: Seu problema está na modelagem do domínio.
Alguns problemas:

Você está lidando com um relacionamento N x N (Muito pra Muitos), mas não criou uma classe / tabela associativa para especificar itens do relacionamento de Order x Color.

Você está usando nomenclaturas que não ajudam na abstração do problema e são diferentes do negócio do cliente (domínio do problema).

Vamos começar criando uma classe associativa:
///
/// Uma tabela associativa para guardar os itens do relacionamento N x N
///
public class OrderColor
{
    public int Id { get; set; }
    public Color Color { get; set; }
    public int OrderId { get; set; }
    public int QtdPecas { get; set; }
    public string Talao { get; set; }
    public string Status { get; set; }
    public string Observacoes { get; set; }
}

Aproveite para melhorar as nomenclaturas das entidades para facilitar a análise. Por exemplo, invés de usar o nome Programa, chame de Order, e Color invés de Programa_Cor.
///
/// Pedido
///
public class Order
{
    public int Id { get; set; }
    [System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public Nullable<System.DateTime> Data_Registo { get; set; }
    public string Num_Encomenda { get; set; }

    ///
    /// Todas as cores escolhidas
    ///
    public List<OrderColor> Colors { get; set; } = new List<OrderColor>();

    public void Add(Color color)
    {
        var corEscolhida = new OrderColor { OrderId = this.Id, Color = color };
        Colors.Add(corEscolhida);
    }
}

public class Color
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public override string ToString()
    {
        return Nome;
    }
}

Sua ViewModel continua igual, só adicionei um comentário para explicar a diferenças dessa propriedade Cores e a propriedade Cores da classe Order:
public class EncomendaViewModel
{
    public IEnumerable<Order> Encomendas { get; set; }
    ///
    /// Lista todas as cores disponíveis
    ///
    public IEnumerable<Color> Cores { get; set; }
}

Para vermos como fica o uso, criei uma implementação de exemplo em ConsoleApplication:
static void Main(string[] args)
{
    Console.WriteLine("TODAS AS CORES");

    // cria lista de cores
    var cores = new List<Color>();
    var branco = new Color { Id = 1, Nome = "BRANCO 500" };
    var lima = new Color { Id = 1, Nome = "LIMA 540" };
    var azul = new Color { Id = 1, Nome = "AZUL CLARO 560" };
    var taupe = new Color { Id = 1, Nome = "TAUPE 584" };

    cores.Add(branco);
    cores.Add(lima);
    cores.Add(azul);
    cores.Add(taupe);

    // lista na tela todas as cores disponíveis para serem escolhidas
    foreach (var c in cores)
    {
        Console.WriteLine(c);
    }

    Console.WriteLine("------------------------------------------------");
    Console.WriteLine("TODAS OS PEDIDOS");
    // cria as encomendas
    var encomendas = new List<Order>();
    var encomenda1 = new Order() { Id = 29798 };
    var encomenda2 = new Order() { Id = 29799 };

    encomenda1.Add(branco);
    encomenda1.Add(taupe);
    encomenda2.Add(lima);
    encomenda2.Add(azul);
    encomenda2.Add(taupe);

    encomendas.Add(encomenda1);
    encomendas.Add(encomenda2);

    // cria a viewmodel
    var model = new EncomendaViewModel
    {
        Encomendas = encomendas,
        Cores = cores
    };

    foreach (var o in model.Encomendas)
    {
        Console.WriteLine();
        Console.WriteLine($"PEDIDO - Artigo: {o.Id}");
        Console.WriteLine("CORES DO PEDIDO: ");

        foreach (var c in o.Colors)
        {
            Console.WriteLine($"Cor: {c.Color} | Observacoes: {c.Observacoes}");
        }
    }
}

Output:
TODAS AS CORES
BRANCO 500
LIMA 540
AZUL CLARO 560
TAUPE 584
------------------------------------------------
TODAS OS PEDIDOS

PEDIDO - Artigo: 29798
CORES DO PEDIDO:
Cor: BRANCO 500 | Observacoes:
Cor: TAUPE 584 | Observacoes:

PEDIDO - Artigo: 29799
CORES DO PEDIDO:
Cor: LIMA 540 | Observacoes:
Cor: AZUL CLARO 560 | Observacoes:
Cor: TAUPE 584 | Observacoes:


Não quero que o scanner inicie antes do loop

Question: Estou tentando fazer um exercício em que tenho de ler 10 número com scanner e decidir qual o maior e o menor. Consegui fazer isso com um for loop pedindo 10 valores, porém, ao iniciar o scanner ele pede um valor a mais, antes de entrar no loop, queria que o programa pedisse input apenas ao chegar no loop. Esse é o código que eu consegui fazer:
<code>import java.util.Scanner;

public class Exercicio4 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int max = n;
        int min = n;
        for (int i = 0; i < 9; i++) {
            System.out.println("Digite um número: ");
            n = scan.nextInt();
            if  (n > max)
                max = n;
            if (n < min)
                min = n;
        }

        System.out.println("O maior número é: " + max);
        System.out.println("O menor número é: " + min);
        scan.close();
    }
}
</code>
Comment: É por causa da linha `int n = scan.nextInt();`. Você não precisa iniciar uma leitura de scanner se não quer obter o dado de entrada do usuario. A simples inicialização da classe `Scanner` já e suficiente.
Comment: Você não precisa iniciar a leitura do scanner, somente iniciar a variavel. Apenas um `int n = 0;` ja resolveria
Comment: já tentei isso, porém, ao fazer isso a variável n fica com o erro "cannot resolve symbol"
Comment: Na verdade vc inicia o `min` com `Integer.MAX_VALUE` (o maior valor possível para um `int`), assim vc garante que qualquer número lido na primeira iteração será menor. O mesmo vale para `max`, basta iniciá-lo com `Integer.MIN_VALUE`.
Comment: foi assim que consertei, se iniciar com int n = 0, o min nunca vai mudar
Answer: seu codigo deveria esta parecido com esse.
<code> int n = sc.nextInt();

    int in = 0;
    int out = 0;

 for (int i=0; i<n; i++) {
        int x = sc.nextInt();
        if (x >= 10 && x <= 20) {
            in = in + 1;
        }
        else {
            out = out + 1;
        }
    }

    System.out.println(in + " in");
    System.out.println(out + " out");
</code>
Comment: Continua errado, pois o problema está justamente em iniciar a variavel n com leitura do Scanner.


Como mudar o valor de um date input com javascript?

Question: Tenho esse input do tipo date e quero fazer mudanças nele pelo localStorage:
<input type="date" id="dateMin"placeholder="Data Inicial">

Parte do javascript:
document.getElementById("dateMin").value = localStorage.dataMin;

O que deveria ser feito era o valor do input ser alterado para essa variável do localStorage, porém, aparece esse erro no console: TypeError: Cannot set property 'value' of null at"
Já conferi a parte do localStorage, e ele não tem nada a ver com o erro.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Olá, primeiro vc deve armazenar o valor no localStorage dessa forma por exemplo:
localstorage.setItem('date', '2021-11-11');

Após armazenar o valor vc pode pegar ele utilizando o método do localStorage chamado: getItem.
const data = localStorage.getItem('keyUsadaParaGuardarOValor');

Então seu código ficaria assim:
document.getElementById("dateMin").value = localStorage.getItem('date');

Você também deve verificar o formato da data que você está tentando passar para o input do tipo date, vc pode consultar por aqui:
https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/input/date#manipula%C3%A7%C3%A3o_do_suporte_do_navegador
Normalmente, o formato que vc deve utilizar par setar o valor é: 'YYYY-MM-DD'

Y = ano
M = mês
D - dia
Comment: Eu já havia feito a parte do setitem em outro trecho do código .. e como eu disse, o localstorage não tem nada a ver com o erro, até verifiquei as variáveis no console. Mesmo se eu tirar tudo do local storage e deixar somente um ```document.getElementById("dateMin").value = "2021/12/02" ``` ainda retorna o mesmo erro ```Cannot set property 'value' of null at```
Comment: Hmm entendi, vamos por partes.... o erro diz que o `document.getElementById('dateMin")` não está encontrando nada.

Então faça da seguinte forma, para garantir que aquele input já existe na DOM no momento que você está tentando setar um valor para ele:

`let input = document.getElementById('dateMin')
if(input) {
input.value = localStorage.getItem('seuDado');
}
`
Comment: Você pode adicionar evento no window para garantir que seu código rode apenas quando o document já estiver carregado dessa forma:

`window.addEventListener('load', (event) => {
  console.log('Seu código');
});`


momentJS convert possibility day into Date() js format

Question: I am trying to convert a date in format momentjs into a date from javascript native new Date().
The problem is that if I have moment(myDay).toDate(); it converts to the current date, and I want the date from myDay.
myDay looks like: "YYYY-MM-DD" => 2017-11-24 and I would like to have it with the format: Fri Nov 24 2017 20:17:11 GMT+0100 (Hora estándar romance) but I get Thu Nov 16 2017 etc...
It is possible to convert it like that way?
Comment: `moment('2017-11-24').toDate()` is like `Fri Nov 24 2017 00:00:00 GMT-0600 (CST)`. Isn't that what you wanted? If you wanted the hours and minutes you would have to include those in `myDay` string to be able to format it with Moment.
Comment: Can you provide a snippet or a fiddle showing your issue? I agree with ThisClark, `moment('2017-11-24').toDate()` will give your desired output.
Answer: Don't need moment:
let [yr, mn, day] = myDay.split('-').map(Number);
// note that JS months are 0-11 not 1-12
let datestr = new Date(yr, mn - 1, dy).toString();
console.log(datestr); // "Fri Nov 24 2017 00:00:00 GMT-0500 (EST)"

Comment: @RobG you are correct, but subtracting 1 from a string just *feels* wrong :D
Comment: The conversion to Number is superfluous. ;-)
Answer: you want something like this:
moment(myDay, "YYYY-MM-DD").toString();

moment().toString() Returns an english string in a similar format to JS Date's .toString().
moment().toString() // "Sat Apr 30 2016 16:59:46 GMT-0500"


Navigate table  with keyboard Up/Down Arrows

Question: I searched a lot to find a solution for this but I didn't found clear explanation. I actually have table (listing data from mySQL database with PHP) & I want it to be navigable with keyboard arrows: when the user press the up or down arrow, it focuses on the row above/over and that the background color changes. I want to learn how to do this in JavaScript please not the jQuery solution
Here is the table:

                      NO
                      Nom

                  <?php
                   include 'database.php';
                   $pdo = Database::connect();
                   $sql = 'SELECT * FROM pokemons ORDER BY id ASC';
                   foreach ($pdo->query($sql) as $row) {
                            echo '
';

                            echo ''. $row['id'] . '	';
                            echo ''. $row['name'] . '	';
                            echo ''. '	';

                            echo '
';
                   }
                   Database::disconnect();
                  ?>

Also the table has a search bar which filters rows with this script :

function searchPokemon() {

            var input, filter, found, table, tr, td, i, j;
            input = document.getElementById("mySearch");
            filter = input.value.toUpperCase();
            table = document.getElementById("pokemons-list");
            tr = table.getElementsByTagName("tr");

            for (i = 0; i < tr.length; i++) {

                td = tr[i].getElementsByTagName("td");

                for (j = 0; j  -1) {

                        found = true;
                    }
                }

                if (found) {

                    tr[i].style.display = "";
                    found = false;
                } else {

                    tr[i].style.display = "none";
                }
            }
        }
Comment: What does selecting a cell do or look like?
Comment: Have you tried yourself? If so, what did you do? Share!
Comment: @Feathercrown I want that when the user press the up or down arrow, it focuses on the row above/over and that the background color changes
Comment: Alright @Nas I've made an answer. If it's what you're looking for feel free to click the checkmark to accept it and give an upvote; if it's not just tell me and I'll see if I can change it when I get home.
Answer: Try using this as your JS:
var rows = document.getElementById("pokemons-list").children[1].children;
var selectedRow = 0;
document.body.onkeydown = function(e){
    //Prevent page scrolling on keypress
    e.preventDefault();
    //Clear out old row's color
    rows[selectedRow].style.backgroundColor = "#FFFFFF";
    //Calculate new row
    if(e.keyCode == 38){
        selectedRow--;
    } else if(e.keyCode == 40){
        selectedRow++;
    }
    if(selectedRow >= rows.length){
        selectedRow = 0;
    } else if(selectedRow < 0){
        selectedRow = rows.length-1;
    }
    //Set new row's color
    rows[selectedRow].style.backgroundColor = "#FFFFAA";
};

I've made a quick example of this working on a more basic table:

var rows = document.getElementById("pokemons-list").children[1].children;
    var selectedRow = 0;
    document.body.onkeydown = function(e){
        //Prevent page scrolling on keypress
        e.preventDefault();
        //Clear out old row's color
        rows[selectedRow].style.backgroundColor = "#FFFFFF";
        //Calculate new row
        if(e.keyCode == 38){
            selectedRow--;
        } else if(e.keyCode == 40){
            selectedRow++;
        }
        if(selectedRow >= rows.length){
            selectedRow = 0;
        } else if(selectedRow < 0){
            selectedRow = rows.length-1;
        }
        //Set new row's color
        rows[selectedRow].style.backgroundColor = "#8888FF";
    };
    //Set the first row to selected color
    rows[0].style.backgroundColor = "#8888FF";
th, td {
   border: 1px solid black;
}

            NO
            Nom

            1	Charmander

            2	Squirtle

            3	Bulbasaur

            4	Pikachu

            5	Arceus

Comment: This is exactly what I was looking for but I don't know why this is not working on my table @Feathercrown
Comment: Is there a way to get the HTML of your table once it's generated? I might be able to help you there. Also, make sure to put the Javascript after the table.
Comment: I get an error : "Cannot read property 'children' of null at list.php:10" and when my table is generated it's a serie of 1Bulbizarre
Comment: Alright! It's working I've put the Javascript after the table as you said, just a last question, I'm using this table with a search bar and when the table is filtered it's not working well, a solution for this please ? @Feathercown
Comment: I'd need to see the HTML of the filtered table to find a solution.
Comment: I added the filter script at the end of question, I tried something like : for (var tr[i] of table) { rows--;} and moved the variables declaration out of their respective functions to put them at the beginning of script but it didn't work. Thank you for helping me understand!


iOS Static Library as a Subproject of a Project That Has Custom Build Configurations?

Question: I'm trying to share code between multiple Xcode projects. I've followed Apple's notes on creating a static library subproject within a project:
http://developer.apple.com/library/ios/technotes/iOSStaticLibraries/iOSStaticLibraries.pdf
This works great! However, when I follow the same instructions using my own project, I find that the header files I make public in the static library can not be found by code within my app.
This is because my project uses custom build configurations. I have one for Ad Hoc builds, App Store builds, etc.
For example: when I build the project using a build config called "Ad Hoc", the static library subproject builds the Release configuration and copies its public headers to a folder called "Release". The main project then fails to build, complaining that it can't find headers that I'm importing from the static library. The errors appear in the Issue Navigator as: Lexical or Preprocessor Issue
So my question is: how do you set up a static library as a subproject of a project that has build configurations that the library doesn't?
Comment: As a trouble shooting step, try changing "include/${PRODUCT_NAME}" in the sub-project static library Copy Files panel with more simply, "include" and see if that works. It should work fine with the former, and it keeps everything neat and tidy for when a human is browsing the product directory, but it's not necessary and can cause problems if you have been fiddling about with configurations.
Comment: You don't need to copy them at all; my (OSX) app which uses a C++ library, simply needs `$(PROJECT_DIR)/../mylibrary` added to the *Header Search Paths*. That's assuming that the library project is a sibling to the app project and I use a workspace to bind them all together (there are actually two library projects and an app project).
Comment: Are you releasing the library itself?  If not why make the headers public or copy them anywhere?  Surely they don't change between build types?
Comment: @trojanfoe i'm not releasing the library itself. It will be built into all of our projects. Currently the headers are getting copied to include/${PRODUCT_NAME} in the "Products Directory" destination. Do you know where I should have it copy them to so my app can see them in any build configuration?
Comment: @TheBasicMind I tried your suggestion but it yielded the same results. The headers were copied to a Release folder and the project failed to build.
Comment: @trojanfoe that did the trick! But won't I have issues debugging a debug-compiled version of my app with a release-compiled library? I'm wondering specifically about debugging within the library.
Comment: I don't understand your concern.
Answer: I came across this issue when making my custom project templates.
Add "$(BUILD_DIR)/Release$(EFFECTIVE_PLATFORM_NAME)" to the "Header Search Paths" and "User Header Search Paths" for any build configurations you use Archive with and make sure it is set to be "recursive" as opposed to "non-recursive". This will tell your app to search the "Release" directory in your build directory for header files.
The problem is that for Debug builds ALL header files are copied to a single directory under derived data. But when you archive the files are copied to a folder named after the build configuration. So when you do a "Ad Hoc" build all your files get copied to the "Ad Hoc" folder but your static libraries files get copied to the "Release" folder. These folders sit side by side beside one another and unless told to do so the header files will only be searched for under the "Ad Hoc" folder.
Here is the GitHub commit for my project templates where I fixed the problem
https://github.com/reidmain/Xcode-5-Project-Templates/commit/e465aa3d5c82118cc0d5af3a7f6f094d86b1ec63