How to reload item of combobox in c#?

Question: I have 10 items in combobox and when I delete one of those items, the combobox don't show automatically next item it show white space. I want to display next item in range.
I delete them normaly
cmbsomename.Items.Remove(cmbsomename.SelectedItem);
How to do that?
Comment: How are you deleting them because that will determine how to pick next item in items?
Answer: Because you deleted the selected item, you need to set another item as selected:
comboBox.SelectedIndex = 0;

Edit:
The code above sets the selected item as the first item in the list.
For the next item, you need to find the index of the item you are deleting first:
int index = cmbsomename.SelectedIndex;
cmbsomename.Items.Remove(cmbsomename.SelectedItem);

if (index < cmbsomename.Items.Count) // Make sure there IS a next item
   cmbsomename.SelectedIndex = index; // Next item will have same index value

Comment: OP said next item not first item.
Answer: after deleting an Item set the selectedindex
int index = comboBox.SelectedIndex;
comboBox.Items.Remove(comboBox.SelectedItem);

if (index < comboBox.Items.Count)
   comboBox.SelectedIndex = index;

Comment: OP said next item not first item.
Answer: var selectedIndex = cmbsomename.SelectedIndex;
cmbsomename.Items.Remove(cmbsomename.SelectedItem);
comboBox.SelectedIndex = selectedIndex < cmbsomename.Items.Count() ? ++selectedIndex : 0;

How to reload item of combobox in c#?


Convert a java Hashmap to a c++ std::map with android ndk

Question: How to convert a java Hashmap<Mat, bool> to a c++ std::map<Mat, bool> with android ndk ?
Thank you!
Comment: Pass each key/value pair separately...
Comment: There is no built-in way. You need to do it yourself.
Comment: mmh, how? I have no idea...
Comment: Oh sorry I didn't write it : I want to pass the pointer of the map just one time and then fill the map on the java side, then calculate on the c++ side, and get the calculated result back on the map on the java side... Can I do it maybe with an array of structure? (the c++ is a thread)
Comment: You can do whatever you want on the C++ side, and you can do whatever you want on the Java side, but passing the map between those will be a huge pain no matter what you do.
Comment: @Adrien: You cannot easily make a native thread update data in a Java thread. If I were you, I'd forget about it. Move all multi-threading to Java (using the `AsyncTask` Android framework class) and let C++ only do whatever high-performance calculations are needed. `HashMap` has nothing to with `std::map`, other than meeting similar requirements.
Answer:
Pass each key/value pair separately

by @immibis was the solution


Random Variables

Question: Let $X$ be a random variable uniformly distributed on the interval
$[−2, 2]$, and $Y = (X − 1)^2$.
$(a)$ Find the density function and the distribution function of $X$.
$(b)$ Find the distribution function and the density function of $Y$.
Comment: Please read: http://meta.math.stackexchange.com/q/1803/ attentively.
Comment: Sow us what you have tried: (a) is easy while (b) may require some thought.
Comment: Related meta thread: http://meta.math.stackexchange.com/questions/4001/what-is-ptwo-distinct-users-with-poor-mse-etiquette
Answer: I'll leave part a) for you, but I will point out that the  density function, $f_X$, for $X$ is zero outside the interval $[-2,2]$; after all, $X$ takes all its values in this interval.

Before tackling part b), it would be beneficial to first determine the values that $Y$ takes: Since $X$ takes values in $[-2,2]$ and since $Y=(X-1)^2$, it follows that $Y$ takes values in the interval $[1,9]$.
From this it follows that $f_Y(x)=0$ for $x\notin[1,9]$. From this it follows that $F_Y(a)=0$ for $a\le1$ and that $F_Y(a)=1$ for $a\ge 9$.

