Naming non-tertian trichords

Question: Commonly used scales such as the major and minor heptatonic scales contain only two different intervals between their neighbouring notes: the major second (whole tone) and the minor second (semitone). The common major scale has the semitones between its 3rd and 4th step, and 7th and 8th step, whereas the minor between 2nd and 3rd and 5th and 6th.
To create a trichord we take any note from the scale as a base note and and 2nd next and 4th next notes starting from the base one. The intervals between the base and 2nd and 2nd and 4th are always major or minor thirds (if we're using the scales mentioned above). These four combinations of major and minor thirds are all possible tertian trichords and their naming is well documented (e.g. C, Cm, Caug, Cdim).
Now, if we instead take a scale that contains different intervals between its neighbouring notes (semitones, whole tones, a whole tone plus a semitone), we can end up with different intervals between a base note and its 2nd next and between the 2nd next and 4th next: we could have a chord made out of a major second and major third.
In other words, the three notes have 2 and 4 semitones between the chord's notes.
How do we name such non-tertial chords?
Are there rules for naming secundal-tertian or other hybrid (tertian-quartal?) chords?
Comment: You're considering natural minor. Don't forget melodic, and also the commonly used harmonic, with  a tone and a half between 6 and 7.
Answer: Chord names and symbols themselves are tertian ideas as they grew out of functional harmony. There are some chord symbols that kind of convey quartal or quintal ideas like the 7sus4 and the 6/9 chords, but how they are names still reflects looking at them as tertian. If I understand you correctly and you would have a C, D, and E for example I would be tempted to call it a Cadd9 as the only note missing in this is the 5th which is implied by the root.
There are ways to look a chord that may make more sense then relying on  tertian ideas. One is pitch class set where all notes are enumerated from 0 to 11 for that repeat each octave. this you can look for similar relationships between sets.  The 0 can be any starting note that makes sense, but to keep with the traditional ideas C is typically 0.
In a pitch class set a C major chord would be represented as [0, 4, 7] and any major chord in any inversion would reduce to this as its prime form which is just smallest way to represented the chord in an enumerated fashion like this. You can even extend these ideas to any system with a set number of pitches like 24 equal temperament if desired, just the numbering change. In the example above, you would just look at it as [0, 2, 4] which could make much more sense than the Cadd9 chord symbol.
This site gives a good list of possible pitch class sets and what they would be in traditional music and as you'll see a good chunk of them are not tertian in nature.
Comment: Thanks for your extensive answer! I have a follow-up: The chord with a major second (whole tone) and a major third (two whole tones) interval would be C-D-F#. It is a secundal-tertian hybrid. Does it have a name?
Comment: Honestly, I'd look at it as D7 in third inversion without a 5th.  You typically don't look at multiple systems in the same chord as it screws with the goals of each different type of harmony
Comment: I've never understood why C,D,E should be called Cadd9, when the 9 is actually a 2.  I'd go with C,D,F# as 3rd inversion of D7 too. - D7/C.
Comment: I found it in the table you linked: it is a 0-2-6 and is called Incomplete Dominant-seventh Chord.1/Italian-sixth, it seems.
Comment: @Tim chord symbols are never meant to show voicings, only what notes make up the harmony. It could be it is C, D, E, in closed position or the D could be a 9th away from the C.
Comment: True, but I always feel that add2 makes a bit more sense! Although generally speaking, the distance of a 9th is more commonly used.

Naming non-tertian trichords


How does the canonical commutator works on differential operators?

Question: I'm having trouble understanding how the canonical commutator works on differential operators: in this article, page 2, they define the multiplication-by-$x$ operator, that is a linear operator acting on some space of functions of the variable $x$, that simply multiplies any function by $x$. Then they extend it into the following time dependent operator:
$$\hat{x}(\tau)=e^{H\tau}xe^{-H\tau}$$
with $H=(a-bx)\partial_x+\frac{\sigma^2}{2}x\partial^2_x$.
Then they claim that in order to get the equation of motion (the derivative of $\hat{x}(\tau)$) they use the canonical commutator:
$$[\partial_x,x]=\partial_xx-x\partial_x=1$$
so that
$$[H,x]=a-bx+\sigma^2x\partial_x$$
and the equation of motion becomes
$$\frac{d}{d\tau}\hat{x}(\tau)=a-b\hat{x}(\tau)+\sigma^2\hat{x}(\tau)\hat{p}(\tau) \tag{1}$$
where $\hat{p}(\tau)=e^{H\tau}\partial_xe^{-H\tau}$.
I tryed to do the explicit calculation: $[H,x]=((a-bx)\partial_x+\frac{\sigma^2}{2}x\partial^2_x)x-x((a-bx)\partial_x+\frac{\sigma^2}{2}x\partial^2_x)=$ $(a-bx)\partial_xx-x(a-bx)\partial_x+\frac{\sigma^2}{2}x\partial^2_xx-x\frac{\sigma^2}{2}x\partial^2_x=(a-bx)(\partial_xx-x\partial_x)+\frac{\sigma^2}{2}x\partial_x(\partial_xx-x\partial_x)=$ $a-bx+\frac{\sigma^2}{2}x\partial_x$ but I have a $\sigma^2/2$ here and not just $\sigma^2$ as they claim. Also I don't understand then how to get to the equation of motion since the right hand side seems to be just their $[H,x]$ multiplied by $e^{H\tau}$ on the left and $e^{-H\tau}$ on the right, but why should $e^{H\tau}[H,x]e^{-H\tau}$ equal $\frac{d}{d\tau}\hat{x}(\tau)$?
Answer:
Notice that
\begin{align}
x\partial_x^2(x\psi)-x(x\partial_x^2\psi)&=x\partial_x(x\partial_x\psi+\psi)-x^2\partial_x^2\psi \\
&=x(x\partial_x^2\psi+\partial_x\psi+\partial_x\psi)-x^2\partial_x^2\psi \\
&=2x\partial_x\psi,
\end{align}
which explains the factor of $2$ that you are missing.
Differentiate $\hat{x}(\tau)=e^{H\tau}xe^{-H\tau}$ with respect to $\tau$ to obtain $\frac{d}{d\tau}\hat{x}(\tau)=e^{H\tau}[H,x]e^{-H\tau}.$


What does a red circle on a task mean in an SSIS package?

Question: I am creating a similar package to this package but I don't know the meaning of the red mark in the pic below:
Comment: It means debugging is set up
Comment: you can right click task and enable debugging
Comment: I still cannot find the debug option, please let me know where is it?
Comment: I am not sure that you can get to this specific breakpoint the way the answer states. This is a script task. Open the code and remove the breakpoint if needed. But you put a breakpoint in a script task so that you can get a much better error than "the script task failed"
Answer: Basically, you need to have breakpoints in that task, to have red mark coming in.
See the below steps to enable breakpoints.
Reference: Breakpoints in SSIS

Go to breakpoints for a task

Enable breakpoints for specific event
Comment: Thank you so much, I also found that I haven't open my package with solution explorer, that's maybe why the option Edit Breakpoint disappeared.


How to sort all elements of a 2d matrix in MATLAB?

Question: The sort() function sorts the elements row/column wise but how to sort the elements absolutely? The result should be another matrix with smallest element in (1,1) , second smallest in (1,2) and so on.
Comment: What shape do you want the result? Just flatten the array, sort, and reshape as desired.
Comment: 'A(:) = sort(A(:))' may sort so that reading column by column from letf to right would go in increasing order ... but your question is unclear ... the column operator ':' here just serve as taking the elements one after the other to vectorise things (columnwise)
Answer: Take some random input
input = rand(5,10);

If you want the output to be a row vector, simply use
sortedRow = sort(input(:)).';

If you want the result to be the same shape as the input, then use
sortedOriginalShape = reshape(sort(input(:)), size(input,2), size(input,1)).';

Note that when maintaining the shape, we must use the reversed size dimensions and then transpose. This is because otherwise the result is column-wise i.e. smallest element in (1,1), next in (2,1) etc, which is the opposite of what you requested.
Answer: You can use the column operator (:) to vectorize all elements of 'nxm' matrix as a vector of 'nxm' elements and sort this vector. Then you can use direct assignement or 'reshape' function to store elements as matricial form.
All you need to know is that matlab use column-major-ordering to vectorize/iterate elements:
A = rand(3, 5);
A(:) = sort(A(:);

Will preserve colum-major-ordering, or as you said you prefer row-major ordering:
A = rand(3, 5);
A = reshape(sort(A(:)), fliplr(size(A)).';

Note the fliplr to store columnwise with reversed dimension and then the .' operator to transpose again the result.
EDIT
Even if matlab uses column-major-ordering for storing elements in memory, here below are two generic routines to work with row-major-order whatever the number of dimension of your array (i.e. no limited to 2D):
function [vector] = VectorizeWithRowMajorOrdering(array)
%[
    axisCount = length(size(array)); % Squeezed size of original array
    permutation = fliplr(1:(axisCount + 2)); % +2 ==> Trick to vectorize data in correct order
    vector = permute(array, permutation);
    vector = vector(:);
%]
end

function [array] = ReshapeFromRowMajorOrdering(vector, siz)
%[
    siz = [siz( : ).' 1]; % Fix size if only one dim
    array = NaN(siz); % Init
    axisCount = length(size(array)); % Squeezed size!
    permutation = fliplr(1:(axisCount + 2)); % +2 ==> Trick to vectorize data in correct order

    array = reshape(vector, [1 1 fliplr(size(array))]);
    array = ipermute(array, permutation);
%]
end

This can be useful when working with data coming from C/C++ (these languages use row-major-ordering). In your case this can be used this way:
A = rand(3, 5);
A = ReshapeFromRowMajorOrdering(sort(A(:)), size(A));


Annihilating polynomials of non-diagnolizable matrices

Question:
For every non-diagonalizable matrix in $M_n(\mathbb{F})$, there is a polynomial $P(t)$ with coefficients over $\mathbb{F}$ and of degree $n-1$ such as $P(A)^2=0$.

Is the above statement true for $\mathbb{F}=\mathbb{C}$ or $\mathbb{F} = \mathbb{R}$? Or none of them?
How can I find out if this is true for any field?
Answer: This is true iff the field is algebraically closed. For non-algebraically closed fields, any matrix (at least of size 2x2) with with an irreducible characteristic polynomial is a counterexample.


Select com Sql e Input Dinâmico

Question: Estou tentando fazer com que o select abaixo, que puxa dados de um sql quando selecionado a opção, altere o valor no input ao lado, também vindo do banco de dados sql.
Qual seria a melhor opção?
Segue o codigo.

    Servico:

    <select name='servico[]' id="servico[]" style="text-transform:uppercase">
      <?php

    $sql="SELECT * FROM servicos ORDER BY nome";

    $resultado=mysql_query ($sql) or die ("Problema na lista!");

    while ($linha=mysql_fetch_array ($resultado))

    {

    $id=$linha["id"];
    $cliente=$linha["nome"];

    ?>
        <option>
          <?=$cliente?>
        </option>
        <?
    }
    ?>
    </select>

    Valor:

    <input name="valor[]" type="text" id="valor[]" size="6">

Comment: Não entendi. Você que que, ao selecionar itens no ``, eles aparecem no ``? Tipo, separados por vírgula, algo assim?
Comment: eles vem dinamicamente por sql, preenchem o select. Mas cada select deste, é um serviço, que contem um valor ($). queria que este valor aparecesse no input quando trocasse o serviço nas opções do select.
Answer: Para melhor atender a sua necessidade, ou seja, recuperar o valor de acordo com o produto selecionado no campo select vou apresentar a seguinte solução:

Fazer com que quando o valor do select for alterado, seja criado um evento que dispare uma requisição que retorne o valor do produto em formato JSON.

Segue abordagem:
<?php
$sql = "SELECT * FROM servicos ORDER BY nome";
$resultado = mysql_query ($sql) or die ("Problema na lista!");
?>
<select name='servico' id="idservico" style="text-transform:uppercase">
    <option value=''> Selecione</option>
    <?php while ($servico = mysql_fetch_object($resultado)): ?>
    <option value="<?php echo $servico->id?>"> <?php echo $servico->nome?> </option>
    <?php endwhile ?>
</select>

<input name="valor" type="text" id="idvalor" />

Agora, vamos criar o arquivo obtemvalor.php que será responsável por recuperar o valor do produto selecionado no campo select.
<?php
if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checa se valor existe
    $action = $_POST["action"];
    $id = $_POST['idservico'];
    switch($action) {
      case "obtervalor": obter_valor_servico($id);
      break;
    }
  }
}

//Funcao que checa se a requisicao ajax e valida.
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function obter_valor_servico($id){
    $sql = "SELECT id, valor FROM servicos WHERE id = ".intval($id);
    $resultado = mysql_query ($sql) or die ("Problema na lista!");

    $linha = mysql_fetch_object($resultado);

    echo json_encode($linha);
}
?>

Dessa forma, sempre que houver a seleção de um serviço, o campo valor receberá o valor do mesmo.
Tecnologias utilizadas para solução: Jquery, PHP e AJAX.
Comment: Veja se agora atende sua necessidade. Se atender, peço que qualifique a resposta. Por favor!
Comment: Favor, testar novamente! Fiz as correções e em seguida realizei testes aqui e funcionou.
Comment: Poxa, bacana! Fico feliz. Pô mano, dê um voto positivo aí pra nós. Heehee
Comment: Fiz como acima, porem ele resulta no mesmo nome do serviço, e não no campo valor que está na mesma linha no registro no sql.
Comment: Você que que apareça o preço do produto no campo valor?
Comment: Ola, obrigado por entender minha necessidade. Entretanto continua sem voltar valores no campo valor, mesmo eu setando as configurações do banco de dados nos arquivos.
Comment: deu certo o// Muito obrigado!

Select com Sql e Input Dinâmico


Modelstate always throws invalid datetime error

Question: I have a question about Date validations in Asp.net MVC4.
I am using Data annotations for Date validations as follows
   [DataType(DataType.Date)]
   [AllowHtml]
   [DisplayFormat(HtmlEncode = false, ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
   [Display(Name = "Date Of Birth")]
   public Nullable<System.DateTime> DateOfBirth { get; set; }

Next, in Html page, i am using following in MVC Html form
@Html.TextBoxFor(model => model.UserSettings.DateOfBirth,
                          String.Format("{0:dd/MM/yyyy}",
                          model.UserSettings.DateOfBirth),
                       new { id = "DoB", @class = "brth-ipt" })

Lastly, i am using a Jquery Date picker as follows
$(function () {
    $("#DoB").datepicker("destroy");
    $("#DoB").datepicker({
        showOn: "both",
        beforeShow: customRange,
        dateFormat: "dd/mm/yy",  //"mm-dd-yy",
        firstDay: 1,
        changeFirstDay: false,
        changeMonth: true,
        changeYear: true,
        yearRange: "-150:+0"
    });
});

My problem is, when I select a date from datepicker, it is displayed as mm/dd/yyyy format and it works fine.
But when I load the page again to edit the form, it is displaying in mm-dd-yyyy format. Now, when i save the form without chaging the previous date (mm-dd-yyyy format), I am not able to save the form as Data annotation vaidation is throwing me an error. "Date is not in valid format".
I am not able to solve this issue.
Answer: Try this:
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    [Display(Name = "Date Of Birth:")]
    public DateTime? DateOfBirth { get; set; }

As far as i know, you wouldn't even need to use Jquery Date picker. The framework comes with built in helper to pick your dates.
In your View

        @Html.LabelFor(model => model.DateOfBirth )

        @Html.EditorFor(model => model.DateOfBirth )
        @Html.ValidationMessageFor(model => model.DateOfBirth )

This is tested in Google Chrome
Answer: Html.TextBoxFox() doesn't take [DisplayFormat] into account. To utilize this attribute and achieve your goal you may use
Html.EditorFor(x => x.UserSettings.DateOfBirth, new {id = "DoB", @class = "brth-ipt"})

Answer: I ran into the same thing and finally found how to fix my problem.
I made this data annotation in ViewModel
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]

and this code in my date picker

   <input asp-for="MyDate" type="text" class="form-control" />

and I put this code in jquery to send via ajax
$('#calender-container .input-group.date').datepicker({
   todayBtn: true,
   calendarWeeks: true,
   todayHighlight: true,
   autoclose: true,
}).datepicker('update', new Date());

Funny when I changed data-date-format from "mm-dd-yyyy",
which gives me invalid model state, to "MM-dd-yyyy" everything became valid.


How to invert relationship in MySQL Workbench 8

Question: Hi i want to create a relationship ( 1.1 ) (0. N) between two tables in a ER diagram.
<code>Tab 1.                           Tab 2
Id tab2
Foreign key Tab 2             Id tab 2
</code>
But i cant use the inverted relationship option someone can help me ?
I change the order but the foreign key is created in the wrong tables
Comment: Your need is unclear.
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: There's no way to invert a relationship. You have to delete and recreate it in the reverse direction. Use the relationship tools from the vertical palette to quickly do this.


Parametric Equation for A Wiggly Tube

Question: I need to form a shape where the side view in the $xz$-plane is parallel inverse sines, and the surface is a pipe with circular cross-sections. Is there a name for this shape?
I tried messing around with ParametricPlot3D in Mathematica, but couldn't figure it out. I tried messing around with the equation of circles for two slots and inverse sine for the other.
Fig. 1:

Fig. 2:
Comment: Would you like circles parallel to the $xy$-plane or circles contained in a plane perpendicular to the curve?
Answer: This is a circle with a hight dependent centre.
One possible parametrization is
$$x(t)=f_x(z(t)) + r\cos(\omega t)$$
$$y(t)=f_y(z(t)) + r\sin(\omega t)$$
$$z(t) = K t .$$
If you only want the whigglyness in one direction then you can set $f_y(z(t))=0$ and $f_x(z(t))=\sin(z(t))=\sin(Kt)$.
Answer: Since the cross section is a circle and the cross section from the side are parallel arc sine functions, we can form the shape as a continuous sequence of circles whose height changes as we go along the x-axis. With circles lying in the xz-plane and the arcsines in flat in the xz-plane we get this parametric function:
$x=t, y = r_0cos(\theta),z=r_0sin(\theta)-sin^{-1}(t)$ with $0 \leq \theta \leq 2\pi$  and $a \leq t \leq b$
So with $r_0 = 1, a = -10$, and $b = 10$ we have the graph:

Parametric Equation for A Wiggly Tube


Make sure function from React.useContext is called in Jest

Question: Given a custom hook that looks like this:
const getSavedInfo (id) => {
  const endpoint = getEndpoint(id)
  const {updateInfo} = React.useContext(infoContext)

  axios.get(endpoint).then((res) => {
   if (res) {
     updateInfo(res.data)
    }
  })
}

How would I go about properly mocking the updateInfo method so I can make sure it was called within my jest test?
Comment: Please [create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). If I execute the `getSavedInfo` function, I will get `Invalid hook call. Hooks can only be called inside of the body of a function component.` error. So your code is incomplete. What's `infoContext` and `getEndpoint` functions? Do you want to mock `updateInfo` function or just spy it?
Answer: You need to pass the provider in test while rendering the custom hook. You can write your own provider function or use react-hooks-testing-library which does the same thing for you. Like this:
import { renderHook } from 'react-hooks-testing-library';

const wrapper = ({ children }) => (
  <InfoContext.Provider value={{updateInfo: jest.fn}}>{children}</InfoContext.Provider>
);

it('should call update info', () => {
  const { result } = renderHook(() => getSavedInfo(), { wrapper });

  // rest of the test code goes here
});

You can find detailed explanation here


Maximize the distance between a w shaped line construction and two points

Question: I am trying to hang string lights on my rectangular porch in a W-shaped fashion. There are two ceiling fans interrupting the pattern and I need to maximize the distance between the ceiling fan blades and the string lights. The perpendicular distance from the center of each ceiling fan to each line should be equal. I tried to use cad to solve this and I am close but I'd like to get an exact solution if possible. I believe one way to go about it is to use the following Theorem and solve that set of equations along with the equations of the lines. There might also be a derivative involved since we are maximizing something. I began using the theorem and things got pretty nasty right away. I am hoping someone might have a more elegant solution. The unknown variables are x_1, x_2 and x_3.
Comment: Do you want `x_3 = 292`?  If so, only the other two x values are unknown.
Comment: @bubba It was a mistake. The new image has now been posted.
Answer: Just a few suggestions.
Notation: let's call the four diagonal lines $L1$, $L2$, $L3$, $L4$, and let's call the circle centers $C1$ and $C2$. Define some distances $d1 = distance(L1, C1)$, $d2 = distance(L2, C1)$, $d3 = distance(L3, C12)$, and $d4 = distance(L4, C2)$. We want $d1=d2=d3=d4$.

Using a CAD system, or even just PowerPoint, you can move the diagonal lines around until the four distances look roughly equal. This would probably be close enough.

If your CAD system supports constraint solving, you can dimension the four distances, tell the system you want them to be equal, and let the constraint solver do its thing.

You have the formula for the distance from a point to a line, so you can write three equations that express the requirements $d1 = d2$, $d2=d3$ and $d3=d4$. Now we have to solve these three equations to get $x_1$, $x_2$, $x_3$. Solving these equations by hand is likely to be a big mess, unless someone can spot a clever algebra trick (I can't). You can try to solve the equations using a computer algebra system like Wolfram Alpha (free) or Mathematica (far from free). If those systems can't give you an exact algebraic solution, they will at least give you one computed by numerical methods.
Comment: I think calculus can be used because If you pretend to draw the lines by hand you start in the upper left corner and Pick a D1 as a result X1 has been determined by your choice. Let D3=D2=D1, then X2 and X3 have also been determined. At this point D4 has been determined but does not necessarily equal D1. This is because the 4th line in this mental exercise is constrained by the corner point (292,110). I'm thinking you could set it up so that a derivative allows D1 to approach D4. Does this make any sense or would it be more difficult to solve then the algebraic system?
Comment: If you use my approach #3, this all boils down to solving a system of three equations. The numerical methods I mentioned might use derivatives, internally, but we don't need to see that.
Comment: your cad solution worked please see above
Answer: You'll likely be forced to solve numerically no matter what, but here goes:
I'm assuming the optimal solution will have a radius $r$ from the center $C_1$ to the tangent lines $L_1$ and $L_2$ and similarly for $C_2$. I don't know that that's necessarily the case for the optimum, but it's what I'm going with.
For a given $r$, we can calculate $x_1$ by identifying the angle the tangent line $L_1$ makes with the y-axis.
$$x_1 = 110\tan(\frac{\pi}{2} - \arctan(\frac{55}{105.5})-\arcsin(\frac{r}{\sqrt{55^2 + 105.5^2}}))$$
$x_3$ can be found the same way.
$$x_3 = 292 - 110\tan(\frac{\pi}{2} - \arctan(\frac{55}{81}) - \arcsin(\frac{r}{\sqrt{55^2+81^2}}))$$
Once $x_1$ and $x_3$ are found, we can use the tangent lines $L_2$ and $L_3$ and find their intersections with the top of the rectangle. These won't necessarily agree for a given r, but will give two options $x^L_{2}$ and $x^R_{2}$.
$$x^L_2 = \frac{\sqrt{110^2 + x_1^2} \cdot \sin(2\arcsin(\frac{r}{x_1}))}{\sin(\pi - 2\arcsin(\frac{r}{x_1})-\arctan(\frac{55}{105.5})-\arcsin(\frac{r}{\sqrt{55^2+105.5^2}})}$$
and
$$x^R_2 = 292 - \frac{\sqrt{110^2 + (292-x_3)^2} \cdot \sin(2\arcsin(\frac{r}{x_3}))}{\sin(\pi - 2\arcsin(\frac{r}{x_3})-\arctan(\frac{55}{81})-\arcsin(\frac{r}{\sqrt{55^2+81^2}})}$$
Setting those two equal to each other and solving for $r$ should get you where the tangents meet at a common $x_2$. Barring my tangency assumptions about the optimum being wrong or me misreading the diagram, that gives me $r = 29.6833$, $x_1 = 122.2463$, $x_2 = 149.9779$, and $x_3 = 205.5175$
Answer: I put it into CAD. Then checked it against the previous solution. Keep in mind that the tolerance is set to 1/64.

Column got in the way!
Comment: @MichaelBiro your solution worked. See above.
Comment: A numerical solution is going to be the best you can do. After doing out too much algebra:

$x_1 = 122.2463009839560914669064355869597068\dots$ is the real solution of $$2984x^7-2203684x^6+803626114x^5-180830349625x^4+27280292057176x^3-2754957086055401x^2+175453649542580508x-5533650079159662376=0$$

and doesn't seem to have a solution in radicals.


Solution of Double Integral

Question: I am trying to solve the double integral over a rectangular region.
\begin{align*}
\int_{u=a}^{b}\int_{v=c}^{d}\sin(u^2-v^2)\mathrm{d}v\mathrm{d}u,
\end{align*}
where $a,b,c,d$ are any real constants.
I tried using substitution method, $u-v=x$ and $u+v=y$. I do not know how to solve further.
Answer: You cannot go from $2$ variables to $1$ variable.
I suggest the substitution:
$$\begin{cases} u =\cosh(x)\\v = \sinh(y)\end{cases}$$
Don't forget about the jacobian!
Comment: what about limits? Sorry I didnt understand?

Solution of Double Integral


Eliminating a nuisance parameter in likelihood ratio test

Question: I am having an argument with a co-author about how to eliminate a nuisance parameter in a simple likelihood ratio test and am hoping that the community helps us settle it.
Our data $\mathbf{x}$ can be described by the likelihood functions $l(\mathbf{x};\theta_0,\eta)$ and $l(\mathbf{x};\theta_1,\eta)$ under hypotheses $H_0$ and $H_1$, where $\theta$ is the parameter of interest and $\eta$ is the random "nuisance" effect. We know the distribution function $f_\eta(\eta)$ that describes $\eta$.
The likelihood ratio is, of course,
$$\Lambda(\mathbf{x},\eta)=\frac{l(\mathbf{x};\theta_0,\eta)}{l(\mathbf{x};\theta_1,\eta)}$$
Since we have $f_\eta(\eta)$, we can "average" out $\eta$ to obtain a simple test between two point hypotheses.  We can then use Neyman-Pearson and calculate the value of threshold.  Our argument stems from how to average it out. Since $\Lambda(\mathbf{x},\eta)$ is effectively a random variable that is a function of $\eta$, I think the following is the correct test statistic is
$$E_\eta\left[\frac{l(\mathbf{x};\theta_0,\eta)}{l(\mathbf{x};\theta_1,\eta)}\right]$$
while my co-author insists that the correct test statistic is
$$\frac{E_\eta[l(\mathbf{x};\theta_0,\eta)]}{E_\eta[l(\mathbf{x};\theta_1,\eta)]}$$
Who is right, and why?
Comment: When you say "we know the distribution function that describes the nuisance parameter", I'm a little confused. In the LRT, parameters are fixed but unknown. If you're describing a parameter by a distribution it sounds like you're taking a Bayesian approach instead, which would lead people to wonder, why discuss LRT at all? Perhaps more details might help to clarify the situation.
Comment: M.B.M. Are you talking about $\eta$ being a *random effect*? I'd probably have denoted those as $\eta_i$ or something along those lines -- but in any case you should be explicit about what you mean (in your question).
Comment: $\theta\in\{\theta_0,\theta_1\}$ is fixed but unknown, $\eta$ is random, and "uninteresting." Looks like van Trees has it the my co-author's way, Eq. (296) in Sec 2.5 "Composite Hypotheses"...
Comment: @Glen_b: I second your point that the only cases where this makes sense are the Bayesian and random effect situations. But this does not cover all settings with nuisance parameters.
Comment: If $\eta\sim f_\eta(\eta)$, the "true" likelihood is $$\mathbb{E}[l(\mathbf{x};\theta,\eta)]=\int l(\mathbf{x};\theta,\eta) f_\eta(\eta)\,\text{d}\eta$$ so I would second your co-author's perspective.
Comment: @Glen_b I changed the question per your suggestion.  Sorry for the lack of clarity.
Comment: @Xi'an As I mentioned earlier, van Trees also seconds this.
Answer: You have to compare two likelihoods, not doing the mean of a ratio. So your co-worker is right. Since you said that you have the distribution of $\eta$ it seems to me you are using a Bayesian approach.
On the contrary, in high-energy-physics we use a different approach: we "profile" the nuisance parameters and build the profiled-likelihood ratio. In you case:
$$\Lambda(\mathbf{x})=\frac{\sup_{\eta}L(\mathbf{x}|\theta_0,\eta)}{\sup_{\eta}L(\mathbf{x}|\theta_1,\eta)}$$
This is more or less what the Tevatron experiment did to compare hypothesis (with signal / without signal), see http://arxiv.org/pdf/1001.4162v3.pdf
Comment: (+1) See also http://stats.stackexchange.com/a/1051/17230


How can I fit a regression for a variable which have a maximum value?

Question: Let's suppose I have a test which gives me the dosage of an analytic in the blood. The results of the assay are in a range of 0 and 1000; all subjects who have a value higher than 1000 will be categorized as ">1000".
The question is: how can I manage this variable since a significant proportion of the cohort will have levels >1000? how can I fit a regression in which the result of the assay is the dependent variable?
Comment: Methods of "censored regression," including many techniques of survival analysis, have been successfully applied to this problem, especially in situations like this one where multiple imputation is not a reasonable option.
Comment: Do I get you right that your dependent variable suffers from measurement error in that it is capped to 1000? Does it make sense to impute the values, i.e. assume a distribution that fits the values below 1000 fairly well and assign random draws from that distribution to the guys above 1000 (given that the random draw is above 1000).
Comment: Yes, it is right - the dependent variable is capped to 1000, i.e. those who have values over 1000 will be flagged as ">1000".
I don't know if there is any specific methods to manage this type of variable. One option is to categorize them as "1001", but obviously ">1000" may indicates those with 1001 or 20.000, in the same way.

Non-parametric regression may be an obvious option, but the question is, is that correct? how can I handle these values?
Comment: I suggested to do it the other way round, i.e. impute those unknowns and then run standard regression methods. Your imputed values will be wrong, but this will be less wrong than assuming some fix value.
Comment: This is flagged non-parametric, but are you really interested in a *non-parametric* analysis? Consider if you use a parametric model, you can apply the EM algorithm and obtain estimates and predictions, even beyond the 1000 upper limit of detection.
Answer: I'd guess that implicit in your question is not just "what can I do?" but also "what should I do?" The first part is relatively easy to answer, in part because there is so much you can do! The second part will require you to determine what makes the most sense given your setting.
To make sure I understand your question, suppose $Y^*_i$ is the dosage of the analytic in individual $i$, and $X_i$ is some other variable. You observe data $(Y_i,X_i)_i$ for $i=1,\dots,n$, where $Y_i = \min(Y^*_i,1000)$. To make sure we are on the same page regarding terminology, you have a censoring problem. In particular, this is not a truncation problem, which is often confused with censoring (see this question for more on that)
You seem to be interested in a regression model where your dependent variable is censored, as is the case when it's $Y_i$.
1. What you should not do
Before discussing some options, I'd strongly caution against the approach suggested in the first comments of your post, which entails just assigning random values to those with $Y_i = 1000$. To illustrate intuitively why this is problematic, suppose $X_i$ is gender, and suppose all males have $Y_i = 1000$ (i.e. $Y_i^* > 1000$ for all males) and all females have $Y_i < 1000$ (i.e. $Y_i^* < 1000$ for all females). If you just randomly impute $Y_i^* > 1000$ (male data) using $Y_i^* < 1000$ (female data) and run a regression, you will find no effect of gender, when clearly there is one! You may wonder: "Well, what if I impute conditional on $X_i$?" Again, the same problem persists: suppose that males with $Y^*_i < 1000$ have $Y^*_i$ that are like females, but half of males have $Y^*_i > 1000$ whereas all female have $Y^*_i < 1000$. Again, there's a clear difference between males and females, but if you impute all males above $1000$ to have $Y^*_i$ like those males below $1000$, you will erroneously conclude there is no difference between genders, when again you'd expect one!
The lesson here is that a censoring problem should not be solved by imputation, unless you have a very good reason to believe it can.
2. What you may want to do
As you may have guessed based on the above, what you should do will depend heavily on your setup and what you think is reasonable. As a first step, you can always only look at $(Y_i,X_i)$ for $Y_i \leq 1000$. A regression with this data should be fine, except you have to be very clear about the interpretation! Even if the coefficient is the effect of $X_i$ on $Y_i$, here it is that effect for those with $Y^*_i \leq 1000$. Whether that matters depends on your setting. Given that many have $Y^*_i > 1000$, maybe this is not an interesting question.
A general class of regression models such models are called Tobit models, and I'd suggest you check out that page. For more information, check out this note on censored models. These Tobit models typically assume that
$$Y^*_i = \beta X_i + \epsilon,$$
where $\epsilon \perp \!\!\! \perp  X$ and $\epsilon \sim N(0,1)$. This normality assumption can also be relaxed: see the above note for relaxing that issue using Powell's CLAD Estimator.
Another area you may wish to explore is that of survival analysis, where this issue is very prevalent.
Comment: Independent -- should have used $\perp \!\!\! \perp $. I edited. Thanks!
Comment: Thank for the suggestions! I'm gonna try out.
Comment: What is the meaning of $\epsilon \perp X$ please?


Java - Why empty output on console?

Question: I've got a problem here:
I was asked to create a collection of random lottery numbers. These numbers should then be ordered from low to high and duplicates shouldn't be put out on the console.
It's working so far but the console throws an empty output when the size of the collection is not == 6. I gave an else instruction that the method should then be executed again.
Hope anybody understands and can help.
Thank you!
    import java.util.*;

public class Lotto {
    public static Collection<Integer> tippen() {
        List<Integer> liste = new ArrayList<Integer>();

        while (liste.size() < 6) {
            liste.add((int) (Math.random()*49+1));
        }

        Collections.sort(liste);

        LinkedHashSet<Integer> lottotipp = new LinkedHashSet<Integer>(liste);
        liste.clear();
        liste.addAll(lottotipp);

        return lottotipp;
    }

    public static void main (String[] args) {

        Collection<Integer> zahlen = tippen();

        if (zahlen.size() == 6) {
            System.out.println("Ihr Tipp: " + zahlen);
        } else {
            tippen();
        }
    }
}

Comment: @martijnn2008 `zahlen.size() != 0`, the `tippen()` method will never return something with size 0.  It will contain at least 1 element.
Comment: Ok sorry I misunderstood the code, but the purpose of `lottotipp` is magic for me.
Answer: As others have noted, your Collection doesn't always contain 6 elements, and then your method is called again but the results are never printed.
Easiest solution is to make the method always return 6 elements by adding the integers directly to the set until it has 6 elements.  That way you can throw out the whole boolean kludge.
Also note that you added the elements of the set to the list, sorted the list, but then returned the set.
public class Lotto {

    public static Collection<Integer> tippen() {
        TreeSet<Integer> lottotipp = new TreeSet<>();
        Random rand = new Random();

        while (lottotipp.size() < 6) {
            lottotipp.add(rand.nextInt(50) + 1);
        }

        return lottotipp;
    }

    public static void main(String[] args) {
        Collection<Integer> zahlen = tippen();
        System.out.println("Ihr Tipp: " + zahlen);
    }
}

Comment: Thanks Arjan, nice solution and explanation!
Comment: Hey Arjan, can i also just use TreeSet instead of LinkedHashSet?
Comment: @svb Sure, see updated answer.  Also check out this [Java Collection Matrix](https://docs.google.com/spreadsheets/d/1JSBPho-Df_1Km0SxXfjW8a8PRLLTeoDDiY8ePs_Ac-c/pub).  When in doubt, just try :-)
Answer:
I gave an else instruction that the method should then be executed again.

tippen is executed again, yes; but tippen doesn't have any output. You also don't use the result of tippen for anything the second time you call it.
If you want to run the whole thing again, re-run main, not tippen. (Probably by putting all of the code from main into a new function that doesn't take any parameters.)

Separately: If you want an int, I suggest creating a Random instance and using nextInt, rather than using Math.random to get a double, multiplying the double, adding 1 to it, and then coercing it to int.
Answer: Because your random (casted to int) sometimes returns the same value twice (or more)..
(int) (Math.random()*49+1)

Then, you remove the duplicates with LinkedHashSet, so the size aint 6 anymore.
LinkedHashSet<Integer> lottotipp = new LinkedHashSet<Integer>(liste);

Your "else" fixes that by calling the method again, but it does not print the output.
If you run it many many times, it will sometimes print the output, sometimes not...
Answer: You forgot to print your tipps();
Just print it:
System.out.println(tippen());

Answer: The problem is due to that if the size of zahlen is not 6, you invoke the tippen() method but it's not assigned to any object.
I added a do{}while(); block that is executed until the size of zahlen is 6.
public class Lotto {
public static Collection<Integer> tippen() {
    List<Integer> liste = new ArrayList<Integer>();

    while (liste.size() < 6) {
        liste.add((int) (Math.random()*49+1));
    }

    Collections.sort(liste);

    LinkedHashSet<Integer> lottotipp = new LinkedHashSet<Integer>(liste);
    liste.clear();
    liste.addAll(lottotipp);

    return lottotipp;
}

public static void main (String[] args) {

    Collection<Integer> zahlen = tippen();

    do{
    if (zahlen.size() == 6) {
        System.out.println("Ihr Tipp: " + zahlen);
    } else {
        zahlen = (tippen());
    }
    }while(zahlen.size() != 6);

}
}

If you want your program to print the numbers even if they are not six, you can do this:
if (zahlen.size() == 6) {
    System.out.println("Ihr Tipp: " + zahlen);
} else {
    System.out.println("Ihr tipp: " + tippen());
}

That should solve your problem.
Answer: Thank you all very much, i now solved it like this:
import java.util.*;

public class Lotto {
    public static Collection<Integer> tippen() {
        List<Integer> liste = new ArrayList<Integer>();

        while (liste.size() < 6) {
            liste.add((int) (Math.random()*49+1));
        }

        Collections.sort(liste);

        LinkedHashSet<Integer> lottotipp = new LinkedHashSet<Integer>(liste);
        liste.clear();
        liste.addAll(lottotipp);

        return lottotipp;
    }

    public static void main (String[] args) {

        Collection<Integer> zahlen = tippen();

        while(zahlen.size() != 6){
            zahlen = (tippen());
        }
        System.out.println("Ihr Tipp: " + zahlen);
    }
}

Comment: It still contains a bug, and is doing unnecessary looping.  See my [answer for details](http://stackoverflow.com/a/37775079/6178459).

Java - Why empty output on console?


Connecting to a web server via HttpClient

Question: I'm trying to connect to REST web server and I don't know what is going wrong. The code that connects is:
public List<Agenda> getAgenda(String dia) {
    try {
        Log.i(TAG, "It is inside getAgenda()");
        HttpClient client = new DefaultHttpClient();
        HttpGet method = new HttpGet(Settings.getServiceUrl() + "/" + dia);
        Log.i(TAG, Settings.getServiceUrl() + "/" + dia);
        //the line above prints: http://192.168.0.100/odonto/agenda.php/2012-02-01
        HttpResponse resp = client.execute(method);
        //return loadFromJSONArray(client.execute(method));
        Log.i(TAG, "Recebeu a response");
        return loadFromJSONArray(resp);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

Well, here is the thing: the line
Log.i(TAG, Settings.getServiceUrl() + "/" + dia);

prints on the debug window correctly. But the line:
Log.i(TAG, "Recebeu a response");

don't prints. So the problem is in line:
HttpResponse resp = client.execute(method);

But I really don't know how can this be wrong!! I've already tested the REST server with Firefox and it works just fine! The debug window with a filter to show just the tag System.err is in the link:
Answer: You are getting permission denial error. Please add below permission in menifest file after application tag
 <uses-permission android:name="android.permission.INTERNET"/>

Comment: I added the line and worked just fine!! It have other error but the connection is now working. Thanks a lot...


routing all network traffic over a internet host

Question: i would like to replicate what openvpn redirect-gateway does, routing all traffic over a internet server into the internet and back.
my client pc -> home router -> internet -> 126.96.36.199 -> internet
this is my normal "route -n" output with a working internet connection:
0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 ppp0
mydslip         0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

now i would like to send all traffic over 126.96.36.199, so not directly into the internet, but with a router in between.
what i tried:
route add default 188.8.131.52
which results in:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         188.8.131.52         0.0.0.0         UG    0      0        0 ppp0
0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 ppp0
mydslip         0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

this does not redirect the traffic as i would like, its still going straight into the internet and not over 184.108.40.206
so i tried (from the first routing table above):
route del default gw 0.0.0.0
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
mydslip         0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

but now adding:
route add default 22.214.171.124
results in:
SIOCADDRT: Network is unreachable

which makes sense since the default route is gone...how to add it?
the entry with 0.0.0.0 in the first 3 columns doesnt make sense to me:
0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 ppp0

how does that allow traffic to go anywhere?
i also tried this:
0.0.0.0         22.214.171.124         0.0.0.0         UG    0      0        0 ppp0
mydslip         0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
220.127.116.11         mydslip         255.255.255.255 UGH   0      0        0 ppp0
184.108.40.206         0.0.0.0         255.255.255.255 UH    0      0        0 ppp0
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

which does not work, packets go straight into the internet
Answer: Your approach won't work because the way IP routing works in general. Explaining IP routing here is not suitable for a Q&A site like Serverfault, it would take far too much text.
The way to make it happen is like this:

Create a tunnel for IP packets between source and your desired router.
Ensure that your routing table contains a valid route to your router (The public IP address of the router via a working gateway).
Replace the default route with the tunnel IP address of the router at the source computer.

You also need to make sure that this other router has proper configuration to route the packets from/to the tunnel.
Comment: maybe you know the name of a book or a link to a site that would help?
Comment: Googling for "IP routing" gives several resources on the subject. I read "Internetworking with TCP/IP Volume 1" book back in the days.


Can't get value from array

Question: I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57

JSON (value of: $this->bck_content)
{"email":"email@example.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}

My code
    # Display requested user details
    $details_array = json_decode($this->bck_content);

    $value = $details_array['email'];
    print $value;

Comment: Is this code being executed in a class?
Answer: You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);

This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;

Comment: thanks a lot, have been trying to find that error for at least an hour (probably closer to 2) :p
Answer: try this one
$value = $details_array->email;

or
json_decode($json, true);

or
$details_array = (array)json_decode($json);

what have you done wrong is writen in error description

Can't get value from array


Vector Cross Product and Expression for perpendicular distance between any two Vectors

Question: If $B \ne C$, prove that the perpendicular distance from $A$ to the line through $B$ and $C$  is $$\dfrac {|| (A-B)\times(C-B)||}{||B-C||} $$ where $\times$ means the vector cross product.
Attempt:
Let the perpendicular from point $A$ meet the vector joining $B$ and $C$ at the point $P$.
Let $X$ be the unit vector along $AP$.  Then : $||AP|| = ||(B-A) \cdot X|| = ||(C-A) \cdot X ||$
I don't have much idea on how to proceed from here.
Could anyone please give me a direction on how to move ahead.
Thank you very much for your help.
Answer: Hint: Use that $$||{\bf X} \times {\bf Y}|| = ||{\bf X}||\,||{\bf Y}|| \sin \theta,$$ where $\theta$ is the angle between ${\bf X}$ and ${\bf Y}$.
Comment: Thank you for the hint. I got it.
Comment: You're welcome, I'm glad it was useful.


Column 'XXX' in field list is ambiguous

Question: Estou com problema ao executar a seguinte Query:
 SELECT product_id,
       presentation
FROM Variant
INNER JOIN productCategory ON product_id = product_id
LIMIT 10;

Erro:
ERROR 1052 (23000): Column 'product_id' in field list is ambiguous

como posso resolver usando alias ?
Comment: Por mais que seja uma erro bem básico creio  que muita gente recorre para saber o que está acontecendo, +1. Editei a sua pergunta para dá um pouco mais de visibilidade.
Comment: coloque o nome da tabela na frente da coluna.
Answer: Isso acontece quando temos o mesmo nome de coluna em ambas as tabelas, daí ocorre o erro "ambiguous", para que o erro desapareça você deve indicar no seu select a qual tabela a coluna pertence.
Veja:
SELECT
   Variant.product_id,
   presentation
FROM Variant
INNER JOIN productCategory
ON productCategory.product_id = Variant.product_id
LIMIT 10;

Answer: Tente assim, amigo.
SELECT v.product_id,
       presentation
FROM Variant v
INNER JOIN productCategory p
ON v.product_id = p.product_id LIMIT 10;

Column 'XXX' in field list is ambiguous


Bootstrap range slider onSlideStop not working

Question: I'm trying to trigger an event from my range slider (bootstrap). Here's the code for the slider:
<code><input type="text" onSlideStop="alert(this.value);" data-slider-min="0" data-slider-max="10" data-slider-step="1" data-slider-value="[1,2]" id="sl2">
</code>
Now, I am able to trigger an event from JS, but since I'm going to have quite a bit of sliders on my page, I would like to trigger it from the slider itself.
Here's the code that does work on JS:
<code>$('#sl2').slider().on('slideStop', function(ev){
alert($('#sl2').data('slider').getValue());
});
</code>
JS fiddle link:
https://jsfiddle.net/hw1aer2f/
Answer: Turns out, jQueryUI interfered with the bootstrap slider script. I solved it by simply loading jQueryUI after bootstrap slider.


An integral identity, general multidimensional case

Question: A follow-up to this  question. Which of the following equations is true? Can someone give a proof to the correct equation. Thanks.
Please note the prefactors $N$ and $N!$
$$\int_0^A dx_1 \ldots  \int_0^A dx_N \quad f(x_1) \ldots f(x_N) = N
\int_0^A dx_1 \ldots\int_0^{x_{N-1}}dx_N \quad f(x_1) \ldots f(x_N)
\qquad \mathrm{Eq. 1}$$
$$\int_0^A dx_1 \ldots  \int_0^A dx_N \quad f(x_1) \ldots f(x_N) = N!
\int_0^A dx_1 \ldots\int_0^{x_{N-1}}dx_N \quad f(x_1) \ldots f(x_N)
\qquad \mathrm{Eq. 2}$$
Answer: The second is correct. Consider the unit cube and try to see that one sixth of it satisfies $x\le y\le z$. More generally, there are $N!$ permutations of any given $N$-tuple of values, and exactly one of them satisfies $x_1\le\dotso\le x_N$.


call specific name of views from module

Question: Below code changes the all quantity label to none. i am trying to change quantity field label for specific views block for ubercart3. (so in product node, quantity labeled as quantity and in product views block, quantity field is not labeled.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
    $form['qty']['#title'] = t('');
  }
}

How to call specific views from module? or is this something i should do in views template?
i tried the below code and qty label doesn't change.
if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
  $view = $form_state['view'];
  if ($view->name == 'my_view_machine_name') {
    $form['qty']['#title'] = t('');
  }
}

Answer: You need to replace 'my_view_machine_name' with your actual view machine name.
To get view machine name, you can edit your view, and in the URL you will see it: admin/structure/views/view/machine_name/edit
Comment: i did replace it with my view machine name. looks like my question is not clear. to get node type, i can use `$node = node_load(arg(1));
$node =$node->type;` what do i use to get view name? `$view = $form_state['view'];` doesn't load the view name.
Comment: i get Undefined variable warning. this is not the proper way.
Comment: That's odd... there should be a view object in $form_state.
Try this:
`if (strpos($form['#id'], 'your-view-machine-name')) {
    $form['qty']['#title'] = t('');
  }`
Don't forget to replace underscores with dashes in a view machine name, if any.
Comment: I understood what you mean, added another answer.
Answer: So you want to get a name of current view in form alter function, which is not related to this view - this form is just located on the same page.
Use views_get_current_view() to get current view is currently in use: $view = views_get_current_view();
If there is no view is currently is use, views_get_current_view() will return NULL, so we need to add additional condition: if ($view)
if (strpos($form_id, 'uc_product_add_to_cart') !== FALSE) {
  $view = views_get_current_view();
  if ($view && $view->name == 'my_view_machine_name') {
    $form['qty']['#title'] = t('');
  }
}

Comment: `views_get_current_view();` works but it gives notice 'Trying to get property of non-object' at  $view = views_get_current_view(); in product node page without views block.
Comment: I updated the answer: additional check if (isset($view))
Comment: i learned a lot from your answer.

call specific name of views from module


OpenCV image conversion from RGB to Grayscale using imread giving poor results

Question: I'm loading a 24 Bit RGB image from a PNG file into my OpenCV application.
However loading the image as grayscale directly using imread gives a very poor result.
Mat src1 = imread(inputImageFilename1.c_str(), 0);

Loading the RGB image as RGB and converting it to Grayscale gives a much better looking result.
Mat src1 = imread(inputImageFilename1.c_str(), 1);
cvtColor(src1, src1Gray, CV_RGB2GRAY);

I'm wondering if I'm using imread for my image type correctly. Has anyone experienced similar behavior?
The image converted to grayscale using imread is shown here:

The image converted to grayscale using cvtColor is shown here:
Comment: "Color" image in OpenCV means BGR. So second version of your code is not correct. It should use `CV_BGR2GRAY` for color conversion.
Comment: Thanks for the comment. I tried converting the image to grayscale using CV_BGR2GRAY instead of CV_RGB2GRAY, but got the same result.
Comment: Could you also attach your original image?
Comment: Unfortunately I can't post images to my posts with my current reputation. Also there is a limit to 2 hyperlinks within posts with my reputation.
Comment: Thanks for the hint. the original image is located here: https://picasaweb.google.com/lh/photo/F8iLVPIuFR5LiZJVe9sAqmfnfsOOxMA_38d73O1A0AM?feat=directlink
Comment: I've tried your image and both versions of code produce good-looking images. What version of OpenCV are you using? What OS? What version of `libpng` have you installed (if you are working on Unix/Mac)?
Comment: My configuration:
OpenCV 2.3.1
Ubuntu 11.04 x64
libpng: 1.2.44 (checked with libpng-config --version)
Comment: The image in my previous comment might have gotten converted during upload. I've uploaded a version which I checked did not get converted (and shows the bad image quality using code line 1 above). Here is the link: https://picasaweb.google.com/lh/photo/741vgSMlGfsUklVst5H4s2fnfsOOxMA_38d73O1A0AM?feat=email
Comment: I've tried your version of `libpng` and two versions of input image, but both ways of conversion work for me.
Comment: Not sure how to debug this any further...
Comment: Is there any particular reason for which the png image, being grayscale, cannot be saved as grayscale png image?
Answer: I was having the same issue today. Ultimately, I compared three methods:
//method 1
cv::Mat gs = cv::imread(filename, CV_LOAD_IMAGE_GRAYSCALE);

//method 2
cv::Mat color = cv::imread(filename, 1); //loads color if it is available
cv::Mat gs_rgb(color.size(), CV_8UC1);
cv::cvtColor(color, gs_rgb, CV_RGB2GRAY);

//method 3
cv::Mat gs_bgr(color.size(), CV_8UC1);
cv::cvtColor(color, gs_bgr, CV_BGR2GRAY);

Methods 1 (loading grayscale) and 3 (CV_BGR2GRAY) produce identical results, while method 2 produces a different result. For my own ends, I've started using CV_BGR2GRAY.
My input files are jpgs, so there might be issues related to your particular image format.
Comment: Opencv imread returns image in BGR format , so I think the correct conversion to GRAY Scale is CV_BGR2GRAY as you have mentioned in the 3rd method
Answer: The simple answer is, that openCV functions uses the BGR format. If you read in a image with imread or VideoCapture, it'll be always BGR. If you use RGB2GRAY, you interchange the blue channel with the green. The formula to get the brightness is
y = 0.587*green + 0.299*red + 0.114*blue

so if you change green and blue, this will cause an huge calculation error.
Greets
Comment: Isn't it then also interchanging the red channel? In this case interpreting the given `BGR` as `RGB` which then leads to (the actual) `B` being falsely interpreted as `R`, and `R` as `B`?

So according to your answer the fix would be replacing `CV_RGB2GRAY ` in the `cvtColor` call with `CV_BGR2GRAY`?
Answer: I have had a similar problem once, working with OpenGL shaders. It seems that the first container that OpenCV reads your image with does not support all the ranges of color and hence you see that the image is a poor grayscale transformation. However once you convert the original image into grayscale using cvtColor the container is different from the first one and supports all ranges. In my opinion the first one uses less than 8 bits for grayscale or changing to the grayscale uses a bad method. But the second one gives smooth image because of more bits in gray channel.
Comment: Did you find a documentation to support this reasoning? Facing a similar issue & I'm inclined to believe this might be the case but cannot find anything conclusive to put down in my reasoning
Comment: Well it is the case since the frame buffer contains a range of 255 for each color and also 255 for monochrome spectrum. You need floating points to support a better range.


Adding a query string to a link in Views

Question: I've added an "Add Comment Link" to a View and I'm wondering how I would go about adding a custom query string to the generated URL?
I'd guess I need to do something under "Rewrite Results", either with "Rewrite the output of this field" or "Output this field as a link" but I only seem to have an option to include the fully rendered link as a replacement token.
Is there a way (without resorting to regex) to get the URL from the link so I can rewrite the output myself? Or is there an easier way to add the query string?
Thanks
Comment: @j2r: It is a field, but I guess there's nothing in the UI already to do this? That's not a problem as templates are fine for my purposes. If you want to post that as the answer I'll accept it, thanks :)
Comment: IF the link is field of view it could be possible to get the url in tpl using the $row variable.
Answer: If the link is a field of view, it could be possible to get the URL in the template file using the <code>$row</code> variable.


Dúvida com Concat no Oracle

Question: Estou com um problema na exportação de dados para o Excel, o número gravado no banco e muito grande gerando vários  carácteres estranhos na conversão que o Excel tenta fazer, por isso preciso enviar ele
assim:'51150547067525018740550080000038621721439107'

Valor Original : 51150547067525018740550080000038621721439107

Como eu poderia ter está saída?
select  CONCAT( CAST (nf.chave AS VARCHAR(255)),'*')  from NF nf

Resultado atual: 51160307053693005199550510000032181665018130*
Comment: Não foi eu que negativei, apenas editei sua pergunta.
Comment: Qual foi o valor original, que após formatado, gerou o resultado citado?
Comment: @gato, qual foi o problema da pergunta?
Comment: @gato, ok, eu já estou acostumado, tanto que tenho outras opções que passei a utilizar mais devido a isso, já está ficando desgastante utilizar o forum
Comment: @AndersonCarlosWoss, ajustei a pergunta
Comment: Então o que precisa fazer é remover o asterisco no final e colocar entre aspas simples?
Comment: @AndersonCarlosWoss, eu gostaria que tivesse aspas simples dois dois lados, coloquei o * porque desta forma o Excel não consegue alterar o formato do campo
Comment: @AndersonCarlosWoss, encontrei a solução, mais agradeço a ajuda
Answer: A solução para o problema:
select  ''''|| nvl(nf.chave, '-')||''''  from NF nf

Desta forma tenho o resultado:

'51160307053693005199550510000032181665018130'

Dúvida com Concat no Oracle


High CPU load in a data aquisition server

Question: I`ve setup a small python program that uses a websocket connection to acquire data from an API and write it to a postgresql database.
There are only two (user) programs running: the websocket connection that receives data and write it to the database, and another program that is basic a while loop that runs every 15 seconds and check if data is being written.
Both programs are daemonized with supervisor and when no data is being written for 15 seconds, supervisor is restarted (to handle dead websocket connection).
Also I was (very) lazy and used Django ORM to do the db connection for me instead of psycopg2 directly.
It works, but I'm having a steady high cpu load on the server. It is a 1CPU 1Gb memory server (AWS micro). Top command outputs the following:
top - 17:10:58 up 19 days, 15:03,  1 user,  load average: 1,57, 1,63,    1,58
Tasks: 116 total,   1 running, 115 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0,3 us,  0,3 sy,  0,0 ni,  0,0 id, 99,0 wa,  0,0 hi,  0,0 si,  0,3 st
 KiB Mem :  1014552 total,    63440 free,    86572 used,   864540 buff/cache
 KiB Swap:  1048572 total,   987380 free,    61192 used.   615096 avail Mem

Well, system is laggish and ocasionally crashes.
I can see that this is caused by a high IO load (99 wa). Lots of sleeping processes. But I`m writing an average of 400MB per day only on the database.
I've tried modding Postgresql config for high writing load following documentation and setting up a swap memory file (1GB), but those didn`t help on easing the load average.
So, for a non-experienced user like me, I don't know if this is the load I should expect. Can I optimize this setup? If I remove django ORM and write the program using only psycopg2, would it improve? Should I make a different check method for dead websocket connections? Is there any server config that can optimize for this need case?
Thanks!
Comment: If `wait`  is at 99% then there's a huge amount of io happening. 400MB/day should be barely noticeable on any modern hardware. Saying that, 1GB of ram is quite small - what is the memory usage on this system? If you're enabling Swap then this could be that the system is using the disk in place of memory, leading to massive io spikes.  See what effect `swapoff -a` has on io and memory usage?
Comment: Hi @match!  Thanks for the response. Enabling memory swap didn't make any change on the load. I have 600MB free memory (seen in top command). After your comment about 400MB a day, I think my code is messed up somehow. How can I debug this IO access to check for sure if the python process is the bad guy.
Comment: You're right actually that memory isn't the issue - I just clocked the memory lines from top - most of it is in buffers, and swap is hardly used, so it's not swap at fault here. I'd check the python script (I assume it's the `1 running` in top), but also check that nothing has high amounts of debug logging enabled (potential source of lots of disk io).
Answer: I manage to figure out how to fix it using this link http://bencane.com/2012/08/06/troubleshooting-high-io-wait-in-linux/
Basically I ran iotop and that outputed which process was causing high IO load. There I found out that the load was due to reading the database and not writing. So I realized I was doing something stupid: I was quering entire database a lot by counting the number of entries while checking if it was recording. That was averaging 500MB/s of reading. So I changed the code to check the Primary key number of the last entry  instead of counting entries and...  worked. Load average is now 0.01. Thanks @match for the headsup


Is cross validation only for comparing tuning parameters?

Question: If I'm creating a model (in R with caret), and don't have any tuning parameters I want to compare, is there any use for cross validation? In other words, I wouldn't use cross validation to validate my model, right? It's just for finding the model?
Comment: How are you planning on validating the model?
Comment: Splitting my data into training and testing datasets and testing on the testing dataset. However, if I don't need to do that and can use cross-validation, that's what I'd prefer.
Comment: If you are splitting your data to training and testing set, then *you are* using cross validation...
Comment: ... that is, you are performing one particular (and not the best) scheme of the large family of cross validaton resampling schemes.
Answer: It is better to have a separate test set to evaluate the performance of the model. However, if there are too few observations to make a split between test and train set, you could use the PRESS statistic instead, by removing the observations one by one and evaluating the sum of squared differences from the predicted values, using the remaining observations.
$$\text{PRESS} = \sum_{i=1}^n(y_i-\hat{y}_{-i})^2$$
This procedure is a form of cross-validation, so I assume it is what you are referring to.
Comment: Note that in my field (chemometrics) this leave-one-out estimate of PRESS would often be referred to either as $PRESS_{CV}$ or  $MSE_{CV}$  (as opposed to $MSE_P$ for independent predictions) to indicate that the mean squared error was calculated via some cross validation procedure and not from independent testing.
Answer: The primary purpose of cross validation is measuring model performance.
So, yes, you can use cross validation results for validation (or, to be more precise for verification) purposes.
The use of cross validation estimates during model tuning is just another use you can make of model performance estimates. However, it is important to understand that once you've used your cross validation results to drive model tuning, they have become part of your model training and are in that sense training error estimates. So in that case for valdiation adn verification purposes you need to measure the performance of the final model - leading to the typical nested or split-into-3-sets plans.

Whether test set or cross validation are better depends on a number of circumstances, namely

the number of cases you have available (for testing),
the figure of merit you try to estimate (proportions need far more test cases than e.g. mean squared error or Brier's score)
whether you can really achieve splitting into independent training and test sets (depends e.g. on whether your data has clusters of cases)

So,

If the test set is produced by the same splitting strategy (e.g. random selection of data rows) as cross validation, it is worse: it is subject to all the pitfalls of getting dependence between train and test set that cross validation is subject to. In addition, fewer cases are tested, leading to higher random uncertainty (variance) on the results.
Independent test sets are better than cross validation if

you use them to ensure independence by the data generation process, e.g. acquiring the test data only after model training is finished, and
you make sure this test set is large enough to have acceptably low variance on the performance estimate.


Qual a diferença entre '@Url.Action' vs 'asp-controller' junto ao 'asp-action'?

Question: Estou realizando um projeto em ASP.NET MVC e me surgiu essa dúvida, O Url.Action em uma tag '' (por exemplo numa navbar) pode redirecionar a página passando o método e controller como parâmetro. Entretanto existem os atributos asp-controller (defino o controller) e asp-action (defino o método) que traria o mesmo resultado, isso é possivel?

Home

Home

Answer: Na prática não há diferença, a saída gerada será a mesma. O que muda é que auxiliar de marca de ancora é mais semântico com o html, é como se tu escrevesse html puro pra montar tuas tags html


Como armazenar em uma variável o número de linhas encontradas a partir de uma consulta MySQL

Question: Tenho um Menu lateral na minha página e quero exibir um texto de alerta para o usuário, indicando quando ele tem novas mensagens e a quantidade delas. Para isso fiz a consulta no BD e ela me retorna corretamente a quantidade de registros baseados na query que montei.
O problema é quando insiro no código, pois não está retornando dado algum.Fiz assim:
   if ($usuario->getCodEquipe() == 1 ) {

        $dbc = mysql_connect('localhost', 'root', '', 'nome_banco');
        $query = "SELECT count(*)  FROM  FaleConosco WHERE status = '0' ";
        $result = mysql_query($dbc, $query);

        echo "
\n";
        echo "
\n";

        echo "
Comunicação
\n";
        echo "
\n";
        echo "
Voltar
\n";
        echo "
Administrar Notícias
\n";
        echo "
\n";
        echo "
Moderar Comentários
\n";
        echo "
\n";
        echo "
QVT
\n";
        echo "
\n";
        echo "
Fale Conosco";

        if($result != 0)
        {
            echo " - $result Nova(s)";
            mysql_close($dbc);
        }

        echo "
\n";
        echo "
\n";

    }

A intenção é armazenar em uma variável o resultado da consulta, e no if do código comparo o valor e exibo o alerta. Usando a query diretamente no banco, ela funciona e me retorna o número dois, porém neste código não retorna nada. Alguém sabe me dizer o motivo?
Obs: fiz no PHP e MySQL
Answer: Inverte os parâmetros na chamada da função:
Disso
$result = mysql_query($dbc, $query);

Para isso
$result = mysql_query($query, $dbc);

Não cheguei a testar, mas vê aí.
Answer: Primeiramente está usando uma função obsoleta e descontinuada nas últimas versões do PHP.
Dependendo de qual versão do PHP está a usar é impossível usar o mysql_query, assim como impossível usar qualquer função do mysql_*.
Para saber o mais informações sobre o mysql_*, clique aqui.
Solução:

Use mysqli_* (recomendado):
$dbc = mysqli_connect('localhost', 'root', '', 'nome_banco');
$query = "SELECT count(*)  FROM  FaleConosco WHERE status = '0' ";
$result = mysqli_query($dbc, $query);

Isso irá usar o mysqli_* ao invés do mysql_*.

Repare o mysql_:
$dbc = mysql_connect('localhost', 'root', '', 'nome_banco');
$query = "SELECT count(*)  FROM  FaleConosco WHERE status = '0' ";
$result = mysql_query($query, $dbc);

Isso irá corrigir o parâmetro passado, de maneira invertida no $result, como mencionado pelo @CleitonCardoso.
Answer: O resultado é acessado utilizando o método mysql_result
Fiz algumas alterações no seu código, mas não tive como testar pois atualizei o PHP em meus servidores e a lib mysql_... não funciona mais... logo, não tenho como garantir que está funcionando, mas acho que dá uma idéia do caminho a seguir... segue código atualizado:
 if ($usuario->getCodEquipe() == 1 ) {

        $dbc = mysql_connect('localhost', 'root', '', 'nome_banco');
        // utilizai o "as qtd" para identificar o campo por string
        $query = "SELECT count(*) as qtd  FROM  FaleConosco WHERE status = '0' ";
        $result = mysql_query($dbc, $query);

        echo "
\n";
        echo "
\n";

        echo "
Comunicação
\n";
        echo "
\n";
        echo "
Voltar
\n";
        echo "
Administrar Notícias
\n";
        echo "
\n";
        echo "
Moderar Comentários
\n";
        echo "
\n";
        echo "
QVT
\n";
        echo "
\n";
        echo "
Fale Conosco";

// pega o número de registros convertidos para inteiro na base 10
$num_registros = intval(mysql_result($result,0,'qtd'), 10);
        if($num_registros !== 0){
            echo " - $num_registros Nova(s)";
            mysql_close($dbc);
        }

        echo "
\n";
        echo "
\n";

    }

Espero ter ajudado!


How to do a Full Outer Join using old style Oracle syntax

Question: I have two tables with the same columns, Item Code and Qty, for each Table:
TABLE A                    TABLE B
--------------             -------------
X    2                      X   1
Y    1                      S   2
Z    5                      Z   5

The result that I am aiming to get is something like this:
Table C
---------------
X  2  1
Y  1  0
S  0  2

I only need the items where  qty differs in both tables (including the nulls which should be shown as zeroes.
Note: I am using Oracle8 so I can't use the ANSI FULL OUTER JOIN.
Comment: Probably because you didn't say which version of Oracle you were using, something that is *highly pertinent* to the answer. Three people wasted their time providing answers which you couldn't use because you failed to provide that simple piece of information.
Comment: Oracle8? Really? That has been put out of support for ages. You should really, really think about an upgrade.
Comment: @nayef Out of interest, why are you still on Oracle 8? I hated that whole major release.
Comment: (late to the party) For future reference: http://stackoverflow.com/privileges/vote-down *"Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect."*
Comment: What version of oracle?
Comment: Why The Negative Vote ???!
Comment: @DavidAldridge the retail Company I Work Didn't Approve The Budget to upgrade this Year Hopefully Next Year :) Its Giving Me A Head Ache also
Comment: Presumably they haven't approved the budget for the last decade.
Comment: This question has been the best fun ever.
Comment: (I admit I haven't always adhered to that guideline consistently in the past)
Answer: Edit, Since the question is specific to Oracle 8 which does not use ANSI syntax, the following should work:
select col1,
  nvl(a_col2, 0) as a_col2,
  nvl(b_col2, 0) as b_col2
from
(
  select a.col1, a.col2 as a_col2, b.col2 as b_col2
  from TableA a, TableB b
  where a.col1 = b.col1(+)
  union
  select b.col1, a.col2 as a_col2, b.col2 as b_col2
  from TableA a, TableB b
  where a.col1(+) = b.col1
)
where a_col2 <> b_col2
  or (a_col2 is null or b_col2 is null)

See SQL Fiddle with Demo. This will return:
| COL1 | A_COL2 | B_COL2 |
--------------------------
|    S |      0 |      2 |
|    X |      2 |      1 |
|    Y |      1 |      0 |

If you are using a version of Oracle that supports ANSI syntax then you can use the following FULL OUTER JOIN:
select
  coalesce(a.col1, b.col1) col1,
  coalesce(a.col2, 0) a_col2,
  coalesce(b.col2, 0) b_col2
from tablea a
full outer join tableb b
  on a.col1 = b.col1
where a.col2 <> b.col2
  or (a.col2 is null or b.col2 is null);

See SQL Fiddle with Demo
Comment: @APC If you notice my version is not the same.  Your version actually does not work, I tested it in SQL Fiddle and it only returned one row.
Comment: @APC remember that answers here are not useful only for the OP. Future readers may benefit from answers especially since most people trying to solve this problem won't still be running Oracle 8. In fact the OP may get the most use out of this answer after all, if and when they migrate from that archaic platform.
Comment: My solution worked in my test environment but I guess something got lost in the retyping.  Anyway I have deleted my answer and I aplogise for any offence caused by my comments.
Comment: @nayefharb What version of oracle are you using?
Comment: @DavidAldridge They had not stated Oracle 8 until after this answer was posted. I have added a note, but I think the downvote is completely unfair
Comment: @APC dude, go step outside and look at the sky for a few minutes. Nobody stole your solution. Accusing someone of theft is a pretty serious allegation, and I'd be very careful about spraying that kind of crap around.
Comment: @APC don't see how that's related to this specific scenario, and I hardly see any community consensus there in any case. Do you see any specific policy anywhere that states that SO users must down-vote answers that are later found to not help the OP because they forgot to mention which version they were using? Or that an answer should be down-voted because it is a useful answer for most but doesn't directly satisfy the OP due to some variable (e.g. they are running an unsupported version)? You are of course free to down-vote whatever you like for any reason. But lighten up.
Comment: It Wont Except Full Outer Join as Syntax i can use the (+) sign
Comment: This is the clearest benefit of the newer ANSI joins;  we can't do this half as easily in pre-9i Oracle using the `(+)` syntax.
Comment: @nayefharb See my edit I added a version that should work in Oracle 8
Comment: @aaronb - regarding answers which don't help the OP but may be relevant to future szeekers: http://meta.stackexchange.com/questions/166566/lots-of-not-always-useful-but-well-intentioned-answers
Answer: Another writing of the query which should work in 8 and (probably earlier versions).
It uses neither FULL JOIN not the horrible (+) syntax for joins so it should work even when an upgrade deprecates it.
Assuming that there are no Nulls already on the tables, you won't need COALESCE() or NVL() either:
SELECT  a.col1,
        a.col2 AS a_col2,
        b.col2 AS b_col2
FROM    TableA a, TableB b
WHERE   a.col1 = b.col1
  AND ( a.col2 <> b.col2
     OR a.col2 IS NULL
     OR b.col2 IS NULL
      )

UNION ALL

SELECT  col1, col2, 0
FROM    TableA a
WHERE   NOT EXISTS
        ( SELECT  *
          FROM    TableB b
          WHERE   a.col1 = b.col1
        )

UNION ALL

SELECT  col1, 0, col2
FROM    TableB b
WHERE   NOT EXISTS
        ( SELECT  *
          FROM    TableA a
          WHERE   a.col1 = b.col1
        ) ;

Tests at SQL-Fiddle
Answer: select code, nvl(a.qty,0) a, nvl(b.qty,0) b
from tableA a full join tableB b using(code)
where decode(a.qty, b.qty, 0) is null

fiddle
Comment: @nayef I don't think you could have known that it would cause this much strife (I think comments would have been more than sufficient once the version was revealed). However you should *always* include the version when posting questions - you can't always know in advance when the version is actually quite relevant.
Comment: Well I didn't conduct a forensic analysis of the exact timings of everything before voting, and unfortunately I can't un-downvote 'em ... apparently it gets locked in by stackoverflow unless the answer is edited. Sheesh! Anyway, if you want to make some minor edit to satisfy stackoverflow I'll take the downvote off ...
Comment: Hey @David would you stop down-voting everyone who answered before the OP bothered to mention what version he was using? A comment would suffice instead of punishing them for assuming the user wasn't on a 15-year-old platform.
Comment: @AaronBertrand - regardless of when the OP posted their version, the fact remains that ANSI syntax solutions are not an appropriate answer to this thread, and hence downvoting is justified.
Comment: @DavidAldridge your responses here have been very gracious indeed in my opinion, 'reasonable' really is your middle name! It's also great to see you on dba.se and I do hope we see more of you over there :)
Comment: @APC I guess we'll have to agree to disagree. *shrug*
Comment: @AaronBertrand Sorry For the Version Trouble i didn't Know that it was a version issue i am a SQL server  guy
Answer: Another option:
select
  full_list.item_code,
  nvl(table_a.qty,0) table_a_qty,
  nvl(table_b.qty,0) table_b_qty
from
  (select item_code from table_a
   union
   select item_code from table_b) full_list,
  table_a,
  table_b
where
  full_list.item_code = table_a.item_code(+) and
  full_list.item_code = table_b.item_code(+)

Comment: Not sure, possibly retribution for down-voting everyone else, who answered before they knew the system was from the dark ages.
Comment: SQL fiddle don't do 8i, so it's relevance would be a bit suspect. Anyway, fat distracted finger error corrected in the answer
Comment: @DavidAldridge SQL Fiddle should be able to support the older syntax, I have no experience with Oracle 8, but this fiddle seems to be working and with a few alterations it returns the result the OP wanted -- http://sqlfiddle.com/#!4/cc96f/9
Answer: The following query should work just right:
SELECT * FROM (
  SELECT nvl(a.c1, b.c2), nvl(a.col1, 0) qty1, nvl(b.col2, 0) qty2 FROM a FULL OUTER JOIN b ON a.c1 = b.c2
) where qty1 != qty2;

http://sqlfiddle.com/#!4/d37ff/5/0


Amplify makes `Failed to load resource: the server responded with a status of 400` error

Question: I got this error with Amplify, I finished the build tho.
Failed to load resource: the server responded with a status of 400
manifest.json:1

This system can work in the local environment. Package.json script of the local env is this.
  .......
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "format": "./node_modules/.bin/eslint --fix --ignore-path .gitignore ."
  },
  .......

My amplify.xml is below.
version: 1
frontend:
    phases:
        preBuild:
            commands:
                - nvm install 14.15.0
                - nvm use 14.15.0
                - yarn install
        build:
            commands:
                - nvm install 14.15.0
                - nvm use 14.15.0
                - node -v
                - yarn run build
    artifacts:
        baseDirectory: public
        files:
            - '**/*'
    cache:
        paths:
            - 'node_modules/**/*'

The screen is totally brank.

Is there anyone who has the same trouble?
Answer: I ran into the same problem and after spending hours troubleshooting, it turned out to be an Amplify CI/CD build configuration problem.
While connecting the repository to the Amplify app, you are prompted to edit the build settings in the amplify.yaml file. For whatever reason, the default value for baseDirectory is set to public.
Download the file, place it in the repository root, and change:
artifacts:
  baseDirectory: public

to
artifacts:
  baseDirectory: build

Commit, push, reconnect the branch and it should work.


Someone suggested i use Jquery to validate my Form But its not working, how do i fix?

Question:

<meta charset="utf-8">
<title>Untitled Document</title>

<form id="Subscribe" method="POST" action="subscribe.php">

Enter Name: <input id="Name" type="text" name="Name"     size="20">

Enter Email: <input id="Email" type="text" name="Email"     size="20">

 Enter DOB: <input id="Dob" type="text" name="Dob" size="20">

<input type="submit" value="Save Data" name="Submit">

</form>

And the PHP which leads to another page once true

$location = "subscribe.1.homepage.html";
header( "Location: $location" );

I need to code to have validation on the email, dob and name and I cant seem to get it working. I believe i've done it all correctly but arnt too sure. i only started looking into it last night
Comment: to add to the answers you only need either the `jquery.validate.min.js` or `jquery.validate.js` not both. Currently you have a typo there as well(jquery.validate.min.jsSS) and for the `DoB` field , use `date:true` instead of `number:true`
Comment: What do you mean by 'not working'? Specifics are helpful. And you can use client side validation as a way to improve the UI and give visual feedback to the user but you shouldn't rely on it to safety check the user input... I can remove your JS from the browser dev tools. Always have a server side validation as well.
Answer: $(document).ready(function(){

$("#Subscribe").validate({

rules: {

    Name: {
        required: true,
        minlength: 2,
        maxlength: 15
        },

    Email: {
        required: true,
        email: true
        },

    Dob: {
        required: true,
        number: true
        }
    }});

});

Comment: how would adding the top part of the code help? The $doc and $("Sub sections? thanks for the () and {} issues though
Answer: your script terminates a little prematurely
$(function() { // you missed the first ( on this line
    $("#Subscribe").validate({
        rules: {
            Name: {
                required: true,
                minlength: 2,
                maxlength: 15,
            },
            Email: {
                required: true,
                email: true
            },
            Dob: {
                required: true,
                number: true
            }, // you stopped here!!

need the following at least
        }
    })
});


R: Parsing multiple values into a single field

Question: I have multi-class classification dataset with data saved in the form.
[number, ..., number],number,number... ,number \n
The numbers inside brackets are the labels and have varying length. Numbers after are features with fixed length $n$. How to parse this into a R table?
Answer: There probably is some perfect way to load everything in one fell swoop but since it sounds like you need a quick-and-dirty solution, you could try something along the lines of:
library(stringi)

df <- read.table(my.table, header=FALSE, sep=']', stringsAsFactors = FALSE)
vals <- stri_split_coll(df$V2, pattern=',', simplify=TRUE, omit_empty = TRUE)
vals <- data.frame(apply(vals, 2, as.numeric))

labels <- stri_replace(df$V1, '', fixed = '[')
rownames(vals) <- labels

Does this get the job done for you?
[Note: If your data has a header then just add the argument "skip=1" to read.table and either add the columns manually or run the function again (with "nrows=1"), etc.]
Comment: Yep, quick and dirty is fine. Getting vals and labels out fine all that is needed. Can't assign rownames(vals) <- labels, since there is requirement for rownames to be unique. Got my data tho, accepted. Thank you!


The rank of a linear combination of operators

Question: Suppose we have two linear operators $X,\,Y$ on $\mathbb{C}^n$. Now let $a,b\in\mathbb{C}$ and consider $Z_{a,b}:=aX+bY$. When we look at their images we clearly have $$im\,Z_{a,b}\subseteq \,im\,X+im\,Y,$$ but in general this inclusion is strict.

Is it true that the equality holds whenever we take $a,b\in\mathbb{C}$ sufficiently general?

What if we know that $X,Y$ satisfy $XY=YX$, that is, if $X,Y$ commute?

Here sufficiently general means that $\frac{a}{b}\in\mathbb{C}$ belongs to the complement of a certain finite set (depending on $X,Y$).
Answer: The answer to 1 is no. For instance, consider
$$
X = \pmatrix{1&0\\0&0}, \quad Y = \pmatrix{0&0\\1&0}.
$$
I suspect that the answer to 2 is yes. It is clear that the answer must be yes when both $X,Y$ are diagonalizable, because in this case $X$ and $Y$ commute and are therefore simultaneously diagonalizable.
Comment: Part 1 is now clear to me. Could you please elaborate more part 2? How the particular format of matrices imply the result?
Comment: @amateur On second thought, simultaneous upper-triangularizabiltiy is not enough.
Comment: I will be happy to know of a third thought.
Comment: A negative answer to the second question is given by
 $$ X=\left[ \begin{array}{ccc} 0 & 1 & 0\\
     0 & 0 & 0\\ 0 & 0 & 0 \end{array} \right],\ \
    Y=\left[ \begin{array}{ccc} 0 & 0 & 0\\
     0 & 0 & 0\\ 0 & 1 & 0 \end{array} \right]. $$


Creating an Apache Virtual Directory, but updating Active Directory DNS

Question: I'm just getting started with using the Zend Framework and am following a recommended procedure where I am supposed to create an Apache Virtual Directory for the public-facing portion of a new Zend project.  I don't THINK I had any issues creating the Virtual Directory, but my knowledge of the required DNS changes is rather lacking.  The dev server I'm using is on a Microsoft Windows Active Directory domain, so I've added A records for both the server name and the subdomain.  Still, trying to browse to the site from a Windows 7 PC isn't working properly.  What am I missing?  What's the proper set of steps for getting an Apache-served subdomain to appear properly in a peer computer's web browser?  Details below:

server: Debian command-line only, freshly installed today with Zend Server CE LAMP stack
server name: ZENDEV
subdomain: SQUARE.ZENDEV
AD Domain functional level: 2008 mixed (run by a mishmash of 03 and 08 servers)
attempting to visit the sites: http://square.zendev and http://square.zendev.domain.local (name of domain redacted, but using the local (not com) suffix)

Apache Virtual Directory added to httpd.conf:
NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot "/var/www/square/public"
ServerName square.localhost
</VirtualHost>

Is this only a problem with DNS?  Or with DNS and my Virtual Directory?
Answer: Create a zendev zone in your AD DNS.
Create an A record within that zone called "square" and point it at the IP address of your server.
In the apache config change ServerName square.localhost to ServerName square.zendev
This is all assuming that your computer resolves DNS via the Active Directory nameservers.
Comment: Ah!  I just figured it out right before you answered. (see my comment, below).  Turns out I did properly by making the A records manually in ADDNS, but ruined the Apache declaration.  Thanks very much!!
Answer: Apologies, after a little more fiddling around, I noticed my issue.  It was leaving "square.localhost" as the ServerName in my Apache declaration...I should have used "square.zendev".  Thanks anyway!


Problema com o "sum" no RStudio

Question: Tenho um problema com a função sum no RStudio que retorna o erro que anexo. Sei que é um erro que não deveria ocorrer pois não é do código. Já reinstalei o RStudio e continua a dar o mesmo erro. Este erro não ocorre no R nem no RStudio de outro portátil. O que me aconselham a fazer? Existe alguma package que corrija isto?
x <- sample( 6, 1000, replace = T)
sum ( x == 3)
Erro
Error in sum(x == 3) : argument "x" is missing, with no default
Comment: pelo que li em outros lugares, isso pode ser por você ter duas funções com o nome sum, se você der um rm(sum) e tentar em seguida, o que acontece?
Comment: Caro Lucas Miranda. Obrigado pelo seu comentário. Ficou resolvido. Ainda tenho pouca experiência e não imaginava que fosse esse o problema.
Comment: Bom dia, taunus, que bom que resolveu! responda a própria pergunta então e marque como certa para futuramente caso alguém ter essa duvida saiba o que fazer!
Answer: A questão foi resolvida com o apoio do Lucas Miranda e a solução consistia em limpar a memória do RStudio através do comando rm(sum)pois existia uma função com o nome de sumque estava a gerar conflito com a operação de somatório

Problema com o "sum" no RStudio


How to get file temporary path in php while file upload

Question: I am using Uploadify jQuery plugin for file upload.Here there is no browse button used.
it will upload the file using ajax on click event.So There is no file temp path is displaying.So i want to make it display.
So, I try to get file temp path using $_FILES['uploadfile']['tmp_name']. But it just return something like this /tmp/phpclqHXj.But i want display actual temp path like C:\Users\Diamantino\Desktop\file.jpg.Can i get this using php. any option in uploadify
plugin, anyway to get jquery or js.Any help would be appreciated.
My Browse button.

Thanks
Comment: Related, though not really a duplicate: http://stackoverflow.com/questions/2427936/php-copy-problem-with-uploaded-file
Comment: You need to display path on page? Or you need it in PHP script?
Comment: @Timur: I want it display in my page. not php.if possible in php i return it from ajax page.if possible in jquery i will use it directly on my page
Comment: @gowri, Uploadify displays the name of selected files. You need full path instead? It is may be under some security restrictions
Answer: At the very least, you're looking for the filename found under:
$_FILES['uploadfile']['name']

Instead of C:\Users\Diamantino\Desktop\file.jpg, this will return the filename: file.jpg
However, with the use of simple Javascript, you may be able to accomplish getting the entire file path. With some logic on your end, you may be able to get the file path only when the file is uploaded. Here is an example, and some clarity on implementation.
Comment: :i'm not looking for file name.looking for only full temp path
Answer: There is no way to get the full path to the file from your user's computer. You can get the file name (in your example that would be "file.jpg") using $_FILES['uploadfile']['name']. Security issues would arise if you could get information about your user's local folder structure when they upload a file, so web browsers are very unlikely to send that data. If there is some browser that does send it, it won't appear in the $_FILES superglobal, nor will there be any other easy way to access is in php.


call js in html.tpl.php

Question: I want to add smoothstate script to my pages.
I have to call 2 files at the bottom just before closing body-tag. Smoothstate.js and Functions.js. How can I call those 2 js in my html.tpl.php

Smoothstate.js
Comment: Are you asking how to add the call to your tpl file, or are you asking how to fire off the functions of these .js files?
Answer: Its too simple my friend. For these types of manipulations template_process_html(&$variables) comes handy. This is provided by theme.inc located in includes/ folder of your drupal directory.
You can put this function in your template.php file of your custom theme directory
/**
 *Implementing template_process_html()
 */

function custom_theme_process_html(&$variables) {
    $path = drupal_get_path('theme','custom_theme');
    $variables['scripts'] .= '
';
}

This will append these new scripts to your scripts variables that is rendered to html.tpl.php as

call js in html.tpl.php


Grafana - create table with column values with Prometheus (dynamic) property/label data

Question: When I have a Prometheus query resulting in:
my_metric{instance="instance1",job="job",prop_1="ok",prop_2="cancel"} 1
my_metric{instance="instance2",job="job",prop_1="error",prop_2="ok"} 1

How can I create a Grafana table showing:
timestamp | instance1 | ok    | cancel
timestamp | instance2 | error | ok

So a Prometheus metric property is mapped to Grafana table column.
OPEN QUESTION: Is it possible to change the value of a tag dynamically? So the 3rd and 4th label (or property) values change over time.
Answer: QUESTION 1: The first part of the question is simple: Formatting the prometheus labels/properties in a table is easy. The answer you can find in this description.

How? Just select the 'table' format as shown in the second red box.

QUESTION 2: any idea?
Comment: Answering "Question 2: Is it possible to change the value of a tag dynamically? So the 3rd and 4th label (or property) values change over time" - Switching "Instant" selector (near the Format: Table) helped me.


Service provider implementation with SAML 2 and Java

Question: After going through so many google sites, reading so many QA in stackoverflow, really getting confused how to implement SP using SAML 2 with Java.
I understand the theory concept but not getting a clue how to implement it exactly.
Currently, my client already shared IDP metadata file with me and asking for SP metadata file. This is my first struggling point.

How to generate metadata files actually? Is there a tool to generate it?
How to implement SAMLRequest generation, SAMLResponse parsing using Java libraries.
People recommending so many publicly available sites which supports IDP, SP functionalities but could not be able to choose the right one to proceed. I need some specific example of Service Provider implementation in Java with SAML 2.

Really appreciate if somebody help me in this context. Please correct me if my questions are not clear so that i will try to edit it.
Answer: If you need to build a SP in Java I would recommend using Spring SAML module or the OpenSAML library, but these may give you more work. If you end up using OpenSAML I have a book, A Guide to OpenSAML, introducing the SAML and the OpenSAML library.
I also have a blogg with many examples.
I would however recommend that you first look into using a ready product for SAML like Shibboleth which is a free and open source solution for SAML. This will save you from needing to learn the specifics of the SAML protocol and also it will be much safer as different security considerations have already been made by the developers.
Comment: Thank you stefan... I read your replies to other questions also. Client specifically asking me to use OpenSAML (I am not sure why...) so I am looking for some sample implementations on that... will work as you suggested.
Comment: OpenSAML is well tested and interoperable code. You are likely to get signing and encryption done in an interoperable manner with an existing library, and OpenSAML is used fairly widely. Shibboleth is developed by the same group that makes OpenSAML and you can see their code at https://wiki.shibboleth.net/confluence/display/DEV/Source+Code+Access
Comment: Ok good luck, my book is based on a example implementation of a SAML sp I  have on github
Answer: @Stefan has some good suggestions.
What you need is a SAML protocol client side stack. Refer : SAML : SAML connectivity / toolkit and the links inside the article.
In terms of your questions, different stack do this in different ways. Some of the commercial stacks that I have used have excellent documentation and sample code to do all this.