What is the Poisson binomial probability, for one flip of one fair coin and two unfair coins with probability-of-heads $p_u$, of flipping $r$ heads?

Question: The binomial probability, for one flip of $n$ unfair coins with probability-of-heads $p_u$, of flipping $r$ heads
$$B(n, r, p) = C(n, r) \ p^r \ (q = 1 - p)^{n - r}$$
Answer:
Probability of having $0$ heads

The probability of having $0$ heads is $(q = 1 - p)^{2}*0.5$, since you have twice tail with a probability of $1-p$, and once tail with a probability of $0.5$.This quantity is equal to: $(1+p^2-2p)*0.5=0.5+0.5p^2-p$.

Probability of having $3$ heads

The probability of having $3$ heads is $p^{2}*0.5$, since you have twice head with a probability of $p$, and once head with a probability of $0.5$.

Probability of having $1$ head

The probabilities of having $1$ and $2$ tails are less straightforward.
There are two ways in which you can have $1$ head: either from the fair coin, or from the unfair one.
The probability in the former case is: $(q = 1 - p)^{2}*0.5$, since you have two tails that had a probability of $1-p$, and one head that had a probability of $0.5$. The probability in the latter case is: $(q = 1 - p)*p*2*0.5=(q = 1 - p)*p $, since you have two ways how you can have one head and one tail from the unfair coins, and the probability of tail from the fair coin is $0.5$. The probability is thus given by the sum, that is: $(q = 1 - p)^{2}*0.5+(q = 1 - p)*p =(1 - p)*(0.5-0.5p+p)=(1-p)*(0.5+0.5p)=(1-p)*0.5*(1+p)$. This quantity is equal to: $(1-p^2)*0.5=0.5-0.5p^2$.

Probability of having $2$ heads

There are two ways in which you can have 2 heads: either both from the unfair coins, or one from the fair coin and one from the unfair one.
The probability in the former case is: $p^{2}*0.5$, since you have two heads that had a probability of $p$, and one tail that had a probability of $0.5$. The probability in the latter case is the same as above, since you have again one head and one tail from the unfair coins, and the probability of head from the fair coin is equal to the one of head, that is $0.5$. The probability is thus given by the sum, that is: : $p^{2}*0.5+(q = 1 - p)*p=p*(0.5p+1-p)=p*(1-0.5p)$.This quantity is equal to: $p-0.5p^2$.

Checking the sum of probabilities

To check that the calculations are correct: the sum of the 4 probabilities is $0.5+0.5p^2-p+0.5p^{2}+0.5-0.5p^2+p-0.5p^2=0.5+0.5=1$.

General formula

Suppose you have $n_F$ fair tosses with probability of head $p$ and $n_U$ unfair ones. Then your formula becomes: $$B(n_U, n_F, r, p) = \sum_{j=max(0,r-n_F)}^{min(r,n_U)}C(n_U, j) \ p^j \ (q = 1 - p)^{n_U - j}*C(n_F, r-j)0.5^{r-j}*0.5^{n_F-(r-j)}$$=$$ \sum_{j=max(0,r-n_F)}^{min(r,n_U)}C(n_U, j) \ p^j \ (q = 1 - p)^{n_U - j}*C(n_F, r-j)*0.5^{n_F}$$


How do I tweak an image field markup?

Question: I have an image field that is set to link to content. Drupal makes this markup:

Now I need to tweak the markup and add some styling, for example:

I want to add the inline CSS in this way because the page is for emailing.
What would be the best way to do this? I have tried:

Putting the markup into field--myfield.tpl.php and inserting variables, but the $items array doesn't give me clean image file or target URLs.
Using the Custom Formatters module, but it gives me AJAX errors for some reason and not sure it would do the job anyway.
I could use a preprocess function in template.php, but I am hot sure how.
Answer: For link, it's easy to provide in field--myfield.tpl.php:
$items[0]['#path']['options']['attributes'] = array('style'=>'border-style: none !important;');

But image doesn't have this, so you can miss upper code and rewrite formatter in template.php (add attributes there).
/**
 * Returns HTML for an image field formatter.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
 *   - path: An array containing the link 'path' and link 'options'.
 *
 * @ingroup themeable
 */
function YOURTHEMENAME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
    'alt' => $item['alt'],
  );
  // Do not output an empty 'title' attribute.
  if (drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image); // Here you should add attribute, check that it's your field.
  }
  else {
    $output = theme('image', $image);
  }

  if (!empty($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = $variables['path']['options'];
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);  // Here you should add attribute, check that it's your field. Or just take upper code.
  }

  return $output;
}

How do I tweak an image field markup?


Sort Array by amount of matches and put best fit first php

Question: I create a tag based search and want to sort the search result according to the relevance. The best fit and the number of tags are relevant. Imagine this is the search query:
$search = ['A', 'B'];

and this the result:
$result = [
  [
    'id' => 3011,
    'tags' => ['A', 'B', 'C']
  ],
  [
    'id' => 10798,
    'tags' => ['A','C','D','E']
  ],
  [
    'id' => 92,
    'tags' => ['A']
  ],
  [
    'id' => 4237,
    'tags' => ['A', 'B']
  ]
];

I want to reorganize the whole thing as follows:
$sortResult = [
  [
    'id' => 4237,
    'tags' => ['A', 'B'] // At first place because has 2 values and the search 2, difference 0 and matched good to search
  ],
  [
    'id' => 3011,
    'tags' => ['A', 'B', 'C'] // At second place because has 3 values and the search 2, difference 1 and matched good to search
  ],
  [
    'id' => 92,
    'tags' => ['A'] // At third place because has 1 value and the search 2, difference 1
  ],
  [
    'id' => 10798,
    'tags' => ['A','C','D','E'] // Down here because has 4 values and the search 2, difference 2
  ]
];

Answer: Not sure if this works in all cases but it gives the desired result for your current data:
<?php
$search = ['A', 'B'];

$result = [
[
    'id' => 3011,
    'tags' => ['A', 'B', 'C'],
],
[
    'id' => 10798,
    'tags' => ['A', 'C', 'D', 'E'],
],
[
    'id' => 92,
    'tags' => ['A'],
],
[
    'id' => 4237,
    'tags' => ['A', 'B'],
],
];

usort($result, function ($a, $b) use ($search) {
    $simA = count(array_intersect($a['tags'], $search));
    $simB = count(array_intersect($b['tags'], $search));
    $diffA = count(array_diff($a['tags'], $search));
    $diffB = count(array_diff($b['tags'], $search));
    $absA = abs(count($a['tags']) - count($search));
    $absB = abs(count($b['tags']) - count($search));

    $score = 0;

    $score += $simB - $simA;
    $score += $diffA - $diffB;
    $score += $absA - $absB;

    return $score;
});

echo '
';
print_r($result);
echo '
';

http://phpio.net/s/7yhb
Comment: Wow, it works fine! I thank you. Can you or anyone describe to me what the snippet does?
Comment: Fantastic solution, I was trying to invent a usort myself but gave up, kept getting stuck on the 2 search and 3 vs 1 found.


Redrawing custom marker in leaflet

Question: I have created a custom marker and added it in draw control toolbar like this :
L.Draw.myMarker = L.Draw.Marker.extend({
    initialize : function(map, options) {
        this.type = 'myMarker';
        L.Draw.Feature.prototype.initialize.call(this, map, options);
    }
});

Now I can draw this marker on my map from my draw control toolbar.
Requirements :
Further I need to save the details of all myMarker in database (latlong ,options etc). Later I need to redraw the same markers by fetching the details from DB and then displaying them on map.
Problem :
I only found one solution to re-create marker that is:
//Step 1. Extending marker with Marker class
L.myMarker = L.Marker.extend({});
//Step 2. Recreating marker with the persisted data
L.myMarker([lat, long], {}).addTo(map);

But I want to create instance of L.Draw.myMarker that I drawn previously by toolbar.
So I need something like this L.Draw.myMarker([lat, long], {}).addTo(map);
Comment: Do you really need custom marker functionality, or just a custom icon for markers?
Comment: I am creating custom markers with different types. So I need all functionality to create popup on markers and everything.  I can create markers and save their postions and details lat lng in db but I can't redraw them on map load (from db) because of the above given problem.
Comment: Different types meaning what? I'm asking because I think you are creating extra complexity where you only need custom `L.icon` functionality supported by both Leaflet.Draw and Leaflet by itself..
Comment: I created two type of markers , so that I can get two markers in draw control bar of leaflet. Now I can click on the draw toolbar and draw my custom created markers (with custom icon).  Once drawn ,I saved their details in DB. Now I want to recreate them on map load. For this I need to do something like this  :   L.Draw.myMarker([lat, long], {}).addTo(map);     . So my question in simple term is :   I draw a marker using draw toolbar and saved their latlongs in db. Now how to redraw them on map load (Without mannual draw)? How to create a marker behind the scene and place it on map?
Answer: Given your circumstances, I think you are going to have to duplicate some of your custom marker logic in something that extends from L.Marker to be able to use it outside of the Leaflet.draw context...because L.Draw.Marker extends from L.Draw.Feature(https://github.com/Leaflet/Leaflet.draw/blob/master/src/draw/handler/Draw.Marker.js#L1), while Leafet's Marker extends from L.Layer(https://github.com/Leaflet/Leaflet/blob/master/src/layer/marker/Marker.js#L5)..So that's not exactly a clear inheritance tree to be overriding things with between those two.
Comment: So is there any alternative available ?? Or the only alternative is that I provided above in solution section ? Kindly suggest. Thanks in advance :)
Comment: I don't really see an alternative. If Leaflet.Draw had options for multiple buttons for the same base 'type'(but different class) of feature, then things might be different.

Redrawing custom marker in leaflet


Slap and strum technique question

Question: I am trying to learn Bella Ciao arranged by Rodrigo Yukio. How do you play when a part requires you play slap and strum at the same time? (See the image below) Do you use:

only the index finger?
middle+ring?
index+middle+ring?

From the video it seems like Rodrigo is using the third alternative, but I might be wrong. (Video Time: 0:08)

There is also this part where I can see that he is using only his middle+ring finger only? (Video Time: 0:14):

I have seen some lessons on this topic where some people slap and strum with index and some other suggest ring+middle? Is there any situation where one is better than the other?
video link:
Answer: I use to strum  with all fingers right before slapping:  It's the same downbeat (just strumming the strings by stretching the fingers right before stopping with the flat hand - all 3 of your variants are possible).

Slap and strum technique question


Is there an easier/analogous explanation of geometric mean, similar to that of arithmetic mean?