That was the easy part. Let's now find the value of $F_Y(a)$ for $a\in[1,9]$.
The idea is write the distribution function of $Y$ in terms of the distribution function of $X$:
We have, for $1\le a\le9$
$$\eqalign{
F_Y(a) &= P[\,Y\le a\,]\cr
&=P[\,(X-1)^2\le a\,] \cr
&= P [\,1-\sqrt a \le X\le 1+\sqrt a \,  ]\cr
&= P[\,X\le 1+\sqrt a\,]-P[\,X\le 1-\sqrt a\,]\cr
&=F_X(1+\sqrt a) -F_X(1-\sqrt a).
}
$$
Now you can write the distribution function of $Y$ explicitly:
$$
F_Y(a)=\cases{0,\vphantom{1\over2}   &$a\le1$\cr  F_X(1+\sqrt a) -F_X(1-\sqrt a),\vphantom{1\over2} &$1\le a\le 9$,\cr 1,\vphantom{1\over2} &$a\ge9$   }
$$
Of course, in the above, you'd replace  $F_X(1-\sqrt a) -F_X(1+\sqrt a)$ with what you obtain from the rule for $F_X$  (note here that $1-\sqrt a$ and $1+\sqrt a$ are in the interval $[-2,2]$).
So, that's $F_Y$.  How do you find $f_Y$? As it turns out, this is easy to do now (and is why you were asked to find the distribution function of $Y$ first) by the following result: in general, if $F$ is a distribution function of a continuous random variable, then its derivative gives the corresponding density function of that variable.
In our case we have
$$
f_Y(x)={d\over dx}F_Y(x).
$$
But before we apply this, let's recall  we already determined that $f_Y(x)$ is zero for $x$ outside the interval $[1,9]$.  For $x\in [1,9]$, we have, using the chain rule and the fact that ${d\over dx} F_X(x)=f_X(x)$,
$$\eqalign{
f_Y(x)={d\over dx}F_Y(x)
&= {d\over dx}\bigl(F_X(1+\sqrt x) -F_X(1-\sqrt x)\bigr)\cr
&={1\over2\sqrt x} f_X(1+\sqrt x)    +{1\over2\sqrt x} f_X(1-\sqrt x).\cr
}
$$
So
$$
f_Y(x)=\cases{  {1\over2\sqrt x} f_X(1+\sqrt x)    +{1\over2\sqrt x} f_X(1-\sqrt x), &$1\le x\le9$,\cr  0,\vphantom{1\over2}&otherwise .  }
$$
(And of course you'll want to simplify this using the density of $X$.)

Random Variables


How to set event-listener for spinner default item?

Question: I have a spinner which loads four different value one, two, three, four.
'one' is default selected value in spinner.
in spinner popup, select one then 'onItemSelected()' not fire...
but select any other then it is fire...
so how to implement?
please help me....
Comment: http://stackoverflow.com/questions/how-to-ask
Answer: This is builtin issue in android. instead of putting first value in it. Insert text like "---Select Value---" at first place and add all values after this text. So by default u will see this text. And then you can easily select any which you want.
Like:
<code>String[] items = new String[] {"---Select Any---","One", "Two", "Three"};
</code>
Comment: i use this code,but when second time selection problem as it is..
Comment: What means second times?
Comment: And one more thing when you select any number one time than you will not reselect it again because it has been already selected. You can first select another and then reselect it. I am using this type of code and it is working nicely
Comment: when i select two then popup close and selected value is two..that time i open popup and select same value (two) that time not event fire
Comment: i know,this code work properly....but client can not understand this situation...thanks bro for help....


Rotation matrix is changed with scipy.spatial.transform.Rotation

Question: I perform PCA on 3D images after semantic segmentation to define the orientation of objects and align them.
It works fine, produced eigenvectors form a valid rotation matrix that aligns objects correctly
But I would like to have rotation angles from the matrix.
When I use scipy.spatial.transform.Rotation.from_matrix and convert to angles with r.as_euler("xyz") it gives me the wrong angles.
Also, returning the matrix back from the same rotation object gives me a different matrix that rotates objects wrong
In short:
r = R.from_matrix(rotation_matrix)   r.as_matrix()
gives me a matrix not equal to the initial matrix, and it is not some variant of correct rotation. It is the wrong rotation.
For example, the matrix.
[[ 0.86345719 -0.48700394  0.13141101]
 [ 0.02362667 -0.221185   -0.97494563]
 [-0.5038685  -0.84492861  0.1794775 ]]

changes into the altered matrix
  [[ 0.82327846 -0.4171921  -0.3849199 ]
 [-0.46561791 -0.88418854 -0.03755775]
 [-0.32467296  0.21014609 -0.9221855 ]]

The initial rotation matrix looks ok, it is orthonormal, and the determinant is 1.
And it is not singular, gimbal locks are not present.
By the way, the second matrix, given by scipy is "stable"; it remains the same after further retrieving.
The problem is permanent; every rotation matrix produced from PCA is mistreated by scipy
What do I miss?
I tried other python tools, like transforms3d, and converted the matrix to Euler angles and back to the matrix - the matrix becomes different (although it also differs from scipy case).
UPD: transforms3d gives a "secondary" matrix that makes the same correct rotation, so I think this is just an optimized variant of the original matrix.
I checked the matrices for orthogonality and calculated determinants - they are fine.
Besides, initial rotation matrices work as expected when I apply them to the data.
I expect that scipy would give me the correct extrinsic Euler angles or at least don't alter the rotation matrix, which I use as an indicator for wrongdoing.
Answer: Solved!
My fault, the matrix contains reflection, so it is not a proper rotational matrix.
https://github.com/scipy/scipy/issues/17324


Implicit Differentiation problem in Apostol Calculus vol.II 9.8.5

Question: Exercise 9.8.5 from Apostol Calculus vol II:

I'm having problems understanding how to solve this apparently straightforward problem.
It asks for a normal vector to the surface defined by the 3 equations F(u,v). I know the normal vector of a surface is its gradient. But I'm having problems wrapping my head around this surface. I guess that the point exercise is to infer the gradient without and explicit definition of the surface. But how to do this exactly?
Answer:
Any differentiable map induces a linear map on the tangent spaces i.e if  $f: U \to V$ and $p \in U, f(p) \in V$ then $Df(p): T_pU \to T_{f(p)}V$ defined by $[\gamma] \mapsto [f\circ \gamma]$.
The notation means, "for any point, you have a curve $\gamma$ going through it, let $[\gamma]$ be the velocity of $\gamma$ at $t_0$ where $\gamma(t_0) = p$. It follows that if $U,V$ are euclidean open sets then,

$$Df(p) = \begin{bmatrix} \frac{\partial f_i}{\partial x_j}(p) \end{bmatrix}_{i,j}$$

Similarly we have $[f\circ \gamma]$ is the velocity vector of $f \circ \gamma$ at $p$. We use the equivalence class notation because any other differentiable function defined in a neighborhood of $p$ which agrees with $\gamma$, will give the same velocity vector. Here you have your surface $X = F^{-1}(\{0\})$ and so $F(X) = 0$ i.e,

$$DF(\textbf{x}): T_{\textbf{x}}U \to T_{F(\textbf{x})}\mathbb{R}: DF(\textbf{x}) (\vec{v})= \langle \nabla f(\textbf{x}),\vec{v} \rangle$$
where the angle bracket denotes the standard dot product.

Furthermore we have $\ker(DF(\textbf{x})) = \{\vec{v}: \langle\nabla f(\textbf{x}),\vec{v} \rangle = 0\}$. Now what fact from multivariate calculus can you use about the gradient vector of a differentiable real-valued function in relation to the tangent plane?
If you wish to use implicit differentiation, there's a reason why I wrote $F(X) = 0$.
Comment: Thanks for taking the time to answer! I really appreciate it. But your answer seems to be waaaaaay above my current level of understanding. I'm learning the material for the first time. I haven't seen tangent spaces (besides tangent vectors). I also don't understand what you mean by 'velocity' precisely.
Comment: I made an edit.
Comment: I'm sorry but it didn't help much. What do you mean by velocity?


Handling file not found

Question: I have a link say TestLink.
Clicking on which normally yields me a pdf.
Sometimes it diplays a page in a new window with message file not found
I need to respond when second case happens ,how do i handle this case via javascript?
Answer: You could use jQuery
$.ajax( "http://link.to.pdf" )
 .fail(function() {
     // ... disable the link --> PDF is not reachable
 });

source
You can check the link, if the PDF is not reachable disable the link.
Comment: It doesn't seem very useful to tell the browser to download an entire PDF and then just show an alert instead of giving the user access to that PDF.

Handling file not found


For what $n \in \mathbb{N}$ and $r \in \mathbb{R}$ $n^r = n!$?

Question: Background: I was solving following question.
Which is bigger $2^{30!}$ or $\left(2^{30}\right)!$ ?
$2^{30!}$ can be expressed as $\left(2^{30}\right)^{29!}$
Note that for sufficiently large $n \in \mathbb{N}$ we have that $n! >> 2^n$.
Moreover, $\forall_{n \in \mathbb{N} \wedge n \ge 5}\ n! > 2^{n+1}$
Hence, $29! > 2^{30}$
Finally,
$$2^{30!} = \left(2^{30}\right)^{29!} > \left(2^{30}\right)!$$
since $29! > 2^{30}$ and the fact every multiplicand of $\left(2^{30}\right)^{29!}$ is greater or equal than every multiplicand of $\left(2^{30}\right)!$.
(If you have other approaches please share them)
Then, I started thinking how would I approach something more generalised.
Question: For what $n \in \mathbb{N}$ and $r \in \mathbb{R}$ $n^r = n!$ ?
Some thoughts
Following the same argumentation implies that $\forall_{r > n}\ n^r > n!$.
This equation is trivially satisfied when $n = 1$ by all $r \in \mathbb{R}.$
Update
Courtesy of Shaun who pointed that $r = \log_n (n!)$ solves the equation $n^r = n!$.
Comment: Consider when $r=\log_n(n!)$.
Comment: Have you heard about [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation)?
Comment: So you suggest to substitute $n! \approx \sqrt{2\pi n}\left(\frac{n}{e}\right)^n$ to approximate the solutions?
Comment: There's the case when $n=2, r=1$: $2^1=2=2\times 1=2!$.
Comment: You could make use of the [Gamma function](https://en.m.wikipedia.org/wiki/Gamma_function) for $n!$.
Comment: Thank you Shaun. I haven't spotted that $r = \log_n (n!)$ definitely solves the equation since the base of the power and base of the logarithm are the same.
Comment: Do you want an exact equality or only the approximate intersection point ?
Comment: @MaciejCaputa I misinterpreted you question. Please tell me if you find my answer useful nevertheless!
Answer: For $n\ge 25$ , we have $$10^n<n!<n^n$$ which can be proven by induction
Hence
$$\large (2^{30})!<(2^{30})^{2^{30}}=2^{30\cdot 2^{30}}<2^{(10^{30})}<2^{30!}$$
Perhaps you can use the double inequality above for your generalized problem.
Comment: I really like this thought process. The first equation you have might be applicable to lots of things. I will make sure to keep it in mind.
Comment: The magnitude of $(2^{30})!$ is roughly $10^{9\ 230\ 534\ 754}\approx10^{10^{10}}$, whereas $2^{30!}=10^{log_{10}(2)\cdot(30!)}\approx10^{8\cdot 10^{31}}$
Comment: So, $\large 2^{30!}$ is far bigger
Comment: You can calculate those results here : https://mrob.com/pub/comp/hypercalc/hypercalc-javascript.html
Comment: I could use the double inequality to estimate the values, however, the 3 functions diverge quite rapidly.
Comment: If the values don't get too big, you can still use the logarithm or even the double-logarithm. For very large numbers, we have $10^n\approx n^n$ in some sense (which seems to be absurd since $n^n$ is growing much faster than $10^n$). You can find this phenomen in the site above. So, if $n$ is large enough , we have $10^n\approx n!$. Use hypercalc to distinguish $(10^{10^{100}})!$ and $10^{10^{10^{100}}}$. You will see no difference!


Gravar no banco valores do ComboBox C# ao invés das descrições

Question: Tenho uma tela em um form de cadastro simples, onde possui alguns combobox. Setei seus valores manualmente mesmo.
EX; Em um combo que irá cadastrar o perfil de acesso de um usuário, tenho nesse combo a opção 1- Limitado, 2 - total. Porém, como eu faço para hora que gravar no banco caso seja a opção 1 - Limitado ele persista com a sigla L e se for a opção 2 - Total ele persista com a sigla F na coluna de minha tabela?
Comment: Bem-vindo ao StackOverflow em Português! Por favor explique melhor o problema, e se possível inclua um [exemplo de código que reproduza o que está acontecendo](http://pt.stackoverflow.com/help/mcve), pois não está perceptível a sua pergunta. [Veja na Central de Ajuda Como Perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Answer: Para você ter o resultado esperado (numa implementação "melhor"), você precisa definir uma classe que represente um item em seu comboBox. Ex:
public class MeuComboBoxItem
{
    public string TextoDoItem { get; set; }
    public object ValorDoItem { get; set; }

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

Populando o combo:
MeuComboBoxItem item = new MeuComboBoxItem();
item.TextoDoItem = "1- Limitado";
item.ValorDoItem = "L";

comboBox1.Items.Add(item);

Para resgatar o valor do item selecionado:
string valorDoItemSelectionado = (comboBox1.SelectedItem as MeuComboBoxItem).ValorDoItem.ToString();

Resposta baseada nessa resposta.
Comment: Pow cara, muito bom vou testar...era exatamente isso que eu precisava.Top.
Comment: Legal! Fico feliz por ter ajudado! :-)
Answer: Você pode criar uma lista e atribuir ela ao combobox.
public sealed class ComboBoxItem
{
    public string Texto { get; set; }
    public string Valor { get; set; }

    public override string ToString()
    {
        return this.Texto;
    }
}

Uso:
var itens = new List<ComboBoxItem>();
itens.Add(new ComboBoxItem { Valor = "1", Texto = "Ola" });
itens.Add(new ComboBoxItem { Valor = "2", Texto = "Oi" });

cbo.DataSource = itens;
cbo.DisplayMember = "Texto";
cbo.ValueMember = "Valor";

Resgatar valor selecionado:
var item = (ComboBoxItem)cbo.SelectedItem;

Answer: Você pode criar uma classe contendo o texto e o valor e atribuir para o comboBox. Exemplo:
public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

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

Exemplo de utilização:
private void Test()
{
   ComboboxItem item = new ComboboxItem();
   item.Text = "Item text1";
   item.Value = 12;

   comboBox1.Items.Add(item);

   comboBox1.SelectedIndex = 0;

   MessageBox.Show((comboBox1.SelectedItem as   ComboboxItem).Value.ToString());
}

Comment: Caio, obrigado pela resposta, ajudou demais...
Answer: A melhor maneira de se fazer isso é usando a propriedade DataSource do ComboBox, desta forma o Combobox já fica preparado para utilizar o DataBinding, sem contar que se o valor do campo de chave for de um tipo diferente de string, evita de ter de usar casts pelo código, veja um exemplo abaixo:
// ***** Exemplo 1 - Utilizando uma List
// Neste exemplo utilizarei uma lista de KeyValuePar para identificar os meus itens.

var lstData = new List<KeyValuePair<int, string>>
{
    new KeyValuePair<string, string>(1, "Valor 1"),
    new KeyValuePair<string, string>(2, "Valor 2"),
    new KeyValuePair<string, string>(3, "Valor 3"),
    new KeyValuePair<string, string>(4, "Valor 4")
};

cboComboBox1.DataSource = null;
cboComboBox1.Items.Clear();
// Utilizo um BindingSource para "bindar os dados com os itens do Combobox"
cboComboBox1.DataSource = new BindingSource(lstData, null);
// Aqui fala qual será o campo a ser exibido
cboComboBox1.DisplayMember = "Value";
// Aqui fala qual campo será selecionado
cboComboBox1.ValueMember = "Key";

// ***** Exemplo 2 - Utilizando uma List de um objeto
// Neste exemplo utilizarei uma lista de KeyValuePar para identificar os meus itens.
class ObjetoTeste
{
    public ObjetoTeste (int codigo, string descricao)
    {
        this.Codigo = codigo;
        this.Descricao = descricao;
    }

    public int Codigo { get; private set; }
    public string Descricao { get; private set; }
}

var lstData = new List<ObjetoTeste>
{
    new ObjetoTeste(1, "Valor 1"),
    new ObjetoTeste(2, "Valor 2"),
    new ObjetoTeste(3, "Valor 3"),
    new ObjetoTeste(4, "Valor 4")
};

cboComboBox1.DataSource = null;
cboComboBox1.Items.Clear();
// Utilizo um BindingSource para "bindar os dados com os itens do Combobox"
cboComboBox1.DataSource = new BindingSource(lstData, null);
// Aqui fala qual será o campo a ser exibido
cboComboBox1.DisplayMember = "Value";
// Aqui fala qual campo será selecionado
cboComboBox1.ValueMember = "Key";

Quando for pegar os dados do combobox é só utilizar a propriedade SelectedValue do mesmo:
int intCodigoSelecionado = (int) cboComboBox1.SelectedValue;

Answer: Bem pelo que percebi da pergunta você quer um código assim
string escolha;

if (comboBox1.Text == "Limitado")
{
    escolha = "L";
}
else if (comboBox1.Text == "Total")
{
    escolha = "F";
}

Depois é só usar a variável escolha quando for inserido na base de dados.


Simple power tower $x^{1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}}=x$

Question: I was not clear in my last post :

Let $0<x$ a real number then we have :
  $$x^{1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}}=x$$

I take the logarithm of both side we get :
$$\ln(x)({1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}})=\ln(x)$$
We can simplify into :
$${1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}}=1$$
Wich is true recalling the initial equality .
Edit : I prove nothing but see the comment above .
I would learn if you have other proof ?
thanks in advance .
Comment: This is not a proof. It's circular.
Comment: Oh I see so How to make a proof ?
Comment: First of all, proof of what?  What are you trying to prove?  Youre given a statement of equality, not a theorem.  Equations are solved, not proven.
Comment: The right hand side tells you that $x$ is being defined, and the left hand side gives the definition. If you notice the definition for $x$ is repeated in the exponent.  We can rewrite the equation as $x^{1-x+x}=x$.  That simplifies to just $x=x$ straight away.  It doesnt tell you anything. In fact, I see no obvious reason why $x$ cannot be any positive real number at all.  It may even be possible for $x=0$ or $x<0$. Your manipulations with the natural log simply wouldnt be allowed if $x<0$.
Comment: @SquishyRhode  Thanks so it's trivial ?
Comment: @SquishyRhode what about the infinite case ?
Answer: Firstly let us define the LHS expression. I will assume that we define it as follows
$$x^{1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}}=\lim_{n\to\infty}a_n$$
Where $a_n$ is the sequence defined by the recurrence relation
$$a_1=x^{1-x}\qquad a_{n+1}=x^{1-x+a_n}$$
Now consider the subsequences given by $b_n=a_{2n}$ and $c_n=a_{2n-1}$. These sequences can be defined by the recurrence relations
$$b_1=x^{1-x+x^{1-x}}\qquad b_{n+1}=f(b_n)$$
$$c_1=x^{1-x}\qquad c_{n+1}=f(c_n)$$
where the function $f:(0,1)\mapsto(0,1)$ is defined by $f(y)=x^{1-x+x^{1-x+y}}$. It is possible to then prove that
$$y\lt x\implies y\lt f(y)\lt x$$
$$y\gt x\implies x\lt f(y)\lt y$$
Then, noting that $b_1\lt x$ and $c_1\gt x$, we can see that $b_n$ is a strictly increasing sequence and $c_n$ is a strictly decreasing sequence. Using these statements we can also show that $b_n\lt x$ and $c_n\gt x$ for all $n\in\mathbb{N}$. So, $b_n$ and $c_n$ converge by the monotone convergence theorem. We can then show that $b_n$, $c_n$ (and hence $a_n$) converge to $x$ as $n\to\infty$ by solving the equation $f(y)=y$ which has the unique solution $y=x$ for $0\lt x\lt1$. Thus we can finally say that
$$x^{1-x+x^{1-x+x^{1-x+x^{1-x+\cdots}}}}=\lim_{n\to\infty}a_n=x$$
Comment: The other answer contradict you Where is the problem because both seems to be clear ...?
Comment: Yes you're right so I accept.


