MouseMotionListener inside JTable

Question: I am trying to add MouseMotion event to the label and move it based on the dragging of the mouse and make it move along with my mouse.However the mousemotion is very difficult to control making this action not usable.
Here is the code
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableTest
{
    public TableTest()
    {
        String[] columnNames =
        { "FileName", "Integer" };
        Object[][] data =
        {
        { new FileName("AAA.jpg", Color.YELLOW), new Integer(2) },
        { new FileName("BBB.png", Color.GREEN), new FileName("BBB.png", Color.GREEN) },
        { new FileName("CCC.jpg", Color.RED), new Integer(-1) }, };
        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            public Class getColumnClass(int column)
            {
                System.out.println("column is" + column);
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable(model);
        //JTable table = new JTable(data, columnNames);
        table.setDefaultRenderer(FileName.class, new FileNameCellRenderer());
        final JLabel label = new JLabel("TESTING", SwingConstants.CENTER);

        label.setBackground(java.awt.Color.RED);
        label.setBounds(450, 100, 90, 20);
        label.setOpaque(true);
        label.setVisible(true);

        label.addMouseMotionListener(new MouseMotionListener()
        {

            public void mouseDragged(MouseEvent arg0)
            {
                label.setBounds(arg0.getX(), arg0.getY(), 90, 20);

            }

            public void mouseMoved(MouseEvent arg0)
            {
                // TODO Auto-generated method stub

            }

        });
        table.add(label);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(table);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    static class FileNameCellRenderer extends DefaultTableCellRenderer
    {
        public Component getTableCellRendererComponent(JTable table, Object v,
                boolean isSelected, boolean hasFocus, int row, int column)
        {
            super.getTableCellRendererComponent(table, v, isSelected, hasFocus,
                    row, column);
            FileName fn = (FileName) v;
            setBorder(BorderFactory.createMatteBorder(0, 60, 0, 0,
                    new java.awt.Color(143, 188, 143)));
            return this;
        }
    }

    static class FileName
    {
        public final Color color;

        public final String label;

        FileName(String l, Color c)
        {
            this.label = l;
            this.color = c;
        }

        public String toString()
        {
            return label;
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new TableTest();
            }
        });
    }
}

I just want to make the label follow the label follow my mouse and the label should be attached to the table.Is there an easy way than this.
Comment: What does "attached to the table" exactly mean?
Answer: First of all, I think you using the mouse event coordinates (x,y) incorrectly, since those are relative to the source component. In this case the source is the label itself. So you should add to those values the original (x,y) of the source component:
label.setBounds(label.getX() + arg0.getX(), label.getY() + arg0.getY(),90,20);

It's been a while since I had to struggle with the mouse events, but maybe you could try this and let us know if it helps.
Another thing which I'm not sure of is the adding of label to the JTable. The LayoutManager of the JTable might prevent you from actually implementing this way, you may need to use GlassPane or something on top of the table.
Comment: thanks it worked..we can add the label to the table easily this way and setting the setOpaque(true);

MouseMotionListener inside JTable


Resharper: 'contains' mode searching

Question: Is it a way to set up Resharper to search inside names (instead from beginning) ?
Eg assume when pressing Alt + \ in dialog's results I can see

JohnSmith
JonnyBalboa
MariaSmith

I'm looking for all members contain 'Smith' substring - so I'm forced to use asterisk:
*Smith
But I want just enter 'Smith' without anything more (like in DPack)
EDIT
I've opened R# ticket for this. If anyone interested PLEASE VOTE !
UPDATE
'Contains' mode was implemented in R# ver 5. Works perfectly. Even better I dreamed - intellisence also supports that!
Try it and vote for it!
(RS v5. available here)
Comment: I opened a similar ticket relating to 'contains' searching and filtering in intellisense popups: http://www.jetbrains.net/jira/browse/RSRP-101619
Answer: I don't believe this is available.  You would always have to enter a '*' at the beginning.
If you feel that this is a feature you would use (personally I think I'd find it annoying as I usually search for items by prefix) then you can enter a suggestion on their issue tracking site:
http://www.jetbrains.net/jira/browse/RSRP
Not directly related to your question, but one way of searching for an exact match (i.e. not a prefix) is to include a space after your search term.
Comment: Drew, we are already experimenting with 'contains' mode, and we don't like how it works now, but we have some ideas about how to make it much better. Let's wait for 5.0 :)
Comment: I don't really think this is annoying - eg if you have implemented event "Form_Load" you can just enter "Load" to navigate - "Form" is v.common.
Of course we can always try rename VS auto generated events to be more uniq. / fit to R# searching method etc
But I think R# shall be more flexible in that matter and give config option allowing user searching as he like :)

Anyway thanks for URL - I'll definitely put there my suggestion.
Comment: I work on quite large solution files with many 3rd party and in-house APIs loaded.  Searching by prefix already often turns up more results than I'd like, so having a 'contains' versus a 'startswith' search would return even more.  I also don't see how you could do a one-off startswith search if your suggestion was implemented.  Let us know what JetBrains say about your suggestion!
Comment: Ilya, based on some of the long-term issues I'm seeing closed against version 5, I'm looking forward to seeing what's in the release.
Comment: @Ilya - I dont know wy you dont like how contains work. Do you like how actually *search_pattern work? I do :) So please add additional option in R# cfg not forcing on me putting asterisk each time I start searching :)
Comment: @Maciej, adding an option is the last thing we would like to do. There are already lots of options in ReSharper. I'd like to cut half of them, actually :)

Resharper: 'contains' mode searching


Comparing two Linux servers for any differences