Question: My simple understanding of arithmetic mean is that the arithmetic mean represents a "central point" (central tendency) where all others numbers converge as the accumulative linear distance from the left equals the accumulative linear distance from the right.
While I know (memorize) the definition of geometric mean, I cannot "interpret/visualize" it (maybe I should not?) in a way analogous to that of the arithmetic mean. I suspect that it may have to do with the fundamental concept of "root", which I fail to grasp, (I did try to read up on the concept of root but have yet found anything beyond its definition and application) but still I cannot find a satisfying answer how taking an nth root would yield a "mean" that reasonably represents the group.
Is there an easier way to "understand" geometric mean? (I tried to look for a similar question in this forum but have not found one so far).
Comment: $$
\begin{align}
A & = \big( \text{arithmetic mean of } a_1,\ldots,a_n\big) \\ {} \\
& \underbrace{A+\cdots+A}_\text{$n$ terms}{} = a_1+\cdots+a_n \\{} \\
B & = \big( \text{geometric mean of } a_1,\ldots,a_n \big) \\ {} \\
& \underbrace{A\times\cdots\times A}_\text{$n$ factors} {} = a_1\times\cdots\times a_n
\end{align}
$$
Comment: If you define the "average" growth rate $\ \rho\ $ of some quantity achieved by a sequence $\ \rho_1,\rho_2,\dots,\rho_n\ $ of growth rates occurring in each successive year over a period of $\ n\ $ years to be that constant rate groth rate that will achieve the same total growth over the given period, then $\ 1+\rho\ $ is the geometric mean of $\ 1+\rho_1,1+\rho_2,\dots,1+\rho_n\ $.
Comment: @achillehui : Why do you say "scaling + translation" instead of just "scaling"?
Answer: Ever since I was in about eighth grade I have assumed the reason it's called "geometric" is that it's about things having the same shape, but I've never heard anyone other than myself say so.
$$
\begin{array}{l}
\overbrace{\underline{\quad\quad\quad\quad\quad\quad\quad\quad\quad}}^\text{The length of this is 9.} \\
\underbrace{\underline{\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}\vphantom{\sum_{\displaystyle\bigotimes}}}_\text{The length of this is 12.} \\[12pt]
\overbrace{\underline{\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}}^\text{The length of this is 12.} \\
\underbrace{\underline{\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}\vphantom{\sum_{\displaystyle\bigotimes}}}_\text{The length of this is 16.}
\end{array}
$$
In the first pair of lines, the second line exceeds the first in length by an amount that is one-third the length of the first.
In the second pair of lines, the second line exceeds the first in length by an amount that is one-third the length of the first.
Thus both pairs of lines have the same shape.
So $12$ is the geometric mean of $9$ and $16.$
See also my comment under the question. If a group of people in a room take all their money out of their pockets and divide it equally among them, then the amount that each gets is the arithmetic mean of the amounts they had before that.
Answer: I think of the geometric mean as a log-scale version of the arithmetic mean. That requires a little explanation.
The arithmetic mean of $x_1, \ldots, x_n$ is $\mathrm{AM}(x) = \frac{x_1 + \cdots + x_n}{n}$. Set $y_i = b^{x_i}$ for a fixed base $b>1$. Then the geometric mean of $y_1, \ldots, y_n$ is
\begin{align*}
\mathrm{GM}(y) &= (y_1 \cdots y_n)^{1/n} = (b^{x_1 + \cdots + x_n})^{1/n} = b^\left(\frac{x_1 + \cdots + x_n}{n}\right) \\
&= b^{\mathrm{AM}(x)}.
\end{align*}
As an example, suppose we had 3 bank accounts with $y=\$100, \$1000, \$10000$ in them. The arithmetic mean is basically only going to pick up the \$10000 amount and will be basically $\mathrm{AM}(y) \approx \$10000/3$. However, the geometric mean effectively thinks of these as $\$10^2, \$10^3, \$10^4$ where $x=2, 3, 4$ with $\mathrm{AM}(x) = 3$, so the geometric mean of the amounts in the bank is $\mathrm{GM}(y) = \$10^3 = \$1000$.
Lots of data is really of the form $b^x$. For instance, this is basically the insight behind Benford's law. Consequently the geometric mean is sometimes more appropriate than the arithmetic mean.
Answer: As Jordan Ellenberg nicely shows in his book Shape, the geometric mean of $a_1$ and $a_2$ is the length of the side of a square having the same area as a rectangle with side $a_1$ and $a_2$. This generalizes to the geometric mean of more numbers as well. For more numbers/higher dimensions, the geometric mean is the length of the side of the regular shape having the same multi-dimensional volume.


Find the last four digits of $2^{27653 }- 1$