Libraries API not working in my module

Question: I'm writing a module that will call some external php libraries. When I was searching for a way to import the library I found the Libraries API. After reading some documentation about the module and core features I found some example code.
When I implement it in my module nothing happens.
My movies.module file contains:
/**
* Implements hook_libraries_info()
**/
function movies_libraries_info()
{

  // This array key lets Libraries API search for 'sites/all/libraries/example'
  // directory, which should contain the entire, original extracted library.
  $libraries['imdb'] = array(
    // Only used in administrative UI of Libraries API.
    'name' => 'imdb',
    'vendor url' => 'https://github.com/tboothman/imdbphp',
    'download url' => 'https://github.com/tboothman/imdbphp/releases',
     // Default list of files of the library to load. Important: Only specify
    // third-party files belonging to the library here, not integration files of
    // your module.
    'files' => array(
      // For PHP libraries, specify include files here, still relative to the
      // library path.
      'php' => array(
        'bootstrap.php',
      ),
    ),
    // Optional: Register files to auto-load for your module. All files must be
    // keyed by module, and follow the syntax of the 'files' property.
    'integration files' => array(
      'movies' => array(
        'php' => array('bootstrap.php'),
      ),
    ),
  );
  return $libraries;
}

No errors are thrown when enabling my module when the library is not installed.
How can my module load the external PHP library using the Libraries APi?
Comment: Don't use libraries for PHP dependencies, use composer: https://www.drupal.org/docs/develop/using-composer/using-composer-with-drupal
Comment: Page does not exist on my Drupal 8 instance with Libraries Module enabled
Answer:
Add a composer.json file to your movies module & name it your custom module's name:
{
  "name": "drupal/movies",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "require": {
    "imdbphp/imdbphp": "*"
  }
}

Add a new line to the merge-plugin include array in the composer.json of your Drupal ROOT with your module's composer file path:
"extra": {
  "merge-plugin": {
    "include": [
        "core/composer.json",
        "modules/custom/movies/composer.json"
    ]
  }
}

Enable the movies module
Run composer update & composer dumpauto in Drupal ROOT. This will install & autoload the new dependencies in your vendor directory.
Now you can use the classes provided by this library. In your case for example:
$title = new \Imdb\Title(335266);

Comment: Is this the recommended method for installing a CSS library, too?
Answer: You can load libraries from the Libaries API in Drupal 7 in two ways:
1) You can use the function libraries_load()
2) You can use the #attached method of a render array as follows:
$form['myelement']['#attached']['libraries_load'][] = array('my_library');

Comment: I'm using Drupal 8 and nog Drupal 7.
Comment: Oh, my mistake. The D8 version doesn't even have a release yet, there's only a dev version. It won't be usable.
Comment: Hey @Jaypan, this answer looks like a perfect opportunity to use it for gaining [this](https://drupal.stackexchange.com/help/badges/38/peer-pressure) badge ... wanna try?

Libraries API not working in my module


Problems with css for my navigation bar

Question: I am trying to make it so when a user hovers over  a link in my navigation bar the font colour changes to blue but I cant change it.
I have tried this:
#nav a:hover{
color: #1B8AD8;
background: none;
text-decoration: none;
}

But its still not working. Any help? JSfiddle:https://jsfiddle.net/0k6wnvs6/
Answer: Try the below css
ul#nav li a:hover{
  color: #1B8AD8;
  background: none;
  text-decoration: none;
}

Answer: your rule is conflicting with another rule that are defined after it:
#nav li:hover a{ /* These create persistent hover states, meaning the top-most link stays 'hovered' even when your cursor has moved down the list. */
    text-decoration: none;
    color: #181818; /* <- conflict */
}

Either remove color: #181818;
or add !important flag to the original one:
#nav a:hover{
  color: #1B8AD8 !important;
  background: none;
  text-decoration: none;
}

Edit:
you seem to be changing the css in your fiddle link while i'm updating my answer, just try to avoid conflict.

Problems with css for my navigation bar


Recommended JMX plugin for Nagios?

Question: There are several Nagios JMX plugins out there, according to the Nagios plugin registry and Google. Any recommendations on one JMX nagios service check over the others? The few I glanced at briefly didn't seem to be under active maintenance...
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q&A is hard, lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping) and the [FAQ] for more details.
Answer: Please have a look a jmx4perl. It is acvtively maintained and continously improved (version 0.70 with multi checks is close to release, milestone 4 is already available).
Some unique features of jmx4perl (and check_jmx4perl) compared to the other Nagios JMX Plugins:

No local java installation required on the Nagios Host (pure HTTP/Rest communication)
Bulk requests (multiple JMX request within a single HTTP Request)
Fine granular security policy possible
Relative and incremental checks supported