Question: I tried to find a similar post, but couldn't. Apologies if this is a duplicate.
We have a number of RHEL6 servers hosting different applications. Over time, these servers have had some tweaks to system parameters such as tcp_fin_timeout, /etc/security/limits.conf etc. to improve application performance and fix issues.
We need to upgrade these servers to RHEL7. As previous changes weren't logged anywhere and have long been forgotten about, is there a script/tool that can list out all system parameters and their values so servers can be compared and make sure we don't miss anything?
Comment: Aside: You probably should be upgrading to RHEL 8 rather than 7. RHEL 7 is past its full support phase, which means among other things that new projects generally should not be started on it. See the [Red Hat Enterprise Linux Lifecycle Policy](https://access.redhat.com/support/policy/updates/errata) for further information.
Comment: Any parameter can be listed but you need to know what you're looking for.
Comment: This assumes all configuration for every software can be defined as `paramenter=value` pairs, but that's not true. Many software have hierachical structures to define configuration, like sections in Nginx & Apache, multiple instance `master.cf` in Postfix. Comparing that kind of configuration isn't that easy, because even the exactly same running configuration could be in many forms on the configuration files.
Comment: Some software do have commands for listing running configuration in a standard form, but that's always software specific, so there's no way to list everything at once, and certainly impossible to answer given only these details. Therefore, I'm voting to close this question as too broad.
Answer: To list the different files, you can do a rsync with the --list-only option so that no files are actually transferred.
This isn't a perfect solution, as it won't tell you what the differences are within the files, but it is a start.  Capture the list to a file (rsync --list-only ... > filelist.txt) and then you can copy just those files to a temporary location and run a diff.


Objetivo do Jquery em php

Question: Em minha graduação, estudei sobre RIA - internet rica e não fixei muito bem o conceito da utilização da biblioteca jquery(JS) em linguagens web. Alguém poderia me esclarecer? Obrigado!
Comment: PHP é uma linguagem _backend_, ou seja, roda no servidor e tem por objetivo "montar" a página HTML e enviar para o cliente (geralmente o seu navegador). Enquanto o jQuery é uma biblioteca em JS que roda no cliente. São assuntos completamente paralelos, pois os dois não têm relação nenhuma, o jQuery não sabe (e não precisa saber) quem foi que montou o HTML ou se o HTML é estático.
Comment: Só para elucidar, o jQuery resolveu um problema em sua época e que hoje não é tão evidente, a incompatibilidade de código entre navegadores. É claro que jQuery ainda tem utilidade, mas as principais funcionalidades dele já são nativas em navegadores modernos e tem uma compatibilidade descente.
Comment: Aí você está falando de [AJAX](https://pt.stackoverflow.com/questions/116153/ajax-n%c3%a3o-%c3%a9-uma-linguagem-de-programa%c3%a7%c3%a3o-ent%c3%a3o-o-que-%c3%a9) que, resumidamente, é uma forma de fazer uma requisição para um servidor de forma assíncrona usando JS sem precisar recarregar a página. Mas ainda sim, este servidor pode ser qualquer coisa, não necessariamente PHP.
Comment: Bem, pesquisando agora o argumento era similar, com algumas diferenças no qual a Js  usando a biblioteca Jquery fazia requisições em tempo de execução(real) para que a aplicação web ficasse similar a uma desktop não precisando recarregar a página php toda hora..
Comment: Obrigado pelo esclarecimento.
Answer: O JQuery não tem um objetivo especialmente para PHP, podendo ser trabalhado com outras linguagens da mesma forma.
É uma biblioteca JavaScript rica em recursos para desenvolvimento rápido de páginas e documentos HTML sendo possível manipular componentes, imagens, animações, requisições AJAX entre outros sendo uma API de fácil aprendizado e funcional em vários navegadores.
Exemplos JQuery:

Vai sumir hein

<button onclick='$("p").hide()'>Esconder</button>

No código acima facilmente você pode selecionar um componente e escondê-lo.
Outro exemplo é a atribuição de um evento à um elemento:

$('#ID_Elemento').on('click', function (){
  alert('Evento onClick() funcionando!')
})

<button id="ID_Elemento">Clique</button>

Você pode obter mais exemplos e informações no site do próprio JQuery

Objetivo do Jquery em php


How to add an editable text box to a page

Question: So i have created a page which uses an XML feed to generate some output. I want to be able to add a textarea from the FORM API so that i can allow user of my site to enter some details on to the form itself.
Similar functionality to how entityform works, seemed like a simple task, but not sure how to do it.
Comment: Take a look at https://www.drupal.org/project/admin_notes
Comment: OK thanks for your answer, for something that should be an easy functionality was kind of an issue. Managed to find some information on how to do it using a block.
Answer: OK thought i would answer my own question and show the method in which this is done. First declare a block, with a block view and then define a custom callback function that defines the textarea, are any output from Drupal's Form API.
<code>function hook_block_info() {
  $blocks['box_question'] = array(
    'info' => t('Box question area'),
  );
  return $blocks;
}

function hook_block_view($delta = '') {
  $block['subject'] = t('TEST');
  $block['content'] .= drupal_render(drupal_get_form('custom_block_form'));
  return $block;
}

function custom_block_form($form, &$form_state) {
  $form['question'] = array(
    '#markup' => 'this is a block,
  );
  $form['answer'] = array(
    '#type' => 'textarea',
    '#resizable' => FALSE,
    '#default_value' => $default,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#name' => 'save',
    '#attributes' => array(
      'class' => array('save-button'),
    ),
  );
  return $form;
}
</code>
The custom_block_form is what defines the form blocks, call the submit functions to make your own callback on what to do when the form is saved.


Related to "division with remainder property"

Question: This is a standard theorem in probably many books at introductory level to number theory:

For $a,b \in \mathbb Z$ with $b >0$, there exist unique $q,r \in \mathbb Z$ such that $a=bq+r$ and $0 \leq r < b$.

If we agree that from now on the multiplication and addition and ordering are the "usual" ones over $\mathbb R$ then I would like to write of what I am thinking about.
I am thinking of does this theorem holds over some other sets than $\mathbb Z$ , that is:

If for every $a,b \in S \subseteq \mathbb R$ and $b>0$ there exist unique  $q,r \in S$ such that $a=bq+r$ and $0 \leq r < b$ is then necessarily $S \subseteq \mathbb Z$? Does $S$ needs to be equal to $\mathbb Z$? Are there some sets that are not subsets of $\mathbb Z$ over which this holds? Are there some exotic ones?
Comment: "*Does $S$ need to be equal to $\Bbb Z$*"  Trivial counterexample: $S=\{0,1\}$.  That is, however, the only example of such a set other than $\Bbb Z$ that I can think of off the top of my head.
Comment: Related concept: [Euclidean domain](https://en.wikipedia.org/wiki/Euclidean_domain).
Comment: @junkquill those examples use a different valuation.
Comment: Yes, you're absolutely right. My mistake, I overlooked an important detail.This makes the question really interesting.
Comment: Can it be that there are some exotic ones? Not trivial, that is.
Comment: If $S$ is a subring, then $S = \mathbb{Z}$. Else for instance $a\mathbb{Z}$ and $a^{\mathbb{Z}}$ work for any $a \in \mathbb{R}^{>0}$.
Comment: You're just looking for Euclidean Domains, which can be the maximal order of some finite extensions of $\mathbb{Q}$
Comment: @junkquill Not just a Euclidean domain, a Euclidean subset with a specific Euclidean valuation in mind.
Comment: (actually, $a\mathbb{Z}$ does not work)
Comment: @TrevorGunn Of course, I understand. But an ED is an example of what OP is looking for. Isn't it?
Comment: @junkquill If the subset happens to also be a subring then yes.
Comment: Right, then the ring of integers of a quadratic extension of $\mathbb{Q}$ with class number 1 is the answer OP is looking for. Examples are then: $\mathbb{Z[\sqrt{2}]}, \mathbb{Z[\sqrt{3}]}, \mathbb{Z[(1+\sqrt{5})/2]}, \mathbb{Z[(1+\sqrt{13})/2]}, \mathbb{Z[(1+\sqrt{17})/2]}$ etc.
Comment: There seems to be nothing in the question which implies that the order on $S$ is induced by the order on $\mathbb R$. What is stated implies that we are working in a real field (every square is positive). But what, in the question as written, implies $\sqrt 2 \gt 0$? Ie the fact that every square is positive, and that $S$ is ordered, does not force a canonical approach to square roots. It is not stated either whether $b\gt 0$ applies in $\mathbb R$ or $S$.
Comment: @nombre: I'm quite sure that $a^\mathbb{Z}$ ($a>0$) does not work either. Namely, wlog $a<1$. Dividing 1 ($=a^0$) by itself, one gets unique exponents $q,r$ with $r>0$ and $1=a^q\cdot 1+a^r$ (which already shows $a$ would need to be algebraic). On the other hand, dividing $a^{-n}$ by 1, we get unique exponents $q(n), r(n)$ with $r(n) >0$ and $a^{-n} = a^{q(n)} + a^{r(n)}$. Multiplying this with $a^n$ gives $1 = a^{q(n)+n}\cdot 1 +a^{r(n)+n}$, and $r(n)+n>0$, so by uniqueness $r =r(n)+n \ge n$ for all $n$, which is absurd.
Comment: @TorstenSchoeneberg: Yes, you're right, and for now your examples are the only ones I can think of.
Answer: So, not an anwser but just a special case:
If $S$ is a subring of $\mathbb{R}$, then it must be discrete (and therefore be $\mathbb{Z}$), since if there is $0 < s < 1$ in $S$, then $s = 1\times 0 + s = 1 \times s + 0$ with $0 \leq 0,s < 1$.
Comment: Does this not show the stronger statement "If $S$ contains $0$ and $1$, then it cannot contain $0<s<1$"?
Comment: Also, the argument generalises to "If $0,x,y \in S$ with $0<x<y$, then $\frac{x}{y} \notin S$. (In this case, $y=1$ and we get the contradiction $x\notin S$.)
Comment: Yes indeed. I insisted on $S$ being a subring because it is easier for me to see how this would be interesting. It would be nice to know in what context Antoine Pal Adeen asked himself that question.
Answer: This is not a definite answer, but a collection of observations, examples and ideas, some of them more worked out than others. Any feedback, refinements, counterexamples etc. are greatly appreciated.

Observation: Every $S\subseteq \Bbb{R}_{\le 0}$ is an example because the condition is vacuously true.
So from now on, we assume $S^+ :=S \cap \Bbb{R}_{>0} \neq \emptyset$. Let $b :=\inf S^+$.
Lemma: Either $b=\min S^+ = 1$ (case 1), or $b = 0$ (case 2). In case 1, necessarily $0\in S$.
Proof: Let $x\in S^+$. First assume $b \ge 1$. By hypothesis there are $q \in S, r\in S^+\cup \{0\}, r<x$ with $x=qx+r$. Since $r<x$ we get $q\in S^+$, hence $q \ge b$, hence the contradiction
$$x = qx+r\quad \ge \quad bx +r \; \stackrel{b>1 \; \text{or} \;b=1, r>0}> \;x,$$
unless $q=b=1$ and $r=0$, which is case 1.
Now assume $0\le b<1$. For every $\epsilon >0$, there is $x_\epsilon\in S^+$ with  $x_\epsilon<1$ and $x_\epsilon-b<\epsilon$. We have $x_\epsilon = q_\epsilon x_\epsilon +r_\epsilon$ with $r_\epsilon<x_\epsilon$, so necessarily $q_\epsilon\in S^+$ and hence $q_\epsilon x_\epsilon \ge b^2$. If $r_\epsilon=0$, we get $q_\epsilon=1$, so $S$ contains the three elements $r_\epsilon = 0<x_\epsilon<1 = q_\epsilon$, which contradicts the argument in nombre's answer. So $r_\epsilon>0$ and thus $r_\epsilon>b$. Now if $b >0$, any $0< \epsilon < b^2$ gives the contradiction $q_\epsilon x_\epsilon = x_\epsilon-r_\epsilon \le \epsilon$. QED.

See below for many different examples for case 1, but as of now, there are no examples for case 2.
Conjecture: Case 2 is impossible.
The argument in nombre's answer shows that an $S$ in case 2 could not contain both $0$ and $1$. Such an example would (obviously) contain arbitrarily small positive numbers, but also (as one sees via "dividing" by such a small number) arbitrarily big numbers.

Here are some examples for case 1 containing elements outside of $\mathbb{Z}$:

For any real $x>1$, $S = \{0,1,x\}$.

What about $\{0,1,x,y\}$ with $1<x<y$? One checks that for existence of mutual divisions with remainder, one needs $y=x^2$ or $y=x+1$, or $y=x^2+1$. For uniqueness in the first two cases, one needs however that $x^2 \neq x+1$ or in other words, $x \neq \frac{1}{2}(1+\sqrt5)$. (Because otherwise, $x\cdot x + 0 = 1\cdot x + 1$ are two different ways to "divide $x^2$ (resp. $x+1$) by $x$ with remainder $<x$".) So:

For any real $1<x$, $S = \{0,1,x, x^2+1\}$.
For any real $1<x\neq \frac{1}{2}(1+\sqrt5)$, $S = \{0,1,x, x+1\}$.
For any real $1<x\neq \frac{1}{2}(1+\sqrt5)$, $S = \{0,1,x, x^2\}$.

Generalising the third example, for any $x>1$ and $k \in \Bbb{N}$,

$S = \{0,1,x, x^2, ..., x^k\}$

as well as the infinite

$S = \{0,1,x, x^2, ...\}$

work, if one makes sure there is no relation of the form $x^a = x^b +x^c$ with $c<b<a$ among the occurring exponents. In particular, each $x\ge 2$, and also each transcendental as well as each rational $x>1$, works.
A general idea here would be to start with a set $\hat S \,(\supseteq \{0,1\})$ of polynomials in $\mathbb{Q}[X]$ (or $\mathbb{Z}[X]$; actually, we want to restrict to non-negative coefficients, $\mathbb{N}_0[X]$) for which we have unique division with remainder (with respect to the degree valuation), and then evaluate those polynomials at $x\in \mathbb{R}$. As long as $\hat S$ is finite, it seems as if by choosing $x$ big enough one can make sure that the order on $\mathbb{R}$ refines the order given by the degree, and the "evaluated set" $S = \hat S(X=x)$ would be an example. But there are some subtleties here I am not sure about.
Finally, here is a non-discrete example which further generalises the last one:
Let $R$ be a non-discrete additive subgroup of $\Bbb{Q}$, and $R_{\ge 0}$ its non-negative elements. Then for each choice of $x>1$, except possibly countably many algebraic ones,

$S= \{0\} \cup \{x^r: r\in R_{\ge 0}\}$

is an example. Namely, again one just has to make sure that there is no relation of the form $x^a = x^b +x^c$ with $c<b<a$ among the occurring exponents. But every $x$ that satisfies such a relation is algebraic (as well as $\notin \Bbb{Q}$).

Finally, even though the OP asks about sets $S$ that are larger than $\mathbb{Z}$, I find it already interesting to think about which subsets $S\subset \Bbb{Z}$ have this property, and, to keep it in the spirit of the considerations above, I want to restrict to those which contain $0$ and $1$ (which makes sense if we want to write every element $a \in S$ as $1\cdot a +0$), and whose elements are non-negative.
The good thing in this situation that one does not need to worry about uniqueness of the division with remainder, since that is obviously inherited from $\mathbb{Z}$. So one just has to make sure that all quotients and remainders of pairs are in the set. Here are some examples, the first four being just special cases of the more general ones above:

For every $n, k \in \Bbb{N}$, $S = \{0,1, n, n^2, ..., n^k\}$.
For every $n \in \Bbb{N}$, $S = \{0,1, n, n^2, ...\}$.
For every $n \in \Bbb{N}$, $S = \{0,1, n, n+1\}$.
For every $n \in \Bbb{N}$, $S = \{0,1, n, n^2+1\}$.
For every $n \in \Bbb{N}$, $S = \{0,1, n, n^2+1, n(n^2+1)\}$.
For every $n \in \Bbb{N}$, $S = \{0,1,2, ..., n\} \cup B$ where $B$ is an arbitrary subset of $\{n+1, ..., 2n+1\}$. (Proposed by Glen Whitney, see his comment).

Note how the last example feels different from the others, as it seems to be not "induced" by certain polynomials, as all the ones before.
One way to think about this problem is to define the following "closure" operator on any subset $\{0,1\} \subseteq T \subseteq \mathbb{Z}$:
$$c(T) := T \cup \{\lfloor a/b\rfloor, a-\lfloor a/b \rfloor b :a,b \in T, 0\neq b\}$$
which adds all quotients and remainders of elements in $S$ to it. A set $S$ that satisfies your property then is one with
$$c(S) =S$$
and one could ask whether one always reaches such a "$c$-closed" set after finitely many iterations of applying $c$. This is certainly true if $T$ is finite, since all elements that get possibly added are bounded by the largest element of $T$. For example, if I start with $T = \{0,1,7,9\}$, I get $c(T) = \{0,1,2,7,9\}, c^2(T) = \{0,1,2,3,4,7,9\}$ and this last set is $c$-closed,

$S = \{0,1,2,3,4,7,9\}$

which is a special case of the last example above. On the other hand, the $c$-closure of $\{0,1,2,10\}$ is just

$S = \{0,1,2,5,10\}$

which is of the type of the penultimate example.
It would be very nice if one had an alternative explicit description of such $c$-closed sets. Also, whose sets' $c$-closure ends up being of what kind?
Comment: Not a characterization of finite "c-closed" sets, but here's one family of them that contains your last example: all sets $C$ of the form $C = [0,m] \cup B$ where $B\subseteq[m+1,2m+1]$. (Using $[x,y]$ for inclusive integer ranges.) We check $C$ is c-closed by cases on which piece of the union $a$ and $b$ lie in. Both in $[0,m]$, obvious; $a\in[0,m]$ and $b\in B$, the quotient is 0 and the remainder is $a$; $a\in B$ and $b\in[0,m]$, the quotient and remainder are in $[0,m]$ (except for the trivial $b=1$); and both in $B$, the quotient is 0 or 1 and the remainder is in $B$ or $[0,m]$, resp.
Comment: They need not be "larger" than Z in the sense of cardinality, just beautiful. +1 for an effort.
Comment: Thanks. I am still thinking about it and occasionally updating this answer.
Comment: I believe that there are some exotic ones, but I do not think much about this.
Answer: the least abstract is polynomials with rational coefficients. There is a gcd and Bezout formula $pa+qb = g.$ Instead of $0 \leq r < b,$ each step gives either $r = 0$ or $\deg r < \deg b \; .$ Constant polynomials get degree zero, as below with 185/16. Notice how one more line is needed to get remainder actually zero, not degree zero.
$$  \left(   x^{4}  + 2 x^{3}  + 3 x^{2}  + 4 x  + 5 \right)  $$
$$  \left(  6 x^{3}  + 7 x^{2}  + 8 x  + 9 \right)  $$
$$  \left(   x^{4}  + 2 x^{3}  + 3 x^{2}  + 4 x  + 5 \right)  =  \left(  6 x^{3}  + 7 x^{2}  + 8 x  + 9 \right)  \cdot \color{magenta}{  \left(   \frac{ 6 x  + 5 }{ 36 }  \right) } +  \left(   \frac{ 25 x^{2}  + 50 x  + 135 }{ 36 }  \right)  $$
 $$  \left(  6 x^{3}  + 7 x^{2}  + 8 x  + 9 \right)  =  \left(   \frac{ 25 x^{2}  + 50 x  + 135 }{ 36 }  \right)  \cdot \color{magenta}{  \left(   \frac{ 216 x  - 180 }{ 25 }  \right) } +  \left(   \frac{  - 72 x  + 180 }{ 5 }  \right)  $$
 $$  \left(   \frac{ 25 x^{2}  + 50 x  + 135 }{ 36 }  \right)  =  \left(   \frac{  - 72 x  + 180 }{ 5 }  \right)  \cdot \color{magenta}{  \left(   \frac{  - 250 x  - 1125 }{ 5184 }  \right) } +  \left( \frac{ 185}{16 } \right)  $$
 $$  \left(   \frac{  - 72 x  + 180 }{ 5 }  \right)  =  \left( \frac{ 185}{16 } \right)  \cdot \color{magenta}{  \left(   \frac{  - 1152 x  + 2880 }{ 925 }  \right) } +  \left( 0 \right)  $$
 $$ \frac{ 0}{1} $$
 $$ \frac{ 1}{0} $$
 $$ \color{magenta}{  \left(   \frac{ 6 x  + 5 }{ 36 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{ 6 x  + 5 }{ 36 }  \right) }{ \left( 1  \right) } $$
 $$ \color{magenta}{  \left(   \frac{ 216 x  - 180 }{ 25 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{ 36 x^{2}  }{ 25 }  \right) }{ \left(   \frac{ 216 x  - 180 }{ 25 }  \right) } $$
 $$ \color{magenta}{  \left(   \frac{  - 250 x  - 1125 }{ 5184 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{  - 10 x^{3}  - 45 x^{2}  + 24 x  + 20 }{ 144 }  \right) }{ \left(   \frac{  - 60 x^{2}  - 220 x  + 369 }{ 144 }  \right) } $$
 $$ \color{magenta}{  \left(   \frac{  - 1152 x  + 2880 }{ 925 }  \right) }  \Longrightarrow  \Longrightarrow  \frac{  \left(   \frac{ 16 x^{4}  + 32 x^{3}  + 48 x^{2}  + 64 x  + 80 }{ 185 }  \right) }{ \left(   \frac{ 96 x^{3}  + 112 x^{2}  + 128 x  + 144 }{ 185 }  \right) } $$
 $$  \left(   x^{4}  + 2 x^{3}  + 3 x^{2}  + 4 x  + 5 \right)  \left(   \frac{  - 60 x^{2}  - 220 x  + 369 }{ 1665 }  \right)  -  \left(  6 x^{3}  + 7 x^{2}  + 8 x  + 9 \right)  \left(   \frac{  - 10 x^{3}  - 45 x^{2}  + 24 x  + 20 }{ 1665 }  \right)  =  \left( 1  \right)  $$
Comment: $\mathbf{Z}\sqrt 6$ does not work because there is no way to write $\sqrt 6 = q \sqrt 6 + r$ with $q,r \in \mathbf{Z}\sqrt 6$ and $0 \le r < \sqrt 6$.
Comment: @WillJagy A Euclidean Domain is also something that I proposed as an answer on the comments of the question. But as TrevorGunn points out, the valuation (which I presume means the norm) which is what defines the condition on the remainder is not the same in $\mathbb{Z}[\sqrt{6}]$ as in $\mathbb{Z}$
Comment: @junkquill I see, he was insisting on the same absolute value and order. I don't think there will be any examples; it may not fit all the conditions the OP thought he wanted, but my original example of polynomials with rational coefficients is a good one to start with.
Comment: I was thinking just about subsets of $\mathbb R$.
Comment: @AntoinePalAdeen, well, $\mathbb Z \sqrt 6$ works.
Comment: Doesn't $q=1$, $r=0$ work?
Comment: @junkquill $1$ isnt an element of $\mathbf{Z}\sqrt 6$
Comment: My apologies. I thought we were talking about $\mathbb{Z}[\sqrt{6}]$, where $1$ is definitely an element.
Comment: @TrevorGunn I see, I left off the bracket signs; my fault. See http://math.stackexchange.com/questions/124484/show-mathbbz-sqrt6-is-a-euclidean-domain/124573#124573
Comment: @junkquill I see, I left off the bracket signs; my fault. See http://math.stackexchange.com/questions/124484/show-mathbbz-sqrt6-is-a-euclidean-domain/124573#124573
Comment: But the OP specifically asks for $S \subset \mathbb{R}$, and your example encounters the same problem as any ED defined - the dependence on the norm function.
Comment: @junkquill fair enough. Let us just say that I answered the question he probably should have asked.
Comment: @WillJagy There I agree with you. Then a general answer would be, keeping in mind that $S \subset \mathbb{R}$, all the ring of integers of a finite extension of $\mathbb{Q}$ with class number $1$.


Playing a Frequency in OpenAL in C

Question: I am trying to write a program to play a frequency for a time. I can't find any way of simply just playing a certain frequency. How do I go about doing this in OpenAL?
Answer: I eventually found a video on properly reading form a WAV file (huge credit to this video) and how a WAV file is formatted (explained here in detail) and did some trial-and-error work until I figured out how to do it. I figured that if I could make a WAV-style file with the frequencies in them and set up the OpenAL buffer and source manually, it would work.
I ran into some trouble when I found that the format differed from the first explanation of WAV file format I found, as some apparently have additional meta-data, which I had to test for and skip over when trying to load a WAV file. Then I made a WAV file containing the frequencies and played it, which worked as well as I could have hoped for.
Here's another article about how bit-depth works that really helped me understand what I was doing.
Hopefully this helps anyone else who is trying to do something similar to this!

Playing a Frequency in OpenAL in C


updating sql table

Question: Whenever i tried to update the form using following code, the update goes silent with the 0 value in title field and previous value in content field. Can someone please help!!!
adminClass.php
update function
 if( $form_title && $form_content ){
       $sql = "UPDATE home_page
       SET title = '{$form_title}' AND content = '{$form_content}' WHERE id = {$id}";
       echo $sql;
       $result = $this->mysqli->query( $sql );
       if(!$result){
         echo 'Error'. mysqli_error();
         return;
       }else{
         $this->success_message = "Update Successfull";
         return;
       }
    }

admin.php view page
if( isset( $_POST['update'] ) ){
   $admin_obj->update($_POST, $id);
}

Comment: You have a SQL injection vulnerability.
Answer: MySQL silently cast your UPDATE statement and performs boolean operation.
The server reads the update statement as
UPDATE home_page
SET title = ('{$form_title}' AND (content = '{$form_content}'))
WHERE id = {$id}

What you are going to do is to replace the AND into , to make it work.
UPDATE home_page
SET title = '{$form_title}', content = '{$form_content}'
WHERE id = {$id}

As a sidenote, the query is vulnerable with SQL Injection if the value(s)  of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

How to prevent SQL injection in PHP?

updating sql table


Why does the natural logarithm function pop up as default link function when doing Poisson regression?

Question: What is the philosophy behind the logarithm as link function for Poisson regression? What is it about count variables that modelling them as a GLM with the natural logarithm function is appropriate?
I suppose it has something to do with the definition of the Poisson distribution, for which the probability function is exponential in lambda?
Comment: Please see https://stats.stackexchange.com/search?q=canonical+link+poisson+-zero or  https://stats.stackexchange.com/search?q=exponential+natural+parameter+poisson+log.
Comment: Does this answer your question? [Calculation of canonical link function in GLM](https://stats.stackexchange.com/questions/17304/calculation-of-canonical-link-function-in-glm)
Answer: The point is that in Poisson regression you are dealing with count variables, which are non-negative by definition. Using the log-link assures that the modelled means on the count scale are strictly positive. This has nothing to do with the exponential function in the Poisson density function. In theory you could use any link function, but e.g. an identity link may yield nonsensical, negative means for some combinations of predictor variables.


How to bind json data in jquery without key

Question: How to append data in table...enter image description here
0
:
{createdBy: 1, UserName: "Anita Wilkins", 2018-02-01: "N/A", 2018-02-02: "N/A", 2018-02-03: "N/A", …}
1
:
{createdBy: 2, UserName: "Genson", 2018-02-01: "N/A", 2018-02-02: "N/A", 2018-02-03: "N/A", …}
length
:
2

__proto__
:
Array(0)

Comment: Please take the [Tour] and read [ask]. Then come back and edit your question. It is currently not clear and too broad.
Comment: You'll have to give us a much clearer explanation of your problem, it's not obvious what you want or what the issue is. Also if you're talking about JSON, please show some actual JSON, the above is not JSON.
Answer: You are trying to iterate the array without knowing the key. The below solution would do it for you.


Do I understand Mid/Side processing correctly?

Question: Recently I've been reading about the mid/side processing and I'ce got this image in my mind:
Let's assume I have 3 guitars in my recording. Guitar one "1" panned 100% left, second "2" in center and third "3" in 100% right. Now when I sum them all together I can process them with Mid/Side processing so I will either deal with guitars "1" and "3" together (Because they are on sides) or with signal "2" because it's in centre. Am I right?
The second question is about the perceived loudness of it. If I have a hi hat panned 70% to the right, that means that 30% of the sound still goes to the left speaker. When I listen to this in Mid/Side processing what amount of dB will come out in either (Side and Mid) of them from my speakers? Will in side processing it be 70% from right and 0% from left, or 40% from left? And what about the Mid side?
In this case scenario, what if my sounds are panned only a bit, a tiny 1% to the side? How Mid/Side processing will affect what I hear in headphones then?
Thanks for reading :)
Answer: I think you've got a few things off. First, let's look at what you've got with your three guitars.
Your left channel has 100% of 1, 50% of 2, and 0% of 3.
Your right channel has 0% of 1, 50% of 2, and 100% of 3.
Mid = L+R which means Mid will have 100% of 1, 100% of 2 and 100% of 3.
Side = L-R which means side will have 100% of 1, 0% of 2, and -100% of 3. In this case, the negative sign means that the polarity of the signal is reversed.
Using Mid/Side means that you can drop the side channel out and still have a mono mix, which is why the mid channel has all three guitars in it. What the side channel does is contain the "stereo width" in a way. If you mid-side encode, then the fader that controls the level of the side channel just widens the image as you bring it up. On the other hand, if you drop out the mid channel you lose guitar 2 entirely.
So what mid/side processing does is let you separately control the overall level and the stereo width. If you compress the side channel more than the mid channel, for example, then you limit the width of the image. If you compress the mid channel more than the sides, then you limit the overall level while still having a dynamic stereo width. It's a bit weird to work out in your head, so I'd suggest playing around with it to really get it.
Your second question I don't get. If you have something panned 30% left, then it's still 30% left. If you mid/side process it then by raising and lowering the side channel you're basically increasing or reducing how far left it is. 0 side means it's panned center. 0 mid and 100% side means it's panned 100% left.
One thing to understand about "mid/side processing" is that it's not about taking away the normal left/right panning. What you do is you take the left/right and encode it mid/side (as above), then you process the mid and the side differently, then you decode it back to left/right. That last step Is pretty much always done because we don't have mid/side speakers or mid/side ears. Sending mid to the left speaker and side to the right would around very strange.
As I mentioned above, I recommend playing around with it and using your ears to understand best how it all works.
For reference, decoding mid-side looks like this:
Left = mid + side
Right = mid - side
See: https://www.soundonsound.com/sound-advice/q-how-does-mid-sides-recording-actually-work
Comment: Good explanation. I'd throw in a ref back to the 'origin' of mid-side, which is a physical mic setup which generates the 'math' you have already explained. - https://www.uaudio.com/blog/mid-side-mic-recording/ looks a good example.


Realizar backup automatico MySQL

Question: Estou utilizando o MySQL como SGBD, e ao pesquisar na internet uma forma de criar uma rotina de backup descobri que as versões antigas possuíam uma ferramenta que deixou de existir nas versões mais novas, acredito que quem usa o MySQL não ficou nas versões antigas.
Gostaria de saber se hoje existe uma forma correta de criar esta rotina de backup ou não cada um faz de uma forma.
Answer: "MySQL Workbench é um cliente de consulta e ferramenta para modelagem e muito bom nisso - o objetivo não é para executar tarefas do servidor - que é o trabalho do servidor. Você pode executar backups manuais usando Workbench, mas eu estou supondo que não é seu objetivo a longo prazo.
Há muitas maneiras que você pode executar backups. Dê uma olhada aqui para 10 deles. Algumas das soluções são dependente do SO basicamente, você tem mais opções se você estiver em Linux /*nix do que no Windows (qual é seu?). Além disso, ele depende que suas tabelas sejam InnoDB ou MyISAM (espero que seja InnoDB!).
Dois outros (Open Source) soluções de backup não mencionados no post acima são de Percona XtraBackup que pode ser cron'd ou Zmanda 's (que foi mencionado no High Performance MySQL livro por Schwartz et al.). Outra solução seria MyDumper - novamente uma ferramenta apoiada Percona (exceto este também lida com tabelas MyISAM).
Se você estiver familiarizado com os sistemas * nix e de arquivo, então talvez uma solução LVM pode ser boa para você? Experimente aqui .
Aconselho-vos a estudar as soluções disponíveis e fazer alguns testes e ver qual deles atende melhor às suas necessidades."
*As vezes é preciso buscar um pouco mais! Abraço.
Texto original
Comment: Eu utilizo Windows.
Comment: então vc pode tentar um desses programas, ou realizar manualmente `Server/Export` ou `Server/Back Up e Recovery` e criar uma configuração no `my.cnf`
Answer:
Você pode usar esse script em Python que eu criei, ele faz backup de todas as bases de Dados.

Baixe ele, execute um chmod +x backup_mysql.py e coloque na pasta /usr/local/bin/
Comment: Tem como você colocar os códigos aqui também? Desta forma vai que acontece algum problema e esse *link* deixe de existir, a resposta não fica inválida. Dá uma revisada em tudo o que postou.
Comment: Nilton, revisando algumas de suas publicações, reparei em várias com esse mesmo formato, e as converti para comentários. Se você editá-las para deixá-las mais completas, não esqueça de sinalizá-las para que um moderador possa avaliar e se for o caso restaurar as respostas. Obrigado
Comment: Tudo bem, colocar o código aqui do script fica muito grande e sempre eu atualizo esse script, é muito raro eu excluir meus próprios scripts pois eles fazem partem de vários projetos.

Realizar backup automatico MySQL


Using aws credentials profiles with spark scala app

Question: I would like to be able to use the ~/.aws/credentials file I maintain with different profiles with my spark scala application if that is possible. I know how to set hadoop configurations for s3a inside my app but I don't want to keep using different keys hardcoded and would rather just use my credentials file as I do with different programs. I've also experimented with using java api such as val credentials = new DefaultAWSCredentialsProviderChain().getCredentials() and then creating an s3 client but that doesn't allow me to use my keys when reading files from s3. I also know that keys can go in core-site.xml when I run my app but how can I manage different keys and also how can I set it up with IntelliJ so that I can have different keys pulled in using different profiles?
Comment: I don't have time to look up links, but you can specify what file to use for credentials rather than using the default provider chain.
Comment: Thanks. Can you provide a little more detail for what you mean? Do you mean still using `AmazonS3Client client = new AmazonS3Client(new ProfileCredentialsProvider("my_profile_name"))`? Not sure how this would apply to reading s3 files with spark using `s3a://`
Answer: DefaultAWSCredentialsProviderChain contains no providers by default.  You need to add some, e.g.:
val awsCredentials = new AWSCredentialsProviderChain(new
  auth.EnvironmentVariableCredentialsProvider(), new
  auth.profile.ProfileCredentialsProvider(), new
  auth.AWSCredentialsProvider())

You can use them with S3 client or, as you mention Spark:
hadoopConfig.set("fs.s3a.access.key", awsCredentials.getAWSAccessKeyId)
hadoopConfig.set("fs.s3a.secret.key", awsCredentials.getAWSSecretKey)

To switch between different AWS profiles you could then switch between profiles by setting the AWS_PROFILE environment variable.  Happy to expand on any particular point if needed.
Answer: If you have the AWS_ env vars set, spark-submit will copy them over as the s3a secrets.
If you want to set a provider chain for S3A, then you can provide a list of provider classes in the option fs.s3a.aws.credentials.provider, These will get created with a Configuration instance if present, otherwise the empty constructor is used. The default list is: one to get secrets from the URI or config, one for env vars, and finally one for EC2 IAM secrets. You can change them to existing ones (anonymous provider, session provider), or write your own...anything which implements com.amazonaws.auth.AWSCredentialsProvider is allowed.
You should be able to set fs.s3a.aws.credentials.provider to com.amazonaws.auth.profile.ProfileCredentialsProvider and have it picked up locally (maybe you'll need your own wrapper which extracts the profile name from the configuration passed in. This will work on any host which has your credentials...it won't work if you only have local secrets and want to submit work elsewhere. It's probably simplest to set environment variables and have spark-submit propagate them.


Show that is $\int_A f$ exists, then so does $\int_A |f|$

Question: Let $f$ be a real-valued function on $A$ in $E^n$. Show that is $\int_A f$ exists, then so does $\int_A |f|$ and $\left | \int_A f\right | \le \int_A |f|$.
I am trying to finish Rosenlicht's Introduction to Analysis and the last chapter is awful. But I do want to finish it because I have come this far. Could someone show me how to do this, so I can at least have some example problems to understand the material. This chapter (Multiple Integrals) really just left more confused than before I started reading the chapter.
Thank you in advance.
Comment: By definition, Riemann integrable functions are bounded. To show the first part, note that for every partition $P$ and every cell $c$ in $P$, $\sup\limits_c|f|-\inf\limits_c|f|\leqslant\sup\limits_cf-\inf\limits_cf$ hence $U(|f|,P)-L(|f|,P)\leqslant U(f,P)-L(f,P)$, which shows that $|f|$ is Riemann integrable. For the second part, note that $-|f|\leqslant f\leqslant|f|$.
Comment: What is $A$? This result seems incorrect, $\int_0^{+\infty} \frac{sin x}{x}$ would be a counter-example.
Comment: $A \subset E^n$ Also, assume $A$ is closed interval to simplify the problem.
Comment: @Jack I think $A$ is bounded (it should be otherwise this is wrong).
Comment: @Hamed Yes I believe you are correct, even though the problem statement is exactly as stated above.
Comment: @Did this is pretty much the answer I was looking for, if you copy it to the answer section I will give you the credit. Thanks
Comment: Thanks but these are at most succinct hints. Please expand them into a full answer and post it below, after a while you may even accept it.
Comment: I am sorry but I am having trouble actually writing out the proof for the first part. Is there any way you could show me how to do the first part? (especially the part where you say "hence")
Comment: Possible duplicate of [Show that the integral of absolute value of $f$ exists if $f$ is integrable.](http://math.stackexchange.com/questions/1542984/show-that-the-integral-of-absolute-value-of-f-exists-if-f-is-integrable)
Answer: In general, the statement is false: $\int_0^\infty {{\sin x}\over{x}} dx$ is well-defined by the alternating series theorem, but $\int_0^\infty |{{\sin x}\over{x}}| dx$ is not.
The statement is true if $A$ is closed and bounded (hence compact). In that case, any continuous measure $\mu$ on $A$ is finite, and so $\int_A f d\mu \leq \infty$ if and only if $f$ is finite a.e. with respect to $\mu$. If $f$ is a.e. finite, then so is $|f|$, from which the first part of the result follows.
The second part follows from Jensen's inequality. $|\cdot|$ is convex on the real line, and hence
$$ {\biggl |}\int_A f d\mu \biggr | \leq \int_A |f| d\mu $$
Comment: I realize that I gave an over-general answer, I guess. Your problem concerns only continuous functions and Riemann integration, so of worrying about a general continuous measure, you can simply consider Lebesgue measure, which corresponds to Riemann integration. The integral is well-defined only if the function is bounded, and the rest goes through as before.

(Edited to correct a misspelling.)


Let $f: A\to B$, $g: B\to C$ and $h: B\to C$ be functions. Suppose that for all $x\in A$ we have $g(f(x)) = h(f(x))$. Prove or disprove $g=h$

Question: Because a single input for a function cannot have different outputs, I have written $g(f(x))= h(f(x))$ as $g(y) = h(y)$ for all $y\in B$. Is this enough to say that $g=h$? The question doesn't specify anything regarding the injectivity of the functions, so I am a little stumped on where to go next. Any advice would be appreciated. Thank you!
Comment: Injectivity isn't the problem - surjectivity is. $g(f(x)) = h(f(x))$ shows that $g$ and $h$ are equal over the image of $f$, but if $f$ isn't surjective then consider what happens with $y \in B$ if $y$ isn't in the image of $f$.
Comment: We can draw this conclusion for any such $C, g, h$ iff $f$ is surjective. That is, surjections are exactly the epimorphisms in the category of sets.
Answer: It suffices to consider that $f$ is not surjective to provide a counter-example.
Indeed, let us consider that $A = B = C = \{0,1,2\}$.
Now we can define $f$ as follows:
\begin{align*}
f = \{(0,0),(1,1),(2,0)\}
\end{align*}
Consequently, if one assumes that $g$ and $h$ are given by:
\begin{align*}
\begin{cases}
g = \{(0,0),(1,1),(2,1)\}\\\\
h = \{(0,0),(1,1),(2,2)\}
\end{cases}
\end{align*}
we arrive at the following relations
\begin{align*}
g\circ f = \{(0,0),(1,1),(2,0)\} = h\circ f
\end{align*}
but we know by construction that $g\neq h$ since $g(2)\neq h(2)$.
So we can conclude the proposed claim is false.
Hopefully this helps !
Answer: Let $A,B,C = \mathbb{R}$, let $f$ be the constant function $f(x) = 2$ for all $x \in \mathbb{R}$. Take $g(x) = x$, $h(x) = 4 - x$.
Then $g(f(x)) = 2 = h(f(x))$ for all $x$, but $g \not= h$.


Implementation of Plotly on pandas dataframe from pyspark transformation

Question: I'd like to produce plotly plots using pandas dataframes. I am struggling on this topic.
Now, I have this:
           AGE_GROUP                       shop_id         count_of_member
0                 10                             1                      40
1                 10                            12                   57615
2                 20                             1                     186
4                 30                             1                     175
5                 30                            12                  322458
6                 40                             1                     171
7                 40                            12                  313758
8                 50                             1                     158
10                60                             1                     168

Some shop might not have a record. As an example, plotly will need x=[1,2,3], y=[4,5,6]. If my input is x=[1,2,3] and y=[4,5], then x and y is not the same size and an exception will be raised. I need to add a null value record for the missing shop_id. So, I need this:
           AGE_GROUP                       shop_id         count_of_member
0                 10                             1                      40
1                 10                            12                   57615
2                 20                             1                     186
3                 20                            12                       0
4                 30                             1                     175
5                 30                            12                  322458
6                 40                             1                     171
7                 40                            12                  313758
8                 50                             1                     158
9                 50                            12                       0
10                60                             1                     168
11                60                            12                       0

For each age_group, I need to have 2 shop_id since the unique set of shop_id is 1 and 12
if there are 10 age_group, 20 rows will be shown.
For example:
           AGE_GROUP                       shop_id         count_of_member
1                 10                            12                   57615
2                 20                             1                     186
3                 30                             1                     175
4                 40                             1                     171
5                 40                            12                  313758
6                 50                             1                     158
7                 60                             1                     168

there are 2 unique shop_id: 1 and 12 and 6 different age_group: 10,20,30,40,50,60
in age_group 10: only shop_id 12 is exists but no shop_id 1.
So, I need to have a new record to show the count_of_member of age_group 10 of shop_id 1 is 0.
The finally dataframe i will get should be:
           AGE_GROUP                       shop_id         count_of_member
1                 10                            12                   57615
**1                 10                             1                       0**
2                 20                             1                     186
**2                 20                            12                       0**
3                 30                             1                     175
**3                 30                            12                       0**
4                 40                             1                     171
5                 40                            12                  313758
6                 50                             1                     158
**6                 50                            12                       0**
7                 60                            12                       0
7                 60                             1                     168

** are the new added rows
How can i implement this transformation?
Comment: _Plotly doesn't allow me to do so_ Do what? It isn't clear what your question is, can you explain things further?
Comment: Plotly doesn't allow me to have a different size of array input.
for example: x=[1,2,3], y=[4,5,6]
if x=[1,2,3], y=[4,5], then x and y is not the same size, exception throw
Comment: Any further explanations should be added to your post, not comments. _exception throw_ What exception? _how can i implement this transformation?_ I thought this question was about Plotly?
Comment: The question is about how to add those null value rows.
Comment: Can you explain/describe the algorithm for adding those?
Comment: i add new explanation in the post
Answer:
How can i implement this transformation?

First of all, you don't have to.
When used correctly, plotly has got a wide array of approaches where you can visualize your dataset as it is when your data look like yours in the third sample:
           AGE_GROUP                       shop_id         count_of_member
1                 10                            12                   57615
2                 20                             1                     186
3                 30                             1                     175
4                 40                             1                     171
5                 40                            12                  313758
6                 50                             1                     158
7                 60                             1                     168

There's no need to apply pandas to get to the structure of the fourth sample. You're not to clear on what you'd like to do with this sample, but I suspect you'd like to show the accumulated count_of_member per age group split by shop_id like this?

You may wonder why the blue bars for shop_id1 isn't showing. But that's just because the size of the numbers are so hugely different. If you replace the miniscule count_of_member for shop_id=1 to something more comparable for those of shop_id=12, you'll get this instead:

Below is a complete code snippet where the altered dataset has been commented out. The dataset used is still the same as in your third data sample.
Complete code:
# imports
import plotly.graph_objects as go
import pandas as pd

data = {'AGE_GROUP': {0: 10, 1: 10, 2: 20, 4: 30, 5: 30, 6: 40, 7: 40, 8: 50, 10: 60},
                     'shop_id': {0: 1, 1: 12, 2: 1, 4: 1, 5: 12, 6: 1, 7: 12, 8: 1, 10: 1},
                     'count_of_member': {0: 40,
                      1: 57615,
                      2: 186,
                      4: 175,
                      5: 322458,
                      6: 171,
                      7: 313758,
                      8: 158,
                      10: 168}}

## Optional dataset
# data = {'AGE_GROUP': {0: 10, 1: 10, 2: 20, 4: 30, 5: 30, 6: 40, 7: 40, 8: 50, 10: 60},
#                      'shop_id': {0: 1, 1: 12, 2: 1, 4: 1, 5: 12, 6: 1, 7: 12, 8: 1, 10: 1},
#                      'count_of_member': {0: 40,
#                       1: 57615,
#                       2: 186000,
#                       4: 175000,
#                       5: 322458,
#                       6: 171000,
#                       7: 313758,
#                       8: 158000,
#                       10: 168000}}

# # Create DataFrame
df = pd.DataFrame(data)

# Manage shop_id
shops = df['shop_id'].unique()

# set up plotly figure
fig = go.Figure()

# add one trace per NAR type and show counts per hospital
for shop in shops:

    # subset dataframe by shop_id
    df_ply=df[df['shop_id']==shop]

    # add trace
    fig.add_trace(go.Bar(x=df_ply['AGE_GROUP'], y=df_ply['count_of_member'], name='shop_id'+str(shop)))

fig.show()

EDIT:
If you for some reason still need to structure your data as in your fourth sample, I suggest that you raise another question and specifically tag it with [pandas] and [python] only, and exclusively focus on the data transformation part of the question.
Comment: sure, i will try that
Comment: @VincentYau Happy to help! I hope this is what you were looking for. And I hope you don't mind, but I'd just like to point out that you've recently gathered enough reputation points to earn the right to award posts with your up-votes. I assure you they will be highly appreciated. The forum even encourages the use of your votes through a couple of badges. Voting on 600 posts (and 25% or more of total votes are on questions) will even earn you a [gold badge](https://stackoverflow.com/help/badges)


Generating function. Problem with understanding.

Question: Let $F_0, F_1, F_2, ...$ be the Fibonacci numbers and let $f$ be the function defined
$$f(x) = \frac{x}{1-x(1+x)}$$
Solution:
The function $f$ is called the "generating function of the sequence $F_0, F_1, F_2, ...$
it is a "formal" algebraic expression in the sense that it behaves in a natural algebraic
way but the $x$ never takes a numerical value, the powers of it merely acting as
'place-markers' in the power series$^1$. Bearing that in mind, we see that
$$f(x) = F_0 + F_1x + F_2x^2 + F_3x^3 + ....$$
$$xf(x) =  F_0x + F_1x^2 + F_2x^3 + ....$$
$$x^2f(x) = F_0x^2 + F_1x^3 + ....$$
But we know that $F_2 = F_1 + F_0, F_3 = F_2 + F_1$, etc., and so subtracting the second
and third lines from the first gives us
$f(x)(1 - x(1 +x)) = f(x) - xf(x) - x^2f(x) = **F_0 + (F_1 - F_0)x** = x$
Please understand me it. I highlight what the most confuesed me.

$^1$ So what is x? f(x) is function or not? I'm so confused.
Answer: This is a subtle point. The idea is that when you were manipulating the power series for $f(x)$ you never said anything about whether or not the series converged -- in other words, you were formally manipulating the series. A formal power series is just a power series used without talking about convergence.
To answer your question, $f(x)$ is not a function. In the (paraphrased) words of Herbert Wilf, a formal power series is a "clothesline on which we hang up a sequence of numbers for display". We use $f(x)$ to keep track of the Fibonacci numbers; that's all. In the same vein, you could use the series
$$
g(x) = 0! + 1!\cdot x + 2!\cdot x^2 + \cdots + n!\cdot x^n + \cdots
$$
to keep track of the factorial numbers even though the series converges only for $x=0$.
Comment: " to keep track of the factorial numbers even though the series converges only for x=0" Why is it important to series would be converged?


Como iniciar Owl Carousel depois de 2 segundos?

Question: Eu tenho um slide Owl Carousel, quando o site está carregando as imagens carregam pela metade e o autoplay, já inicia e começa a passar sem as imagens terem carregado totalmente, gostaria de saber como faço para iniciar o autoPlay depois de 2 segundos que a pagina for totalmente carregada.

$('.slider').owlCarousel({
                        items: 1,
                        loop: true,
                        autoplay: true,
                        autoplayTimeout: 6000,
                        autoplayHoverPause: false,
                        margin: 0,
                        stagePadding: 0,
                        smartSpeed: 2000,
                        responsiveClass: true,
                        responsive: {
                            0: {
                                margin: 0,
                                stagePadding: 0
                            },
                            600: {
                                margin: 0,
                                stagePadding: 0
                            },
                            1000: {
                                margin: 0,
                                stagePadding: 0
                            }
                        }
                    });
<link href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.css" rel="stylesheet"/>

Answer: Mude o autoplay para false:
var owl = $('.slider').owlCarousel({
    items: 1,
    loop: true,
    autoplay: false, //AQUI
    autoplayTimeout: 6000,
    autoplayHoverPause: false,
    margin: 0,
    stagePadding: 0,
    smartSpeed: 2000,
    responsiveClass: true,
    responsive: {
        0: {
            margin: 0,
            stagePadding: 0
        },
        600: {
            margin: 0,
            stagePadding: 0
        },
        1000: {
            margin: 0,
            stagePadding: 0
        }
    }
});

E então adicione chame em onload assim:
$(window).load(function () {
     owl.trigger('play.owl.autoplay', [2000]);
});

O [2000] se refere aos 2 segundos que você pediu.
Comment: Me desculpe amigo, não havia inserido o var owl. @Guilherme Nascimento muito obrigado resolveu meu problema!
Comment: Infelizmente não funcionou, teste com o .load antes e depois do meu código, ambas não funcionaram.
Somente carrega depois ele não dá o play.
Comment: @DeveloperWebSistem... adicionou o `var owl`? Aparece algum erro no console?
Comment: Fui conferir aqui, ele da o play somente em uma imagem. Ou seja passa somente a primeira e as outras não passa. Será o que pode ser?
Answer: var $owl = $('.slider).owlCarousel(options);
var autoplayDelay = 2000;

if (autoplayDelay) {
    $owl.trigger('stop.owl.autoplay');
    setTimeout(function() {
        $owl.trigger('play.owl.autoplay');
    }, autoplayDelay);
}


quarter car model matlab code ode45 plotting

Question: I have a quarter car model which is a 2-dof system with damper and spring
with following codes with a diagram;

function dx = ode_2dof(t,x)
m1=500;
c1=1200;
k1=25000;
k2=15000;
m2=50;
dx=zeros(4,1);
dx(1)=x(2)
dx(2)=-(c1/m1)*(x(2)-x(4))-(k1/m1)*(x(1)-x(3))
dx(3)=x(4)
dx(4)=(c1/m2)*(x(2)-x(4))+(k1/m2)*(x(1)-x(3))-k2*x(3)
end

Here, i tried to put an input as a condition of the road. First, i set the step input as a height of 0.01 metre after 0.5 second so i changed the function dx(4) as changing the function file as following;
dx(4)=(c1/m2)*(x(2)-x(4))+(k1/m2)*(x(1)-x(3))-k2*(x(3)-y)

with adding;
if y>0.5
y=0.01
elseif
y=0

between the code dx=zeros(4,1) and dx(1)=x(2).
recalling this function, I could plot the graphs for x1 and x2 (i.e car and tire) displacements as following codes;
[t x] = ode45(@ode_2dof,[0 3],[0.7 0 0.35 0]) %initial position of the car and the tyre
x1_position=x(:,1);
x2_position=x(:,3);
figure
plot(t,x1_position,t,x2_position);
grid on
legend('x1 position','x2 position');

Question 1, i've got a graph as

but this is not the graph I want, how can I get the graph with x1 settling at 0.7 and x2 at 0.35 respectively as the initial condition, not at 0?
Also, I tried to change the x1, k1 and k2 values to see how it affects on the displacements with changing the x1, k1 and k2 values respectively in the function file and saved separately.
function dx = ode_2dof2700(t,x)
c1=2700

function dx = ode_2dof40000(t,x)
k1=40000

function dx = ode_2dof30000(t,x)
k2=30000

function dx = ode_2dofmix(t,x)
c1=2700
k1=40000
k2=30000

Question 2, i tried to plot the graph all x1 and x2 at the same time in different graphs as following;
[t x] = ode45(@ode_2dof,[0 5],[0.7 0 0.35 0])
x1_position=x(:,1);
x2_position=x(:,3);
[t x] = ode45(@ode_2dof2700,[0 5],[0.7 0 0.35 0])
x1_position_2700=x(:,1);
x2_position_2700=x(:,3);
[t x] = ode45(@ode_2dof40000,[0 5],[0.7 0 0.35 0])
x1_position_40000=x(:,1);
x2_position_40000=x(:,3);
[t x] = ode45(@ode_2dof30000,[0 5],[0.7 0 0.35 0])
x1_position_30000=x(:,1);
x2_position_30000=x(:,3);
[t x] = ode45(@ode_2dofmix,[0 5],[0.7 0 0.35 0])
x1_position_mix=x(:,1);
x2_position_mix=x(:,3);

figure
plot(t,x1_position,t,x1_position_2700,t,x1_position_40000,t,x1_position_30000,t,x1_position_mix);
grid on

but i've got an error that the vector array have to be matched. It is actually different as x1_position is 1361x1 and x2_position_2700 is 1041x1 etc. how can i change the code to match the array?
Question 3, if i want to set a sinusoidal input with an amplitude of 0.01 metre, how should i change the input?
Thanks
Comment: About question2: you have to save each `t` with your `x1` & `x2` to match every [t,x1] pairs.Then you could plot them at a same time by calling something like `plot(t,x1_position,t_2700,x1_position_2700,t_40000,x1_position_40000,t_30000,x1_position_30000,t_mix,x1_position_mix);`
Comment: i don't understand that i have to save each t with x1 and x2. I tried to saved the ode files of the each different values and recalling with plot function and i got an error as what i got before. could you tell me more specifically?
Comment: Sorry, my English is quite weak. I mean `[t1 x1] = ode45(...)` , `[t2 x2] = ode45(...)`; then you could plot them by `plot(t1,x1(:,1),t2,x2(:,1))`. Just match every `t` and `x` in your `plot`.
Comment: Now its working! thank you very much
Answer: I believe there is a minor mistake in your equations, you should divide by m everything like here
dudt(1) = u(2);
dudt(2) = -(c2/m2)*(u(2)-u(4))-(k2/m2)*(u(1)-u(3))-9.8;
dudt(3) = u(4);
dudt(4) = -(k1/m1)*(u(3)-y)+(k2/m1)*(u(1)-u(3))-(c1/m1)*(u(4)-yl)+(c2/m1)*(u(2)-u(4))-9.8;

this includes damping in both dofs, for future fellas looking at the same problem get things right!


Hover Menu Issue on Ipad back and forth

Question: I've been pulling my hair out trying to get my CSS hover menu to work properly on iPad. I have tried applying hover classes using javascript with the same result, so it must be in the css. The site also utilizes twitter bootstrap.
What happens currently is that on a tap, the dropdown/link hover state show for a split second, then the previous link dropdown/hover show, then it shows the correct one again and it remains open as it should.
EDIT: In case anyone else has this problem, update bootstrap (primarily the dropdown class) and you should be fine.
Answer: Updated bootstrap, primarily the dropdown class javascript.

Hover Menu Issue on Ipad back and forth


Proving that $D_{10}/ N$ is isomorphic to $D_5$

Question:
Question: $N:=\lbrace 1,x^5 \rbrace$. Show that the quotient group $D_{10}/N$ is isomorphic to $D_5$.

I was looking over the proof for this and quite frankly I didn't really understand it very well. The proof can be found here and it's question 2, the last part of the question. I understand that they're using a theorem that states that if a function is a homomorphism, then it preserves unity, inverses and powers. But I'm not entirely sure how that proves that $D_{10}/N$ is isomorphic to $D_5$. Also, their conclusion doesn't make much sense to me.
What other approaches can we take to prove this claim?
Comment: Note that $D_{10}$ here is the dihedral group of order $20$, and $x$ is an element of order $10$.
Answer: This may be slightly nonrigorous, but we can think of this simply geometrically and recalling that when we mod out by $N$ we are equating objects that differ only by the objects in $N$. Now, going by the comment by @MJD, we are dealing with a regular 20-gon in the plane. The dihedral group is then made of rotations and reflections. The object $x^5$ is a rotation amplified by a factor of 5 or a 5-fold reflection across a fixed axis, i.e. a single reflection, depending on which element we take to be $x$. So we need only care about the rotations. It shouldn't be too hard to convince yourself that the rotations and reflections in this new space are equivalent to rotations and reflections of the 10-gon, and that will let us construct the needed isomorphism


How to select HTML elements that do not have a specific attribute value?

Question: Basically title, my html looks like this:
 10
 20

and I tried using
x = [td.getText() for td in rows[i].findAll('td') and not rows[i].findAll(attrs={"data-stat":"DUMMY"})]

but that did not work obviously. My desired output would only get the text from data-stat="foo" and  data-stat="bar", which would look like:
x=["10","20"]

Answer: Use an css selector with pseudo-class :not() to select your elements:
soup.select('th:not([data-stat="DUMMY"])')

Note: In your question you try to find td while there is only th in your example.
Just in addition concerning your approach with list comprehension - You were close to a solution but could use if-statement:
[th.getText(strip=True) for th in soup.find_all('th') if th.get('data-stat') != 'DUMMY']

Note: In newer code avoid old syntax findAll() instead use find_all() - For more take a minute to check docs
Example
from bs4 import BeautifulSoup
html ='''
 10
 20

'''
soup = BeautifulSoup(html)

[e.get_text(strip=True) for e in soup.select('th:not([data-stat="DUMMY"])')]

Output
['10', '20']

Answer: You can find easily on the documentation
from bs4 import BeautifulSoup

table = """" 10
 20
  	"""
soup = BeautifulSoup(table, "lxml")
value_list = []

value_list.append(soup.find("th", {"data-stat": "foo"}).text.strip())
value_list.append(soup.find("th", {"data-stat": "bar"}).text.strip())
print(value_list)


phpunit mock does not count the function call

Question: I have a unit test where I create a mock object:
 $resetTokenManagerStub = $this->getMockBuilder(ObjectManager::class)->getMock();

I make this a return value of another mock object
 $managerRegistryStub->method('getManagerForClass')->willReturn($resetTokenManagerStub);

I check if it was called exactly one time:
 $resetTokenManagerStub->expects($this->once())->method('persist');

if I put a var_dump just before the call in the actual unit I see that I pass the code there and that the stub is the resetTokenManagerStub, but still the test result is:
There was 1 failure:

1) App\Tests\Service\UserServiceTest::testGeneratePasswordResetToken with data set #0 (Mock_User_a375caf8 Object (...), 'generatedToken')
Expectation failed for method name is equal to 'persist' when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

Why doesn't it count the call? Is it because I used it as a return value of another mock? The object I get when I call getManagerForClass() is the same as the one in the unittest. I did a ar_dump on it and both look the same:

object(Mock_ObjectManager_142d72a2)#26 (4) {
...

object(Mock_ObjectManager_142d72a2)#26 (4) {
...

What am I doing wrong here?
Answer: Once again I was stupid. sorry for this post. This is like the rubber ducky method. I struggle for an hour, and when I submit it to a forum I see what I was doing wrong...
The $resetTokenManagerStub->expects($this->once())->method('persist'); line was being called after the actual function call...


Android: how to detect when items are successfully loaded in ListView?

Question: I am using ListView which gets populated by the use of Adapter.
One of its features is also highlighting position on the list for the user with listView.getChildAt(savedViewPosition).setSelected(true).
At the conformation change, I would like to retaing poisiton of the selected item.
However, while I have tried several options, the best so far was to set a delay with .postDelay() and wait for the listView to load.
With this in mind, I would ask if there is any call that would enable me to wait until the items are loaded/visible and then posting the method immediately?
Answer: This sounds like something that could be accomplished by overriding notifyDataSetChanged() and selecting the item once the data has been loaded. There may be more to it to fit the exact behavior you want but it should be workable.
See the documentation here.
Comment: First of all, thank you for the comment. However, I need this with the configuration change and not when the data are updated so the solution is not that sensible.


prevent angular from triggering filter function and binding function of directive for hidden elements

Question: As far as I know angular doesn't link hidden HTML elements, so I assume when the viewport width is 500px or larger, the first paragraph is not linked (the mydirective link function is not triggered).

{{content | customFilter}}

{{content}}

p {
    display:block;
}

@screen and min-width:500px {
    p:nth-child(1) {
        display:none;
    }
}

However, the filtering function is still triggered as well as binding function for mydirective. Is there any way to prevent angular from triggering filter function and binding function for hidden HTML elements?
The task here for me is to show filtered data for small screens (less than 500px) and unfiltered data for larger screens.
Answer: Instead of using CSS to hide and show elements, use ng-if which will then remove the elements from the DOM and therefore prevent any Angular related magic happening for those elements (Until you want them back again).
Comment: This is an option, but the problem with this approach is that I should in javascript detect viewport size changes which is not a good thing


Maximizing car park usage efficiency

Question: I'm trying to create a predictive model for a closed car park. This model is expected to estimate available parking spaces given date and time.
Brief information:

the car park has a limited capacity
a driver has to own a monthly subscription
we overbook by about 10%
a vehicle identification system exists, giving us an opportunity to use a real-time model
we don't know "anything" about subscribers (no age/gender/location information)
(optional) I only have 3 months of data.

I want to notice that I already know how to build a simple model using e.g. LASSO or SVR, I also have a few ideas to use real-time data.
My biggest problem is: how do I use driver-specific data?
For instance: let's say someone arrives always about 7AM +/- 10 minutes and spends about 8 hours on car park. We might say that this person's spot will most likely be available for the next 8 hours IF it's not taken until 7:10, right?
How do I build a model on top of such data?
The title says: 'maximizing parking usage efficiency'. Let me explain: I'd like to sell parking space to non-subscribers when they are absent (e.g. at night).
Comment: As far as I know, we pay for an alternative parking spot in the neighbourhood and give some discounts.
Comment: How would you deal with a subscriber who arrives to find the carpark already filled?
Answer: This problem seems ideally suited to Bayesian Decision Theory as it is essentially a gambling problem.  It is a case where the differences between Frequentist and Bayesian methods are important.  Bayesian methods have the statistical property that they are coherent, whereas Frequentist methods are not coherent.  A probability is coherent if a bookie, which is what the carpark management is, can state prices for a gamble in such a way that no actor or combination of actors could game the system and cause a sure loss for the bookie.
Indeed, you have a tremendous advantage in that you have three months of customer specific data and you have plenty of modeling power.  Bayesian decision theory, in this case, would not be very far from LASSO.  The likelihood function might change and the prior might change.  Indeed, if they do not, LASSO and Bayesian posterior analysis will provide the same point estimates.  Still, you may not want to use those point estimates.
The critical example in Thomas Bayes' An Essay towards solving a Problem in the Doctrine of Chances has been popular lately and provides a reason to go the extra step outside posterior analysis.  While Bayes example is a square table, essentially a square billiards table denoted ABCD, we will go into a simplified equivalent to see the difference.  Suppose a random number is generated in the open set (0,1) and the value is kept hidden.  The hidden value will be denoted $\theta$.  You and I play a game where a random number is generated and if the newly generated number is less than $\theta$ then I get one point, otherwise, you get one point.  The newly generated numbers are not observed, merely the outcome.  The first person to six points wins the game.
I have five points and you have three points, what is the probability that you will win?  This, of course, could be "what is the probability that a particular space is occupied?"  The standard frequentist estimator is $5/8$ for me and $3/8$ for you.  You have to score three points in a row so your chance is $\frac{3}{8}^3$.  You have roughly 5.27% chance of winning under Frequentist calculations.  The Bayesian calculation is different.  You have to set a prior distribution for possible probabilities for $\theta$.  Since all are equally likely, $\Pr(\theta)\propto{1}$.  The likelihood function, in this case, is $\theta^5(1-\theta)^3$.
This integrates to $$\Pr(\theta=\Theta)=504(1-\theta)^3\theta^5,\forall\theta\in\Theta$$. Leaving a distribution over $\theta$ which is not at all useful if we need a point measurement to place a gamble with, such as a fixed probability of winning.  This is where the Bayesian method and the Frequentist method part calculations.  I want to consider all possible parameters that could result in five wins for me and three wins for you, in proportion to their actual probability of a value being the true value.  Then I want to make a prediction as to what the chances of you winning are, in order to price the gamble.  The Bayesian predictive distribution is: $$\int_{\theta\in\Theta}\mathcal{L}(\text{future wins}|\theta)\pi(\theta|\text{historical wins})\mathrm{d}\theta,$$ where $\mathcal{L}$ is the likelihood function and $\pi$ is the posterior probability.  In this example the solution would be $$\Pr(\text{3 future wins for you})=\int_0^1[1-\theta]^3\times{504}(1-\theta)^5\theta^3\mathrm{d}\theta=.0909.$$
Which is correct?  The Bayesian one is correct.  The difference is that one is $(1-E(p))^3$ and the other is $E[(1-p)^3]$.  You can test this by simulating millions of parameters and keeping those whose outcome is 5:3 and then generating outcomes if you want to test this by Monte Carlo.
I would construct a simple microeconomic model with a person-specific unknown parameter of being present at time $t_i$ and the constraint that the number of parking spaces being used at any point in time $i$ must be less than or equal to the total spaces with some very high probability of certainty.  I would solve the posterior density for each actor and simplify as much as possible.  I would create a weak prior that included outside information such as holiday schedules, guesses as to peak vacation season and so forth since you only have three months of data.  I would prefer a robust but weak model to a strong model given the amount of time that has been observed.  You do not know about the impact of holidays, weekends, vacations, illnesses and business events on parking cycles.
Then I would impose a predictive distribution with a cost function.  It would depend upon the cost of the garage for being wrong and putting someone in another person's spot versus the cost of being wrong and having nobody in a spot.
As to my likelihood, it would probably be some form of logistic type function.
Answer: This isn't much of an answer; more of a  suggestion.
I think your best opportunity to sell a parking space twice comes from the subscribers who come in, stay a long time, leave, then are unlikely to return.
These contrast with the users who come in, stay a while, leave, return, and might do this two or three times a day.
The former users create an opportunity to sell the space again with a low probability that they will return and want their space back. I suggest you focus initially on identifying them individually using the data you have. Bear in mind that even the most regular user will go away for a day occasionally or even two weeks. Users who did this are still regular users if they come in and depart at regular times each day.
First, identify the group of regular users in the first group.
Next, estimate their aggregate occupancy as a group. There might be a calendar pattern to this with some obvious elements, such as day of the week. (You probably can't identify a seasonal pattern yet.) If they regularly leave a given range of spaces empty, 4 to 10 out of 100 users then you can sell some number of those to another user, say 5 would be fairly safe. If you have 1000 spaces you might safely sell a larger number, such as 55, if they regularly leave 40 to 100 empty.
While some descriptive statistics will be useful in deciding how many places to sell a second time, I think some simulation using the numbers you have might also be useful.
This might be particularly useful in deciding at what time of the day to sell another parking place. It might be risky to sell them at 7:30 but quite safe to sell them at 9:30.
You also have the chance to experiment. You can try selling a given number of places and measure how often you have sold too many or how many empty places you have. You could vary the number sold and the time they are sold.
The second group of users seems too variable to give you much confidence that they have supplied you with an empty parking space. They might, in aggregate, give you some measurable number of spaces at specific times and days. I think it makes some sense to estimate them separately. You might not need accurate estimates of the vacant spaces they give you if you use an experimental approach and vary the number of spaces you sell and the times you sell them for a while. As a group they will supply a (highly variable) number of spaces to sell a second time and this is added to the regular supply you estimate that you get from the first group. This will permit you to sell a very few more spaces, experimentally, but you might not know where they are coming from, only that you can safely sell a few more spaces and perhaps later in the day.
Comment: Seems reasonable. I will experiment with these ideas. Thanks for your advice!

Maximizing car park usage efficiency


Which riders in the 2015 Tour de France have proven doping history?

Question: How many, and who, of the 198 riders to start the Tour de France in 2015 have a proven history of doping? I.e. they have been charged and found guilty by WADA/UCI at some point in the past, or have confessed, or been proven to have doped (but time has expired in which charges can be brought etc.)
Answer: Here is a list of the starters (On the right side of this page). The following have proven history of doping:

Alberto Contador
Ryder Hesjedal
Ivan Basso
Alejandro Valverde
Michele Scarponi
Filippo Pozzato
Rui Costa
Damiano Caruso
Daniele Bennati
Giampaolo Caruso

The Dutch public broadcasting station NOS stated on their website (in Dutch) a list of nine riders who used doping in their past. In their list they do not mention Ryder Hesjedal who confessed to have used doping, as he has never faced charges nor did he get a ban.
Daryl Impey (cleared of the doping charges)


Unexplained behavior while using hashmaps

Question: The stripped down program below works well for me but when I move the hashVal declaration (in bold) outside the for loop, my program does not run correctly. Any reasons why I need it to be inside the for loop when inserting in the hashmap? I found this while thinking of potential optimizations after I had gotten my quick and sloppy implementation to work. However it now seems the quick and sloppy implementation works but not what I think the should be the optimized version.
public class X
{
   public static void foo()
   {
      Integer x1 = 0;
      HashMap<Integer, BigInteger[]> map = new HashMap<Integer, BigInteger[]>();
      int hashKey;
      /* **BigInteger[] hashVal  = new BigInteger[2];**  <-----Does not run correctly
      if I keep the hashVal declaration here. (1) */
      for(x1 = 0; x1 <= 1048576; x1++)
      {
        BigInteger bx1 = BigInteger.valueOf(x1.intValue());
        **BigInteger[] hashVal  = new BigInteger[2];** (2)
        BigInteger res;
        /* Do lots and lots of big integer calculations and get a final result in res */
        hashKey = res.hashCode();
        /* Store res and x1 in hashmap */
        hashVal[0] = res;
        hashVal[1] = BigInteger.valueOf(x1.intValue());
        map.put(hashKey, hashVal);
      }
      Integer x0;
      for(x0 = 0; x0 <= 1048576; x0++)
      {
        /* do lots of BigInteger calculations to generate res */
        hashKey = res.hashCode();
        **bigNum = map.get(hashKey); <--------------Never returns a match if (1) above is enabled instead of (2) !**
    }
}

}
Answer: ...because when hashVal is outside the loop, it only gets created once and therefore inside the loop you continually push the same BigInteger[] into the map.  In other words, every item in the map ends up being a reference to the same BigInteger[].  That means whatever values you put in BigInteger[] during the last time through the loop will be what each reference in the map sees.
When you create a new BigInteger[] inside the loop, then each time through the loop hashVal is a reference to a different BigInteger[].
Comment: Thanks a lot. So how can I optimize this so that I do not have to create new BigInteger[] in the loop each time? In C I do not have this problem right?
Comment: @user2399453, you can't.  You must create a new `BigInteger[]` on each pass, otherwise you will be overwriting the previous values.  The difference between the Java version and the C/C++ version is in Java your calling function creates the new array on each pass and in the C/C++ version the `put` function or `[]` operator copies the array, but the result is similar - one array is created for each pass.
Comment: So in Java, I cannot create an array once (using new BigInteger[2]) and keep assigning different values to index 0 and 1 from then on? Is the new operator like malloc? In Java this is ok I suppose because of garbage collection..
Comment: @user2399453: We do not see your "C" code so we do not know what you are doing. There is no built-in "hashmap" in C and in both C and C++, ordinary "arrays" cannot be assigned or put into collections. If you are using "vector" in C++, then that would be another story because assigning a vector copies it.
Comment: Thanks, actually I am not using C or C++. So is new equivalent to malloc? What I meant was in C I can do this:  int a[2]; a[0] =x; a[1] = y; etc repeatedly and it assigns the values correctly. Can I do something equivalent on Java for an array of BigInteger so that I don't have to do a new each time in the loop? Anyways I found some other big optimizations in my code that cut execution time by a factor of 10 so I am actually in good shape.
Comment: Java's 'new' is similar to 'malloc' in that it creates a place in memory to store some data. But java has a garbage collector to take care of releasing the memory.  Java's 'new' also calls a constructor.  Your C example is exactly what happens in Java too.  Your questions are equivalent to asking, "I want to create an array containing the numbers 1-10, but I want to optimize my code so that I only store the integer 1 in the array."
Comment: As Madhu pointed out, you don't have to repeatedly declare your variable hashval inside the loop, but you must call new every time through the loop and assign the result to the hashval variable.
Comment: In other words, instead of this: for(...){int x = i+10;}, you can write: int x; for(...){x = i+10};
Answer: that's because, (2) is DECLARED and INITIALIZED inside the loop. So, no matter how many iterations go over, hashVal will always contain values from the last iteration. My suggestion would be to declare hashVal outside the loop and use it inside the loop. The new code will look as shown below.
public class X
{
   public static void foo()
   {
      Integer x1 = 0;
      HashMap<Integer, BigInteger[]> map = new HashMap<Integer, BigInteger[]>();
      int hashKey;
      BigInteger[] hashVal  = null; //changed here
      /* if I keep the hashVal declaration here. (1) */
      for(x1 = 0; x1 <= 1048576; x1++)
      {
        BigInteger bx1 = BigInteger.valueOf(x1.intValue());
        hashVal  = new BigInteger[2]; //changed here
        BigInteger res;
        /* Do lots and lots of big integer calculations and get a final result in res */
        hashKey = res.hashCode();
        /* Store res and x1 in hashmap */
        hashVal[0] = res;
        hashVal[1] = BigInteger.valueOf(x1.intValue());
        map.put(hashKey, hashVal);
      }
      Integer x0;
      for(x0 = 0; x0 <= 1048576; x0++)
      {
        /* do lots of BigInteger calculations to generate res */
        hashKey = res.hashCode();
       bigNum = map.get(hashKey);
    }
}

My changes have been commented in the code as 'changed here'.
Do let me know if this approach solved your problem.
Thanks,
Madhu.
Answer:
What I meant was in C I can do this:

int a[2]; a[0] =x; a[1] = y;

etc repeatedly and it assigns the values correctly.

The same thing that happens in your Java program also happens in C:
int main()
{
    int numbers[2];
    int* array_of_int_pointers[2];

    for (int i=0; i<2; ++i) {
        numbers[0] = i * 10;
        numbers[1] = i * 20;

        printf("%d : %d \n", numbers[0], numbers[1]);

        array_of_int_pointers[i] = numbers;
    }

    int* first_array = array_of_int_pointers[0];
    int* second_array = array_of_int_pointers[1];

    printf("%d \n", first_array[1] );

    return 0;
}

--output:--
0 : 0
10 : 20
20

Your questions asks why the last line of the output is not 0.


Showing the description for the term identified by the argument in the Taxonomy Term view

Question: I have a view that is a clone of the Taxonomy Terms default view, it has the depth modifier turned on.  I would like to provide the description field for the taxonomy that has been loaded in the header if it exists.  I'm using this with pathauto, so while the actual url may be something like /pub/by/geo-area/ethiopia, views gets the tid (lets say 3046) as the argument.
How can I then put the description field from that taxonomy term into the header of the view?  I tried creating a relationship for the taxonomy term content, but since I don't know at the time of creating the view what vocabulary the term will be from, and because it is possible that there will be multiple terms for that vocabulary attached to some of the nodes, that doesn't seem to be workable.
I considered an attachment, but I'm not sure how I could pull that off either.  Can I do this without an extra module?
Comment: `but since I don't know at the time of creating the view what vocabulary the term will be from` when you add the relationship, just check all of them :-)
Comment: Yes but I don't want the description for all terms associated with the node via any field at all, I want the description for the term coming in via the contextual filter argument.
Answer:
I want the description for the term coming in via the contextual
  filter argument

Ok then,
1) Create a new view

Show: Taxonomy Terms.
☑ Create a Block

Display format: Unformated list of Fields

2) Save and Continue.

Add the Contextual Filter.
Add the description field.

3) Go back to your other view and attach view to header.
Comment: Oh ok, I knew you could attach displays I don't think I knew you could attach separate views. That'll be great if it works. I won't be able to check it for a bit but I'll look as soon as I can. Thanks!
Comment: @UltraBob, yes, attaching separate views is allowed, no prob.


Is there a way to allow specific permissions to a non-root user?

Question: I have a program that, at some point, create/destroys tun/tap virtual adapters.
Obviously, for these specific operations this program requires root privileges.
According to the program specifications, root privileges are dropped as soon as they are no longer needed (I assume after the tap adapter was created).
However, I'd like to secure this even more and to run it as non-root in the first place.
Is there a way of allowing a specific user to just create and destroy tun/tap adapters and leave out all other specific permissions to their default ?
Answer: Look into the sudo mechanism. man sudo and man sudoers.
Comment: Doesn't `sudo` changes the effective user of the command being run ? Ideally, I'd like some of "my" developers to be allowed to create tun/tap adapters without having root access. Using sudo in their case wouldn't work because they can't install the software properly on the system (and I don't want them to) nor can they set `LD_LIBRARY_PATH` within `sudo`.
Comment: You can allow sudo access to very specific commands, not only a general purpose shell. If you write a script that handles everything you need to create/destroy your `tun/tap` devices and grant `sudo` access to only this script, users can only do as root what this script does.
Comment: Now I feel dumb for not having thought of using a script for that... Obviously, if I set the LD_LIBRARY_PATH and the PATH inside the script, users can call it, even as `sudo`. Thanks.


AWS Route 53 and Certificate manager

Question: Because of the confidentiality of the client I can not reveal actual domains. So please bear with me.

There is a domain called abc.com already registered outside of AWS.
Now I have created a Public Hosted Zone on AWS called xyz.abc.com. It created the list of few ns servers
I have created a AWS SSL certificate for domain *.xyz.abc.com
I have added this certificate to classic internet facing ELB
Now I created a type A alias record set in R53 called bbd.xyz.abc.com pointing to a ELB having SSL certificate ( generated by AWS for domain *.xyz.abc.com)

When I am accessing https://bbd.xyz.abc.com - its not able to resolve but when I am directly giving ELB DNS name it works fine.
My Question is : It is not working because ns (name servers) servers are not added to domain abc.com as abc.com is registered outside of AWS.
Please help
Comment: Your SSL certificate has nothing to do with your problem and muddles the question.
Comment: It's also unclear whether you are using Route 53 here by choice or because you believe it's required.  It is not required.  It's great, but not required.
Answer: You must register the Route 53 name servers with your domain registrar. If you do not, then when your browser attempts to resolve your domain name, the DNS system does not know how to get to your Route 53 hosted zone.
The process to do this varies from registrar to registrar. So you'll have to dig into their documentation.
After you've changed the configuration, you may need to wait up to 48 hours for the changes to propagate. Old "bad" resolutions may be cached in various places, so you may need to wait for those to clear.
Answer: You're going to need to delegate management of xyz.abc.com to Route53's nameservers. This is accomplished by adding the four Route53 nameservers as NS records for xyz.abc.com in the existing abc.com DNS.

AWS Route 53 and Certificate manager


Drupal Theming 'Add Content' Page

Question: Is there any module that can help me theming the "add content" page?
I'm also looking for a way to allow the use of the "add content" menu only to the users who paid.
When I talk about "add content" page, I'm actually talking about the template used when creating for example a new article page.
I don't want to give access to other users to the following fields, and basically change the whole look of that page.

Menu settings
Revision information
URL path settings
Comment settings
Authoring information
Publishing options
Comment: What do you mean by theme the "create content" ? The admin page ?
Comment: i mean i want to allow people to add content on my webpage in form of adds, but add content page is kinda complicate for a user to add it's own information on my ads page, hope this helps
Comment: Which version of Drupal you are using ?
Comment: i'm using drupal 7.7
Answer: I found and article explaining how to theme the node form here (http://batayneh.me/post/theming-node-forms-drupal-7). To solve the other part of your question - Only people who pay can use the "create content" you can create a new role and specify that only users with the new role can create content.
Comment: I'm pretty new to creating modules, i was looking for some already made, that guide would be useful for someone with more experience
Comment: link is down please re-check

Drupal Theming 'Add Content' Page


Winbind not enumerating users and groups of trusted domain

Question: I'm using Samba 4.1.6-Ubuntu in Ubuntu 14.04, for authenticating users from two domains with a one-way cross-forest trust between them. Samba machine is joined to DOMAINA, while DOMAINB is the trusted domain. My aim is to allow users from DOMAINA and DOMAINB to get authenticated in Samba machine.
If I run "wbinfo -u" or "wbinfo -g", only users and groups from DOMAINA get enumerated.
Thus, when I run "getent passwd", only local users and DOMAINA users get listed, and the same with "gentent group".
However, if I run "getent passwd DOMAINB+username", this entry appears:
DOMAINB+username:*:51276:50513::/home/username:/bin/bash

If I run "getent group DOMAINB+groupname", this entry appears:
DOMAINB+groupname:x:60860:

As you can see, member of DOMAINB+groupname (DOMAINB+username) doesn't appear.
Additional information, if it helps:
wbinfo -m
    BUILTIN
    COMPUTERNAME
    DOMAINA
    DOMAINB
wbinfo -i DOMAINB+username
DOMAINB+username:*:51276:50513::/home/username:/bin/bash

wbinfo --group-info=DOMAINB+groupname
DOMAINB+groupname:x:60860:

Here's a excerpt of my smb.conf:
security = ADS
domain master = no

idmap config * : backend        = tdb
idmap config * : range          = 1000000 - 1999999

idmap config DOMAINA : backend      = rid
idmap config DOMAINA : range        = 10000 - 49999

idmap config DOMAINB : backend      = rid
idmap config DOMAINB : range        = 50000 - 99999

allow trusted domains = yes
winbind trusted domains only = no
winbind use default domain = yes
map untrusted to domain = yes

template shell = /bin/bash
template homedir = /home/%U
winbind enum groups = yes
winbind nested groups = no
winbind expand groups = 2
winbind enum users = yes
winbind refresh tickets = yes
winbind separator = +
client use spnego = yes

Any help would be gratefully appreciated. Thanks!
Answer: We have the same issue in here. Looking forward for the replies to others who have solutions.
Thanks!