Question: Find the last four digits of $2^{ 27653} - 1. This is one of the questions in a mathematics contest.
I have tried to find the sequence but I found it impossible.
(I have used excel to do this and the sequence repeat after 2 ^ 15XX - 1)
Comment: You should find the remainder modulo $5^4$. The remainder modulo $2^4$ should be easier :-). Use for example the techniques explained [here](https://math.stackexchange.com/q/81228/11619) for the first task. Then apply the Chinese Remainder Theorem. See other threads linked to that mother thread for VERY similar questions.
Answer: Using sage we get instantly
<code>sage: R = Zmod(10000)
sage: R(2)^27653 - 1
2991
</code>
Using pari/gp also ...
<code>? Mod(2,10000)^27653 - 1
%11 = Mod(2991, 10000)
</code>
The human solution would be to compute the result modulo $2^4$ and modulo $5^4$. Of course, the number $$N=2^{27653}$$ is congruent to $0$ modulo $2^4$. Let us compute it modulo $5^4$. The Euler indicator of this number is $\phi(5^4)=5^4\left(1-\frac 15\right)=4\cdot 5^3=500$. So
$$N=2^{27653}\equiv 2^{27653\mod 500}=2^{153}\mod 5^4\ .$$
Now we can compute $2^{153}$ explicitly, it is $11417981541647679048466287755595961091061972992$, or write it like $(2^{51})^3$ and compute the third power of $(2^{51}\mod 5^4)=(2251799813685248\mod 5^4)=(5248\mod 5^4)=(248\mod 5^4)$. In each case we get the wanted $492$. Now we search among the numbers $492+5^4k$ with $0\le k< 2^4$ the one which fulfills the condition modulo $2^4$. The number divisible by $16$ among them is $2992$. We get the same answer as a human ...
Comment: Sorry, the answer was quickly typed, but the connection did not work, not it is submitted. Shall i remove it?!


Highlight grid row on edit

Question: I am on ExtJs3.2.
There is a gridpanel with a column having a textField as an editor.
On change of value in the textfield - i need the corresponding row to be highlighted.
How do I get the 'owning' row index of the text field?
<code> columns: [
      ...........
            {header: 'Revenues',dataIndex: 'percentage',
              editor: new Ext.form.TextField({
                     listeners: {
                        'change' : function (field, newValue, oldValue) {
                          if(oldValue!=newValue){
                         .......
                        //How do I get the row index?
                         Ext.fly(grid.getView().getRow(row)).addClass('yellow-row');
                        }
                    }
            }
</code>
Is there any other way to achieve this?
Answer: Could you please try below?
<code>var grid = Ext.grid.GridPanel({
    store: yourStore,
    id: 'myGrid',
    colModel: new Ext.grid.ColumnModel({
        defaults: {
            width: 120,
            sortable: true
        },
        columns: [
            {id: 'Company', header: 'Company', width: 120, sortable: true, dataIndex: 'company'},
            {header: 'Change', dataIndex: 'change'},
            {
                header: 'Revenue',
                dataIndex: 'percentage',
                editor: new Ext.form.TextField({
                    listeners: {
                        'change': function(field, newValue, oldValue) {
                            if (oldValue != newValue) {
                                var sel = Ext.getCmp('myGrid').getSelectionModel().getSelected();
                                // if you select more than one record use getSelections instead of getSelected
                                console.log(sel);
                            }
                        }
                    }
                })
            }
        ]
    }),
    sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
    width: 500,
    height: 300,
    frame: true,
    title: 'My Grid'
});
</code>
Comment: that wouldn't work  - because in case the user selects another row after filling the field - the selected row changes.
Comment: I didn't understand. If you get selected row index, why don't you set background color?
Comment: if I fill the field Revenue on row 1;and then click on row 2 with the mouse - instead of pressing enter or tab,the getSelected() return row2 instead of row1.
Comment: Then, try to catch deselected row by `rowdeselect` event.
Comment: Is there such an event on the gridpanel?I cant seem to find an example of how to define a listener on that.I am on ExtJs3.2
Comment: Dear friend, you should look `RowSelectionModel`. When you want to get selected rows, always look selection model.

Highlight grid row on edit


How to make a braintree subscription with dropin UI and 3DS2?

Question: I want to create a subscription page using drop-in UI.
Client Side:
I am done with the client-side. I have Drop-in UI implemented and I obtain a payment nonce.
Server Side:
On the server side I receive the nonce from the client but I can't create a subscription with that nonce(I received an unvaulted payment method). I need to create a payment method with this nonce. After this the nonce is consumed, so I need another nonce with 3DS secure (for the subscription creation).
From their documentation I understand that I need to create a second nonce (payment method nonce) and send again to the client for verification. I didn't found any sample of this verification...
The question is how I obtain a second nonce that I need for subscription creation?
Answer: Just checked the documentation for 3DS + subscriptions, I can see where there's confusion. You need to switch to Hosted Fields, not Drop-In.
This is because you need to do the following workflow, which Drop-In doesn't support:

Generate a payment method nonce out of a vaulted payment method token (server-side)
Verify that nonce using 3D Secure in your client. Successful results will have a new payment method nonce that is enriched with 3D Secure data. (on the client)
Use the generated 3D Secure enriched nonce in the Subscription.create() call.

3D Secure is a complex workflow, if you have additional questions on implementing this particular workflow, contact Support
Comment: Thanks for the answer, so drop in is not compatible with subscription & 3DS same time
Comment: This is not true, you can check the https://stackoverflow.com/a/70003913/769677 answer
Answer: The drop-in UI generates a nonce, but this nonce is associated with a vaulted payment method, only if you provide a customer_id when you generate the client_token. In this way you can obtain a bounce that you can use in gateway.subscription.create.
To summary the steps are:

(server) Create a customer without a payment method

(server) Generate a client_token with customer_id from step 1

(client) Generate drop-in UI using client token from step 2

(client) When the end-user adds his payment details drop-in generate a nonce associated with an already vaulted payment method

(server) Call subscription.create with the nonce from step 4
gateway.subscription.create({
"payment_method_nonce": clientNonce,
"plan_id": planId,
"merchant_account_id": merchantAccountId
})


While Inserting the data in MySQL getting error for the update column in Symfony2.4, Doctrine, PHP

Question: Problem - I want to save the data that is submitted from the form, when i am saving it to MySQL getting error as -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'updated' cannot be null

But I have given the update column the default value as 0000-00-00 00:00:00 , by default it must take the default value.
I am using the "prepersist" technique to add the code before saving it to MySQL.
The following is my "prepersist" code snippet from which the above error got generated-
public function setBeforeInsertData() {
    $this->added    =   new \DateTime();
}

I have used the following code to overcome the error just for the time being I know that its a wrong approach.
public function setBeforeInsertData() {
    $this->added    =   new \DateTime();
    $this->updated  =   new \DateTime();
}

The following is the Entity for the respective table -
<?php

namespace Skerp\InventoryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * InventoryLocation
 *
 * @ORM\Table(name="inventory_location")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class InventoryLocation
{
    /**
     * @var string
     *
     * @ORM\Column(name="locName", type="string", length=50, nullable=false)
     */
    private $locname;

    /**
     * @var string
     *
     * @ORM\Column(name="address1", type="string", length=50, nullable=false)
     */
    private $address1;

    /**
     * @var string
     *
     * @ORM\Column(name="address2", type="string", length=50, nullable=true)
     */
    private $address2;

    /**
     * @var string
     *
     * @ORM\Column(name="address3", type="string", length=50, nullable=true)
     */
    private $address3;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string", length=40, nullable=false)
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="zipCode", type="string", length=5, nullable=false)
     */
    private $zipcode;

    /**
     * @var string
     *
     * @ORM\Column(name="state", type="string", length=40, nullable=false)
     */
    private $state;

    /**
     * @var string
     *
     * @ORM\Column(name="country", type="string", length=40, nullable=false)
     */
    private $country;

    /**
     * @var string
     *
     * @ORM\Column(name="telephone", type="string", length=20, nullable=true)
     */
    private $telephone;

    /**
     * @var string
     *
     * @ORM\Column(name="fax", type="string", length=30, nullable=true)
     */
    private $fax;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=40, nullable=true)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="contactNo", type="string", length=20, nullable=false)
     */
    private $contactno;

    /**
     * @var string
     *
     * @ORM\Column(name="addedBy", type="string", length=100, nullable=true)
     */
    private $addedby;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="added", type="datetime", nullable=true)
     */
    private $added;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated", type="datetime", nullable=false)
     */
    private $updated;

    /**
     * @var integer
     *
     * @ORM\Column(name="inventLocId", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $inventlocid;

    /**
     * Set locname
     *
     * @param string $locname
     * @return InventoryLocation
     */
    public function setLocname($locname)
    {
        $this->locname = $locname;

        return $this;
    }

    /**
     * Get locname
     *
     * @return string
     */
    public function getLocname()
    {
        return $this->locname;
    }

    /**
     * Set address1
     *
     * @param string $address1
     * @return InventoryLocation
     */
    public function setAddress1($address1)
    {
        $this->address1 = $address1;

        return $this;
    }

    /**
     * Get address1
     *
     * @return string
     */
    public function getAddress1()
    {
        return $this->address1;
    }

    /**
     * Set address2
     *
     * @param string $address2
     * @return InventoryLocation
     */
    public function setAddress2($address2)
    {
        $this->address2 = $address2;

        return $this;
    }

    /**
     * Get address2
     *
     * @return string
     */
    public function getAddress2()
    {
        return $this->address2;
    }

    /**
     * Set address3
     *
     * @param string $address3
     * @return InventoryLocation
     */
    public function setAddress3($address3)
    {
        $this->address3 = $address3;

        return $this;
    }

    /**
     * Get address3
     *
     * @return string
     */
    public function getAddress3()
    {
        return $this->address3;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return InventoryLocation
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set zipcode
     *
     * @param string $zipcode
     * @return InventoryLocation
     */
    public function setZipcode($zipcode)
    {
        $this->zipcode = $zipcode;

        return $this;
    }

    /**
     * Get zipcode
     *
     * @return string
     */
    public function getZipcode()
    {
        return $this->zipcode;
    }

    /**
     * Set state
     *
     * @param string $state
     * @return InventoryLocation
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return string
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Set country
     *
     * @param string $country
     * @return InventoryLocation
     */
    public function setCountry($country)
    {
        $this->country = $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set telephone
     *
     * @param string $telephone
     * @return InventoryLocation
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;

        return $this;
    }

    /**
     * Get telephone
     *
     * @return string
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * Set fax
     *
     * @param string $fax
     * @return InventoryLocation
     */
    public function setFax($fax)
    {
        $this->fax = $fax;

        return $this;
    }

    /**
     * Get fax
     *
     * @return string
     */
    public function getFax()
    {
        return $this->fax;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return InventoryLocation
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set contactno
     *
     * @param string $contactno
     * @return InventoryLocation
     */
    public function setContactno($contactno)
    {
        $this->contactno = $contactno;

        return $this;
    }

    /**
     * Get contactno
     *
     * @return string
     */
    public function getContactno()
    {
        return $this->contactno;
    }

    /**
     * Set addedby
     *
     * @param string $addedby
     * @return InventoryLocation
     */
    public function setAddedby($addedby)
    {
        $this->addedby = $addedby;

        return $this;
    }

    /**
     * Get addedby
     *
     * @return string
     */
    public function getAddedby()
    {
        return $this->addedby;
    }

    /**
     * Set added
     *
     * @param \DateTime $added
     * @return InventoryLocation
     */
    public function setAdded($added)
    {
        $this->added = $added;

        return $this;
    }

    /**
     * Get added
     *
     * @return \DateTime
     */
    public function getAdded()
    {
        return $this->added;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return InventoryLocation
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Get inventlocid
     *
     * @return integer
     */
    public function getInventlocid()
    {
        return $this->inventlocid;
    }
    /**
     * @var integer
     */
    private $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
    * @ORM\PrePersist
    */
    public function setBeforeInsertData() {
        $this->added    =   new \DateTime();
        //$this->updated  =   new \DateTime();
    }
}

Thanks in Advance.
Comment: show you entity i guess you have mismatched column names and properties of entity
Comment: @bartek Just a sec I will update question with the Entity Code
Comment: The entities are matching perfectly...
Comment: Are you sure that you used proper annotations?
Comment: @bartek is there anything that i need to modify in the annotations
Comment: When such simple lifecycle events are the issue I often rely on `__construct` to do all the stuff. After all, `$em->persist` occurs only once and those fields will be overwritten with current values as soon as you load the data ;)
Comment: @user1696621 Actually it is mismatched; on the functions you set `$this->added_on` and `$this->updated_on` whereas in your entity you have `$added` and `$updated`
Answer: Your entity class should have following annotation: @ORM\HasLifecycleCallbacks(). Your methods should have @ORM\PrePersist annotation. More info: http://symfony.com/doc/current/book/doctrine.html#lifecycle-callbacks
Comment: I might be wrong, but commented code won't work. - //$this->updated  =   new \DateTime();
Comment: @bartek: Legend says it does not :)
Comment: Can you try something simple like throwing an Exception inside this PrePersist() method to see if it is actually executed?
Comment: Even after adding the respective annotations its giving the same error as - "Integrity constraint violation: 1048 Column 'updated' cannot be null ". Is there any other way so that the updated column will get the default value as '0000-00-00 00:00:00'
Comment: Would you please be so kind and update your question by pasting FULL entity class including ALL necessary annotations? BTW have you tried ./app/console c:c after doing changes?
Comment: ya I have even tried "php app/console cache:clear" but facing the same issue...just a sec i wil update my Entity Code
Comment: Ya that wont work out....thats why i have commented it out....for the time being i am using it till i get the solution from you guys....waiting for the one :)


Cassandra2.1 write slow in a 1TB data table

Question: I am doing some test in a cassandra cluster,and now i have a table with 1TB data per node.When i used ycsb to do more insert operation,i found the throughput was really low(about 10000 ops/sec) comparing to a same,new table in the same cluster(about 80000 ops/sec).While inserting,the cpu usage was about 40%,and almost no disk usege.
I used nodetool tpstats to get task details,it showed :
Pool Name                    Active   Pending      Completed   Blocked  All time blocked
CounterMutationStage              0         0              0         0                 0
ReadStage                         0         0            102         0                 0
RequestResponseStage              0         0       41571733         0                 0
MutationStage                   384     21949       82375487         0                 0
ReadRepairStage                   0         0              0         0                 0
GossipStage                       0         0         247100         0                 0
CacheCleanupExecutor              0         0              0         0                 0
AntiEntropyStage                  0         0              0         0                 0
MigrationStage                    0         0              6         0                 0
Sampler                           0         0              0         0                 0
ValidationExecutor                0         0              0         0                 0
CommitLogArchiver                 0         0              0         0                 0
MiscStage                         0         0              0         0                 0
MemtableFlushWriter              16        16           4745         0                 0
MemtableReclaimMemory             0         0           4745         0                 0
PendingRangeCalculator            0         0              4         0                 0
MemtablePostFlush                 1       163           9394         0                 0
CompactionExecutor                8        29          13713         0                 0
InternalResponseStage             0         0              0         0                 0
HintedHandoff                     2         2              5         0                 0

I found there was a large amount of pending MutationStage and MemtablePostFlush
I have read some related articles about cassandra write limitation,but no useful information.I want to know why there is a huge difference about cassandra throughput between two same tables except the data size?

In addition,i use ssd on my server.However,this phenomenon also occur in another cluster using hdd

When cassandra was running,i found the both %user and  %nice on cpu utilization are about 10% while only compactiontask running with compaction throughput about 80MB/S.but i have been set nice value to 0 for my cassandra process.
Comment: You should try to increase the compaction throughput with nodetool setcompactionthroughput
Comment: i have tried,but it not work.
Answer: Wild guess: your system is busy compacting the sstable.
Check it out with nodetool compactionstats
BTW, YCSB does not use prepare statement, which make it bad estimator for actual application load.


Mapeamento mais adequado de JSON para objeto Java

Question: Preciso trabalhar com um JSON que tem informações de receitas. Este JSON possui um objeto (Recipe) com alguns arrays de objetos (ingredients, steps).
O que seria mais adequado, do ponto de vista da orientação a objetos: criar 3 classes-- Recipes, Ingredients, Steps-- com os atributos recebidos pelo JSON (id, name para a classe Recipes, quantity, measure, ingredient para a classe Ingredients, etc...) ou criar uma única classe (Recipes) com os atributos dela (id, name) e dois ArrayList de HashMap com os valores de Ingredients e Steps? E por quê?
Screenshot do json (não aparece o array Steps).
Comment: Não use screenshots no lugar de código, por favor. Isso atrapalha a busca e atrapalha a leitura por usuários de leitores de tela.
Answer: Usar maps quando a chave é sempre a mesma (sempre id, name, ingredients) não faz muito sentido. O ideal, do ponto de vista de deixar o seu código mais expressivo, é ter uma classe pra cada conceito que se repete. O problema é que, quando a gente trabalha com JSON, essas classes explodem em quantidade. O que a gente faz é usar alguma biblioteca que cria esse mapeamento para a gente e alguma ferramenta que gera as classes automaticamente baseado no JSON.
Experimente o Jackson ou o GSON para o mapeamento e o jsonschema2pojo.org para gerar as classes pra você.


Calculate Significance between samples with skewed data

Question: Background:
I have a sample that is very left skewed. The mean of this sample is 4.01 (min = 1, max = 5). I would like to know whether or not a subset of this sample is significantly different than the sample as a whole.
My use case:
I want to take a portion of this sample (344 of the 1140 responses) and use Welch's t-test to determine whether the mean of the subset is significantly different than the mean of the entire sample.
My questions:

Am I correct in assuming that significance should not be measured (at least not using Welch's t-test) if your data is extremely skewed?
Is there a way to determine statistical significance between a sample and a subset of that sample when the data is skewed?

All of my computations are in php, as I am a web developer. So if your answer involves using some sort of statistical software magic I won't have a clue what you're talking about...thanks in advance!
Comment: Phrases like "statistical software magic" are unhelpful. Does that mean you're unprepared to run a simple command in any software, for example? How skewed are the data? Is the distribution also discrete? (can you show some display?) Is it only shift in mean you care about, or is some generic sense of "larger" all that matters?
Answer: Question 1:
Even if your population is highly skewed the distribution of your sample means may not be for a sufficiently large sample size.  You can try this out by making multiple draws from your initial sample and plotting them.
This question may be useful in understanding under what circumstances the t-test isn't applicable.
t-test on highly skewed data
Question 2:
It really depends on what you want to compare, a standard goto would be the (http://en.wikipedia.org/wiki/Mann–Whitney_U_test), but you are violating the independence assumption of the two populations.  There is also simulation which may work, but it is a bit awkward due to the dependence again.
To answer this better you might want to give some feedback on what your goal with this test is.
Comment: Thanks, @Jonathan. Unfortunately, I have no way of collecting a larger sample size. The survey from which I'm getting my data is now closed. Although, the sample size does represent a significant portion of the population (the population being all employees in this particular company).   The _goal_ of my test is to determine whether the mean of the subset is significantly gt or lt than the mean of the entire sample. I will review the other post you linked, as I think that may offer a pretty good summary of what I'm looking for.
Comment: I'm just a bit confused about why you are trying to subsample, since you already have a larger sample.  Are you trying to determine sample size for a future sample?


The derivationof sine to cosine

Question: I am new to mathematics somehow, and I know that:

$\frac{d(\sin x)}{dx}= \cos x$

But I can't understand this:

$\frac{d (a \sin(\omega.t))}{dt} = a.\omega\cos(\omega.t)$

where $a$ is the peak of the wave and $\omega$ is $2\pi f$ (where $f$ is frequency)

Could anyone please explain it for me?
Comment: What do you know about derivatives?
Comment: Have you seen the chain rule?
Comment: Just a little, I studied a small amount of information about it two years ago, and this year I saw this equation in my physics book.
Comment: As Sylvester said, you should apply the chain rule. It is a basic rule that you should know about derivatives. Take a time to learn about it.
Comment: what do you know about mathematics? tell us!
Comment: @PushkarSoni I studied a high school stuff about two years ago, this year I have to study physics and found that one of the topics I study is based on derivatives. And, to be honest, I don't remember so much about it.
Comment: good luck buddy :)
Comment: @PushkarSoni, Thank you, my friend!
Answer: $\frac{d (a \sin(\omega.t))}{dt} = \frac{d(a.\sin(\omega t))}{d(\omega t)}.\frac{d(\omega t)}{dt} = a . \frac{d(\sin(\omega t))}{d(\omega t)}.\frac{\omega.d(t)}{dt}=a.\cos(\omega t).\omega$.
Here this type of above method is known as chain rule .Explore it more!
Hope it helps!
Answer: Here chain rule is used.
$\frac {d}{dt} (\sin (\omega.t)) = \cos (\omega.t). \frac {d}{dt} (\omega.t)$
= $ \cos (\omega.t). \omega. \frac{d}{dt} t$
= $ \cos (\omega.t). \omega . 1$
= $\omega. \cos (\omega.t)$

The derivationof sine to cosine


Apache port forwarding

Question: Some muppet in my company has bunged up the config of an apache server. Basically what I need to do to fix this mess is to capture all traffic on port 8082 (Apache is configured to listen to this port) - then to redirect this traffic to /bugzilla. Is this possible, and if so how?
The box is only visible to internal users so quick dirty hack is just fine in this case.
Comment: Bunged up in what way, what does it do right now?
Comment: Could you define muppet for those that don't understand the term please :)
Answer: Quick and dirty... Install a TCP proxy to redirect the packages from 8082 to another port and maybe another machine. rinetd is really easy and has worked good for me before.
Comment: this solution worked perfectly - thank you very much victor!

Apache port forwarding


Estimating ARMA model with ML and scipy.optimize Python

Question: I am missing something. I am trying to estimate an ARMA(2,2) model using Maximum Likelihood estimation via the scipy.optimize.minimie function.
I have simulated an ARMA(2,2) process via the statsmodel module with AR coefficients 0.75 and -0.25, and MA coefficients 0.35 and 0.5:
rparams = np.array([.75, -.25])
maparams = np.array([.35, .5])
ar = np.r_[1, -arparams] # add zero-lag and negate
ma = np.r_[1, maparams] # add zero-lag
y = arma_generate_sample(ar, ma, 1000)

When I estimate an ARMA(2,2) model using the statsmodels module I get reasonable close coefficients, so my simulation is correct.
But, when I try to estimate the coefficients using Maximum Likelihood and the scipy.optimize.minimize function I am not able to get any reasonalbe results. My code is:
def arma(vPar, vData):
    """ARMA log-likelihood assuming no constant"""
    iT = len(vData)
    AR1 = vPar[0]
    AR2 = vPar[1]
    Var = vPar[2]**2
    vRes = np.zeros((iT, 1))
    vX = np.ones((iT, 1))*np.mean(vData)
    for t in range(2, iT):
        vX[t] = AR1*vX[t-1] + AR2*vX[t-2]
        vRes[t] = vData[t]-vX[t]
    Llk = -0.5*(iT*np.log(2*pi)+iT*np.log(Var)+np.sum(vRes**2)/Var)
    return Llk

x0 = np.array([.15, .11, .22])
res = minimize(arma, x0, args=(y), method='SLSQP', options={'disp': True})

This results in:
Iteration limit exceeded    (Exit mode 9)
            Current function value: nan
            Iterations: 101
            Function evaluations: 1496
            Gradient evaluations: 101

I've noticed that the minimizer sometimes inputs nan as parameter values, but I do now know why. What am I missing?
Comment: Your log likelihood is incorrect for ARMA. You LL only has AR no MA.
Comment: You are certainly right. But that was actually on purpose as part of my debugging procedure, I just forgot to edit it back to the complete model before posting here. I'll edit the post asap.
Answer: The reason why you NaN is because the parameter VAR in your likelihood function is in denominator and when the optimizer is trying to search the objective space it is using the value 0 sometimes and therefore causing NaN. Couple of work arounds: 1.  Try to constrain your parameters in the optimizer to have a lower bound a small value such as 0.000001 OR 2. you can multiply parameter VAR by a small value of 0.000001 in the maximum likelihood function.
Comment: @forecaster, what about suggesting a synonym `structural-break` to the tag [tag:structural-change]? I would, but I do not have sufficient reputation. I think it is a relevant synonym, because if you search for "break" (thinking about structural breaks) it would be natural to get a suggestion [tag:structural-change], which is not the case now. You could also suggest it in Meta and give a link there pointing to where people can vote. Recently I did a similar thing with `adf` as a synonym to [tag:augmented-dickey-fuller], it worked nicely.
Comment: I already tried constraining the parameters to have a lower bound 0.0001. Maybe I did it wrong, but it didn't work.
Comment: Can you show what you did in your post!
Comment: @forecaster, Unrelated request: I have proposed to make [tag:arma] a synonym of [tag:arima] and advertised this on Meta [here](https://stats.meta.stackexchange.com/questions/1200/current-tag-synonym-candidates/4670#4670) a while ago (without much success). As one of the top scorers under the [tag:arima] tag, you may vote on the proposal [**here**](http://stats.stackexchange.com/tags/arima/synonyms).
Comment: @RichardHardy I agree, `structural-break` is more commonly used term than `structural-change`.  Is there a way that I can do this ? I tried to create a synonym but looks like `structural-break` should already be a tag.
Comment: @forecaster, I don't know why that is the case. Maybe `structural break` used to be a tag that got burninated before. Or something like that. You could post a separate question on Meta if you have time. Or if not, I could do it, but I do not know all the details.
Answer: Here is a relevant link that you can have a look at:
https://github.com/philipperemy/arma-scipy-fit/


Show $S^2$ with 2 cells attached is equivalent to a wedge of spheres

Question: Show that a space obtained from $S^2$ by attaching n 2-cells along any collection of n circles in $S^2$ is homotopy equivalent to the wedge of n+1 spheres.
I'm a little confused here. I'm imagining a sphere, and putting 2 dimensional discs inside of it. Attaching one disc along one circle of $S^2$ and then collapsing that disc to a point would appear to me to create a wedge of two spheres.
However, if I attached 2 discs along 2 different circles of $S^2$ and collapsed each to a point, to me it seems I would have created a wedge of four spheres, one sphere for each division created by the two discs inside the sphere.
What is wrong with my thinking here? Thanks!!
Comment: Consider what happens if the circles are parallel. What, if anything, changes when we move the circles to not be parallel?
Comment: You can use an inductive argument: attaching $n$ 2-cells to $S^2$ is equivalent to attaching one 2-cell to the space obtained by attaching $(n-1)$ 2-cells to $S^2$. Then if you agree that attaching one 2-cell is equivalent to wedging with a new sphere, the claim follows.
Comment: Specifically, I don't understand why you are imagining four spheres instead of three. [This](https://i.imgur.com/BqDEmw5.png) is what I have in mind.
Answer: If you form $Z= S^2 \cup_f e^2$ then the attaching map- $f: S^1 \to S^2$ is null homotopic, as $S^2$ is simply connected. So $Z \simeq S^2 \vee S^2 $. The general result you need is that if $Z= B \cup_f X$ where $f: A \to B$,  and the inclusion $i : A \to X$ is a closed cofibration, then the homotopy type of $Z$ depends only on the homotopy class of $f$.


$M=X\cup Y$. If $S\subset M$ is open in $S\cup X$ and open in $S\cup Y$ then $S$ is open in $M$.

Question:
Let $M=X\cup Y$ be a metric space. If $S\subset M$ is open in $S\cup X$ and open in $S\cup Y$ then $S$ is open in $M$.

I can't do anything with this exercise. I think that is the hardest problem in my book.
Answer: Since $S$ is open in $S\cup X$, there must be an open set $U$ in $X$ such that $U\cap(S\cup X)=S$. Similarly, since $S$ is open in $S\cup Y$, there must be an open set $V$ in $X$ such that $V\cap(S\cup Y)=S$. Clearly $S\subseteq U$, so $U\cap S = S$, and $$S=U\cap(S\cup X)=(U\cap S)\cup(U\cap X)=S\cup(U\cap X)\;,$$ and therefore $U\cap X\subseteq S$. Similarly, $S\subseteq V$, so $$S=V\cap(S\cup Y)=(V\cap S)\cup(V\cap Y)=S\cup(V\cap Y)\;,$$ and therefore $V\cap Y\subseteq S$.
Next, note that $S\subseteq U\cap V$; $U\cap V$ is open in $M$, so we're done if we can show that $S=U\cap V$. We know that $U\cap X\subseteq S$, so certainly $U\cap V\cap X\subseteq S$. Similarly, from $V\cap Y\subseteq S$ we can infer that $U\cap V\cap Y\subseteq S$. But then
$$\begin{align*}
U\cap V&=(U\cap V)\cap M\\
&=(U\cap V)\cap(X\cup Y)\\
&=(U\cap V\cap X)\cup(U\cap V\cap Y)\\
&\subseteq S\;,
\end{align*}$$
so indeed $U\cap V=S$.
As you can see, the result is valid for topological spaces in general, not just for metric spaces.
Comment: Thanks a lot, I didn't note the fact that $S\subset U$ and $S\subset V$.
Comment: Is the same if $S$ is closed in both sets. Then $S$ is closed in $M$. Only fact that do you use is that intersection of two closed sets is closed and intersection of two open sets is open.
Comment: @Gastón: Yes, that's right.


How do I theme user reset password page?

Question: How I can template the user reset password page when I receive the reset password token based link?
/user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4
Answer: Wooha! I found the answer myself. These are the template file names which can be overridden to theme the pages.
page--user--reset.tpl.php
- To theme the reset password page when you will receive this of reset password URL in the email. /user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4
page--user--login.tpl.php
- To reset the user login page.
page--user--pass.tpl.php
- To theme the user password page when user enters the email address to recover the password.
See this for more information as well.
https://www.drupal.org/node/350634


View em Django não retorna objeto HttpResponse

Question: Estou fazendo um CRUD simples em Django para fins de aprendizado. Porém, estou tendo um problema. Ao criar uma view para adicionar dados em uma agenda, o servidor retorna o seguinte erro:

The view agenda.views.adiciona didn't return an HttpResponse object.

Segue o código da view "adiciona" que escrevi:
def adiciona(request):
    if request.method == "POST":
        form = FormItemAgenda(request.POST, request.FILES)

        if form.is_valid():
            dados = form.cleaned_data
            item = ItemAgenda(data=dados['data'], hora=dados['hora'], titulo=dados['titulo'], descricao=dados['descricao'])
            item.save()
            return render_to_response("salvo.html", {})
        else:
            form = FormItemAgenda()
        return render_to_response("adiciona.html", {'form': form}, context_instance=RequestContext(request))

Defini as rotas em "urls.py" da seguinte maneira:
urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'agenda.views.lista'),
    url(r'^adiciona/$', 'agenda.views.adiciona'),
)

Procurei no Google e na documentação do Django 1.6.x e não encontrei nenhuma resposta significativa. Como posso corrigir esse erro?
Answer: Se o seu código é somente esse mostrado, então o que parece estar faltando é um else para tratar de requisições e não de um post. De fato, o render_to_response retorna um HttpResponse e, caso o problema fosse uma exceção, a mensagem de erro seria outra. O que pode estar acontecendo então é a sua view estar sendo chamada com outro método HTTP (provavelmente get) e - como não tem else - ela estar retornando None.
Experimente, no final do método, colocar uma resposta padrão caso a visão não reconheça o método:
def adiciona(request):
    if request.method == 'POST':
        ...
    else:
        return HttpResponse('Método inválido para essa operação: {}'.format(request.method))

Comment: Obrigado por tirar minha dúvida. De fato ele retornou a mensagem indicando método GET. Agora preciso descobrir como fazer para que o formulário passe o método POST, como deveria ser...
Answer: def adiciona(request):
    if request.method == 'POST':
        form = FormCrud(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render_to_response("salvo.html",{})
    else:
        form = FormCrud()

    return render_to_response("adiciona.html",{'form':form},context_instance=RequestContext(request))

Comment: Poderia explicar o que esse código faz?


Is using cat command to merge files created by multiple threads efficient?

Question: I have a multi-threaded C++11 program in which each thread produces a large amount of data that need to be written to the disk. All the data need to be written onto one file. At the moment, I use a mutex that protects accesses to the file from multiple threads. My friend suggested me that I can use one file for each thread, then at the end merge the files into one file with cat command done from C++ code using system().
I'm thinking if cat command is going to read all the data back from the disk and then write it again to the disk but this time into a single file, it's not going to be any better. I have googled but couldn't find cat command implementation details. May I know how it works and if it's going to accelerate the whole procedure?
Edit:
Chronology of events is not important, and there's no ordering constraint on the contents of the files. Both methods will perform what I want.
Comment: The two methods are not equivalent. You'll have a chronology of events when multiple threads are writing to the same file. If you write to multiple and then concatenate you'll lose that. If that's not important to you, you should mention that in the question.
Comment: Please don't use system calls for file operations.
Comment: It breaks portability and it is easy enough using `fstream`s (or if you are using boost, `boost::filesystem`)
Answer: You don't specify if you have some ordering or structuring constraints on the content of the file. Generally it is the case, so I'll treat it as such, but hopefully my solution should work either way.
The classical programmatic approach
The idea is to offload the work of writing to disk to a dedicated IO thread, and have a multiple producers/ one consumer queue to queue up all the write commands. Each work thread simply format its output as a string and push it back to the queue. The IO thread pop batches of messages from the queue into a buffer, and issue the write commands.
Alternatively, you could add a field in your messages to indicate which worker emitted the write command, and have the IO thread push to different files, if needed.
For better performance, it also interesting to look into async versions of the IO system primitives (read/write), if your host OS supports them. The IO thread would then be able to monitor several concurrent IO, and feed the OS with new ones as soon as one terminate.
As it has been advised in comments, you will have to monitor the IO thread for congestion situations, and tune the number of workers accordingly. The "natural" feedback based mechanism is to simply make the queue bounded, and workers will wait on the lock until space free up on it. This let you control the amount of produced data at any point during the process life, which is an important point in memory constrained scenarios.
Your cat concerns
As for cat, this command line tool simply read whatever is wrote to its input channel (usually stdin), and duplicates it to its output (stdout). It's as simple a that, and you can clearly see the similarity with the solution advocated above. The difference is that cat doesn't understand the file internal structure (if any), it only deals with byte streams, which means that if several processes write concurrently to a cat input without synchronization, the resulting output would probably be completely mixed up. Another issue is the atomicity (or lack thereof) of IO primitives.

NB: On some systems, there's a neat little feature called a fork, which let you have several "independent" streams of data multiplexed in a single file. If you happen to work on a platform supporting that feature, you could have all your data streams bundled in a single file, but separately reachable.
Comment: @Farzad:  just realized something else, you will need a blocking queue anyway for managing the concurrent access to the queue by workers and the writer, and because the writer will be blocking on reading the queue when it is empty.  WHICH REMINDS ME:  make sure when workers are done, something (the thread that dispatches the workers?) puts a message onto the queue telling the writer thread that no more messages are coming. That way the writer thread will know not to block on the empty queue anymore and can shut down.
Comment: @Farzad I was writing my comment above before I read yours.  I have been having the same problem.  Try tuning to reduce the number of worker threads.  It seems counterintuitive but you will see throughput improvement as results will not overwhelm memory by being queued faster than they can be written.  Keep reducing until you find you are actually losing throughput.  Also, take a good look at your writer thread and try to find optimizations (e.g. reduce the complexity of output formatting, etc.)
Comment: @sparc_thread, yes, or limit the size of the queue, forcing workers to block when it's full (though that would boils down to the original solution, though the multplexing would be done by the IO thread instead of the OS).
Comment: @Farzad, unfortunately, the data produced by the workers will have to go somewhere, either temporary files, or a memory buffer (the queue). Indeed it'll be a matter of tuning the number of workers so that the IO thread doesn't get overwhelmed.
Comment: @Farzard:  Yes that is correct.  I am not as familiar w/ C++11 provided concurrent data structures but I imagine by this time the new libraries would include a blocking queue.
Comment: Thanks. I'm aware of such solution. I have a memory usage constraint (maybe I had to mention it in the question). IO thread queue may end up consuming (probably unpredictable) memory space, and I have to avoid using disk space as memory.
Comment: @didierc: True.  The main thing is that it's faster for 1 thread to write to 1 file then for multiple threads to contend over write access to that file.  It may also be worth mentioning that the single writer thread shouldn't be too much slower than the worker threads, as big result objects could take up lots of memory in the queue (mentioning this because it's happening to me right now; then again I'm doing it in Java so mem impact harder to manage :-) )  This can always be managed by tuning to reduce the number of worker threads until throughput stops increasing.


How to auto refresh page/component view in angular

Question: I have a dashboard page which displays around ten tables. Each table is a separate component and fetches data using it's on API. I have a requirement to auto refresh this page every five minutes (let's say). I tried the following but it doesn't work.
ngOnInit(): void {
    this.updateSubscription = interval(120000).subscribe(() => {
      this.getDataByName();
    });
  }

  public getDataByName(): void {
    this.httpMarketData.getTableByType('Customer Table').subscribe((response: TableData[]) => {
      this.getTableData(response);
    });
  }