You can find information about jmx4perl and some blog posts about it the jmx4perl website.
(of course this info is a bit biased as I'm the author of jmx4perl ;-)

Recommended JMX plugin for Nagios?


how to return 0 instead of null in Laravel

Question: I have a huge problem in my code. I'm trying to return 0 if the wanted row returns null (which mean no data match the search criteria)
My query is:
$total7 = DB::table('agencies')
->join('users' , 'users.id' , '=' , 'agencies.user_id')
->join('user_addresses' , 'user_addresses.user_id' , '=' , 'users.id')
->join('cities' , 'cities.id' , '=' , 'user_addresses.city_id')
->join('country_states', 'country_states.id' , '=' , 'cities.state_id')
->select('agencies.id as agenID ','country_states.name as sName', DB::raw('count(agencies.id) as agencount') , 'agencies.created_at as agencreate' )
->where ('country_states.name','=','Capital Governorate')
->whereNULL ('agencies.id')
->whereBetween('agencies.created_at' , ['2017-01-01' , '2017-03-31'] )
->groupBy(DB::raw("MONTH(agencies.created_at)") , 'country_states.name')
->get();

this statement should return 0,0,2 but now it returns nothing.
I want it to search throw the specified month range (3 months) and return the value if exists or 0 if no value.
I tried IFNULL but nothing.
Any help?
Comment: well after you finish your query just do simple if (!$result)  ?
Comment: ->whereNULL ('agencies.id')

I dont understand this part really. if ID is an auto increment value why do  you check if it is null or not ? it will never be null
Comment: @Rodrane I'm trying to get any parameter that makes my statement work as I want. If no id for this governorate in this month, return zero.
Answer:     if(!$total7) {
      $result = 0;
     }

Then use $result variable where you want, in your controller or your blade file
Answer: Try to check the count for the collection : $total7->count();
`
Comment: it shows me only the count of returned values not what I need which is go throw the first month, if there is value, print it, if not give me zero.
Answer: you can do it from the query:
Use IFNULL:
IFNULL(fieldname, 0)
Comment: I'm not getting how to use IFNULL because it test it before and nothing worthy happened
Answer: You can use the php function count:
 count($total7)

It will give you 0 when there is a null collection
Check the first example:
http://php.net/manual/es/function.count.php
Answer: UPDATE FOR ANSWER:
I changed the query in terms to return what I need only which is
count(agencies.id)

So the query was with the code for output is:
 $countt = 3;
$ii = 1;
do{

                  $total7 = DB::table('agencies')
->join('users' , 'users.id' , '=' , 'agencies.user_id')
->join('user_addresses' , 'user_addresses.user_id' , '=' , 'users.id')
->join('cities' , 'cities.id' , '=' , 'user_addresses.city_id')
->join('country_states', 'country_states.id' , '=' , 'cities.state_id')
->select( DB::raw('ifnull(count(agencies.id),0) as agencount'))
->where ('country_states.name','=', $gover)
->whereMonth('agencies.created_at' ,  $ii)
->groupBy(DB::raw("MONTH(agencies.created_at)") , 'country_states.name')
->first();
if ( count($total7) == 0 ){
    echo '0,';
}else{
  echo $total7->agencount.',';
}

$ii++;

}while ($ii <= $countt);

$gover is a value come from another bigger foreach loop to loop throw all the governorate I have. $ii is a counter works as month counter to search throw the wanted range of months. do the query search until you reach the limit of wanted months (from 1 till 3 is 3 months).
if the current month has no value the returned values will be 0, if its zero, print it otherwise, give the returned value.
I thank all whom commented on this question. I own favor for you.


Is it a waste of money if I buy a multi-effect pedal when I have an amp which has built-in multi effects?

Question: I have the Nux Mighty Space desktop amp, which I like very much. For a reasonable price, this 30W comes with wireless module, foot switch, ability to connect via USB, and built-in effects.
The tones that I can get out of the Nux is limited due to similar IRs.
Now, I would like to buy a multi-effect pedal to expand my range of tones. However, I am a bit hesitant because maybe I can already get approximate tones from the amp itself and buying an extra processor would be a waste of money.
Would it be within reason to buy an extra multi-effect pedal as a support, or am I being too wasteful?
Comment: Is the tone selection limited to the IRs? To me it looks like it has emulation for most imaginable types of effects
Comment: The tone selection is definitely more than only IRs, but the IRs (and also amps) being too similar limits the tone variety.
Comment: This is why I didn't ask about the amp or cabinet selection but the effects. If the problem is the amp model and not the effects, I'm not sure how external multi-effect pedal would help.
Comment: I don't have a clear answer for that. My best approximation is; a multi-effect pedal has more effect and IR variety, and some of them also have an expression pedal with them. As I've said, I'm not sure whether that would be an unnecessary purchase
Answer: Pedals can be turned on and off by stomping on them during a live performance giving you more control and feel to your tracks. Setting the effects by hand on the amp is ok but if you're playing live you need a pedal.


A player doesn't want to take a kick during kicks from the penalty mark

Question: I happened to see the final of Women's football at Tokyo Olympics between Canada and Sweden. Since there were quite a few saves and misses during kicks from the penalty mark, I have a hypothetical question.
Suppose the player taking the first kick gets dizzy or cold feet or nervous or complains of illness, what happens next? What if the same thing happens to the goalkeeper?
Answer: Kicker
Teams do not have to name a kicker until the time of the kick. If a player feels they won't be able to kick, a different player can step forward to do it.
Once the kicks go into 'sudden death' all eligible players must eventually take a kick before any player can take a second kick. If they refused at the point they must take a kick, they would eventually be cautioned for delaying the game or unsporting behaviour, and the kick is counted as missed.

If the kicker is penalised for an offence committed after the referee has signalled for the kick to be taken, that kick is recorded as missed and the kicker is cautioned

Goalkeeper
The goalkeeper can be replaced by

any eligible player

any player excluded to balance numbers

any substitute, if they still had permitted substitutes remaining

So any sensible referee will ask the team to send forward a replacement, and proceed with the kicks.
If the goalkeeper refused to take a kick when required, the same conditions apply as above.


Can I alias a member of the base class in derived class without increasing class memory?

Question: I would like to do something like this:
template <int N, typename type>
class BaseClass{
public:
    type array[N];
};

template <typename type>
class Derived : public BaseClass <1, type>{
public:
    type &alias = ( BaseClass<1, type>::array[0] );
};

but when I use:
cout << sizeof( Derived <char> ) << endl;

it prints out 16, I would expect it to print 1 or 5, not 16. Is there a way to do it so it takes only sizeof(array[N])? Why 16? When I change BaseClass<1, type> to BaseClass<3, type> it also prints out 16.
EDIT:
I found a way around this for my needs:
the base class:
template <typename container, int N>
class BaseClass : public container {
public:
    // constructor example
    BaseClass(){
        for(int i = 0; i < N; i++)
            container::array[i] = 0;
    }

    // function examples
    BaseClass operator+( const BaseClass& arg ){
        BaseClass result;
        for( int i = 0; i < N; i++ )
            result.array[i] = container::array[i] + arg.array[i];

        return result;
    }

    friend ostream& operator << ( ostream& stream, const BaseClass& arg ){
        for( int i = 0; i < N; i++ )
            stream << arg.array[i] << ' ';
        return stream;
    }
};

for a derived class I would use something like this:
template <typename type>
class container3{
public:
    union{
        type array[3];
        struct{
            type x;
            type y;
            type z;
        } ;
    };
};

class Derived : public BaseClass< container3<float>, 3 >{
public:
    Derived( float x = 0, float y = 0, float z = 0 ){
        this->x = x;
        this->y = y;
        this->z = z;
    }
};

now I can use them like this:
Derived var1( 1, 2 );
Derived var2;

var2.y = 3;
var2.z = 6;

cout << var2 + var1 << endl;
cout << sizeof( Derived ) << endl;      /// this prints 12

return 0;

Comment: What is `sizeof(void*)` on your platform?
Comment: `cout << sizeof(void*) << endl;` outputs 8
Comment: Aha, so you're on a 64-bit platform (data pointers and references will take 8 bytes each).
Comment: ok, now I get why 16, but no way to create an alias with no memory overhead? Isn't it basically a rename of the same variable?
Comment: No. An reference is an actual variable in its own right. It's essentially semantic sugar for a pointer (with a few added constraints on how it can be used, notably that it can't be null).
Answer:
Why does it print 16?

First of all, this is implementation defined. But here is a plausible explanation.
The reference in the derived class costs you the size of a pointer, which, on a 64 bit platform, is likely 8 bytes. The array of 1 char in the base class costs you an additional byte. However, due to alignment restrictions, the compiler rounds 1 + 8 up to 16, as your platform probably likes addresses to be aligned to 8 bytes.

What can I do about it?

Get rid of the reference. If it's always going to point to the array in the base class, there is no need to store it as a member. If you think that spelling out the BaseClass<1, type>::array[0] every time is too much typing, you can add a member function.
type&
getit() noexcept
{
  return BaseClass<1, type>::array[0];
}

This will not increase your object size.  You'll probably also want a const overload.
Answer: Not without increasing the size of the object, no.
But you can write a method that does the same thing, and call that method everywhere you'd use the reference. It will be inlined when compiled with optimizations on and shouldn't result in much overhead compared to the alias (or any overhead at all, if the common subexpression elimination pass is good enough, which it will be in your example since the aliased expression is as simple as can be).
template <typename type>
class Derived : public BaseClass <1, type>{
public:
    type& alias() { return array[0]; }
    type const& alias() const { return array[0]; }
};

The reason your object size was 16 is because the compiler creates structures that are padded to a multiple of your machine word size. This allows you to create arrays of such structures without worrying about weird alignment (and without having gaps in between instances).
I suspect your machine word size is 8 bytes (64-bit CPU). So, 8 bytes for the reference alias (which is really just a special syntax around a pointer), plus one for the array, plus 7 bytes of padding to bring it to a multiple of 8.
Answer: According to the C++ standard it is unspecified whether a reference takes up storage.  So you will only be able to investigate this case by trying it out and seeing what happens.
Having a reference member of your class means that the default-generated copy-constructor, move-constructor, and assignment operators won't work properly though. So this adds considerable complexity to your class.
Of course you could write:
type &alias() { return BaseClass<1, type>::array[0]; }

which won't take up storage.


Proof of Soundness Lemma

Question: We are given that $\Gamma \vdash \phi$ and want to show that for any truth assignment $\nu$ such that $\bar{\nu}(\psi) = T$ for all $\psi \in \Gamma$ then $\bar{\nu}(\phi)=T$
We are given the hint to use "induction on the length of the gamma proof".
Since  $\Gamma \vdash \phi$, there is a sequence $s= \langle\phi_1,\dots,\phi_n\rangle$ is a gamma proof and $\phi_n = \phi$.
By the construction of a gamma proof, all $\phi_i$ of $s$ must at least be one of:
(a) $\phi_i$ is in $\Gamma$
(b) $\phi_i$ is a logical axiom
(c) there are $j_1$ and $j_2$ less than $i$ such that $\phi_{j_2} =(\phi_{j_1}\to \phi_i)$
How do we use induction on length of the gamma proof to reach that $\bar{\nu}(\phi)=T$?
Can we argue that since $\phi= \phi_n$ must satisfy at least one of (a),(b),(c)?
If $\phi_n$ satisfies (a) then it's in $\Gamma$ by definition so it is true. If it satisfies (b) then it is a logical axiom and is thus a tautology so it's true. If it satisfies (c), then what?
Comment: For (c) you have to prove that *modus ponens* is sound, i.e. that $ϕ_j : = (ϕ_k → ϕ_i)$ and $\overline ν(ϕ_j) = \overline ν(ϕ_k) = T$, then $\overline ν(ϕ_i) = T$. This is part of the induction step needed.
Comment: You have to perform *induction* on the lenght $l$of the derivation : *(i) Basis* lenght $l = 1$ : we have only cases (a) and (b), of course and we can check them. *(ii) Induction step* lenght $l = i$ : now we have to check cases (a), (b) **and** (c) and for (c) we have to use the *induction hypotheses* i.e. that $ν(ϕ_j)=ν(ϕ_k)=T$.
Comment: The induction variable hides elsewhere, though: For a given $\Gamma$-proof, show that $\bar\nu(\phi_k)=T$ for all $k\le n$
Comment: So I did not need to use any induction on the case that the last $\phi_n=\phi$ was (a) or (b)? I only need to do so for (c), starting with a Gamma proof of length 1 then assuming true for n and showing it holds for n+1 length gamma proofs?
Answer: I can only give you a proof sketch since you did not tell us which axioms you have in your system.
Lemma (Soundness)

$Γ \vdash ϕ ⇒ Γ \vDash ϕ$

Proof Sketch: Let  $Γ⊢ϕ$. We need to show that $Γ \vDash ϕ$, that is, that for any truth assignment $ν$ such that $ν(ψ)=1$ for all $ψ∈Γ$ then $ν(ϕ)=1$. By definition of $Γ⊢ϕ$, there is a derivation $D$ with conclusion $ϕ$ and hypothesis in $\Gamma$ where every line is either:

an axiom;
an element of $\Gamma$ or
follows from previous lines by Modus Ponens

We proceed by induction on the lenght of the proof:
(basis) We consider the case where the derivation $D$ is atomic. We have two cases:

$ϕ \in Γ$. Then it is easy to see that $Γ \vDash ϕ$.
$ϕ$ is an axiom. Then we need to show that every axiom of our system is valid. This can be done by reductio ad absurdum: suppose that Axiom so-and-so is not valid, then derive a contradiction. This shows that $\phi$ is valid, therefore $Γ \vDash ϕ$.

(Inductive Case) Induction Hypothesis: if $\frac{D}{\phi}$ and $\frac{D'}{\phi \to \psi}$ are derivations with its hypothesis contained in $\Gamma$ and $\Gamma'$ then $Γ \vDash ϕ$ and $Γ' \vDash \phi \to \psi$. We need to show that if
$$\frac{\frac{D}{\phi} \frac{D'}{\phi \to \psi}}{\psi} \tag{$D$*}$$
is a derivation with its hypothesis contained in $\Gamma \cup \Gamma'$ then $Γ, \Gamma' \vDash \psi$. Consider ($D$*). Now by the IH for any truth assignment $ν$ such that $ν(\xi)=1$ for all $\xi∈Γ\cup \Gamma'$ then $ν(ϕ)=1$ and $ν(ϕ \to \psi)=1$. Then by the interpretation of the connectives, $ν(\psi)=1$ and $Γ, \Gamma' \vDash \psi$.
In other words, the above step shows that our inference rules are "truth preservative", that is, for every derivation $Γ⊢ϕ$ we have that $Γ \vDash ϕ$. Since we have established that our property holds for every atomic derivation too, this suffices to show that if $Γ \vdash ϕ$ then $Γ \vDash ϕ$.
Comment: "This can be done by reductio ad absurdum: suppose that Axiom so-and-so is not valid, then derive a contradiction."  Whenever I've done this I usually end showing the formula to evaluate to the designated value.  In other words, I can tell that if a formula does not taking on a designated value, then it takes on that designated value.  Then I infer that the formula takes on that designated value.  It seems like the Law of Clavius in action to me.

Proof of Soundness Lemma


Detect correlations in some range

Question: I have a dataset that contains bivariate data (x, y). Upon visual inspection, I can see that when the data are above certain threshold value (x_crit, y_crit), there is strong correlation between x and y. Below this value the two variables are largely not correlated.  I have a large number of such datasets so visual inspection for each one of them is not possible.
So my question: is there any way to automatically determine this optimal cut off value of x_crit and y_crit?
I am thinking of plotting coefficient of correlation coefficient r of data where x > x_crit and y > y_crit against x_crit and y_crit (think r = f(x_crit, y_crit) and find the optimal x_crit and y_crit values giving best r. This is based on the assumption that when the critical values are too low, the uncorrelated observations will degrade the coefficient and when critical values are too high, correlation will also be corrupted by range truncation. But that sounds quite inefficient and I'm not sure whether that is going to work...
Any suggestions are welcome!
Update: There are requests for examples. I would like to post a toy example here:
You can see a big cluster of points under (2,2) that are completely unrelated to each other. However above 2,2 there is strong correlation. If try to do linear regression for all values, you will get r=0.62 only.
I want to detect the strong correlation above the threshold (x=2, y=2 for this example) out of the mess. Ideally the program should be able to identify x=2, y=2 as the threshold.
Comment: The highest correlation coefficient will occur when there are just 2 points (r^2=1); you need to define the problem with some sort of penalty for including too few points otherwise each will devolve into this trivial case.
Comment: Your question is interesting. Please post 1 example .
Comment: @user177357 It depends on what you want to do with this bit of information called correlation. Are you going to fit a model? clustering your data?
Comment: @tkmckenzie Thanks for your comment. I have updated the question with an example.
Comment: @horaceT Yes I was thinking of clustering as one approach, but unfortunately I am not too sure how to deal with this exactly...
Comment: Is [this](https://i.stack.imgur.com/XSEj1.png) the sort of thing you're after - points above a single line demarking the "linear" points from a cloud below it? If so, how much variation around the line would there be in the red points? Are they effectively "on the line" or are they just a good deal less noisy? Your example has y=x in the upper part, but you talk about "correlation" rather than "equality" -- which is it in general?
Comment: @Glen_b Yes. That's almost exactly what I want. Just that the bound I want is value of x and/or y (i.e. lines parallel to x or y axis) rather than a sloped line.  x and y are not necessarily equal - I just use a toy example for illustration. there are noises, or even no correlation at all so the question is to detect correlation, if any.
Comment: Okay, that would be a minor adaptation of the algorithm I used.
Comment: Should the [green points](https://i.stack.imgur.com/LvKl5.png) be red? Or should those be blue? (This stuff should all be clearer in the question)
Comment: @Glen_b Sorry for the ambiguity! In my opinion the blue points shouldnt matter, because even if the small number of blue points are included, if I use a robust regression (Sen's slope, for e.g.), the strong correlation in the red+blue regions will not be affected by too much. I am not an expert in this so please correct me if I am wrong! I am happy with either including and excluding green ones, but ideally robust towards outliers include those because they are indeed part of the strong correlation.
Answer: Suggested approach:

choose a fraction of points with the largest x-values and fit a robust regression to them
(You probably want a line that will go through the line when most are "on the line")
- I used quantile regression; a Theil line might be better in some cases.
- a number of other possible lines should also be fine
find a rough idea of a "small" residual that should have a good chance to include
all the good points (will require some tweaking of the criteria to suit your
particular needs/data situation)
identify the points with larger residuals
- then find the largest x-value with a large residual
and the largest y-value with a large residual
mark as "good" the points that are larger than either

Four examples using the implementation below:

An example coded in R (it would take little effort to turn this script into a function):
<code># make some sample data
z=runif(20,1,3);x=c(rnorm(50,1,.4),z);y=c(1.3*rnorm(50,1,.4)+1,1.3*z+1+rnorm(20,0,.04))

library(quantreg) # for L1 line (rq)
medabs.c=3     # Various constants to try to make it work for particular cases
tolr=1.e-5;tola=1.e-4
upperfrac = 0.2; trimfrac= 0.2
dfrac=0.1; rfrac=0.7

# choose a small fraction of the largest x-values & fit a robust regression
# want a line that will go through the line when most are "on the line"
safeish=x>quantile(x,1-upfrac)
xu=x[safeish];yu=y[safeish]

# fit robust line to upper small fraction
 linf=rq(yu~xu)
 ab=linf$coefficients; a=ab[1]; b=ab[2] # extract coefs

# d are the residuals for *all* the data not just the subset
 d=y-a-b*x
 r=residuals(linf)  # the residuals in the subset

# find a rough idea of a "small" residual
m=mean(abs(r),trim=trimfrac)
smallish=m*medabs.c+tola+sd(r)*rfrac+sd(d)*dfrac # will probably need to adjust
out=abs(d)>smallish  # which points have residuals that are "too big"

# find the largest x-value & y-value with a large residual
mx=max(x[out]); my=max(y[out])
plot(x,y,pch=16,col=4)
abline(v=mx+tola,h=my+tola,col=8)  # shift the lines a tiny amount so points look inside

# points that should be good
aboveor=x>mx|y>my
points(x[aboveor],y[aboveor],pch=16,col=2) #colour "good" points red
</code>

Detect correlations in some range


Cheap clustering for SQL server

Question: Does anyone know of a way to simulate a clustered SQL server solution? We obviously don't want to spend a lot of money prototyping the idea, but we have quite a few PCs available. I was just wondering if there was any way I could fool SQL server into thinking it's being installed on to clustered hardware by either using physical machines or even virtual machines?
I don't hope to do any performance testing of course, it's more to do with testing fail over scenarios and replication etc.
Any ideas?
Answer: The easiest way to do this is to build a virtual cluster in VMware.  It's not technically supported unless you're on approved hardware/software, but for your needs, that's fine.
The tricky part is the shared storage configuration, and this article explains how to do it:
https://web.archive.org/web/1/http://techrepublic%2ecom%2ecom/5208-6230-0.html?forumID=102&threadID=220875&start=0
Answer: I was going to mention this exact approach that Brent outlined as it's a cheap way (from a hardware perspective) to play around with what's typically referred to as a 'pocket cluster'.
Obviously though... this doesn't end up being that cheap if you're planning on using it in production, as you'll need at least 2 licenses of Windows Server Enterprise, and 1 license of SQL Server Enterprise (per each proc). But if it's just for testing then MSDN/TechNet licenses can be used and it's then just a question of hardware, virtualization, and configuration.
Answer: Physically you can likely do it using the physical workstations and an iSCSI solution for shared storage, since you're doing it as a test. The simpler approach is VMware, as Brent suggested. And just to make it clear, from a Microsoft perspective a fail-over cluster in VMware is not supported, even in an approved hardware/software solution.
From Server Virtualization Validation Program FAQ:

Does the SVVP cover all Windows Server roles?
  All Windows Server roles are supported with SVVP-validated solutions, except Hyper-V and Clustering Services. It does not make sense to run a hypervisor (Hyper-V) on another virtualization solution/hypervisor, and Clustering requires all of the hardware components to be tested by the hardware OEM (e.g. server, storage, HBA controller, operating system).

Cheap clustering for SQL server


How to concatenate if the adjacent cell value is true?

Question: I am trying to concatenate text if the adjacent cell value is "True".
I have written code that works for all the text in the cells but I can't piece together code using an if statement.
The table begins on B6 and looks like this:
True   Butter
False  Cream
False  Milk
False  Water
True   Soda

I tried declaring an integer to use as a row and set it to add 1 if the condition is met.
Here is the code that strings together all of the cell values:
Sub JoinText()

Dim result As String
Dim comma As String
Dim col As String

comma = ","

For i = 6 To 10
    col = Sheets("Test").Cells(i, 3).Value
result = result & comma & col

Next

result = Right(result, Len(result) - Len(comma))

MsgBox (result)

End Sub

How the results display:
Butter,Cream,Milk,Water,Soda

Here is my modified code:
Dim result As String
Dim comma As String
Dim col As String
Dim row As Integer

row = 2
comma = ","

For i = 6 To 10

If col = Sheets("Test").Cells(i, row).Value = "True" Then
    col = Sheets("Test").Cells(i, row + 1).Value
End If

result = result & comma & col

Next

result = Right(result, Len(result) - Len(comma))

MsgBox (result)

What the result looks like now:
,,,,

I messed with the code and have been getting various results like:
Butter, Butter, Butter, Butter, Butter

or
,,,,Soda

Edit: I removed "col =" in the if statement and now my results are showing as "butter, butter, butter, soda, soda, soda". How do I narrow it down to just two results?
Comment: For this example, I want it to display "Butter, Soda"
Comment: `If col = Sheets("Test").Cells(i, row).Value = "True" Then` remove that `col = `
Comment: Seem my answer below. Have you moved the `result = ...` into the if statement?
Comment: sorry i did forget to do that part ad now when I moved it in the if statement, it only displays the very last result no matter what value the adjacent cell is.
Answer: In addition to what @Tim Williams said, move result = ... into the if statement.
Example:
If Sheets("Test").Cells(i, row).Value = "True" Then
    col = Sheets("Test").Cells(i, row + 1).Value
    result = result & comma & col
End If

Answer: Option explicit
public function concatConditional(r As Range, Optional delim As String = ",") As String
   Dim rowCnt    As Integer
   Dim v()       As Variant
   v = r.Value2
   concatConditional = ""
   for rowCnt = 1 to r.Rows.Count
      if v(rowCnt,1) then
         concatConditional = concatConditional & delim & v(rowCnt,2)
      end if
   next rowCnt
end function

I omitted error handling.
Comment: Thanks for the response. I will try this when I get home from work and let you know if this worked.


Bind DNS Server wont start

Question: I'm currently running a VPS with CWPPro and my BIND DNS wont start. It gives this errors. Any ideas?
     named.service - Berkeley Internet Name Domain (DNS)
       Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor preset: disabled)
       Active: failed (Result: exit-code) since Fri 2022-07-08 19:36:11 UTC; 7s ago
      Process: 906 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; then /usr/sbin/named-checkconf -z "$NAMEDCONF"; else echo "Checking of zone files is disabled"; fi (code=exited, status=1/FAILURE)

Jul 08 11:56:06 server.mydomain.live systemd[1]: Stopped Berkeley Internet Name Domain (DNS).
Jul 08 19:36:11 server.mydomain.live systemd[1]: Starting Berkeley Internet Name Domain (DNS)...
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:34: unknown option 'recursion'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:36: unknown option 'dnssec-enable'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:37: unknown option 'dnssec-validation'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:40: unknown option 'bindkeys-file'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:42: unknown option 'managed-keys-directory'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:44: unknown option 'pid-file'
Jul 08 19:36:11 server.mydomain.live bash[906]: /etc/named.conf:45: unknown option 'session-keyfile'
Jul 08 19:36:11 server.mydomain.live systemd[1]: named.service: control process exited, code=exited status=1
Jul 08 19:36:11 server.mydomain.live systemd[1]: Failed to start Berkeley Internet Name Domain (DNS).
Jul 08 19:36:11 server.mydomain.live systemd[1]: Unit named.service entered failed state.
Jul 08 19:36:11 server.mydomain.live systemd[1]: named.service failed.

//This is my named.conf file
//
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a any DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
// See the BIND Administrator's Reference Manual (ARM) for details about the
// configuration located in /usr/share/doc/bind-{version}/Bv9ARM.html

options {
    listen-on port 53 { any; };
    listen-on-v6 port 53 { ::1; };
    directory   "/var/named";
    dump-file   "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    recursing-file  "/var/named/data/named.recursing";
    secroots-file   "/var/named/data/named.secroots";
    allow-query     { any; };
};

    /*
     - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
     - If you are building a RECURSIVE (caching) DNS server, you need to enable
       recursion.
     - If your recursive DNS server has a public IP address, you MUST enable access
       control to limit queries to your legitimate users. Failing to do so will
       cause your server to become part of large scale DNS amplification
       attacks. Implementing BCP38 within your network would greatly
       reduce such attack surface
    */
    recursion no;

    dnssec-enable yes;
    dnssec-validation yes;

    /* Path to ISC DLV key */
    bindkeys-file "/etc/named.root.key";

    managed-keys-directory "/var/named/dynamic";

    pid-file "/run/named/named.pid";
    session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
    type hint;
    file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

// zone server.mydomain.live
zone "server.mydomain.live" {type master; file "/var/named/server.mydomain.live.db";};
// zone_end server.mydomain.live

zone "ns1.mydomain.live" {type master;file "/var/named/ns1.mydomain.live.db";};
zone "ns2.mydomain.live" {type master;file "/var/named/ns2.mydomain.live.db";};

// zone mydomain2.co.uk
zone "mydomain2.co.uk" {type master; file "/var/named/mydomain2.co.uk.db";};
// zone_end mydomain2.co.uk

Comment: What does `named-checkconf /etc/named.conf` say?
Comment: my named.conf was missing a domain Master file connection statement  @Ace.  Thanks
Answer: You seem to have superfluous right bracket } right after allow-query option.
Comment: Removing the right bracket fixed it @Tomek

Bind DNS Server wont start


If statement doesn't trigger

Question: I have a really odd issue.
This is my code, as-is:
<?php
    $cur = file_get_contents("./req.txt");
    if(($_POST['bid'] >= $cur + 0.25) & $_POST['contact'] !== '')
    {
        $fi2 = "./req.txt";
        file_put_contents($fi2, $_POST['bid']);
        echo "Success";
    }
    else
    {
        echo "Error.";
    }
?>

When it's like that, it works fine.
But, if I change the else to if($_POST['bid'] >= $cur + 0.25) (which is copied and pasted from above), the page loads fine and it doesn't run the file_put_contents, but it doesn't echo Error. This is what the code looks like changed:
<?php
    $cur = file_get_contents("./req.txt");
    if(($_POST['bid'] >= $cur + 0.25) & $_POST['contact'] !== '')
    {
        $fi2 = "./req.txt";
        file_put_contents($fi2, $_POST['bid']);
        echo "Success";
    }
    if($_POST['bid'] >= $cur + 0.25)
    {
        echo "Error.";
    }
?>

What am I doing wrong?
Comment: it sounds like you have a syntax error and the page isn't executing at all. That's the only way that code _after_ the `if` could prevent the `if` from triggering.
Comment: Please post the code that doesn't work, rather than describing the changes.
Comment: The page loads fine. CSS and html run. I put `echo "test";` on the bottom line and it worked fine.
Comment: Please clarify. When you run the first version, it echoes `Success`, but if you run the second version with the same input it doesn't echo anything?
Answer: If $_POST['bid'] >= $cur + 0.25 is false, then both your codes in the if won't be executed.
The first piece of code will come into the else, but the second won't come into the second if.
Comment: Whoops... Thanks for pointing this out. Always the silly mistakes haha.
Comment: When you said the first version "worked", I thought you meant it echoed Success.
Answer: & is the bitwise and operator in PHP, which has higher precedence than the !== operator. Try replacing the & with &&.
Comment: Good catch, but how would that explain what he's seeing?

If statement doesn't trigger


Solve $x^2\equiv -3\pmod {\!91}$ by CRT lifting roots $\!\bmod 13\ \&\ 7$

Question: Question 1) Solve $$x^2\equiv -3\pmod {13}$$
I see that $x^2+3=13n$. I don't really know what to do? Any hints?
The solution should be $$x\equiv \pm 6 \pmod {13}$$
Question 2) $\ $ [note $\bmod 7\!:\ x^2\equiv -3\equiv 4\iff x\equiv \pm 2.\,$ Here we lift to $\!\!\pmod{\!91}\ $ -Bill]
Given $x\equiv \pm 6 \pmod {13}$ and $x\equiv \pm 2 \pmod {7}$ find solutions $\pmod {91}$. I see that $91=13 \times 7$, does it mean I have to use chinese remainder theorem on 4 equations? If,so $x=6\times 13\times 7 \times 7\times (13\times 7 \times 7)^{-1}...$
Comment: $x^2\equiv -3\equiv 36\pmod{13}\iff x\equiv \pm 6\pmod{13}$.
Comment: You do have to use the CRT on $4$ systems of congruences. Luckily much of the work can be recycled, and the answers come in two $\pm$ pairs.
Comment: For question 1 just compute all the different squares, there are only 13 of them.
Comment: @AndréNicolas When I apply CTR I seem to always need to find the inverse of 0, because no matter which other 3 I pick, since I'm always mulitpying $7$ and $13$ I always get 0 mod 13 and 0 mod 7?
Comment: @AndréNicolas I know that they should be coptime, which they are not since 7 is clearly not coprime with itself. Same for 13. But How can I work around it?
Comment: I have written out a solution. You can ask about any details left out. Answers may not be instantaneous, busy.
Answer:
Just try all candidates $0,1,2,3,4,5,6$. You can stop at $6$ because $(13-x)^2\equiv x^2$. This will also give you a second solution if you find one.
Answer: The numbers are small, and one could find the answers without the full CRT machinery. But we will go ahead and use a "general" procedure.
The idea is that to solve $x\equiv a\pmod{7}$, $x\equiv b\pmod{13}$, you use
$$x\equiv (C)(13)(a)+(D)(7)(b)\mod{91},$$
where $C$ is the inverse of $13$ modulo $7$ and $D$ is the inverse of $7$ modulo $13$. We can see I think easily that $C=-1$ and $D=2$ will work, so we get
$$x\equiv -13a+14b\pmod{91}.\tag{1}$$
Now let us for example take $a=-2$ and $b=6$, one of your $4$ possibilities. That gives $x\equiv 110\equiv 19\pmod{91}$.
Comment: Thank you very much. My mistake was that I was considering all 4 of them at the same time, as opposed to only consider 2, but with 4 cases.
Comment: You are welcome. A favour please, you had accepted another answer to another part. I felt uncomfortable answering. The only reason I did is that comments are awkward if they are of any length. It would make me feel better  if the accept reverted to the previous one.
Comment: Nicolas I was reading this over today and I noticed I didn't change the answer, as you requested I changed it back.
Answer: For Question 2), you can use the Chinese Remainder Theorem on the one equation
$$
13x+7y=1\tag{1}
$$
Using the Extended Euclidean Algorithm, an implementation of which is in this answer, compute
$$
\begin{array}{r}
&&1&1&6\\\hline
1&0&1&-1&7\\
0&1&-1&2&-13\\
13&7&6&1&0
\end{array}\tag{2}
$$
that is,
$$
13(-1)+7(2)=1\tag{3}
$$
From $(3)$, we can get
$$
\begin{align}
14&\equiv1\pmod{13}\\
14&\equiv0\pmod{7}
\end{align}\tag{4}
$$
and
$$
\begin{align}
-13&\equiv0\pmod{13}\\
-13&\equiv1\pmod{7}
\end{align}\tag{5}
$$
Now adding $6$ times $(4)$ to $2$ times $(5)$, we get
$$
\begin{align}
58&\equiv6\pmod{13}\\
58&\equiv2\pmod{7}
\end{align}\tag{6}
$$
Adding other multiples of $(4)$ and $(5)$, we can get the other answers you are looking for.


How to reload lazy collections with hibernate after transaction is closed

Question: Let's say I got two Java POJOs: University and Student. "University" includes a list of Students.
That collection is marked for lazy loading in the hibernate mapping file.
So if I receive a "University"-object from hibernate, I can't access the students list after the transaction is closed.
That is a problem for me, because in some (not every!) case I need to access this list. This would be no problem, if i would do all the work in the database layer of my application. But as you can imagine: that layer is only responsible for CRUD tasks.
Changes are made in the business layer. So if the business layer receives that object, the transaction is already closed.
What is best practice for this?
Answer: One solution is Open Session View. Also you can initialize the child entities by calling getters/ iterating through child collection before closing the session.


Factorization, Prime Numbers, and Limits to Our Grasp of Each

Question: I have been fascinated with prime numbers ever since I was very young and actually setup a "Sieve of Eratosthenes" long before I ever knew that something like that existed. As I have gotten older and more exposed to methods of evaluating the "primeness" of numbers, I more and more wonder whether the ways that we are taught to count "on our fingers" and the pervasive use of Base-10 number systems affect our ability to actually find and prove theorems on Prime Numbers and Factorization.
Sorry for taking so long to come to my question: Has there been any research into how counting and the human need to find patterns may hinder our ability to determine the best way to factor numbers? Is there a practical approach to overcoming these limitations?
Please forgive me for not being able to express this in a more technical fashion. I am very much an amateur mathematician and have had little formal training in higher mathematics. My background is in computer programming and it seems to me that one of the basic challenges is that the programmer must be able to define and understand a solution before he/she can instruct a computer to do something with it.
Answer: I don't think that our use of base 10 to represent numbers has inhibited our factorization algorithms. I don't know of any that use base 10 at all, aside from quick tests for divisibility by small numbers. Pollard's rho, SQUFOF, ECM, the quadratic sieve (single- or multiple-polynomial), and the NFS don't take advantage of decimal.
To answer the question asked: No, I'm not aware of any such research.


count consecutive column values with same other column value

Question: I have a WITH SQL statement who select user's activities from a view.
<code>WITH activities AS (
    SELECT a.user_uuid as user_uuid,
           EXTRACT(WEEK FROM a.activity_at) as week_number,
           EXTRACT(DOW FROM a.activity_at) AS dow
    FROM activities_view_validated a
    WHERE a.activity_at > '2022-01-01 00:00:00'
      AND a.activity_type = 'xxx'
    GROUP BY a.user_uuid, a.activity_at
)
SELECT a.user_uuid, a.week_number, a.dow as dow
FROM activities a
GROUP BY 1, 2, 3
ORDER BY 1, 2 , 3
;
</code>
The output look like this (uuid's are truncated)
<code>  user_uuid   | week_number | dow
--------------+-------------+-----
 000debd96628 |           4 |   2
 000debd96628 |          11 |   6
 001034f0d828 |           3 |   5
 001e8576e9a7 |          11 |   1
 001e8576e9a7 |          12 |   1
 001e8576e9a7 |          13 |   1
 0023e9905086 |          12 |   6
 0025cfcb6a1e |           1 |   3
 0025cfcb6a1e |           2 |   5
 0025cfcb6a1e |           3 |   0
 0025cfcb6a1e |           4 |   0
 0025cfcb6a1e |           6 |   0
 00277fec3a8f |           5 |   4
 002cf17fa0da |          13 |   1
 0041f6e950f8 |           5 |   6
 0041f6e950f8 |           6 |   6
 0041f6e950f8 |           7 |   6
 0041f6e950f8 |          10 |   2
 0041f6e950f8 |          10 |   6
 0041f6e950f8 |          11 |   2
 0041f6e950f8 |          13 |   2
 0050c9c16ec4 |           6 |   6
 0050c9c16ec4 |          10 |   0
 00614a48d8de |           7 |   1
 00614a48d8de |          11 |   1
 00614a48d8de |          12 |   1
 00614a48d8de |          13 |   1
 006495e46a1a |          12 |   6
</code>
I want to query user_uuid with their consecutive week_number count having the same day of the week (dow).
So something like that in output, for the three consecutive tuesday of activity on weeks 11, 12, 13 of 001e8576e9a7 user_uuid
<code>  user_uuid   | count
--------------+-------
 001e8576e9a7 |     3

</code>
Is there a solution that can handle to loop to the first one if the curent week is the last.
Comment: Please add an example of what you want the output to be. The question is confusing.
Comment: I think you should group by uuid, and check if all the dow values are the same using having expression and do count on them. Check this [SO Answer](https://stackoverflow.com/a/54298186/4381062)
Comment: With this approach i'll not count consecutives week_number values, maybe i need to prepare in a different way my data.
Comment: How can you select Tuesdays when you don't have the date or the day of the week in the data that you show?
Comment: This is data from my previsous WITH SQL statement, i'll add it
Answer: Here we use the difference between dense_rank and week_number as group number, which means that the group number changes if there is a gap in the data.
The user with user_uuid '00614a48d8de' was present week 7 day 1 then weeks 11,12 & 13 day 1 so we have 2 groups: 1 with count 1 and 1 with count 3.
<code>;with rn as
(select
 user_uuid   , week_number , dow,
 dense_rank() over (partition by user_uuid, dow order by week_number) dr
 from activities)
select
  user_uuid,
  dow,
  (week_number - dr ) as "group",
  count(*)
from rn
where user_uuid='00614a48d8de'
group by
  user_uuid,
  dow,
  week_number - dr
order by
  user_uuid,
  dow;
</code>

user_uuid    | dow | group | count
:----------- | --: | ----: | ----:
00614a48d8de |   1 |     6 |     1
00614a48d8de |   1 |     9 |     3

db<>fiddle here
Comment: Very clear, thank you, just discovered the dense_rank(). I want to retrieve users having a "group" count over defined thresholds so this is fine, the only downside i see will be at the end of a year when reaching the last week but just a SQL CASE to add.


tomcat error: java.net.BindException: Cannot assign requested address (Bind failed)

Question: Unable to resolve this error, i tried changing the shutdown port first, it didn't work, then i changed connector port too still it didn't work.
24-Nov-2020 16:44:39.487 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat/webapps/manager] has finished in [69] ms
24-Nov-2020 16:44:39.498 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8088"]
24-Nov-2020 16:44:39.524 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
24-Nov-2020 16:44:39.566 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [7,031] milliseconds
24-Nov-2020 16:44:49.713 SEVERE [main] org.apache.catalina.core.StandardServer.await Failed to create server shutdown socket on address [localhost] and port [8012] (base port [8012] and offset [0])
    java.net.BindException: Cannot assign requested address (Bind failed)
        at java.base/java.net.PlainSocketImpl.socketBind(Native Method)
        at java.base/java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:436)
        at java.base/java.net.ServerSocket.bind(ServerSocket.java:381)
        at java.base/java.net.ServerSocket.<init>(ServerSocket.java:243)
        at org.apache.catalina.core.StandardServer.await(StandardServer.java:584)
        at org.apache.catalina.startup.Catalina.await(Catalina.java:721)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:667)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
24-Nov-2020 16:44:49.732 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8088"]
24-Nov-2020 16:44:51.740 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
24-Nov-2020 16:44:53.745 INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
24-Nov-2020 16:44:53.939 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8088"]
24-Nov-2020 16:44:53.960 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
24-Nov-2020 16:44:53.967 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8088"]
24-Nov-2020 16:44:53.980 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]

Comment: https://stackoverflow.com/questions/8965155/cannot-assign-requested-address-using-serversocket-socketbind
Answer: Looks like another application is already listening on that port.
If you are in Linux try to run this command to find out:
netstat -tulpen|grep 8012


Move data from root ZFS into child filesystem

Question: I have a zpool (pool verion 13, FS version 3, called tank0) with about 2.5TB of data in the root of the pool (i.e. directly in /mnt/tank0). OS is FreeBSD, actually FreeNAS version 0.7.2.
I would like to move all of that data to a child filesystem (i.e. one created with zfs create tank0/work) in line with best practice (that I know now).
Not too bothered about keeping the snapshots, but I am bothered about ensuring continual data integrity. I am also space constrained - not enough disk space to just backup and restore to the new location.
Is this possible? Guidance appreciated.
Answer: If you don't care about the snapshots, I'd probably just run mv in a screen session. Do you have any logical groupings of data that you can move piecemeal? I'm not sure what other options you have if you can't offload the data to another set of storage.
Comment: Several days later, done. Thanks for the simple suggestion.


Ajax Security Question: JQuery ajax() + PHP scandir() = Security Issue?

Question: I'm a beginner with PHP security issues. Someone reported a security issue with my code, but never gave details.
Below is a condensed version of the code. I'm using the JQuery AJAX function to send some data to the server where it's used by the PHP scandir() function.
Do you see any security issues?
HTML Document

PHP Document
<?php

$foo = filter_var($_POST["foo"], FILTER_SANITIZE_STRING);
$bar = filter_var($_POST["bar"], FILTER_SANITIZE_STRING);

$foo = scandir($foo);
$bar = (explode(",",$bar));

foreach ($foo as $a) {
    echo "";
}

?>

Answer: Yes, I can enumerate every file on your machine. And possibly other machines that your server has access to via fopen wrappers. This information can help identify other vulnerable software running or sensitive files, in order to help me target further attacks.
FILTER_SANITIZE_STRING is designed to protect HTML, not file path references, so it really isn't helping you here. You should only use that as an output filter to the generated HTML and not when using a backend function.
You want to restrict uses of dangerous path tokens like :, @, .., \ and /. But do this by whitelisting the characters or values that you consider safe, as in Tom Haigh's example code.
Answer: You could potentially obtain a listing of any files on your filesystem by posting a malicious value called 'foo' - if a value '/' was sent, you would be able to see in the HTML source all the files in your filesystem root. This might not always work because of things like open_basedir restrictions, but it still isn't a good idea.
A possible solution would be to sanitise the 'foo' parameter first - e.g. only allow certain characters, or you could only allow 'foo' values which exist within a whitelist of allowed directory names, e.g.:
$foo = filter_var($_POST["foo"], FILTER_SANITIZE_STRING);

if (!in_array($foo, array('allowed_dir1', 'allowed_dir2'))) {
    //not valid, not in whitelist
}

//or

if (!preg_match('/^[a-zA-Z0-9+]+$/', $foo)) {
   //not valid, contains more than just letters and numbers
}

Comment: I would like the "foo" value to contain "/" or even an absolute path to a URL. This way, images can be sourced from anywhere. For example, I want to be able to make foo equal to "http://www.somesite.com/directory/directory". Is there a secure way to do this? If not, I'll probably remove the foo from the JavaScript object & php doc, and require that the desired directory be coded directly to the getdir function. I would really like to avoid this as it could require separate php files be created per page that is using my program.
Comment: "This way, images can be sourced from anywhere" - You really don't want to give any remote user the ability to look at any file "anywhere" on your machine. Even if only image files. And remember, just because a file has an image extension, such as "jpg", it doesn't mean that it contains image data. A malicious attacker may have left code there via some other vulnerability. I strongly recommend you rethink your design and requirements.


How to count the node of content type for corresponding entity reference field

Question: I am creating a report. I want to count the nodes of a content type saved for particular entity reference field.
So far I have worked with Views Aggregator and Forena Reports.
But I am not able find it. Can anyone help me on this please?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/29749/discussion-on-question-by-rose-how-to-count-the-node-of-content-type-for-corresp).
Answer: In Views, under Advanced, Use Aggregation - Yes.
Suppose you have content type A and B. B has entity reference field which refers A.
Now you have already created a view for content type A and added its relationship to B.
Now under Fields, Add a new field of the content type B(suppose body), change the label to Count set its aggregation settings to count.


ncat on UDP protocol (RH 7)

Question: I'm resuming the discussion "Check if remote host/port is open - Can't use GNU Netcat nor NMap - RHEL 7".
I can't obtain the correct result because on my rh versions (5.6 and 7.1) there isn't the path /dev/tcp nor /dev/udp.
Here https://access.redhat.com/solutions/1214763 is explained that it can be resolved using
echo | nc -w1  $host $port >/dev/null 2>&1  ;echo $?

and it runs with TCP protocol only but not with UDP:
echo | nc -w1 -u $host $port >/dev/null 2>&1  ;echo $?

Indeed checking an inexistent service it ends with 0.
Using the same ip and port on the RH 5.6 with the old option -z
nc -zu $host $port and it ends with 1, correctly.

Do you have an idea to resolve it?
Thanks
Answer:
there isn't the path /dev/tcp nor /dev/udp

That is correct. Those aren't present in your file-system as directories, but when you include both a hostname/ip-address and and port number AND use them in a redirect bash will do some magic. As phrased in the manual:

Bash handles several filenames specially when they are used in redirections, as described in the following table:

/dev/fd/fd
                   If fd is a valid integer, file descriptor  fd  is  duplicated.
/dev/stdin
                   File descriptor 0 is duplicated.
/dev/stdout
                   File descriptor 1 is duplicated.
/dev/stderr
  File descriptor 2 is duplicated.
/dev/tcp/host/port
  If host is a valid hostname or Internet address, and port
  is an integer port number or service name, bash  attempts
  to open a TCP connection to the corresponding socket.
/dev/udp/host/port
  If host is a valid hostname or Internet address, and port
  is an integer port number or service name, bash  attempts
  to open a UDP connection to the corresponding socket.

Instead of for instance:
$ ls -l /dev/tcp/serverfault.com/80
ls: cannot access /dev/tcp/serverfault.com/80: No such file or directory

try a redirect with >  or <
$ echo "" > /dev/tcp/serverfault.com/80
$ echo " " > /dev/tcp/serverfault.com/81
-bash: connect: Connection refused

Comment: Hi HBruijn,thanks but it doesn't run. It didn't give me any output, using both a valid couple IP/PORT and an invalid couple.

ncat on UDP protocol (RH 7)


Does $\Vert \mathbb{U(a)} \times \mathbb{U(b)} \Vert = det(\mathbb{U})\Vert \mathbb{a} \times \mathbb{b} \Vert?$

Question: If $\Vert \mathbb{U(x)}\Vert =\Vert{\mathbb{x}}\Vert$, does $\Vert \mathbb{U(a)} \times \mathbb{U(b)} \Vert = det(\mathbb{U})\Vert \mathbb{a} \times \mathbb{b} \Vert?$
Here $\mathbb{U}:\mathbb{R^n} \to \mathbb{R^n}$ is linear, and $\mathbb{x,a,b} \in \mathbb{R^n}$
My attempt:$\Vert \mathbb{U(a)} \times \mathbb{U(b)} \Vert = \Vert det(\mathbb{U})(\mathbb{U^{-1}})^T(\mathbb{a} \times \mathbb{b}) \Vert $
I think I miss a trivial property of the linear map, can anyone give me a hint?
Any help would be appreciated.
Comment: What does $\times$ mean for $n \neq 2, 3$?
Comment: That cannot possibly be true. What if $\mathbb U=-\operatorname{Id}$?
Answer: The statement is false, but it is close to a true one. (Also, it's not clear what is meant by the cross product on $\Bbb R^n$.)
Hint So far you have not used the condition $||U({\bf x})|| = ||{\bf x}||$. It is equivalent to $||U({\bf x})||^2 = ||{\bf x}||^2 ,$ which we may rewrite without using the norm as $${\bf x}^\top U^\top U {\bf x} = {\bf x}^\top {\bf x} .$$
Since this holds for all ${\bf x}$, the condition is also equivalent to
$$U^\top U = I.$$ Rearranging then gives a simplification for a quantity that appears in the attempt:
$$(U^{-1})^\top = U .$$
Remark A (square) matrix that satisfies $U^\top U = I$ is called orthogonal.

Additional hint Applying the transformation identity to $U$ and taking the norm of both sides gives $$||U({\bf a}) \times U({\bf b})|| = ||{\bf a} \times {\bf b}|| .$$ Comparing with the original claim, we see that it holds precisely when $\det U = 1$, that is when $U$ is special orthogonal. In particular, the original claim fails precisely when $\det U = -1$, including in the simple case $U = -I$ mentioned by José in the comments.
Comment: Very clear answer, it really helps. Thanks.
Comment: You're welcome, I'm glad you found it helpful.


Sequence in B* space

Question: Suppose $X$ is a $B^* $ space ,which means a normed vector space (not need to be complete),and $\{x_n\},n=1,2,3\dots$ is a sequence in $X$. And for all bounded  linear functional $f$,the sequence $\{f(x_n)\}$ is bounded,try to prove that $\{x_n\}$ is therefore bounded.
I made some attempts. I try to show that if $\{x_n\}$ is not bounded ,then there must exist an  $f\in X^*$,such that  $\{f(x_n)\}$  is not bounded. I do see a proof ,as this An unbounded sequence in a normed linear space.However this proof involes $X^{**}$ space and the corresponding embedding of it.These are given in the next charpter in my text book.And the charpter this problem in is about Hahn-Banach Theorem. I try to construct an linear space of $X$ via the condition of "unbounded" and apply this theorem to it.But I failed .I cannot find out  any property of this problem related with this theorem.
Hints will be wellcomed! Please do not post a full proof of this problem,appreciation!
Answer: One way to avoid the double dual is to use the fact that the dual space of a normed space is a Banach space together with the uniform boundedness principle.
Suppose that $\{x_n\}_{n=1}^{\infty}$ is a sequence in $X$.
Consider the map $T_n:X^*\to \mathbb{R}$ defined by
$$T_n(f)=f(x_n),\qquad (f\in X^*)$$
By hypothesis, for every $f$, there exists some constant such that
$$|T_n(f)|=|f(x_n)|\leq C_f$$
Therefore, by the uniform boundedness principle, there exists a constant $C>0$ such that
$$\sup_n\|T_n\|\leq C$$
This means that for every $f\in X^*$ one has
$$\sup_n \sup \{|f(x_n)|: \|f\|=1\}\leq C$$
which (follows from the Hahn-Banach theorem), is the same as saying that
$$\sup_n\|x_n\|\leq C$$
i.e., the sequence is bounded.

Sequence in B* space


One-To-Many Foreign key must have same number of columns as the referenced primary key

Question: I am trying to implement a one to many association between an order and orderproduct and I am always encountering this exception:
Foreign key (FKmn6eaqdlnl33lnryjkwu09r0m:order_product_entity [order_id,product_id])) must have same number of columns as the referenced primary key (orders [id])

I know what it means but I´m not sure how I should change my scheme to solve it. My design is based on this tutorial : Spring Java eCommerce Tutorial
I can´t tell the difference except my code is written in Kotlin.
I am using Spring Boot with Spring Data JPA and Kotlin.
My Product Entity:
@Entity
@Table(name = "product")
data class ProductEntity(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long,
        @NotNull(message = "Product name is required")
        var name: String,
        var price: Double,
        var description: String

)

My Order Entity:
@Entity
@Table(name = "orders")
data class OrderEntity(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id:Long,

        var dateCreated:Date,

        var status:String,

        @JsonManagedReference
        @OneToMany(cascade = arrayOf(CascadeType.ALL), mappedBy = "orderProductEntityId")
        @Valid
        val orderProducts: List<OrderProductEntity>
)

OrderProductEntity:
@Entity
data class OrderProductEntity(
        @EmbeddedId
        @JsonIgnore
        var orderProductEntityId: OrderProductEntityId,

        @JsonBackReference
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        var order: OrderEntity,

        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        var product: ProductEntity,

        @Column(nullable = false)
        var quantity: Int = 0
)

My composite primary key:
@Embeddable
data class OrderProductEntityId(
        @Column(name = "order_id")
        var orderId: Long = 0,

        @Column(name = "product_id")
        var productId: Long = 0
) : Serializable

Any suggestions?
Comment: forgot to specifiy the orderId explicitly in the mappedBy
Answer: I believe you are using "derived identities". Try mapping OrderProductEntity like this:
@Entity
data class OrderProductEntity(
    @EmbeddedId
    @JsonIgnore
    var orderProductEntityId: OrderProductEntityId,

    @JsonBackReference
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @MapsId("orderId") // maps orderId attribute of embedded id
    var order: OrderEntity,

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @MapsId("productId") // maps productId attribute of embedded id
    var product: ProductEntity,

    @Column(nullable = false)
    var quantity: Int = 0
)

Note the new @MapsId annotations.
Derived identities are discussed (with examples) in the JPA 2.2 spec in section 2.4.1.


Params not being saved in rails

Question: Disclaimer: I am very new to Ruby + rails. I'm not sure if this is a bug, but my params variable always seems to be null. I am working on a large and unfamiliar codebase so I'm not sure if it's something else interfering or my own code; any suggestions would be welcome however.
In my routes file I have match '/proxy_request/:number/:ref' => 'proxies#show', via: :get- I was under the impression that this would store :number and :ref variables in params. However when my proxies#show function runs (below), params is an empty hash.
In case it probably is something else interfering with params, is there another way to pass :number and :ref to proxies#show?
class ProxiesController < ApplicationController

  include Service

  skip_before_action :restrict_access!

  def show
    binding.pry #params is null here
    data = { date: Adapter.staging_date.get(params[:number], params[:ref])}
    render json: data, content_type: "application/javascript", callback: @_request.env["QUERY_STRING"].match(/jQuery\d*_\d*/)
  end

end

Comment: so you are accessing this using a route that looks like `/proxy_request/x/y` correct where `x` is :number and `y` is :ref? This is how those variables end up in params.
Comment: how do you call this route?
Comment: You're on the right way. Check your link again.
Comment: @engineersmnky yes, however they are not being passed in; might be an access control issue
Comment: Which Rails version are you using?
Comment: @Bustikiller Rails 5
Comment: I am not sure if it will solve your problem, but have a look at strong parameters in controllers
Answer: I removed the include Service and all seems to be ok now

Params not being saved in rails


Create all combination of IPL cricket teams with validation criteria

Question: So, I place bets on Dream11 app. In the app, you have to select your team of 11 out of playing 22 players. It has some constraints on a valid team.
Constraints(eg. CSK vs. MI):
Number of wicket keepers can be from 1 to 4
Number of batsmen can be from 3 to 6
Number of allrounders can be from 1 to 4
Number of bowlers can be from 3 to 6
Number of players selected from CSK should be less than equal to 7
Number of players selected from MI should be less than equal to 7
Sum Credits of all the selected players should be less than equal to 100
Now the thing is that sometimes creating these team becomes a really difficult task when they release the lineups and a lot of players you selected are not playing or when one of the playing team is way stronger than other. So, I thought of making a program in which I can input the playing 22 and I can get all the valid teams of 11 players that I can make.
Here is the input file format:
(The first line is just for reference, it's not there in the original file. Every column is tab-separated because it is easy to copy-paste from Excel that way.)

#Name   #Credit   #Team1   #Team2   #WK   #BAT   #ALL   #BOWL   #Sel
Glenn Maxwell   8.5 1   0   0   0   1   0   0
Chris Woakes    9   0   1   0   0   1   0   0
Mitchell Marsh  8   1   0   0   0   1   0   0
Marcus Stoinis  8.5 1   0   0   0   1   0   0
Jonny Bairstow  9.5 0   1   1   0   0   0   0
Jos Buttler 9.5 0   1   1   0   0   0   0
Alex Carey  8.5 1   0   1   0   0   0   0
Eoin Morgan 9   0   1   0   1   0   0   0
Sam Billings    8   0   1   0   1   0   0   0
Joe Root    10  0   1   0   1   0   0   0
David Warner    10  1   0   0   1   0   0   0
Aaron Finch 9.5 1   0   0   1   0   0   0
Marnus Labuschagne  8.5 1   0   0   1   0   0   0
Jason Roy   9   0   1   0   1   0   0   0
Jofra Archer    9   0   1   0   0   0   1   0
Tom Curran  8.5 0   1   0   0   0   1   0
Adil Rashid 9   0   1   0   0   0   1   0
Mark Wood   8.5 0   1   0   0   0   1   0
Josh Hazlewood  8.5 1   0   0   0   0   1   0
Mitchell Starc  9   1   0   0   0   0   1   0
Pat Cummins 9   1   0   0   0   0   1   0
Adam Zampa  8.5 1   0   0   0   0   1   0

The Credit column has credit for the respective player. In all other columns, 0 represents that the respective player is not that thing and 1 represents that the respective player is that thing(eg. 1 in Team1 column represents that player is in Actual Playing Team 1 and 1 in the WK column represents that player is wicket-keeper.)
Here is what I programmed to do this task.
import itertools
ValidTeam = []
with open("Players.txt", "r") as dfile:
    players = [t for t in dfile.read().split("\n")]
combos = list(itertools.combinations(players, 11))
for combo in combos:
    crd, t1, t2, wk, bat, alr, bowl = 0, 0, 0, 0, 0, 0, 0
    for tplayer in combo:
        player = tplayer.split("\t")
        crd += float(player[1])
        t1 += int(player[2])
        t2 += int(player[3])
        wk += int(player[4])
        bat += int(player[5])
        alr += int(player[6])
        bowl += int(player[7])
    if crd <= 100 and t1 <= 7 and t2 <= 7 and (wk in range(1,5)) and (bat in range(3,7)) and (alr in range(1,5)) and (bowl in range(3,7)):
        ValidTeam.append(combo)
        print(player)
    print("")
print(ValidTeam)

Now the problem is for some reason that I don't understand it is showing this error message
Traceback (most recent call last):
  File "C:\Users\RACHIT\Desktop\TM.py", line 12, in <module>
    crd += float(player[1])
IndexError: list index out of range

Please, help me out with this problem.
Also, since there will be 22C11 possible teams and for the future, chosen captains and vice-captains have special privileges so that makes it 2! * 22C11, plus the validation part of that many teams, plus I'm thinking of processing those valid teams too in future to choose the best out of them, so it can take a lot of time to process. So ideas to make it faster, efficient and better will be much appreciated and welcomed.
PS: I'm using itertools for the first time so don't have much idea about it but it so really convenient.
Comment: Don't copy paste from excel to create a csv, save it to a csv from the excel with a delimeter or best read excel directly using existing python modules. Use appropriate modules like csv or pandas to read the csv. If you choose a delimeter which is already present in the file the excel application should take care of appropriately escaping the characters following [standards](https://tools.ietf.org/html/rfc4180) of a csv file. A simple copy paste will not ensure the escaping of characters, making it unable to parse again.
Comment: @Suparshva Thanks man, It turns out when I copy-pasted, it took one extra "next line" at the end. It's running now but validating 22C11 teams is taking lot of time. Any suggestion to improve on that?
Comment: My guess, there might be a blank line in your input file. The error suggest that the size of list after split is smaller than 2.
Comment: @Suparshva Also, not thinking of taking data directly from CSV or Excel playing 22 is fixed only after the lineup is out, so it's faster if I delete the non-playing player rows manually and copy-paste in a txt.
Answer: Scope for improvements:

players = [t.split('\t') for t in dfile.read().split("\n")]
String operations are expensive. Instead of doing it later after generating combinations, do it before. This way you will only do it once for all players.

You can process combos in parallel. Convert your inner loop to a function that processes a list. Use pool.map.

Example implementation:
import multiprocessing as mp

def fun(combo):
    # Implement your logic here for one team, similar to your logic inside current for loop
    # return True if valid else if invalid return False

if __name__ == '__main__':
    .
    .  # Implement reading players from file and generating list of combinations
    .

    num_workers = mp.cpu_count()
    with mp.Pool(num_workers) as pool:
        valid_teams = [c for c, keep in zip(combos, pool.map(fun, combos)) if keep]

    # do something with valid_teams

Reference: https://docs.python.org/3/library/multiprocessing.html
Comment: Thanks a lot. Haven't ever done parallel processing. Will look into the documentation but it'll be a lot easier for me if you could explain me how to implement it. If it's a lot to explain then leave it, I'll look into it anyway. Thanks again for the help.
Comment: Added an example implementation structure.
Answer: list index out of range implies that you are trying to access an array index which does not exist,
player[1] assumes that the player array formed in tplayer.split("\t") has at least 2 elements. the split has not resulted in such an array, fixing that should help
Comment: When I tried to print out only `player` after commenting out all these summation operations, it is showing that the list is forming just right.


Qual é a finalidade do git update-index?

Question: Eu estava enfrentando problemas com pastas, que deveriam ser ignoradas no repositório, mas não eram mesmo quando colocava no .gitignore, e fiz várias pesquisas a fim de solucionar o problema.
Dentre várias pesquisas, vi alguém aconselhando que, em alguns casos, é melhor usar git update-index --assume-unchanged do que usar o .gitignore.
Eu gostaria de saber qual é a finalidade desse comando. Para que ele serve?
E, observando que ele usa o argumento --assume-unchanged, existem outros argumentos que possam ser usado?
Answer: O comando update-index atualiza o índice do GIT, o principal uso é para considerar arquivos modificados como não modificados com o parâmetro --assume-unchanged. Outro parâmetro importante é o --no-assume-unchanged, que desfaz o comando anterior.
Outro comando importante nesse contexto é:
git ls-files -v | grep '^[[:lower:]]'

Usado para listar arquivos marcados como assume unchanged. Fonte.

Retirado do manual, os outros parâmetros:
git update-index
    [--add] [--remove | --force-remove] [--replace]
    [--refresh] [-q] [--unmerged] [--ignore-missing]
    [(--cacheinfo <mode> <object> <file>)...]
    [--chmod=(+|-)x]
    [--[no-]assume-unchanged]
    [--[no-]skip-worktree]
    [--ignore-submodules]
    [--really-refresh] [--unresolve] [--again | -g]
    [--info-only] [--index-info]
    [-z] [--stdin] [--index-version <n>]
    [--verbose]
    [--] [<file>...]

A descrição de cada um dos parâmetros pode ser consultada em https://git-scm.com/docs/git-update-index