I referred it from here. But it doesn't work and I stop seeing any data. Any suggestions how to achieve it? I was thinking to call these APIs from each component to auto refresh themselves in a similar way.
Comment: first data will be fetched after your set delay, i think you want to use timer(0, 5000) instead of interval(5000)
Comment: @enno.void Thanks a bunch mate. That seems to be the issue.
Answer: Try this:
ngOnInit(): void {
    this.updateSubscription = timer(0, 120000).pipe(
      switchMap(x => this.httpMarketData.getTableByType('Customer Table'))
    ).subscribe((response: TableData[]) => {
      this.getTableData(response);
    });
}

Explanation:

Use timer instead of interval
Use switchMap to switch to the http-observable after every delay.
Comment: 1.Yes you need it. You have to unsubscribe in ngOnDestroy, otherwise it will produce a memoryleak because the timer runs for an infinte amount of time, even if the table-component is destroyed.

2. I think ngOnInit is a good place.

3. "but view isn't getting updated" this seems to be an problem of `this.getTableData(response)` if the requests are fired properly
Comment: Do we need `updateSubscription` ? Also, can I move this piece of code in the method itself than `ngOnInit` block? Would I then need to call `ngOnInit` from this one to update the view? I see data coming now at regular interval but view isn't getting updated.
Comment: `this.getTableData(response)` is actually an `input` to the parent component selector, does that mean rather than input, should be like an event or something? I believe the input change isn't getting transmitted to the parent properly on the refreshes?
Comment: Dont really get your last comment, so i created this example - hope it helps:
https://stackblitz.com/edit/angular-ivy-np9vky?file=src/app/app.component.ts
Comment: Thanks for the help!! In my last comment I was trying to say that this data is an array and it works as an input to another component. Now it displays properly for the first time but next time when this data array changes, I think angular doesn't detect it. Just a guess. Thanks for all the help again!!


how the wiki site work i mean the sql structure

Question: any one know
that in wiki sites
any one can edit the page
i want know
how i can make this is mysql
i want to know the mysql table structure fot that job
and how approve edits
Comment: Data base structure is described here: http://www.mediawiki.org/wiki/Manual:Database_layout. Most detailed diagram is http://upload.wikimedia.org/wikipedia/commons/thumb/3/33/MediaWiki_database_schema_1-19_(r102798).svg/2193px-MediaWiki_database_schema_1-19_(r102798).svg.png
Answer: That's an extremely broad question — almost like asking, "What tables should I have for an e-commerce site?" It depends entirely on what content you want to store.
If you want to know more about a particular wiki implementation (e.g., MediaWiki, which powers Wikipedia), you can simply download and install the application. The actual tables with real data in them will then be right there for you to look through at your leisure.
If you're designing a new wiki application, you'll have to know a lot more about the data involved before you can begin to define a table structure.
In general, though, any time you want to store a history of revisions, you'll need a table representing revisions. Each row in this table stores the text of a revision, and a foreign key connects it to the page (or other object) it's a revision of.
Answer: You can take a look to the Mediawiki data base schema:
click here for the full size image
Answer: You can have a table containing pages and a table containing page history (with a PageID foreign key)


How to get the largest and smallest of 3 values with fewest comparisons?

Question: This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.
I need to only use if statements.
This is what I tried so far: which required 4 comparisons.
int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;

smallest = x;
largest = x;

if (y > largest)
        largest = y;
if (z > largest)
        largest = z;
if (y < smallest)
        smallest = y;
if (z < smallest)
        smallest = z;

cout << "largest: " << largest << ", and smallest: " << smallest << endl;

My question is: Is it possible to only use 3 comparisons, or less? I think when y > largest, it also tells us something else as well?
Comment: tip: bubblesort would only be three comparisons, and would tell you the min and max.
Comment: Actually, bubblesort normally does swaps so it would be more complex than some of the answers.  [But here's an unrolled inlined bubblesort!](http://ideone.com/SGiYGu)
Comment: `auto [smallest, largest] = std::minmax({x, y, z})` promises merely "no more than 4" comparisons
Answer: The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example
if (y > largest)

don't just treat the true case. Also try to reason about the case when the condition doesn't hold.
if ( x < y )
{
    smallest = x;
    biggest = y;
}
else
{
    smallest = y;
    biggest = x;
}

if ( z < smallest )
   smallest = z;
else if ( z > biggest )
   biggest = z;

This contains only 3 comparisons.
Comment: @George: If your exercise is limited to that, just put the first `else` part before the `if` (so it gets executed every time, but if the `if` condition is true, the values are overwritten), and drop the other `else` which is just an optimization.
Comment: @George the `else` **is part** of the `if` statement.
Comment: I'm pretty sure if z is biggest three comparisons get executed.
Comment: @LuchianGrigore I don't know if it matters, but if it is only `if statement`, no `else statement`. Can it also be done in 3 comparison?
Comment: @LuchianGrigore I know, but that's because this question came in the chapter before the book teaches `else` statement, I was just wondering.
Answer: Why are you checking if (y < smallest)? At this point in the flow, smallest must be x, but you've already checked if y > x in the first condition (if (y > largest)), so the third condition is redundant.
Comment: Sure, just start with `largest = y` instead of `largest = x` and see where it takes you...
Answer: The question is finding the largest or smallest by only if else statements, and we have three variables to use, so we only need two comparisons.
{
    int valueOne,
    valueTwo,
    valueThree,
    smallest;

//User input for valueOne, valueTwo, valueThree.

smallest = valueOne;

if (smallest < valueTwo)
{
smallest = valueTwo;
}
if (smallest < valueThree)
{
smallest = valueThree;
}

//No matter what happens, smallest will have the smallest value now.

//Use >, rather than <, and "largest" rather than "smallest" for finding largest value.

//With this logic, you always will have one less comparison than the total number or variables to compare

//i.e. 7 variables means 6 comparisons.

//This contains only 2 comparisons.

Answer: In general you can determine a sort for three numbers x, y, and z using at most 3 comparisons:
if (x < y)
    if (y < z)
       //x,y,z -> x min
    else if (x < z)
       //x,z,y -> x min
    else
       //z,x,y -> z min
else
    if (z >= x)
       //y,x,z -> y min
    else if (z >= y)
       //y,z,x -> y min
    else
       //z,y,x -> z min

So getting the min can also be done with 3 comparisons.

You can get the min in 2 comparisons by doing:
m = x;
m = min(m,y);
m = min(m,z);

where min(a,b) is a < b ? a : b.

In general you can get the min of N numbers using N - 1 comparisons.
Answer: I find this easiest to understand for you.
a = 5;
b = 10;
c = 15;

//FIND MAX
if (a >= b && a >= c)
{
   max = a;

} else
{
    if (b >= c)
        max = b
    else
        max = c;
}

//FIND MIN
if (a <= b && a <= c)
{

    min = a;
} else
{
    if (b <=c)
        min = b;
    else
        min = c;
}

Answer: This one is just for fun and I believe the myabs function is actually supposed to be undefined behaviour, but I've only ever seen places that it works as expected.
    double myabs(double x)
    {
        int64_t * p = (int64_t*)&x;
        //clear sign bit
        *p &= 0x7fffffffffffffff;
        return x;
    }

    int main()
    {
        double x = 0, y = 1, z = 2;
        //find max/min of first two numbers
        double min = (myabs(x+y)-myabs(x-y))/2;
        double max = (myabs(x+y)+myabs(x-y))/2;
        //find max/min of previous max/min and third number
        min = (myabs(min+z) - myabs(min-z))/2;
        max = (myabs(max+z) + myabs(max-z))/2;
        std::cout << min << ' ' << max << std::endl;
        return 0;
    }

Which outputs 0 2 correctly with 0 comparisons in total.
Comment: It works only if `long` is 64bit. Not too many places where it will work. I never saw such places, for example
Comment: @kotlomoy `long` is 64 bits on Linux, but not Windows.  There are defines for different data types for Windows that you can use instead.  I'm not sure what it is offhand though.
Comment: @kotlomoy changed `long` to `int64_t` defined in `stdint.h`.  That should make it work on Windows as well (not that I'm able to test that, however)
Comment: Preferrably `` instead of ``, since this is a C++ question.
Comment: `` is actually c++11, it was actually the first thing I tried.
Answer: int main(){
    int numb1, numb2, numb3;
    if(numb1>numb2 && numb1>numb3){
        printf("%d is largest.\n%d is smallest.", numb1, numb2<numb3? numb2:numb3);
    }
    else if(numb2>numb1 && numb2>numb3){
        printf("%d is largest.\n%d is smallest.", numb2, numb1<numb3? numb1:numb3);
    }
    else{
        printf("%d is largest.\n%d is smallest.", numb3, numb1<numb2? numb1:numb2);
    }
}

Comment: You should add explanation.
Answer: int a; int b; int c;
cin >> a >> b >> c;

if ( a > b && b > c ){ cout << a << " MAIXM \n" << b << " MEDIU \n" << c << " MINIM \n"; }

if ( b > a && a > c ){ cout << b << " MAIXM \n" << a << " MEDIU \n" << c << " MINIM \n"; }

if ( c > b && b > a ){ cout << c << " MAIXM \n" << b << " MEDIU \n" << a << " MINIM \n"; }

if ( a > c && c > b ){ cout << a << " MAIXM \n" << c << " MEDIU \n" << b << " MINIM \n"; }

if ( b > c && c > a ){ cout << b << " MAIXM \n" << c << " MEDIU \n" << a << " MINIM \n"; }

if ( c > a && a > b ){ cout << c << " MAIXM \n" << a << " MEDIU \n" << b << " MINIM \n"; }


Automatizar impressão de arquivos dentro de uma pasta

Question: Preciso fazer com que qualquer arquivo que esteja na pasta, exemplo c://imprimir vá sendo impresso automaticamente, verifica se tem algo e manda para impressora padrão.
Estive pesquisando em Python porém consegui basicamente acessar a pasta e listar e contar cada arquivo que esta dentro 1 a 1.
import os
import time
import glob

try:
    #Passa o caminho onde estão os arquivos pdf
    loc = input('Localizacao: ')

    #localizar pasta
    floc = loc.replace("'\'","'/'")

    #nav até caminho informado
    os.chdir(floc)

    x = 0

    #Verifica todos arquivos .pdf que tem na pasta
    for file in glob.glob('*.pdf'):
        if(file != ''):
            os.startfile(file, 'print')
            print('Imprimindo arquivo.. ' + str(file))
            x += 1
            time.sleep(2)

    print('Arquivos impressos: ' + str(x))

except Exception as a:
    print(a)

@Resultado:
=============== RESTART: C:/Users/willian/Desktop/imprimir.py ===============
Localizacao: C:/imprimir
Imprimindo arquivo.. teste - Cópia (2).pdf
Imprimindo arquivo.. teste - Cópia.pdf
Imprimindo arquivo.. teste.pdf
Nenhum arquivo para imprimir 3
>>>
=============== RESTART: C:/Users/willian/Desktop/imprimir.py ===============
Localizacao: C:/imprimir
Arquivos impressos: 0
>>>

Como poderia mandar imprimir e se possível imprimir e mover ou excluir o arquivo?
Comment: Relacionado, mas não duplicado:
https://pt.stackoverflow.com/questions/65072/como-imprimir-um-arquivo-txt-em-python/65122#65122
Comment: @jsbueno no caso seu está para abrir no navegador e a pessoa ter que dar o comando.. neste caso não fica viável porque esta forma que preciso irão colocar muita coisa na pasta
Answer: Os seus arquivos já estão em PDF - é a grande diferença para a resposta em Como imprimir um arquivo txt em Python. mas ela dá um bom embasamento do que está envolvido na impressão e por que o Python ou outras linguagens não tem um comando direto para "imprimir".
Mas o link que está naquela resposta para windows (http://timgolden.me.uk/python/win32_how_do_i/print.html) tem, no último exemplo, como imprimir um arquivo PDF no Windows direto a partir do Python:
você deve instalar a win32api (está no Pypi com o nome de pywin32 - pip install pywin32 deve ser o suficiente).
E em seguida a chamada na ultima linha no último exemplo no link acima,
deve ser o suficiente para desencadear a impressão em si:
win32api.ShellExecute (0, "print", pdf_file_name, None, ".", 0)

Se o restante do seu programa estiver ok, pode ser que isso aqui seja o suficiente:
import os
import win32api
import pathlib

...
loc = input('Localizacao: ')

#localizar pasta
floc = pathlib.Path(loc)

#Verifica todos arquivos .pdf que tem na pasta
try:
    os.mkdir(floc/"impressos")
except OSError:
    # pasta já existe
    pass
for file in glob.glob(floc/'*.pdf'):
    if(file != ''):
        os.startfile(file, 'print')
        print('Imprimindo arquivo.. ' + str(file))
        win32api.ShellExecute (0, "print", os.path.join(floc, file), None, ".", 0)
        x += 1
        time.sleep(2)
        os.rename(floc/file, floc/"impressos"/file)

Se o win32api para imprimir falhar, o caminho que eu tentaria aí é  é instalar o ghostview - http://pages.cs.wisc.edu/~ghost/ - em seguida experimentar e ver a documentação até encontrar uam forma para imprimir com o ghostview a partir de uma linha de comando - e aí usar o o módulo subprocess do Python para chamar o ghostview com a linha de comando para imprimir cada arquivo.
(uma dica a parte: evitar usar o os.chdir e esperar que as coisas funcionem depois - o ideal é sempre concatenar o nome da pasta ao do arquivo antes de cada operação com arquivos: em scripts pequenos não tem tanto problema - mas em sistemas maiores o "current work dir" é global para a aplicação, em todas as threads e é muito pouco confiável. )
(Se a pathlib não funcionar por conta da sua versão do Python, use os.join.path acima)
Uma outra dica legal aí: No Windows, aplicações de terminal são extremamente desconfortáveis. O Python já vem com ferramentas para criar aplicações gráficas que são bem simples de usar - o que dá trabalho realmente é construir uma aplicação mais sofisticada.
Mas nesse caso, você só precisa de uma pasta, e ficar monitorando a mesma para ver se aparecem mais arquivos - em caso positivo, disparar a impressão.  Criar o app inteiro não posso - mas experimente aí, em vez do input usar isso:
from tkinter import filedialog

loc = filedialog.askdirectory()

Você pode por o o laço que verifica arquivos no seu script numa função, e chamar essa função com o método after da sua janela a cada dois segundos, por exemplo - dessa forma qualquer arquivo colocado lá vai ser impresso.
Apesar da maior parte dos tutorias criar uma classe que herda de tkinter.frame, isso não é necessário: seu programa pode estar numa função normalizinha e simplesmente chamar tkinter.Tk() para ter uma janela.
A estrutura ficaria mais ou menos
<importacoes>

pasta = ""

def principal():
    global pasta, janela
    janela = Tkinter.Tk()
    # criar Labels para conter o nome da pasta, mensagens de impressao
    ...
    botao = tkinter.Button(janela, text="Mudar pasta...", command="seleciona_pasta")
    # chama a funcao imprime em 2 segundos:
    janela.after(2000, imprime)

def imprime():
    # basicamente o mesmo código que está na versão de terminal
    # sem o input - a pasta vem na variável global "pasta"
    ...
    # se chama de volta (opcional)
    janela.after(2000, imprime)

def mudar_pasta():
    global pasta
    pasta = filedialog.askdirectory()
    # atualizar label com o nome da pasta atual.

principal()


MySQL router in K8 gets connection overflow

Question: I had successfully deployed MySQL router in Kubernetes as described in this answer.
But recently I noticed mysql router was having overflow issues after some time.
Starting mysql-router.
2022-03-08 10:33:33 http_server INFO [7f2ba406f880] listening on 0.0.0.0:8443
2022-03-08 10:33:33 io INFO [7f2ba406f880] starting 4 io-threads, using backend 'linux_epoll'
2022-03-08 10:33:33 metadata_cache INFO [7f2b63fff700] Starting Metadata Cache
2022-03-08 10:33:33 metadata_cache INFO [7f2b63fff700] Connections using ssl_mode 'PREFERRED'
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700] Starting metadata cache refresh thread
2022-03-08 10:33:33 routing INFO [7f2b617fa700] [routing:myCluster_ro] started: listening on 0.0.0.0:6447, routing strategy = round-robin-with-fallback
2022-03-08 10:33:33 routing INFO [7f2b60ff9700] [routing:myCluster_rw] started: listening on 0.0.0.0:6446, routing strategy = first-available
2022-03-08 10:33:33 routing INFO [7f2b3ffff700] [routing:myCluster_x_ro] started: listening on 0.0.0.0:64470, routing strategy = round-robin-with-fallback
2022-03-08 10:33:33 routing INFO [7f2b3f7fe700] [routing:myCluster_x_rw] started: listening on 0.0.0.0:64460, routing strategy = first-available
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700] Potential changes detected in cluster 'myCluster' after metadata refresh
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700] Metadata for cluster 'myCluster' has 1 replicasets:
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700] 'default' (3 members, single-primary)
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700]     node3.me.com:3306 / 33060 - mode=RW
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700]     node2.me.com:3306 / 33060 - mode=RO
2022-03-08 10:33:33 metadata_cache INFO [7f2b9c2c8700]     node1.me.com:3306 / 33060 - mode=RO
2022-03-08 10:33:33 routing INFO [7f2b9c2c8700] Routing routing:myCluster_x_rw listening on 64460 got request to disconnect invalid connections: metadata change
2022-03-08 10:33:33 routing INFO [7f2b9c2c8700] Routing routing:myCluster_x_ro listening on 64470 got request to disconnect invalid connections: metadata change
2022-03-08 10:33:33 routing INFO [7f2b9c2c8700] Routing routing:myCluster_rw listening on 6446 got request to disconnect invalid connections: metadata change
2022-03-08 10:33:33 routing INFO [7f2b9c2c8700] Routing routing:myCluster_ro listening on 6447 got request to disconnect invalid connections: metadata change
2022-03-08 14:59:30 routing WARNING [7f2b9d2ca700] [routing:myCluster_rw] reached max active connections (512 max=512)
2022-03-08 14:59:30 routing WARNING [7f2b9d2ca700] [routing:myCluster_rw] reached max active connections (512 max=512)

We have innodb cluster (MySQL 8)  and router is connected to it.
When I check show processlist in master node :
| 6176344 | routeruser                  | 192.168.10.6:61195 | my_db | Sleep   |   23946 |                                                          | NULL
|
| 6176345 | routeruser                  | 192.168.10.6:62671 | my_db | Sleep   |   23946 |                                                                | NULL
|
| 6176346 | routeruser                  | 192.168.10.6:65531 | my_db | Sleep   |   23946 |                                                                | NULL
|
| 6176347 | routeruser                  | 192.168.10.6:39541 | my_db | Sleep   |   23946 |                                                                | NULL                          |
| 6176348 | routeruser                  | 192.168.10.6:34074 | my_db | Sleep   |   23946 |                                                                | NULL

I had stopped all custom applications running in K8,but still I got this issue.
In /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
datadir     = /var/lib/mysql
log-error   = /var/log/mysql/error.log
log_timestamps='SYSTEM'
max_connections = 1000

What am I missing here? why router service overflow after working few hours? Any help to solve/further debug this issue is highly appreciate.
Answer:
Why router service overflow after working few hours?

From what I know, you would modify the max_connection setting at mysqld section in your MySQL configuration file. You could determine where the location of the configuration file is by running command:

mysqld --help --verbose

After modify don't forget about restart your MySQL server.
You have to set $defaultvalue  as the your desired value how it writes in MySQL documentations:

Default Value = 512,
Minimum Value = 1,
Maximum Value = 9223372036854775807

And also look in max_total_connections parameter at the same file.
Comment: @Sachith Muhandiram Hello, did this answer help you? Do you still need help with it issue?
Comment: @Sachith Muhandiram Can you try to add `max_total_connections = 1000` parameter in In `/etc/mysql/mysql.conf.d/mysqld.cnf` file?
Comment: Yes, its set for 1000
Comment: No, this did not help, as details are same as given.
Comment: This is not an issue with MySQL. It has available connections 1000. This issue is with MySQL-router


unramified quadratic extension of number field

Question: I try to understand the following statement
There are only finitely many quadratic unramified extension of a number field $K$
I know by Kummer theory that such extensions are of the form $K(\sqrt{a})$ for some $a \in K$ such that $a$ generates $K^*/(K^*)^2$. But I can't figure out how to use this to show the claim.
Comment: Are you familiar with the Hilbert class field?
Comment: Exactly (and, of course, any quadratic extension $L/K$ is abelian).
Comment: @JyrkiLahtonen One can just replace 'Hilbert class field' with 'Narrow class field' which is finite—its Galois group is an extension of $\mathrm{Cl}(K)$ by a finite product of $\mathbb{Z}/2\mathbb{Z}$s.
Comment: I've just read the definition, and this seems answer my question since it has finite degree over $K$, isn't it?
Comment: Minor remark: Hilbert class field also needs "unramified at infinite places". IOW all the real embeddings of $K$ need to extend to real embeddings of $H$. This need for extra care may or may not arise depending on $K$.
Comment: Thanks, @AlexYoucis. I really need to learn that stuff. If only my learning curve still...
Answer: One can prove this directly:
Firstly, as noted by the OP, Kummer theory says that a quad. ext. is of the form $K(\sqrt{a})$ for $a \in K^{\times}/(K^{\times})^2.$
However, the condition for this extension to be unram. is mis-stated.
If $\mathfrak p$ is a prime of odd residue characteristic, then $K(\sqrt{a})$ is unramified at $\mathfrak p$ if and only if $v_{\mathfrak p}(a)$ is even.
If $\mathfrak p$ has even residue characteristic, then the condition that
$v_{\mathfrak p}(a)$ be even is necessary, but not sufficient, for $K(\sqrt{a})$ to be unramified at $a$.
One way to exploit this information is as follows:
There is a natural map
$$K^{\times}/(K^{\times})^2 \to \oplus_{\mathfrak p} \mathbb Z/2\mathbb Z$$
(the sum begin taken over all primes)
given by $a \mapsto (v_{\mathfrak p}(a) \bmod 2)$, and the $a$ we are interested in lie in the kernel of this morphism.  Thus, if we can show this kernel is finite, we'll be done.
To analyze this kernel, let's begin with a basic exact sequence:
$$ 1 \to \mathcal O_K^{\times} \to K^{\times} \to \oplus_{\mathfrak p} \mathbb Z \to \mathrm{Cl}_K \to 0.$$
Note that $\oplus_{\mathfrak p} \mathbb Z$ is just another way of describing the group of fractional ideals, and so the maps here are the obvious ones: the inclusion of $\mathcal O_K^{\times}$ into $K^{\times}$, the map sending an element of $K^{\times}$ to the corresponding fractional ideal, and the map sending a fractional ideal to the corresponding ideal class.
First, if $\mathrm{Cl}_K$ were trivial, we would see (by tensoring this exact sequence with $\mathbb Z/2\mathbb Z$) that
$\mathcal O_K^{\times}/(\mathcal O_K^{\times})^2$ surjects onto the kernel we're interested in.  But this quotient is finite (as $\mathcal O_K^{\times}$ is f.g.), and hence so is the kernel we're interested in.
In general, $\mathrm{Cl}_K$ is finite, and so a little bit of homological argumentation shows that the cokernel of the induced map from
$\mathcal O_K^{\times}/(\mathcal O_K^{\times})^2$ to the kernel of interest is finite.  This again implies that the kernel of interest is finite.

This argument illustrates in a special case the Kummer theory arguments that appear in the proofs of class field theory.
Comment: I apologize for giving what is essentially the same answer as yours—I just thought a different (more 'geometric') perspective would be helpful!
Answer: Here is a proof similar to tracing's but phrased in slightly different language, and which shows that, in fact, $K$ has only finitely many quadratic extensions unramified outside of primes over $2$.
Namely, let $U$ be $\mathrm{Spec}(\mathcal{O}_K)-S$, where $S$ is the set of primes lying over $2$. In other words, $U=D(2)$, and so is just $\mathrm{Spec}(\mathcal{O}_K[\frac{1}{2}])$. Note then that we have a surjection
$$\mathrm{Cl}(\mathcal{O}_K)\to \mathrm{Cl}(U)$$
and so $\mathrm{Cl}(U)$ is finite (this also just follows since it's a ring of $S$-integers, and so one can use the generalized version of the finiteness of the class number). In particular, we se that $\mathrm{Cl}(U)[2]$ is finite.
So then, note that from Kummer theory we have a short exact sequence
$$1\to \mathbf{G}_m(U)/\mathbf{G}_m(U)^2\to \mathrm{Hom}_\mathrm{cont.}(\pi_1(U),\mathbb{Z}/2\mathbb{Z})\to \mathrm{Pic}(U)[2]\to 1$$
But, $\mathrm{Pic}(U)[2]=\mathrm{Cl}(U)[2]$ is finite, and $\mathbf{G}_m(U)/\mathbf{G}_m(U)^2$ is finite by the generalized version of Dirichlet's unit theorem (again, it's just a ring $S$-integers).
Thus, we see that $\mathrm{Hom}_{\mathrm{cont.}}(\pi_1(U),\mathbb{Z}/2\mathbb{Z})$ is finite. But, this is precisely the set of quadratic extensions $L/K$ unramified outside of $S$ (i.e. unramified outside of primes dividing $2$). So, evidently the set of quadratic extensions unramified everywhere is finite.
Of course, note that if $K\supseteq\mu_n(\overline{K})$ the above proof goes through to work for degree $n$ unramified abelian extensions.


Derivative of a function with modulus terms.

Question: Please any one help me in calculation of $f(x)$, where $f(x)=-i\hbar\frac{\partial}{\partial x}\left(e^{-\frac{\left|x\right|}{a}}\right)$. Here $\hbar$ and $a$ is constant. Also scetch the $f(x)$.
Comment: Can you please add your own efforts? I mean what you have true till now?
Answer: $f(x)=-i\hbar\frac{\partial}{\partial x}\left(e^{-\frac{\left|x\right|}{a}}\right)$
It is sufficient to apply chain rule.
$\newcommand{\sign}{\text{sign }}$
$f(x)=-i\hbar e^{-\frac{\left|x\right|}{a}}\cdot\left(-\frac{1}{a}\sign x\right)=i\frac{\hbar}{a}(\sign x)e^{-\frac{\left|x\right|}{a}}\\\forall x\in\mathbb{R}\land x\ne0$
where $\;\sign x= \left \{ \begin{array}{rl}
1\;\;\;\;\;\text{ if }x>0\\
-1\;\;\;\;\;\text{ if }x<0
\end{array}
\right.$
$f(x)$ is not defined at $x=0$ and
$\lim_\limits{x\to0^-}f(x)=-i\frac{\hbar}{a}$ ,
$\lim_\limits{x\to0^+}f(x)=i\frac{\hbar}{a}$ .
The graph of the function $f(x)$ for $a=1.86$ is the following:
Answer: Let, $\psi(x)=e^{-\frac{\left|x\right|}{a}}$. So according to the question,
$$f(x)=\widehat{P}_x\psi(x)=-i\hbar \frac{\partial}{\partial x}\left(e^{-\frac{\left|x\right|}{a}}\right)$$
Now we can consider that $\left|x\right|=\sqrt{x^2}$. By considering this identity $f(x)$ can be rewritten as,
$$f(x)=-i\hbar \frac{\partial}{\partial x}\left(e^{-\frac{\sqrt{x^2}}{a}}\right)$$
Now it is sufficient to apply chain rule for the calculation of $f(x)$-
$$f(x)=-i\hbar \cdot \left(-\frac{1}{a}\right)\cdot \left(e^{-\frac{\sqrt{x^2}}{a}}\right)\cdot \left(\frac{1}{2\sqrt{x^2}}\right)\cdot \left(2x\right)$$
$$\Rightarrow f(x)=\frac{i\hbar}{a}\cdot\frac{x}{\sqrt{x^2}}\cdot \left(e^{-\frac{\sqrt{x^2}}{a}}\right)$$
$$\Rightarrow f(x)=\frac{i\hbar}{a}\cdot\frac{x}{\left|x\right|}\cdot \left(e^{-\frac{\left|x\right|}{a}}\right)$$
So, $f(x)$ exists for $\forall x \in \mathbb{R} \wedge x \neq 0$
So, $f(x)$ is not defined only at $x=0$ and $\displaystyle{\lim_{x \to 0^+}} f(x)=\frac{i\hbar}{a}$, $\displaystyle{\lim_{x \to 0^-}} f(x)=-\frac{i\hbar}{a}$.
Now we will consider a variable transformation that is $x'=ix$, where $x'$ is a purely imaginary variable. So,
$$f(x')=\frac{\hbar}{a}\cdot\frac{x'}{\left|x'\right|}\cdot \left(e^{-\frac{\left|x'\right|}{a}}\right)$$
Now, a graphical representation of $f(x')$ vs. $x'$ is following-
Comment: Welcome to MSE: I suggest that you edit it, since there are some problems concerning MathJax.


Componentes React que recebem a propriedade de um objeto como conteúdo não atualizam, como lidar com isso?

Question: Basicamente tenho um estado que é um objeto complexo e vários componentes que renderizam apenas uma propriedade dele, como a aplicação é meio grande fiz este protótipo para ilustrar:
//Component principal que guarda um objeto como state
export default function App() {
  const [data, setData] = useState({
    count: 0,
    title: "generic title"
  });

  const handlerIncrementData = () => {
    const newData = data;
    newData.count = newData.count + 1;
    setData(newData);
  };

  return (

Contador: {data["count"]}

  );
}

Teoricamente toda vez que eu clicar no h2 o valor do count vai ser incrementado e, de fato, checando pelo React Dev Tools, ele está sendo, porém a renderização do componente não atualiza. Aparentemente o React não atualiza componentes que só usam uma propriedade do state. Estou fazendo algo errado ou isso faz parte da biblioteca? Caso seja, como posso contornar esse problema?
O código funciona perfeitamente usando um tipo primitivo no lugar do obj como state.
Answer: Esses dias teve o mesmo problema é uma pergunta, onde até relatei para o usuário que me perguntou sobre copiar o novo estado para o objeto, que no caso usei spread operator, pelo que entendo quando vai se alterar objeto(s) ou lista(s) precisa utilizar uma nova cópia do objeto e/ou lista para que o componente tenha essa nova realidade ou atualização da informação, exemplo:

//Component principal que guarda um objeto como state
function App() {
  const [data, setData] = React.useState({
    count: 0,
    title: "generic title"
  });

  const handlerIncrementData = () => {
    let { count } = data;
    count ++;
    setData({...data, count});
  };

  return (

Contador: {data["count"]}

  );
}
ReactDOM.render( <App/> , document.getElementById('root'));

Referencias:

Using the spread operator in React setState
Updating an object with setState in React
Remover Todo de uma lista
Comment: Muito obrigado, eu to fazendo uma aplicação meio grande e demorei pra perceber que alguns componentes não tavam funcionando, ja tava com medo de ser tarde demais pra mudar algo, enfim, valeu mesmo.
Answer: Conforme consta na documentação do hook useState, o React utiliza o método estático Object.is para determinar se dois valores são iguais. O componente só será atualizado caso a desigualdade entre os valores seja confirmada.
A comparação feita pelo Object.is é muito similar ao operador ===. A diferença é que, para Object.is, dois valores NaN são considerados iguais e +0 e -0 são considerados diferentes.[1]
Desse modo, precisamos lembrar que, para o === (e portanto para o Object.is também), dois objetos são iguais se possuirem a mesma referência. Veja:

const obj = { name: 'Foo' };
const b = obj; // Mesma referência.

console.log(Object.is(obj, b)); //=> true

// Mesmo se alterarmos em `b` (ou em `obj`), a igualdade manter-se-á:
b.name = 'Bar';

console.log(Object.is(obj, b));

Agora veja o que você está fazendo no seu componente:

const newData = data;
newData.count = newData.count + 1;
setData(newData);

Já deu pra ver o problema, certo? :)
Veja que você está atribuindo à newData a referência do objeto data (a atribuição de objetos não cria uma "cópia", apenas a referência é atribuída). Desse modo, você não tem um novo objeto, mas sim o mesmo objeto!
Portanto, mesmo que você modifique uma das propriedades do objeto newData (que é o mesmo que data), o algoritmo de Object.is ainda determinará que são o mesmo objeto do estado anterior (já que, como vimos, essa comparação é feita com base na referência).
Enfim, para corrigir, você deve garantir que está passando um novo objeto (isto é, de diferente referência) para a função setData.
Uma forma de fazer isso é utilizar o spread operator para espalhar as propriedades em um novo literal (conforme sugeriu a outra resposta):
const handlerIncrementData = () => {
  const { count } = data;
  count++;

  // Note abaixo que um **novo** literal está sendo criado (portanto, diferente referência):
  setData({ ...data, count });
};

Uma outra opção é utilizar o Object.assign, passando um novo objeto em seu primeiro argumento:
const handlerIncrementData = () => {
  // Novo objeto sendo utilizado como "base":
  //                    ↓↓
  setData(Object.assign({}, data, { count: data.count + 1 }));
};

Em suma: para que o componente seja renderizado novamente, você há de garantir que o valor que está passando é diferente do valor anterior (de acordo com a comparação de Object.is). No caso de objetos, basta assegurar que a referência é diferente.
É justamente por isso que funciona se utilizar um primitivo ao invés de objeto. Primitivos são comparados por valor; enquanto objetos, por referência.
Para saber mais sobre as diferenças sobre o spread operator em objetos e Object.assign, leia Qual é a diferença entre Object.assign e spread operator?.
Comment: resposta perfeita, muito obrigado pela atenção