unable to check and create aws security group with boto3

Question: I'm trying to create a security groups and get the secutity group id as output using boto3. I want something like this:

If the security group exists, get/return/output the groud id.
If the security group doesn't exists create and authorize the group with the given rule and output the group id

This is my code so far:
ec2 = boto3.client('ec2', region_name='us-east-1')
for rds_security_group in ec2.describe_security_groups()['SecurityGroups']:
    if rds_security_group['GroupName'] == 'testgroup':
         print(rds_security_group['GroupId'])
         return (rds_security_group['GroupId'])
     else:
          rds_security_group_name = ec2.create_security_group(
                GroupName='testgroup',
                Description='rds-security-group',
                VpcId='vpc-12345')
          client.authorize_security_group_ingress(
                CidrIp=10.10.10.10/11,
                IpProtocol='tcp',
                FromPort=90,
                ToPort=90,
                GroupId=rds_security_group_name['GroupId'])
          print(rds_security_group_name['GroupId'])
          return(rds_security_group_name['GroupId'])

if security group doesn't exists code works perfectly by creating the group and returns the group id. but fails to return the group id if the security group already exists and throws up the existing error.
botocore.exceptions.ClientError: An error occurred (InvalidGroup.Duplicate) when calling the CreateSecurityGroup operation: The security group 'testgroup' already exists for VPC 'vpc-12345'
please help me on this ?
Answer: Your problem is that you are looping thru each security group and checking its group name. If the first security group is not called "testgroup" then you try to create it. Change your code to the following:
ec2 = boto3.client('ec2', region_name='us-east-1')
for rds_security_group in ec2.describe_security_groups()['SecurityGroups']:
    if rds_security_group['GroupName'] == 'testgroup':
         print(rds_security_group['GroupId'])
         return (rds_security_group['GroupId'])

# Security Group was not found, create it
rds_security_group_name = ec2.create_security_group(
      GroupName='testgroup',
      Description='rds-security-group',
      VpcId='vpc-12345')
client.authorize_security_group_ingress(
      CidrIp=10.10.10.10/11,
      IpProtocol='tcp',
      FromPort=90,
      ToPort=90,
      GroupId=rds_security_group_name['GroupId'])
print(rds_security_group_name['GroupId'])
return(rds_security_group_name['GroupId'])

Comment: Thanks for the comment. But i did find the answer myself with simple chnage in the above code.
Comment: Post your solution.
Comment: i will certainly give it a try with your solution and will upvote if it goes well
Answer: ec2 = boto3.client('ec2', region_name='us-east-1')
for rds_security_group in ec2.describe_security_groups()['SecurityGroups']:
    if rds_security_group['GroupName'] == 'testgroup':
         print(rds_security_group['GroupId'])
         return (rds_security_group['GroupId'])
else:
     rds_security_group_name = ec2.create_security_group(
          GroupName='testgroup',
          Description='rds-security-group',
          VpcId='vpc-12345')
     client.authorize_security_group_ingress(
           CidrIp=10.10.10.10/11,
           IpProtocol='tcp',
           FromPort=90,
           ToPort=90,
           GroupId=rds_security_group_name['GroupId'])
     print(rds_security_group_name['GroupId'])
     return(rds_security_group_name['GroupId'])

I did find answer to my question with slight change in the existing code its self
Comment: What is the change other than formatting which does not even look right?
Comment: @MichaelR `else` is not paired with `if` but with `for`, i. e. the "else commands" are executed iff no `break` happened in the `for` loop. Where `break` is not part of the code a "for-else" should be avoided. If the `if` condition in the loop triggers then the method returns (or fails) and "for-else commands" cannot be reached. John Hanley's solution should be preferred.


Client side event that fires after ASPxClientGridView.ApplyFilter performs its work

Question: This link explains how to handle it on the server side via the ASPxGridView.AfterPerformCallback event:
http://www.devexpress.com/Support/Center/p/Q274366.aspx
How can I handle it on the client side?
I am working on a custom server control and I have this client side function on my control:
    applyFilterToGridView: function () {
        this.theGridView.ApplyFilter(this.filterCondition);
        this.filterAppliedEvent();
    }

Because ApplyFilter does a callback, this.filterAppliedEvent() is not called at the right time which should be after the filtering is complete. this.filterAppliedEvent() is a client side function.
This event is fired after the filter is applied:
protected void theGridView_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            if (e.CallbackName == "APPLYFILTER")
            {
            }
        }

Is there some way to to tell the client to call filterAppliedEvent from the AfterPerformCallback event?
I would prefer to be able to run this.filterAppliedEvent() after AfterPerformCallback on the client side if possible.
Thanks in advance.
EDIT ( Solution thanks to Filip ):
C#:
  protected void theGridView_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            if (e.CallbackName == "APPLYFILTER")
            {
                ASPxGridView gv = sender as ASPxGridView;
                gv.JSProperties["cp_FilterApplied"] = "true";
                gv.JSProperties["cp_VisibleRowCount"] = gv.VisibleRowCount;
            }
        }

theGridView.ClientSideEvents.EndCallback = "function(s,e){"theGridView.theGridView_OnEndCallback(s, e);}";

JS:
theGridView_OnEndCallback: function (s, e) {
    if (s.cp_FilterApplied) {
        if (s.cp_FilterApplied.indexOf('true') != -1) {
            this.adjustGridViewSize();/*Uses visible row count.*/
            delete s.cp_FilterApplied;
        }
    }
}

Answer:
In theGridView_AfterPerformCallback add entry to JSProperties collection, e.g. cp_FilterApplied.
Add EndCallback client side event handler.
In EndCallback handler execute this.filterAppliedEvent() if cp_FilterApplied exists.
Delete that property so that subsequent callback doesn't execute filterAppliedEvent method.

Look at my answer to this question for code example.
It's really the same problem, just set js property in theGridView_AfterPerformCallback instead of ASPxGridView1_RowUpdated and adjust names/js code to your needs.
Comment: Worked perfectly! Thanks! I will update my question with the solution code.
Comment: you guys rock! For some reason, ClientEnabled property needs to be set to true from clientside atleast once per postback, for it to work correctly. It's kinda weird, but I ended up using JSProperties to set ClientEnabled = true in my code!


Linear programming combination of variables

Question: I am trying to formulate the following linear programming problem.
My inputs are the following:

A set of $N$ tables $\Pi_1, \dots, \Pi_N$
A cost budget $G$

I have the following decision variables:

$X_i$, $i \in [1, N]$ for whether or not we will perform transformation $X$ on table $\Pi_i$
$Y_i$, $i \in [1, N]$ for whether or not we will perform transformation $Y$ on table $\Pi_i$
$Z_i$, $i \in [1, N]$ for whether or not we will perform transformation $Z$ on table $\Pi_i$

The objective function is as follows:
min: $A_i\cdot X_i + B_i \cdot Y_i + C_i \cdot Z_i + D_i \cdot X_i + E_i \cdot Y_i + F_i \cdot Z_i$
where $A_i, B_i, C_i$ constants that influence the runtime of the original workload and $D_i, E_i, F_i$ calculate the runtime of the transformation.
And here are my constraints:

$X_i, Y_i, Z_i \in \{0, 1\}$
$Y_i + Z_i \leq 1$ as we do not want to both perform transformation $Y$ and $Z$ on a table
$Y_i \leq X_i$, as we have an advantage by applying transformation $Y$ only if we have performed transformation $X$ first
$T_i\cdot X_i + U_i\cdot Y_i + V_i\cdot Z_i \leq G$, where $G$ is a cost budget and $T_i, U_i, V_i$ is the cost of a transformation $X_i, Y_i, Z_i$ for $\Pi_i$ respectively.

My problem is the following: If we apply more than one transformations on a table, let's say $X$ and $Z$ for convenience then we have a discount factor, meaning that we won't have to pay both $A_i$ and $C_i$ runtime wise and $T_i$ and $V_i$ cost-wise. We will have a constant that is smaller than the sum of these two constants. I can calculate how much smaller this would be. How can we represent this in the problem? Should I have combined variables $XY$, $XZ$, $YZ$, $XYZ$ that are indicator variables that represent the combinations? Or is there another way to solve this type of linear programming problems?
Thanks a lot
Answer: Out of the $2^3=8$ combinations $(X_i,Y_i,Z_i)$, only $5$ are feasible:
\begin{matrix}
X_i & Y_i & Z_i \\
\hline
0 & 0 & 0 \\
0 & 0 & 1 \\
1 & 0 & 0 \\
1 & 0 & 1 \\
1 & 1 & 0
\end{matrix}
So introduce binary variables $w_{ij}$ for $i\in\{1,\dots,N\}$ and $j\in\{1,\dots,5\}$, precompute the objective coefficients $c_{ij}$ and constraint coefficients $a_{ij}$, and minimize $\sum_{i,j} c_{ij} w_{ij}$ subject to linear constraints
\begin{align}
\sum_j w_{ij} &= 1 &&\text{for all $i$} \\
\sum_{i,j} a_{ij} w_{ij} &\le G
\end{align}
Comment: Thanks! That's what I ended up doing.
Answer: It seems you need a binary variable for each table, that is $0$ if no transformation happened, and $1$ if at least 1 transformation happened. equivalently you mean :
$$
\gamma_i \equiv X_i \lor Y_i \lor Z_i \quad \forall i.
$$
So this can be added to model by
$$
X_i \leq \gamma_i \\
Y_i \leq \gamma_i \\
Z_i \leq \gamma_i \\
\gamma_i \leq X_i+Y_i+Z_i.
$$
These constraints force $\gamma_i$ to be 1 if even one of transformations is supposed to apply. and make it $0$ if $X_i=Y_i=Z_i=0$.
therefore in cost function and runtime budget just use $\gamma_i$ for table $i$ instead of all transformation variables.
Comment: if for constant $i$ , $A_i$, $B_i$ and $C_i$ are not same so it means it's important which combination of transformations are applied. and if you apply for example $X_i$ and $Y_i$ but the runtime isn't $A_i+B_i$ so it means the optimization model is not correct for problem and you should break the problem into more microstate detailed cases. for example for Table $i$ the states are $\{ 0,X_i,Y_i,Z_i,X_iY_i,X_iZ_i,Y_i,Z_i,X_iY_iZ_i \}$. and you should define a cost (and budget) for each one of these 8 states!
Comment: Thanks! Then how should I incorporate the constants if multiple transformations are applied to a table? Because the $A_i$ for example is different if we apply only $X_i$ or $X_i$ and $Y_i$ together.
Answer: If i understand your problem you may need binary variables like $ \delta_{i,xy},\delta_{i,xz},\delta_{i,yz}$ and following constraints
$ x_i + y_i -1 \le \delta_{i,xy}$  (1)
$ \delta_{i,xy} \le x_i$  (2)
$ \delta_{i,xy} \le y_i$  (3)
Likewise for $ \delta_{i,yz}, \delta_{i,xz}$ assuming your $ x,y,z$ are binary.
So your $ \delta_{xy} = 1$ only when corresponding variables $ x,y = 1$
If $ x,y,z$ are continuous then constr (1) can be
$ x_{i}+y_{i}-M \le M\delta_{i,xy}$ where $x_i, y_i \le M \le max(x_i+y_i,0)$
Assuming $ ab$ is your discount cost, in your objective you can replace $ x,y$ part with
$ a_i(x_i-\delta_{i,xy}) + b_i(y_i -\delta_{i,xy}) + ab\delta_{i,xy}$+.....continue with $c,d,e,f$ with $ \delta_{xz},\delta_{yz}$,


How to get the label values for list fields in Twig?

Question: I'm trying to fetch the label of the list and display it on the twig template.
Using node.field_list.value outputs the key value. I tried using node.field_list.label but it returns empty. I tried using node.field_list.title, node.field_list.0.label or node.field_list[0]['#markup'] but it still returns empty on the twig template
Comment: Ah, I understand your question properly now from the accepted answer, I was thinking of the field label rather than the human names for the values.
Answer: There are a few ways:
It calls List allowed values and it stores in the field configuration.
When field cardinality is 1

  {% set list_value = node.filter_list.value %}
  {{ node.filter_list.getSetting('allowed_values')[list_value] }}

When field cardinality is more than 1

  {% set allowed_values = node.filter_list.getSetting('allowed_values') %}
  {% set list_values = node.filter_list.getValue() %}
  {% for list_value in list_values %}

      {{ allowed_values[list_value['value']] }}

  {% endfor %}

In case when your template is node.html.twig you can render it based on field formatter in your view mode.

  {{ content.filter_list }}

Comment: @clestcruz good point, I updated my answer
Comment: Thanks, but what if the field is set to `unlimited` and not to `limited`? I tried this `{% set list_value = node.field_list.value %}

                {% for list in node.field_list.getSetting('allowed_values')[list_value] %}

                {{ list }}

                {% endfor %}`

but it does not seem to output anything on the loop
Comment: Hmm I tried your solution but nothing seems to output within the twig template
Comment: @clestcruz ahh yes, ->value returns only single value, I updated answer, try one more time
Answer: Here is how I've been able to display the label of a Single Choice Text List inside a custom Entity referenced on a node with an EntityReference field :
{% for entity_ref_item in node.field_my_entity_ref_field %}
  {% set my_choice_key = entity_ref_item.entity.field_my_list_field.value %}
  {% set my_choice_label = entity_ref_item.entity.field_my_list_field.getSettings('allowed_values')['allowed_values'][my_choice_key] %}

{{ my_choice_label }}

{% endfor %}

I believe that Alex Kuzava's code might have been missing one array ['allowed_values']
{{ node.filter_list.getSetting('allowed_values')[list_value] }}

might need to be
{{ node.filter_list.getSetting('allowed_values')['allowed_values'][list_value] }}

instead.
To be sure, you can use devel kint()
{{ kint(node.filter_list.getSetting('allowed_values'))}}

That's how I found out there was one more array level before getting to the label. But maybe my situation was different because I am accessing a custom entity...
Answer: You can use the module Twig Field Value to help with this task. Once installed the code:
{{ content.field_list|field_label }}

should display the label. The way the label is stored and accessed not affected by the field's cardinality.
Comment: I tried using `Twig Field Value` to output the value as you mentioned but it only returns empty. I even tried `{{ node.field_list.value|field_label }}`
Comment: Try using "content" instead of "node". I just checked the comments in the base node template and that's the correct way to get rendered field data.
Comment: Yah I tried that also, the thing it is rendered within `page.html.twig`
Comment: In page.html.twig? That's not where you'd normally render field data directly. If you need to go off-piste it would be better to sort out your data in a preprocess hook instead.
Answer: I'm using Drupal9 and did the same as @alex_kuzava. But got a problem with the key, seems that it was an array or something. So this is my answer:
{% set list_key = node.field_location_tag[0].value %}
{% set list_value = node.field_location_tag.getSetting('allowed_values')[list_key] %}
{{ list_value }}

Notice the [0] before field_location_tag. I don't really know whats happening here but my first clue was that list_key wasn't a string. So I try to apply the |string filter and Drupal told me that I was trying to do an array to string transformation.
I guess is something to do that the content I'm getting is from a lists of nodes inside a paragraphs that are loaded using \Drupal\node\Entity\Node::loadMultiple($nids);
Or maybe that I'm using the language module. Somehow the value is converted to an array first.
Answer: Adding a PHP code solution since Search Engines are leading here
private function getListTypeValue($node, $fieldName) {
  $listField = $node->get($fieldName);
  return $listField->getSettings()['allowed_values'][$listField->value] ?? '';
}


independent censoring

Question: Independent censoring is one of the fundamental assumptions in the survival analysis. However, I cannot find any test for it or any paper which discusses how real that assumption is. I would be grateful if anybody could point me to some useful references. I have found the following paper as an interesting reference but it is not freely available.
Leung, Kwan-Moon, Robert M. Elashoff, and Abdelmonem A. Afifi. "Censoring issues in survival analysis." Annual review of public health 18.1 (1997): 83-104.
Any feedback would be much appreciated.
Kind regards
DK
Comment: Kalbfleisch and Prentice (2002) The Statistical Analysis of Failure Time Data, is a classical textbook on survival analysis.
Answer: Independent censoring is the requirement that the hazard rate of an at-risk
subject coincides with the hazard rate in the surviving population, i.e.
$$
\lim_{\Delta t \rightarrow 0} \frac{\Pr \Big( t \leq T < t + \Delta t \,\Big|\, T \geq t, \, C \geq t \Big)}{\Delta t}
 = \lim_{\Delta t \rightarrow 0} \frac{\Pr \Big( t \leq T < t + \Delta t \,\Big|\, T \geq t \Big)}{\Delta t}
$$
This requirement essentially means that the uncensored subjects under
follow-up must be representative of the surviving population; a condition
that is satisfied when censoring occurs independently of the survival
time (e.g., censoring due to calendar termination of the study). If there
are covariates, then the independent censoring assumption is made conditional
on the covariate information.
Comment: Thank you Ocram for your reply. Much appreciated. However, I am not sure that I can agree with you. If I am not mistaken, your equation shows that survival time does not depend on censoring time, but not the other way around. In my opinion, your equation does not show that censoring time is independent of survival time. The independent censoring means that both variables (survival time, censoring time) are independent.
Comment: If Pr(A|B) = Pr(A) then Pr(B|A) = Pr(B).
Comment: The above equation is not Pr(A|B)=Pr(A) but Pr(X|A,B) = Pr(X|A). I argue that if Pr(X|A,B) = Pr (X|A) then it does not mean that Pr(X|B) = Pr(X|B,A)
Comment: In your notations, Pr(X|A,B) = Pr (X|A) means that the probability to die at time t does not depend on the censoring status at time t. This is non-informative censoring. On the other hand, Pr(X|A,B) = Pr(X|B) would mean that the probability to die at time t does not depend on the surviving status at time t. Of course, the probability to die does depend on the surviving status. Am I missing something to your point??
Comment: Thank you very much for looking at this problem with me. You have excellently explained the difference between non-informative and independent censoring in a previous post http://stats.stackexchange.com/questions/22497/problem-with-informative-censoring/22605#22605 However, my problem is the above equation in your answer. I might be wrong, but from it I can only conclude that survival times do not depend on censoring times, but not the other way around. In short, in your answer you have italic section "a condition,,," with which I have difficulty of agreeing.
Comment: If T and C are independent, then the above condition is satisfied. I.e., if censoring occurs independently of the survival time (or other way around), then the above condition is satisfied.
Comment: An attempted editor suggests the following reference for the claims in this answer: *The Statistical Analysis Failure Time Data*, 2e, Kalbfleisch & Prentice, 2002 ([pdf](https://pdfs.semanticscholar.org/7624/103ae633517b78510ee6619168ccdab881cd.pdf), page: 13).

independent censoring


Requiring config.js file in VSCode extension with absolute path (e.g. "C:\...") does not work

Question: I am developing the Argdown VSCode extension. The Argdown parser can be configured using either argdown.config.json files or argdown.config.js files exporting a config object. Using Javascript files is the easiest way to allow users to add custom plugins to the Argdown parser.
If the user tells the parser to use a Javascript file, the file is loaded using import-fresh, (which uses node's require, but deletes the cached version.
Using the Argdown commandline tool (@argdown/cli) this works fine, but in the VSCode extension the module of the config file can not be found. The extension is using absolute file paths to require the config module (e.g. "C:\Users\my-username\projects\my-argdown-project\argdown.config.js"). These paths work with import-fresh outside of the VScode extension.
Is there a security restriction for VSCode extensions that does not allow to require modules with absolute file paths? Or is there some other reason why this does not work?
Answer: This was not related to VSCode. The problem was caused by bundling up import-fresh with webpack. I thought that webpack would ignore dynamic imports, but it did not.
I was lucky: Since last month, webpack supports "magic comments" for require (not only for import). So I can use:
require(/* webpackIgnore: true */ file);

You have to activate magic comments support in your webpack config:
module.exports = {
    parser: {
      javascript: {
        commonjsMagicComments: true,
      },
    },
}

Now the next question is how to add the magic comments to the import-fresh package. For that I used the string-replace-loader:
module.exports = {
  module: {
    rules: {
      {
        enforce: "pre",
        test: /import-fresh[\/\\]index\.js/,
        loader: "string-replace-loader",
        options: {
          search:
            "return parent === undefined ? require(filePath) : parent.require(filePath);",
          replace:
            "return parent === undefined ? require(/* webpackIgnore: true */ filePath) : parent.require(/* webpackIgnore: true */ filePath);",
        },
      },
    }
  }
}

After that, I could load the argdown.config.js files again, even after bundling everything with webpack.


multivariate derivative of integrals

Question: Is it true that
\begin{align}
\frac{d^2}{dy_1dy_2}\left(\int_0^{f(y_2)}\int_0^{f(y_1)}g(x_1, x_2)dx_1dx_2\right)= f'(y_2)f'(y_1)g(y_1, y_2)
\end{align}?
Answer: No it's
$
f'(y_2)f'(y_1)g(f(y_1),f(y_2))
$ as a simple example shows
$$
\frac{d}{dx}\int_0^{x^2}\cos(y)dy=\frac{d}{dx}\left[ \sin(y) \right]_0^{x^2}=\frac{d}{dx}\sin(x^2)=2x\cos(x^2)
$$

multivariate derivative of integrals


Show data from database using ajax javascript

Question: I want to create form in popup and then show the result in the same popup. Data has been inserted, but after insert, the popup was close.
What I want is after submit form clicked, the data insert to database, and the result data show in same popup page.
Here's the view page

            <button type="button" class="close" data-dismiss="modal">×</button>

Category Product

            <form method="post" id="task-form">

                            Product Name

                            <input type="text" class="form-control" name="product_name" id="product_name">

                            Price

                            <input type="text" class="form-control" name="price" id="price">

                            <input type="hidden" id="category" name="category" value="">

                            <button type="submit" class="btn-primary" value="Submit" id="add_btn">Add Product</button>

            </form>

                        Product Name
                        Price

Here's controller
   public function add_product()
   {
       $product_name= $this->input->post('layanan');
       $price = $this->input->post('kapasitas');
       $category = $this->input->post('jenis');

       $data2 = array(
        'product_name' => $product_name,
        'price' => $price,
        'category' => $category
        );

        $this->product_model->input_product($data, db_prefix() . 'product');
        $data=$this->product_model->list_product($category);
        echo json_encode($data);
    }

Here's my model
public function input_product($data2,$table)
{
   $this->db->insert($table,$data2);
}

public function list_product($category){
    $abc=$this->db->query("SELECT * FROM tblcategory WHERE category='$category'");
    if($abc->num_rows()>0){
        foreach ($hsl->result() as $data) {
            $desc[]=array(
                'product_name'           => $data->product_name,
                'price'                  => $data->price,
            );
        }
    }
    return $desc;
}

Thank you
Comment: change button type from submit to button . overall it looks fine
Comment: Hi @AhmedSunny, the data result is not showing after I click the button, but yes, the data success go to database
Answer: 100% [ SOLVED ]
Here's view page

            <button type="button" class="close" data-dismiss="modal">×</button>

Category Product

            <form method="post" id="task-form">

                            Product Name

                            <input type="text" class="form-control" name="product_name" id="product_name">

                            Price

                            <input type="text" class="form-control" name="price" id="price">

                            <input type="hidden" id="category" name="category" value="">

                            <button type="button" class="btn-primary" value="Submit" id="add_btn">Add Product</button>

            </form>

                        Product Name
                        Price

Here's controller
public function add_product()
   {
       $product_name= $this->input->post('layanan');
       $price = $this->input->post('kapasitas');
       $category = $this->input->post('jenis');

       $data2 = array(
        'product_name' => $product_name,
        'price' => $price,
        'category' => $category
        );

        $this->product_model->input_product($data, db_prefix() . 'product');
        $data=$this->product_model->list_product($category);
        echo json_encode($data);
    }

Here's my model
public function input_product($data2,$table)
{
   $this->db->insert($table,$data2);
}

public function list_product($category){
    $abc=$this->db->query("SELECT * FROM tblcategory WHERE category='$category'");
    if($abc->num_rows()>0){
        foreach ($hsl->result() as $data) {
            $desc[]=array(
                'product_name'           => $data->product_name,
                'price'                  => $data->price,
            );
        }
    }
    return $desc;
}

I hope it's working well.
Thankyou
Comment: okay. please upvote my answer if you are satisfied with my answer


Como fazer Jquery datepicker aceitar apenas de meses e ano?

Question: Como posso converter meu jQuery datepicker para aceitar apenas meses e anos ?
Comment: Exemplo usando o jQueryUI datepicker: http://jsfiddle.net/DBpJe/5106/
Comment: você está usando esse datepicker https://jqueryui.com/datepicker/ ?
Answer: Para esse jQuery datepicker você pode fazer um hack que funciona da seguinte maneira:
Adiciona none na class CSS dos dias conforme abaixo:
<code>.ui-datepicker-calendar {
    display: none;
}
</code>
Logo depois você configura seu datepicker dessa maneira:
<code>$('.date-picker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function (dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
</code>
Segue o jsfiddle.
Comment: Boa ideia, o unico problema que vejo é caso haja outros datepickers na mesma página. Mas juntando uma `id` ou uma classe específica fica resolvido. `+1`
Comment: Muito bom era exatamente isso que precisava. Obrigado
Comment: Bem colocado @Sergio, vou colocar essa observação :))
Answer: Sei que foge um pouco da sua pergunta... mas utilizo seguinte plugin:
https://bootstrap-datepicker.readthedocs.org/en/latest/options.html#maxviewmode
Veja se é isso que vc precisa. Não tenho nada que reclamar dele... fora que ele é muito elegante!
Comment: Fiz alguns testes aqui com esse datepicker, alem de ele ser muito bonito funciona lindamente rs .. +1 :D
Answer: <code><script>
$(".datepicker" ).datepicker({
  startView: 1,
  minViewMode: 1,
  maxViewMode: 3,
  format: "mm-yyyy",
  changeMonth: true,
  changeYear: true
});
</script>
</code>


Relation between Fundamental theorem of calculus and the definition of the derivative

Question: What is the link/relation between the fundamental theorem of calculus and the definition of the derivative?
Comment: One link is that you have to know the definition of 'derivative" to understand the theorem.
Answer: The fundamental theorem of calculus states that given a continuous function $f:[a,b]\to\mathbb R$ which is differentiable on $(a,b)$, if we define $F:(a,b)\to\mathbb R$ by $$F(x)=\int_a^x f(t)\ \mathsf dt$$ then $F$ is differentiable and $F'=f$. By the definition of the derivative, this means that for $x\in(a,b)$, $$\lim_{y\to x}\frac{F(y)-F(x)}{y-x} = f(x). $$ To see this, given $\varepsilon>0$ we may choose $\delta>0$ so that $0<|y-x|<\delta$ implies $|f(y)-f(x)|<\varepsilon$ (by continuity of $f$). So when $0<|y-x|<\delta$,
\begin{align}
\left|\frac{F(y)-F(x)}{y-x} - f(x) \right| &= \left|\frac{\int_a^y f(t)\ \mathsf dt-\int_a^x f(t)\ \mathsf dt}{y-x}-\frac{f(x)(y-x)}{y-x} \right|\\ &= \left|\frac{\int_x^y f(t)\ \mathsf dt - \int_x^yf(x)\ \mathsf dt}{y-x} \right|\\ &= \left|\frac{\int_x^y f(t)\ \mathsf dt-\int_x^y f(x)\ \mathsf dt}{y-x} \right|\\ &= \left|\frac{\int_x^y (f(t)-f(x))\ \mathsf dt}{y-x} \right|\\ &\leqslant \frac{\int_x^y|f(t)-f(x)|\ \mathsf dt}{|y-x|}\\&\leqslant \frac{\varepsilon|y-x|}{|y-x|}\\ &=\varepsilon,
\end{align}
as was to be proved.


For time series, is non stationary an issue for machine learning models like they are for traditional time series models like ARIMA?

Question: Sorry if the question seems basic. I understand that non stationary data is a big issue for traditional time series forecasting methods like ARIMA and VAR but is it the same for machine learning methods like XGBoost and neural networks? Meaning to say, do I have to do differencing on the y variable for machine learning methods like I do for ARIMA?
Comment: ARIMA is built for non-stationary series, the I stands for "integrated"
Comment: I understand that, but the main question is - do i have to do differencing for machine learning methods like XGBoost and Vanilla neural networks for time series?
Comment: You don't need to be sorry for asking a question. Just mentioned your understanding & effort about the issue along with references, if any, to show the readers you've put in enough effort before asking a new question.
Comment: I've tried finding googling for answers but the views are always contradictory. Some say it's better to do differencing whenever possible but there are some who say that detrending the y variable is not ideal especially if your x variable is not detrended as well
Comment: The short answer is yes, you need to difference to preserve neurons and limit computations
Answer: No, you don't have to do differencing when using XGBoost or neural networks. The idea with those data-driven models is that they have so many parameters that they can adapt to any property of the data. You don't have to presume any model, meaning you don't have to do the work to figure out an appropriate model. The disadvantage of data-driven models is that you learn much less about the "inner properties" of your data-generating system. But if you only care about prediction, that is totally fine.
Comment: Thank you for the answer. As far as I understand, we're talking about non-stationarity in the target variable. Would your answer change if we have one or several non-stationary **predictors** with, say, a binary target in a panel data?


How to prove $\sum_{k=1}^\infty\frac{k^k}{k!}x^k=\frac{1}{2}$ where $x=\frac{1}{3}e^{-1/3}$

Question: How to prove that
$$
\sum_{k=1}^\infty\frac{k^k}{k!}x^k=\frac{1}{2}, ~\text{where}~~ x=\frac{1}{3}e^{-1/3}~?
$$
I found this sum in my notes, but I don't remember where I got it. Any hints or references would be nice.
Comment: A generalization: $\sum_{k=1}^\infty\frac{k^k}{k!}\big(\frac{1}{ae^a}\big)^k=\frac{1}{a-1}$
Comment: @NilotpalSinha It should be  $\sum_{k=1}^\infty\frac{k^k}{k!}\big(\frac{1}{ae^{1/a}}\big)^k=\frac{1}{a-1}$ (note the exponent $1/a$ ).
Comment: @NilotpalSinha it seems you are right. Can you prove it?
Comment: It might be easier to prove the above generalization by summing over a or integrating over a and using some sort of nice exchange of summation or differentiation or something.
Comment: @Asvin - You are right, typpo
Answer: Idea, too long for a comment: use the Lambert function.
$$W(x) = \sum_{n=1}^\infty\frac{(-n)^{n-1}}{n!}x^n,$$
$$W'(x) = \sum_{n=1}^\infty\frac{(-1)^{n-1}n^n}{n!}x^{n-1} = \sum_{n=1}^\infty\frac{n^n}{n!}(-x)^{n-1}$$
$$\cdots$$
Comment: Note that you have solved the problem since $$W'(x)=\frac{W(x)}{x+xW(x)}$$ so $$\sum_{n\geq1}\frac{n^{n}}{n!}x^{n}=-\frac{W(-x)}{1+W(-x)}.$$ Taking $x=e^{-1/3}/3$ we can conclude since $$-\frac{W(-e^{-1/3}/3)}{1+W(-e^{-1/3}/3)}=\frac{1/3}{1-1/3}=\frac{1}{2}.$$
Comment: this proves also the general claim from the comments (+1)
Answer: Let's consider  $\sum_{k=1}^\infty\frac{k^k}{k!}\big(\frac{1}{ae^{1/a}}\big)^k=\frac{1}{a-1}$ for $a > 1$ (as in the question).
Then $\frac{1}{a-1} = - 1+ \frac{1}{1-1/a} = \sum_{k=1}^\infty (\frac1a)^k$ by the geometric series. So one has to show
$\sum_{k=1}^\infty\Big[-1 + \frac{k^k}{k!}{e^{-k/a}}\Big](\frac{1}{a}\big)^k=0$
Writing some terms
$0 = \Big[-1 + {e^{-1/a}}\Big](\frac{1}{a}\big) + \Big[-1 + \frac{2^2}{2!}{e^{-2/a}}\Big](\frac{1}{a}\big)^2 + \Big[-1 + \frac{3^3}{3!}{e^{-3/a}}\Big](\frac{1}{a}\big)^3 + \cdots$
Expanding the exponentials and writing the terms up to $(1/a)^3$, say,  requires to take the  terms
$0 = \Big[-\frac{1}{a} + \frac12 (\frac{1}{a})^2 + \cdots \Big](\frac{1}{a}\big) + \Big[-1 + \frac{2^2}{2!}(1-\frac{2}{a} + \cdots)\Big](\frac{1}{a}\big)^2 + \Big[-1 + \frac{3^3}{3!}(1 + \cdots)\Big](\frac{1}{a}\big)^3 + \cdots$
Sorting for powers of $1/a$ gives
$0 = \Big[0 \Big](\frac{1}{a}\big) + \Big[-1 -1 + \frac{2^2}{2!}\Big](\frac{1}{a}\big)^2 + \Big[\frac12 - 2 \frac{2^2}{2!} -1 + \frac{3^3}{3!}\Big](\frac{1}{a}\big)^3 + \cdots$
and all the prefactors are zero, as required. The full solution then comes upon expanding all exponentials. Clearly this requires some more formal work.


Gitlab with Auth0 authentication

Question: I'm having problem setting Gitlab with Auth0 authentication. I followed this tutorial https://gitlab.com/help/integration/auth0.md. When I try to sign in with Auth0, I'm redirected back to Gitlab, but there is an error message 'Signing in using your Auth0 account without a pre-existing GitLab account is not allowed.'. I followed this post https://stackoverflow.com/questions/33024270/connect-a-gitlab-account-with-saml but that didn't helped.
When I try to connect existing user with Auth0 the connection is stored, but for some reason the 'Identifier' in the account is empty. I didn't found any option how to configure identifier key or anything similar.
My config looks like this:
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['oauth2_generic']
gitlab_rails['omniauth_auto_link_ldap_user'] = true
gitlab_rails['auto_link_saml_user'] = true
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['sync_profile_attributes'] = ['name', 'email', 'location']
gitlab_rails['omniauth_providers'] = [
  {
    'name' => 'auth0',
    'args' => {
      client_id: 'xxxxx',
      client_secret: 'xxxxx',
      namespace: 'xxx.eu.auth0.com'
    }
  }
]

Any idea where can be the problem? GitLab has Standard login, LDAP and now the Auth0 enabled.
There is nothing interesting in the log file.
Answer: You haven't set the Auth0 provider to be used.
Set gitlab_rails['omniauth_allow_single_sign_on'] = ['auth0'] and it should work.
Also, noting the recency of the post, you will also need to add scope to your config.
Example:
gitlab_rails['omniauth_providers'] = [
        { "name" => "auth0",
          "args" => { client_id: '...',
                      client_secret: '...',
                      namespace: '....auth0.com',
                      scope: 'openid profile email'
                    }
        }
]

Ref: https://gitlab.com/gitlab-org/gitlab-ce/issues/38945
Comment: Yes, I found that bug two. It looks like this is the last problem with oauth. I tried to allow single sign on with value 'true', which will allow all omniauth providers.
I'll wait for the bug fix and then update this thread.

Gitlab with Auth0 authentication


Android: after changing orientation, a duplicate layout appears under ScrollView

Question: The following image might further clarify my problem:

I have a RecyclerView that inside a ScrollView. Scrolling the view after changing the orientation produces an output like the screenshot. (NOTE: I'm not sure if changing orientation has anything to do with this issue as I can't scroll in portrait mode)
It is as if there are two identical layouts on top of each other, but when the user scrolls, only the topmost layout moves but the other one stays still.
Here's my xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_16">

        <com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/question_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:layout_margin="@dimen/margin_8"
            android:adjustViewBounds="true"
            android:maxWidth="300dp"
            android:scaleType="centerInside"
            android:src="@drawable/zm_image_placeholder" />

        <TextView
            android:id="@+id/doubt_comment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/question_image"
            android:layout_alignParentEnd="true"
            android:layout_marginHorizontal="@dimen/margin_8"
            android:layout_marginStart="@dimen/margin_56"
            android:layout_marginEnd="@dimen/margin_8"
            android:fontFamily="@font/gothambook"
            android:paddingHorizontal="@dimen/padding_8"
            android:paddingVertical="@dimen/padding_4"
            android:text="This is the comment added by the student. This is the comment added by the student. This is the comment added by the student. "
            android:textSize="16sp" />

        <com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/answer_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/doubt_comment"
            android:layout_alignParentStart="true"
            android:layout_margin="@dimen/margin_8"
            android:adjustViewBounds="true"
            android:maxWidth="300dp"
            android:scaleType="centerInside"
            android:src="@drawable/zm_image_placeholder" />

        <TextView
            android:id="@+id/doubt_answer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/answer_image"
            android:layout_alignParentStart="true"
            android:layout_marginTop="@dimen/margin_8"
            android:layout_marginEnd="@dimen/margin_56"
            android:fontFamily="@font/gothambook"
            android:paddingHorizontal="@dimen/padding_8"
            android:paddingVertical="@dimen/padding_4"
            android:text="This is the comment added by the student. This is the comment added by the student. This is the comment added by the student. "
            android:textSize="16sp" />

    </RelativeLayout>

</ScrollView>

Edit: This problem also occurs in portrait mode after I've changed orientation (portrait -> landscape -> portrait). If I don't change the orientation, everything works fine.
Comment: Use `NestedScrollView` instead of `ScrollView`  if you're using a recylcerview inside. Also, are you adding he recyclerview dynamically(in code)?
Comment: @AbdullahZKhan there's no recyclerview, just simple `TextView` and `ShapeableImageView`. And I've also tried using `NestedScrollView`, but it produced same result.
Comment: > I have a `RecyclerView` that inside a `ScrollView`.

Duplicates usually happen when views are added by code in onCreate, it renders over the existing views
Comment: @AbdullahZKhan in its corresponding java file, I just set the image and text from okhttp3 response. I did not manipulate the view in any other way (other than setting visibility to GONE if there is no text or image)
Answer: Adding android:configChanges="orientation|screenSize" in the Manifest solved the issue in this case.
It is similar to this issue


Basic PHP Register / Profile Page

Question: I was wondering if anybody could show me a pretty decent and basic PHP Register form page that saves a profile page in to the database.
I was going to use it to try and build off to make a more advanced one as I'm trying to get better with PHP.
If you could show me one and explain a little bit of it that would be great.
Comment: A very nice, practical question. I don't agree to those downvoting and voting to close it. It can be considered rhetorical but can have some very practical answers. There are many cases when using a 3-rd party framework/engine seems an overkill for your simple site and reasonable no-bloat code snippet can turn the most adequate solution. Moreover, such a clean solution can be a good subject to explore security risks and hardening measures possible.
Answer: Basic PHP Register / Profile Page
http://www.webdeveloper.com/forum/showthread.php?265799-Login-amp-Registration-form-with-profile
make a member.php like a profile template and create an url like bellow when user finished the registration
<code>$profileUrl = http://www.yousite.com/members.php?user='.$userId;
</code>
generate a user id when any user finished the registration and get the userId usiong $_GET
In members.php
<code>$userId = $_GET['userId'];
</code>
and get the user details from the database according to the user id .that's it
In members.php
<code>$userId = $_GET['userId'];

include('your database class file');

$sth = $dbconnect->prepare("SELECT first_name,last_name FROM register WHERE userId = :userId");
$params = array("userId" => $userId);
$sth->execute($params);

$status = $sth->fetchAll();
</code>
Use it like above.Create your own codes for additional details to fetch from the database
Comment: Thanks! This helped kinda, although do you know how I would make it so that in the members.php file I could have a variable for their username to have their own user-page. like members.php?user=3 for example. Any ideas?
Comment: So could you give me an example of what the members.php file would look like? I understand how to make it save userID to the database after registering though.
Comment: Update buddy,it take time to create the code in full.but this sound good for starting

Basic PHP Register / Profile Page


Flask serves static file, but without images

Question: I am trying to serve static files from Flask, but said static file contains an image which is not showing up. Here is my flask code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return app.send_static_file("somefile.html")

if __name__ == '__main__':
    app.run(debug = True)

And here is my html file "somefile.html" which is in the "static" sub-directory under the directory which holds the above code:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>

 this is some garbage text

The graphic is sitting in the same "static" subdirectory as somefile.html.
If I drag the html file directly into the browser, no problem, I get the graphic, but if I run the flask server and point to localhost:5000 then the graphics doesn't show up (though the text does).
What's going on? Thank you.
Answer: You are serving the HTML page under the root URL, /. The browser will then load all relative URLs based of the root url.
Your image is thus going to be loaded as /ppnow.svg, not /static/ppnow.sgv.
You could fix the link to the image, or you could alter the base URL with a <base> tag:
<base href="/static/">

Note that without a domain name (an absolute URL) the base tag may be ignored by IE.
Comment: Do even the latest versions of IE ignore the base tag if an absolute URL is not provided?
Comment: @ThomasBrowne: I try to avoid front-end issues. [IE doesn't support relative paths in the base element when referencing CSS files](http://stackoverflow.com/q/6541721) suggests that IE 7, 8 and 9 do not support it, certainly. The [MSDN documentation](https://msdn.microsoft.com/en-us/library/ms535191(v=vs.85).aspx) doesn't say newer versions do support relative URLs.


Too slow growth for violin?

Question: I am not sure if this is the right place to ask this, but I am wondering about the pace of learning of typical working adult (~ 30 years old) learning violin.
I have work (PhD research work, really) that takes the usual daytime and sometimes often the night, and it's hard to practice consistently. I typically managed to squeeze at least 1 hour a day and at least 3-5 times a week (I know this is too little even if playing "for fun"), and I cannot really practice too late since other people living with me require some peace (walls are thin...).
I am basically at 2.5-year mark, taking 30-minute lesson per week (36 lessons per academic year), and as far as I can tell my teacher has been excellent and meticulous. However, I feel like my pace is too slow ~ I am still at midpoint of Suzuki book 2, RCM Violin Repertoire book 2, and also at the beginning of "Level 4 scale" of RCM Preparatory-4 Techniques and Etudes book.
I am wondering if for working adults this growth is too slow (I actually am not sure about grading systems and levels that exist). For example,

Is there a rough estimate of what a typical working adult can achieve with X hours per day in Y number of years? Or is it simply wrong to measure progress by time? Does this vary greatly with people?
Is the slowness mostly due to "wrong" practice at home?
Any other similar experiences with the same instrument or other instruments?

It does not help that I probably will have to move from place to place (country to country) once every two years or so after I graduate from PhD, which is why I am hoping to find a way to sustain this in near future. At the very least I have learnt to cope with the fact that young kids around me, sometimes below 12, can play much much better than I do.
Any thoughts, advice or personal experience would be great!
UPDATE: Seeing all the comments and answers, I decided to consider this question answered (even though I cannot give the right answer for every comment. Thanks everyone for your thoughts.
Overall, I should mention that since I am doing PhD in physics, which by nature is depressing enough (job prospect wise), actually my violin progress right now would have made me feel better about my life, so I am not really dissatisfied or anything like that. This post should help me navigate violin and physics for some time to come, and I appreciate everyone's help!
Comment: Only for the sake of consideration, suppose your learning is, in some absolute sense, too slow. Then what?
Comment: I have struggled with this too, fwiw I started my instrument age 51. But then I realised this is not the right question. Always practice as well and focussed as you can. The real question is: " what do you want to achieve playing the violin". I.e. what type of pieces do you eventually want to play and how well? Discuss with your teacher if that is realistic. Don't care about the pace of progress then, just practice   well.
Comment: I have many thoughts and can't write a full answer until tomorrow, but these are concerns that are common among adult learners, and many earlier questions on here are similar. You can find some helpful advice on [this one](https://music.stackexchange.com/questions/110147/expectations-from-a-violin-teacher-towards-an-adult-learner), and maybe other results from a search for "progress."
Comment: @Aaron Good point. What I have in mind is that while there is no rule that says I must learn as quickly as I can, everyone has finite (life)time and so I would love to grow efficiently given my own limitations. A large part of this is psychological, since I am quite hard on myself, so I want to do what I can to alleviate this.
Comment: There is probably research about this in psychology. But I think I have gathered that it was something like the brain has to process what you did while you sleep, and that you have to vary your approach and try to find why it's not working, perhaps look in mirror or something...
Comment: (I usually think of it as a nonlinear optimization problem with the extra twist that the domain you can visit changes as you learn...)
Comment: Fair enough, but if the answer turns out to be that your learning is slow, that's only going to increase the psychological pressure. Maybe a different question will better suit: say, describing how you practice and ask about what could make it more efficient Or perhaps indicating your long-terms goals and whether your current path toward them can take a straighter route.
Comment: What is your "growth measure"? If you want statistics for many people you probably need to measure in some standardised way right? I think I saw some youtube video that argued it was like a stepwise logarithm looking curve, the better you are the longer it takes to learn a new skill and then suddenly bam you learned the new skill.
Comment: Pretty sure a lot of kids won't put in as much practice as you do. First person to ask will be teacher. Who should have worked out what kind of practice *you* should be doing, but essentially, we all progress at our own rates.
Comment: I should say that this thread has been very helpful and so is everyone's comments; they have given me a lot of things to think about. I appreciate your responses!
Answer: There are certified Suzuki teachers, and then there are teachers who use the Suzuki books, but without having been trained in the Suzuki method.  If your teacher has been trained in the Suzuki method, then your pace is fine.  I've seen children with strong aptitude for music, and a supportive parent coach, take two years to complete Book 1.  I've only known one student who completed Book 1 in one year.  There are many things that can and should be learned while going through Book 1.
If you are feeling frustrated and dissatisfied, then I suggest you take a bit of time each week to play some simple duets with someone, or with yourself, by recording one line and then playing along with the recording.  Making music in an ensemble -- as opposed to working on technique -- is fun.  And to quote Dr. Seuss, "fun is good."  My hope is that this will help you relax and enjoy your learning process.  It is a tremendous challenge to learn a string instrument as an adult, and I admire any adult who embarks on this and keeps going, despite the inherent difficulty.  I hope this experience with music enriches your life, despite the intensity of your academic study.
Answer: I am fairly familiar with the Suzuki series, and I would say that your progress is not too slow.
From what I know, it usually takes about a year and a half to graduate from Book 1. The following books can usually all be tackled in a year, but sometimes a book can stretch to a year and a half.
So I don't think you're going too slow at all. Don't be disturbed at the fact that people around 12 are playing better than you. I would imagine that some of them have been playing for three-five years or more.
One suggestion, though: I would talk to your teacher about bumping up your lesson from 30 minutes to 45 minutes or even an hour. This would ensure that more time can be spent on each piece you are playing, which would serve to fix more mistakes faster.
Comment: Thanks, I cannot vote two answers, but I appreciate your thoughts!
Answer: A few thoughts from an older (50+) adult learning different instruments (clarinet and piano):
"This is where you should be in 0-24 months" by a violin teacher. I don't play violin, but the targets seem reasonable. So for a "rough estimate of what a typical adult can achieve in Y years" that's probably as good an answer as you can get.
I have experimented with practice amounts and schedules, and found that my speed of progress depends very much on how much I practice: Practicing 1 hour per day 6 days a week I can progress at a steady clip. At 30 minutes per day progress is slower, well below half the speed of the 1 hour practice.
But if I only get 3 days per week, progress is glacial. 5 days is OK, but at 3 days/week my rate of progress is only marginally above zero even with a full hour per practice day. The specific numbers may be different for you; the point is that it can be useful to experiment with different practice routines. We don't always have the option to practice as much as we would prefer, but at least we can be aware of the tradeoffs we make.
Paraphrasing Josh Goo, a clarinet teacher on Youtube:

Best case, practice 2 hours per day six days a week. The minimum is around 20 minutes per day three days a week. With the minumum amount of practice you will probably still see progress, but it will be slow.

He also has a video on what distinguishes the (clarinet) students that progress the fastest. He thinks it's because a) they put in the practice time (45 minutes/day, most of his students don't do that), and b) they are more experimental and less concerned abut sounding bad, so they sample a larger portion of the parameter space and hone in on good combinations more quickly. I think the video is worth a watch for adult learners on other instruments too.
Although time is limited, we can experiment with ways to get more out of the time we have. E.g. "What musicians can learn about practicing from current brain research" by a violinist with a background in neuroscience. (There are tons of tips on how to practice all over the internet. There are probably no magic fixes or "one size fits all" approaches, it's more a matter of trying out ideas to see what works for you.)
Finally, there isn't much point in comparing yourself with people in a very different situation, like the highly skilled 12-year olds may have 5-7 years experience already and/or more time to practice. (Someone in my clarinet group had a 3-month progress similar to my 2-year progress. But he was also semi-pro on sax before he started on clarinet and spent a lot more time practicing. I don't think it's a matter of talent, but a matter of previous knowledge, amount of practice, and efficiency of practice.) The relevant part for all of us is how to make the best out of our own situation, whatever it might be.

Too slow growth for violin?


Taxonomy Term description in views when "no results" (Haven't associated nodes)

Question: need help with Taxonomy Term description when no results in views.
I'm using Drupal 7.44 / Views 3.14 and render content from node teaser template without using fields, and for showing description used Header area / Global:Text area / Php Filter and this code
<?php
$view = views_get_current_view();
if (is_numeric($view->args[0])){
$term = taxonomy_term_load($view->args[0]);
return $term->description;
}?>
But it's work only when term have associated node, but some terms doesn't have nodes and description not showing.
Maybe some one knows how can I fix it?
Answer: Forgot about "Empty Results". insert code in "Global:Text area" and It's works. Thanks me for helping)))


Apache / PHP Begins to Deny SQL Requests after about 2000

Question: We have a web page on our server that we use to run administrative scripts. For example, we might run the script "unenrolStudents()" which runs 5,000 SQL SET commands one after another and sets 5000 student entries in an SQL database to unenrolled.
However, we are finding that after running a few thousand queries (it is not totally consistent) we will be "locked out" by our server.
SYMPTOMS OF LOCKING OUT:
- unable to connect to server with winSCP
- opening putty with that connection shows a blank screen (no login / pass)
- clearing cookies / cache in chrome does NOT fix locking out
- other computers in the office ALSO become locked out
- locking out can be triggered with a high frequency of requests (10000 in 1 second) or by less over time (10000 in 500 seconds - this will still cause a lockout even though the frequency is much less)
We believe this is a security feature of our own Apache. I know we are using Suhosin but I didn't configure it so I don't know.
How can I disable this locking effect so that I can confidently run all my SQL requests and they will go through? Has anyone else dealt with this and found workarounds?
Thanks
DS
Comment: Are you hitting this webpage once for every student? Or do you hit it a single time and pass in 2000+ student ids? One for every student will almost certainly trigger an attack defense, since you're basically slamming the server with requests.
Comment: debugging is best done in knowing the facts, not believing something (at least not after you have spend the first 5 minutes without success).
Comment: This can hardly be a security feature if you can't even SSH into the server anymore
Comment: "other computers in the office ALSO become locked out" and the fact that SSH doesn't work any more seems more like a server network security error to me (blacklisting the IP). Some sort of DOS protection, maybe? Have you tried SSH'ing from another IP while this 'lockout' is going on?
Answer: php script has a very short execution time. Have you tried extending it??
<code><?php  ini_set('max_execution_time', 300);
// code here
?>
</code>
Answer: Sounds to me like you're trying to fix a software architecture problem with a configuration setting.
I'd suggest writing your software to re-use connections rather than opening new ones for each operation.
Answer: Two things come immediately to mind.

If you're running 5,000 queries to do the same thing to 5,000 records you need to change that to a single query with and appropriate "where" clause.
Running that many queries may be causing your server to be hitting memory limits.


Why do people think rapping is new and different from singing?

Question: Why do people think rapping is new and different from singing?
Are Staccato (short) and Tenuto (held) the correct terms to differentiate the length of the notes and weren't these two note speeds both considered singing?
In old chorale music (choirs),there was still instances of short notes being sung fast. There was also of course, instances of short fast notes being sung and then longer notes, within the same song.
People didn't think of short fast notes as not being singing until recently.
Comment: "I don't think rap and singing are different":  if you hear an unfamiliar piece of music on the radio (or elsewhere), are you unable to distinguish whether it is being rapped or sung?  Whatever the difference is, though, it has nothing to do with rhythm.  You can easily take a rap and compose a song using the same rhythm.  The primary difference is in the use of pitch.  Rap is (primarily) spoken, and the difference between speech and singing is largely a function of pitch.  Watch _The Music Man._  It has an explanation of this phenomenon along with examples of pre-rap musical speech, sung...
Comment: "Are Staccato (short) and Tenuto (held) the correct terms to differentiate the length of the notes": no.  "Weren't these two speeds both just considered singing?": Yes.  The difference between rap and song has very little to do (if anything) with the presence of short or long notes.
Comment: @phoog So would it  be "sixteenth notes and whole notes" or even shorter or longer notes? I asked this because I don't think rap and singing are different and wanted to know if we differentiated them in the past. The main thing is that i'm not sure where the idea that rap is not melodic came from. So the only thing that could be truly different is the length of the notes.
Comment: Almost everyone can hear a difference between rapping and singing. They are different things. Are you intentionally implying that you cannot hear a difference between rapping and singing? Short fast notes are still considered singing. Is that what you think rapping is? Singing short fast notes? Have you ever listened to Snoop Dogg? It's rap, and it's not usually fast.
Comment: I don't think notes describe the percussive elements and emphasis involved in rap very well, it would probably be a mess with glissando everywhere ?
Comment: (Not to mention dynamics, there would be dynamics everywhere)
Comment: I think there would have to be a lot of stuff like with a throaty voice or with a silly voice or whatever under the notes as well, especially for skits, It would be interesting if someone had tried to make a system for that :-)
Comment: Sorry, even explaining why this question can't be answered would take an answer-length comment. Ultimately, it's a question about how certain terms are used, and it assumes several definitions that aren't universal. The short version is: Anyone who says rapping isn't  singing is presumably defining it as speech. (The term "rapping" after all comes from a usage meaning "conversing.")
Comment: I'm voting to close this question because it's about definitions of terms, but uses too many terms and assumes many definitions and perhaps rests on some false premises.
Comment: @AndyBonner I understand! Its a reddit question or chat room. My apologies again lol.
Comment: ..."patter" songs that in some ways approximate speech but serve as counterexamples to your apparent hypothesis that fast rhythms preclude singing, and more.  Try Rex Harrison in _My Fair Lady._  See what you think of Copland's _Lincoln Portrait._  Listen to operatic recitative from different periods -- it changed dramatically between 1600 and 1900.  There are many places where you can find gray areas between speaking and singing, but you will not find that rhythm is the critical factor in any of them.
Comment: I meant that I think a lot of rap does have intended tonality, and that from my understanding all phonations are pitched. So the only way to differentiate rap and singing would be by note length, and thats the only difference I personally perceive. This article has some good examples https://www.esm.rochester.edu/integral/34-2020/komaniecki/
Comment: If the only difference you perceive between rap and singing is note length, then I'm afraid your problem is you. People think rap is different from singing because they can hear a lot of differences that go well beyond note length.
Answer:
Why do people think rapping is new and different from singing?

Because, well, they are.  Perhaps you meant to ask what the differences are.

I asked this because I don't think rap and singing are different and wanted to know if we differentiated them in the past.

I suspect that you know very well that they are different.  When you hear a piece of music for the first time, you know whether the performance includes someone rapping or singing.  It is not difficult to determine that Steve Perry sings "Don't Stop Believin'" and Melle Mel raps "White Lines."
But the focus on rhythm is misplaced.  Look at "Rapper's Delight" and the "Ketchup Song": it's the same rhythm, but one is rap and the other isn't.  Yes, rap is less likely to contain slowly declaimed text than singing, because long, drawn out, single syllables are weird and awkward in speech.  But rapid declamation does not by itself turn song into rap.  The Major General's song from Pirates of Penzance comes to mind.
What makes rap different from song is the use of pitch.  Singing generally has more or less well defined units of constant pitch -- notes, if you will.  These don't necessarily correspond with syllables, but often they do.  Some styles of singing don't have constant pitch, but instead the pitch slides around as it does in speech.  Still, the pitch generally begins or ends on a musically significant pitch, and may linger there a wile, in contrast to speech where the pitch isn't necessarily related to the musical accompaniment, and the variations in pitch tend to serve rhetorical ends, not musical.
So, in summary, yet another attempt to answer your question:

Why do people think rapping is ... different from singing?

Because they hear rap as rhythmic speech rather than as singing.
The part I omitted just there is the part about whether rap is new.  Certainly rhythmic speech with musical accompaniment is an ancient art form.  In that respect, rap as a musical technique isn't new.  But rap as a musical genre, as a style of making music, also known as "hip hop," was universally recognized as an innovation of the last quarter of the 20th century.  Many aspects of it were new or given new importance, and the synthesis of the various elements was certainly innovative.  These include not just the performance technique of speaking rhythmically but also the practice of using short samples of other songs to create the rhythmic background, various stylistic elements such as African-American rhythmic patterns, and even the choice of topic.  You might reasonably (if anachronistically) describe rhythmic chanting in a 1930s big band number as "rapping," but you'd be on much thinner ice if you tried to describe the music as "rap."
Answer: It probably has more to do with the fact that rapping is closer to rhythmic recitation than singing at a defined pitch. At least, that's why I think that rapping is different from singing. Not speed, but defined pitch as an applicable category and the fact it uses the technique of speech, which is different from the technique of singing.
I'm not convinced it's a new invention (I'm not informed, but I'd place my bet on "very old, has been with humanity since forever"), but it sure has gained popularity that it didn't have before.
Comment: Rap being with humanity forever makes sense. As far as it being more popular than it was before that is part of my question because I thought it was always a part of singing. Minus purists that think rap has to have speech as you pointed out, or a story etc, I'm pretty sure most rap actually has a defined pitch. Basically, if we strip away the language element.
Comment: @Lecifer Not sure what you mean by "language element". If you mean that rap doesn't usually include nonsense lyrics, whereas it's not that uncommon to sing "la la la", I don't think that's a defining feature. Most songs have comprehensible lyrics from beginning to end, and I don't see any reason why it should be principially impossible to use scatting in rap.
Comment: @Lecifer A lot of music classified as rap or hip-hop today does have singing in it, and a lot of rapping done on recordings does have an intentional pitch component, however rapping in its purest sense may have pitch but that doesn't mean it has tonality. Just talking always has a pitch but there isn't a musical meaning behind the pitch content of talking. With rap, there may be pitch but there isn't musical meaning to the pitch in the same way there is with singing.
Comment: @Divizna what I mean is that, if I listen to a french rapper I have no idea what he's saying but I could still pick out his rapping as being melodic or monotonous. But many rap purists will argue that in order for it to be true rap there needs to be words and maybe even a story being told (language).
Answer: First of all, who are "people"?
Rapping has been around since the 1970's and there are also many examples and influences that predate it by quite a bit so I think we can safely take "new" off the table.
Rapping and singing have similarities. The main one is the fact that they both are mostly done in a rhythmic way, using specific rhythms and conforming to an established beat or tempo. The main difference is that singing incorporates hitting specific pitches with the words along with the rhythms and even though the spoken word does have pitch, rapping is done in a conversational way with little regard for specific pitches. Our voices do rise and fall in pitch to emphasize or minimize certain words or phrases as does a rappers but almost never with specific musical pitches in mind
There are instances of crossing over, where rappers will sometimes sing melodies in parts of their songs and singers will sometimes speak parts of their lyrics. This plus the fact that singers and rappers sometimes collaborate confirms there is a connection between the two.
As for long or short notes or the way they are articulated, neither rapping or singing are confined to notes of a certain length, speed or articulation. Once again, the difference is whether or not there is the intent to assign specific pitches to the words that are being spoken or sung.
Comment: "since the 1970s" is incredibly recent in music history, so, yes, it's entirely reasonable to call something that started in the 1970s "new" as compared to something that has been going on for millennia.
Comment: @phoog If you want to talk about millennia in reference to music history thats your prerogative but 50 years is a significant amount of time in musical history, especially in the last 100 to 150 years.
Comment: Well that's also true of course, but in the context of a question about an innovation that occurred within living memory we can understand "new" to mean "different from what came before." Come to think of it, that sense of "new" can be applied to innovations occurring centuries ago, such as opera around 1600.


Scale-invariant geometries where $C/d \neq \pi$

Question: Is there a geometry where everywhere, or locally: $$ \frac{C}{d} = \mathrm{constant} \neq \pi$$
$C, d$ being the circumference and diameter of a circle?
Answer: Yes. For example, if you equip $\mathbb{R}^2$ with the $l_1$ metric, then a circle of diameter $d$ has circumference $4d$.
Comment: @Eelvex: with $l_\infty$, we again have $C/d=4$. The other $l_p$s all have $C/d$ constant but I haven't tried to work out what the values are.
Comment: Thanks! Any other examples?
Comment: any other examples apart from $L^p$ spaces?


Finding the centerpoint and boundaries of an arbitrary closed curve (random walk)

Question: Suppose you have an arbitrary closed curve (endpoint returns relatively close to first point) generated through a bunch of dataset coordinates, how do you find the centerpoint and the boundaries of the resulting shape?
Answer: There are two possible interpretations (perhaps more) for your question.
The first one was already addressed by @AakashM, and we may depict it in the following plot:

Where the red square is the "boundary".
I'll cite @AakashM here, because I understand his remark VERY important:"(I note that for you to have a closed curve, you need the endpoint to be not just 'close to', but coincident with the first point)"
As for the centerpoint, you have at least two "natural ways" for calculating it with this definitions:

Centerpoint = Middle Point of the Red Square
Centerpoint = { Mean of x coordinates of your curve, Mean of y coordinates of your curve}

Both of them may serve as a center point, but the results will be different.
The other way of dealing with the problem is finding the Convex Hull of your curve, as depicted below:

If you google for it, you will find algorithms for finding the Convex Hull, a nice introduction is here.
Again, you have two "natural ways for calculating the centerpoint:

Centerpoint = { Mean of x coordinates of your curve, Mean of y coordinates of your curve}
Centerpoint = { Mean of x coordinates of the CH points, Mean of y coordinates of the CH points}

HTH!
Answer: (I note that for you to have a closed curve, you need the endpoint to be not just 'close to', but coincident with the first point)
If by 'centerpoint' you mean center of mass, and you are assuming uniform density, then this question has what you want.
If by 'boundaries' you mean bounding rectangle with sides parallel to the axes, you just need the minimum and maximum x and y values on the curve.
If either of those aren't what you mean, please say...
Answer: For the boundaries, you can refer to the answers given by @belisarius and @AakashM.
As for centerpoint, you want "center of mass".  Good 'ol Wikipedia has explanations and recipes at http://en.wikipedia.org/wiki/Center_of_mass and http://en.wikipedia.org/wiki/Centroid.
In general, you get a different result calculating the centroid than calculating the average of the vertices.  This difference will be pronounced if the vertices are not uniformly distributed.


invalid constant value in flutter

Question: How to fix this Constant value error
                  actions: [
                IconButton(

                      icon: Icon(
                        Icons.cancel,
                        color: Colors.red,
                      ), onPressed: () {
                        Navigator.pop(context);
                       },
                    )

              ]

Click Here
I have provided a code snippet for a Flutter application that includes an IconButton widget with an icon for the cancel button. When the button is pressed, the current screen is displayed using Navigator.pop(context) How to implement pop from navigation layer ?
Comment: Remove const keyword from AlertDialog
Answer: The problem is on your AlertDialog.
You just need to remove const before AlertDialog.
Comment: this problem has clear . thank you so much..
Answer: There will be a const before the dialog box code. Please remove it.

invalid constant value in flutter


Spring boot shut down when I close the session

Question: My Spring Boot Rest Api works veryy good, but I have problem with him.
When I'm closing the terminal SSH, my application rest shut down also.
What I should do ? How to fix that ?
Comment: Run in background
Comment: how to run in background ?
Answer: try nohup
nohup yourcommandtolauncjava

Comment: nohup: ignoring input and appending output to 'nohup.out'
Answer: You can start your spring application as systemd service. It helps in managing the service in several ways.
How to: Setup systemd service
Once the configuration is done, you can use it for starting, stopping and restarting the service. And it also provides a way to auto-restart the application when the service goes down for whatever reason or after the restart of the machine.
Usage:
service <app name> start
service <app name stop
service <app name> restart

Answer: nohup
nohupyesno hang up Do not suspend means that if you are running a process and you feel that the process will not end when you exit the account, you can use thenohupCommand. This command can continue to run the corresponding process after you exit the account / close the terminal. ==After the command is run, it is the foreground process==
eg: nobup java -jar xxx.jar &
& Let the program run in the background
eg:  java -jar xxx.jar &


Confusion related to the union of two type 3 grammar

Question: I have this confusion. Lets say I have two languages produced by type 3 grammar such that
<code>L(G1) = <Vn1,Vt,P1,S1>
L(G2) = <Vn2,Vt,P2,S2>
</code>
I need to find a type3 grammar G3 such that
L(G3) = L(G1)U L(G2)
I can't use $S3 \rightarrow S1$ and $S3 \rightarrow S2$ rule in this new G3 to get the union, because the production is not type 3 as well. So what should I do?
Comment: Those productions *are* type $3$: they have a single non-terminal on the lefthand side.
Comment: @Brian. But in type 3 grammar the production rules should be like $S \rightarrow aA$ or $S \rightarrow a$ where A and S are non terminals and a is terminal. So if I had $S3 \rightarrow S1$, then it is not type 3
Comment: Sorry: I was thinking context-free. You're right. Hang on a minute and I'll write you a quick answer.
Comment: @Brian. I think if L(G1) has start state lets say $S1 \rightarrow aA$ and L(G2) has $S2 \rightarrow aB$ then L(G3) will have $S3 \rightarrow aA$ and $S3 \rightarrow aB$. Since both G1 and G2 are type 3, this will follow I guess
Comment: You have the right idea, but you have to be a bit more careful: you  want to make sure that the grammar doesn't allow derivations that start out with $G_1$ productions and then switch to $G_2$ productions.
Answer: First note that a regular grammar can be modified to make an equivalent regular grammar in which the initial symbol does not appear on the righthand side of any production. A simple example is converting the grammar whose productions are $S\to\lambda$ and $S\to aS$ into one whose productions are $S\to\lambda$, $S\to aX$, $X\to aX$, and $X\to\lambda$. I'll let you think about how to do this in general, and from here on I'll assume that $G_1$ and $G_2$ have this property.
If the original grammars are $G_1=\langle N_1,\Sigma,P_1,S_1\rangle$ and $G_2=\langle N_2,\Sigma,P_2,S_2\rangle$, construct $G$ as follows. First note that you can assume that $N_1\cap N_2=\varnothing$: if this is not the case, replace each non-terminal $\nu\in N_2$ by a new symbol $\nu'$ that is not in $N_1\cup\Sigma$.
Now let $S$ be a new non-terminal symbol, and let $N=N_1\cup N_2\cup\{S\}$; the new grammar will be $G=\langle N,\Sigma,P,S\rangle$, where $P$ is constructed as follows. First, $P$ contains every production in $P_1\cup P_2$ that does not contain $S_1$ or $S_2$. If $P_1$ contains a production $S_1\to\alpha$, replace it with $S\to\alpha$. Similarly, if $P_2$ contains a production $S_2\to\alpha$, replace it with $S\to\alpha$. This is exactly what you suggested in your comment above, and it works, once you've made sure that $N_1$ and $N_2$ are disjoint and that no production has an initial symbol on the righthand side.

In case it isn't quite clear, the problem with having $S_1$, say, on the righthand side of a production $A\to aS_1$ in $P_1$ is that you'd get $A\to aS$ in $P$, and then you could continue the derivation with productions that originated in $G_2$. Thus, you could end up with a word whose derivation was half in $G_1$ and half in $G_2$, the word itself being in neither language.


Calculating the accuracy of matching between two sets of strings lists

Question: To give some background - the question is about measuring the accuracy of name disambiguation algo results (and not about the algo itself)
Let's say we have three groups of entities, each corresponding to the same name (instead of real names they will be represented as numeric ids, just for simplicity). This is our ground truth:
+---------+------------+
| Groups  | Duplicates |
+---------+------------+
| Group 1 | [1, 2, 3]  |
| Group 2 | [4, 5, 6]  |
| Group 3 | [7, 8]     |
+---------+------------+

That means, that [1, 2, 3] correspond to one name, [4, 5, 6] for another one and so on.
Then, the results of our matching algo (not real data, just for example) look this way:
+---------+------------+
| Groups  | Candidates |
+---------+------------+
| Group 1 | [1, 2]     |
| Group 2 | [3, 5, 6]  |
| Group 3 | [4, 7, 8]  |
+---------+------------+

Knowing which candidates group corresponds to which group from he ground truth we can measure F1 easily:

But what if we don't know which candidates group corresponds to which ground-truth group?
At first I tried "unpacking" groups, meaning I've created pairs of id: other ids from the same group, for example, for ground truth 1: [2, 3], 2: [1, 3] and so on, and measure the F1 for each such pair (between truth and prediction):

That gave me a result pretty far from the "real" one (the one where I knew the connections between groups)
Then I tried to create one-to-one pairs - id: single id from the group, for example for ground truth 1: 2, 1: 3, 2: 3 and so on.

Which gave me result far from desired as well (if I interpret it right, in this particular case accuracy equals precision, recall and f1)
And finally the question is - is there any way to measure how accurate the prediction is (without knowing which prediction corresponds to which group from ground truth) and at the same time to have that measure as close to the one where we knew the relations as possible?
Comment: Important question: When calculating prediction accuracy, do you know which words are duplicates of each other (i.e ground truth) or not ? In the former case it is a classification problem (which variable class name), in the second case a clustering problem. (To reviewers: Please give some time, do not close question in a hurry)
Comment: @steffen not sure if I understood your question right, but I'm not using ground truth in prediction calculation, only in prediction accuracy testing. All words (ids in this particular case) within one group in ground truth are considered to be the duplicates.
Answer: As it sounds to me the question is simply about comparing two classifications. I this case - one is "true", the other is "artificial".
Out of the n=8 objects create all the n(n-1)/2=28 pairs. Calculate the 2x2 confusion table of counts which in this case is called the comembership confusion table. The rows dimension is True classification, the columns is Prediction classification, both with labels "In the same group", "Not in the same group". Thus, cell (1,1) contains the count of pairs of objects where both objects belong to the same group both in T and P classification. Cell (1,2) is the count of pairs where both objects belong to the same group in T classification but not in P classification. Cell (2,1) is the count of pairs where both objects belong to the same group in P classification but not in T classification. Finally, cell (2,2) is the count of pairs where both objects do not belong to the same group neither in T nor in P. The sum in the table will be 28, number of pairs.
The comembership confusion table in your example is:
                     Predicted
                SameGr  NotSameGr
True  SameGr      3         4
      NotSameGr   4        17

Then, based on this confusion table you can compute a number of "matching coefficients" or "external clustering criterions" (other names are used in literature too), including F1, Rand index, Jaccard, Dice, Fowlkes-Mallows, McNemar, Phi correlation, etc etc (the many association measures based on a 2x2 contingency table). I think that you know some of them. They are used to compare classifications or partitions - any, not necessarily "true" one with "predicted" one. The key point here was that the indices are computed based in the confusion table which unit of count is pair of objects and the table labels are "in the same class" vs "in different class" - rather than a confusion table where count unit is object and the table labels are "true/positive" vs "false/negative".
From this point of view, an object was classified "correctly" or "accurately" if it met in one group in P classification with the same objects as it meets with in T classification; one don't have to know group (classes) labels and their correspondence between the two classifications (the number of groups can even be different in T and P). Groups identity are determined by their members togetherness.


Sum of products basics (proof verification)

Question: I know that for a collection of random variables $\{x_i\}_{i=1}^n$, I have
$$\sum_{i,j=1}^nE(x_ix_j)=\sum_{i=1}^{n}E(x_i^2)+2\sum_{i<j}E(x_ix_j). \quad (a)$$
Then triangle inequality gives
$$\Big\lvert\sum_{i,j=1}^nE(x_ix_j)\Big\rvert\leq \sum_{i=1}^{n}\lvert E(x_i^2)\rvert+2\sum_{i<j}\lvert E(x_ix_j)\rvert. \quad (b)$$
My question is: does the following hold?
$$\sum_{i,j=1}^n\Big\lvert E(x_ix_j)\Big\rvert\leq \sum_{i=1}^{n}\lvert E(x_i^2)\rvert+2\sum_{i<j}\lvert E(x_ix_j)\rvert. \quad (c)$$
My attempt
From the inequality (b), it is not  clear if the same upper bound holds for $\sum_{i,j=1}^n\lvert E(x_ix_j)\rvert$.
But looking at the first equality (a), I see that the tuple of indices $(i,j)\in[n]^2$ can be equally partitioned as $$\{(i,j)\in[n^2]:i=j\}\cup \{(i,j)\in[n^2]:i>j\}\cup\{(i,j)\in[n^2]:i<j\}.$$
Since $\lvert E(x_ix_j)\rvert=\lvert E(x_jx_i)\rvert$, I would also have
$$\sum_{i,j=1}^n \lvert E(x_ix_j)\rvert=\sum_{i=1}^{n}\lvert E(x_i^2)\rvert +2\sum_{i<j}\lvert E(x_ix_j)\rvert,$$
which implies that (c) holds.
Thanks in advance!
Comment: what is the question? what are you trying to prove?
Comment: @Masacroso See if it is clear now.
Answer: The RHS of
$$
\sum_{i,j=1}^nE(x_ix_j)=\sum_{i=1}^{n}E(x_i^2)+2\sum_{1\leqslant i<j\leqslant n}E(x_ix_j)\tag1
$$
is just a reordering of the LHS, therefore
$$
\sum_{i,j=1}^n|E(x_ix_j)|=\sum_{i=1}^{n}|E(x_i^2)|+2\sum_{1\leqslant i<j\leqslant n}|E(x_ix_j)|\tag2
$$
There is nothing to prove here more than the use of the commutativity of the sum of real numbers, but this was already used in (1). The unique difference between (1) and (2) is that we use in (2) absolute values of it addends.
In general we have that
$$
\sum_{i,j=1}^n a_{i,j}=\sum_{i=1}^{n}a_{i,i}+\sum_{1\leqslant i<j\leqslant n}a_{i,j}+\sum_{1\leqslant i<j\leqslant n}a_{j,i}\tag3
$$
for arbitrary complex numbers $a_{i,j}$. In your case we have that $E(x_ix_j)=E(x_jx_i)$ so
$$
\sum_{1\leqslant i<j\leqslant n}E(x_ix_j)+\sum_{1\leqslant i<j\leqslant n}E(x_j,x_i)=2\sum_{1\leqslant i<j\leqslant n}E(x_ix_j)\tag4
$$
Comment: Just for curiosity. Do you know what would be a generalization of (3) for $\sum_{i,j,k,l=1}^n a_{i,j,k,l}$?
Comment: @CelineHarumi it depends what you mean by a "generalization" of such reordering, generalization in what sense?
Comment: A formula for $\sum_{i,j,k,l}a_{i,j,k,l}$ like in (3).


why this binary conversion does not work?

Question: #include<stdio.h>
#include<conio.h>

unsigned * bin(unsigned n) {
    unsigned a[16];
    int i = 0, j = 0;
    for (i = 0; i < 16; i++) {
        a[i] = n & 0x1;
        n = n >> 1;
    }
    return a;
}

void main() {
    unsigned n = 5;
    int i = 0;
    unsigned * a = bin(n);
    for (i = 15; i >= 0; i--) {
        printf("%d\n", (*(a + i)));
    }
    getch();
}

Please help this binary conversion does not work. I'm trying to calculate x^n using binary conversion.
can anybode help??
Comment: `a` has auto storage duration, and won't survive past the end of `bin`.  You're returning a dangling pointer.  You'll want to `malloc` (or `new` up) an array to return, and free (or `delete[]`) it in the caller.  Or, in C++, use a `std::vector` instead, which will take care of the mundane memory stuff for you.
Comment: First thing to do (before posting here) is probably to read the compiler warnings. Your compiler will typically catch the problem with returning local variables.
Comment: Should I add that `` is not only non-portable, but deprecated on the few systems which support it, and that `main` is required to have `int` as its return type.
Comment: @JamesKanze: You probably should.  :)
Answer: You are returning a pointer to a local variable. This variable is stored on the stack, and will not be valid after the function returns.
Dereferencing this pointer will lead to undefined behavior.
The solution is to either make the variable static, or pass in the array as an argument to the function, or (as noted in a comment by James Kanze) use a type that copies the contents.
Comment: While using a static variable is technically correct, it's a bad idea for other reasons. Please don't do that.
Comment: Use `std::vector`.  Both as return value and the local variable.
Comment: Otherwise: passing in the array is the best of the C solutions I've seen to date.
Comment: @MarkRansom As Posix has learned:-).  Learn from them, and pass in the array.
Answer: you can not return a local array defined in the function in this way.
The content of the array will be erased when the function finish the execution.
instead of using
 unsigned a[16];

you can use the following:
unsigned *a =malloc(16 * (sizeof *a));

And do not forget in your main to free the memory allocated for a when the a array become useless in your program. you can free the array with:
free(a);

Comment: You can if you declare the array `std::vector` (the normal way to declare an array in C++).
Comment: didnot u mean unsigned *a=(unsigned*)malloc(16 * (sizeof *a));
Comment: @user2362994 [Do not cast the malloc result](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)
Comment: @MOHAMED Don't use `malloc` to begin with, use `std::vector` (and forget about C).  But if you have to use C, the cast is perfectly valid, and recommended by some of the better C programmers.
Comment: @user2362994 You can use it directly without casting as mentioned in the answer
Comment: @JamesKanze Concerning the `std::vector`, the OP source code looks like pure C code. so I give my solution in C and not C++.
Comment: it is giving me this error
Error BIN.C 7: Cannot convert 'void *' to 'unsigned int *' in function bin(unsigned int)
Comment: @user2362994 what happen when you use the cast `unsigned a=(unsigned)malloc(16 * (sizeof *a));` Does the compilation work without problems ?
Comment: @user2362994 so keep the casting
Comment: @user2362994 if you are compiling your source as C++ so you have to keep the casting . and if you are compiling your source as C then you can remove the casting
Comment: how about my other question
Comment: the question is not clear.  Try to open new question for that and try to clear more the question and provide what you have tried
Answer: Actually, this is a typical case where using new (or malloc) is a pretty bad choice. However, as others have said, returning a pointer to a local array is bad.
Instead, pass in an array:
void bin(unsigned n, unsigned a[]) {
    int i = 0;
    for (i = 0; i < 16; i++) {
        a[i] = n & 0x1;
        n = n >> 1;
    }
}

and in main:
unsigned a[16];
bin(n, a);

Now you have no need to allocate or return an array from bin.


Does $\limsup_{n \to \infty }\left | \frac{a_{n+1}}{a_{n}} \right |=\limsup_{n \to \infty }\left | a_n \right |^{1/{n}}$?

Question: Question: Does $\limsup_{n \to \infty }\left | \frac{a_{n+1}}{a_{n}} \right |=\limsup_{n \to \infty }\left | a_n \right |^{1/{n}}$?
I guess the identity is true, given $\limsup_{n \to \infty }\left | \frac{a_{n+1}}{a_{n}} \right |\neq 0$, and here is my "proof", is it correct?
Proof:
Suppose all $a_n$ are non-zero, and $s=\limsup_{n \to \infty }\left | \frac{a_{n+1}}{a_{n}} \right | \neq 0$,
For any $\varepsilon >0$, there exists $N\in \mathbb{N}$ such that $n>N$ implies:
$$s-\varepsilon < \underset{m\geq n}{\text{sup}}\left | \frac{a_{m+1}}{a_{m}} \right |<s+\varepsilon$$
$$\Rightarrow s-\varepsilon < \left | \frac{a_{n+1}}{a_{n}} \right |<s+\varepsilon$$
for all $n>N$.
$$\Rightarrow (s-\varepsilon)|a_{n}| < |a_{n+1}|<(s+\varepsilon)|a_{n}|$$
$$\Rightarrow (s-\varepsilon)^{n-N}|a_{N+1}| < |a_{n+1}|<(s+\varepsilon)^{n-N}|a_{N+1}|$$
where we may set $0<\varepsilon <s$, where $s \neq0$. So, for all $n>N$, we have:
$$\Rightarrow (s-\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}} < |a_{n+1}|^{1/{n+1}}<(s+\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}}$$
So, for $n>N$:
$$ (s-\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}} \leq  \underset{m\geq n}{\text{sup}}|a_{m+1}|^{1/{m+1}}\leq (s+\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}}$$
Now,
$$(s+\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}}\underset{n \to \infty }{\rightarrow}(s+\varepsilon)(s+\varepsilon)^0(1)=s+\varepsilon$$
and
$$(s-\varepsilon)^{1-\frac{N+1}{n+1}}|a_{N+1}|^{1/{n+1}}\underset{n \to \infty }{\rightarrow}(s-\varepsilon)(s-\varepsilon)^0(1)=s-\varepsilon$$
By comparison test,
$$s-\varepsilon \leq \limsup_{n \to \infty }\left | a_n \right |^{1/{n}} \leq s+\varepsilon $$
for arbitrarily small $\varepsilon$.
So, $$s=\limsup_{n \to \infty }\left | a_n \right |^{1/{n}}$$ and we are done.
Any help will be appreciated!
Comment: Your removal of the $\sup$ is not allowed. If $\sup b_m>z,$ it is not true that all $b_m>z.$
Comment: In general they're not equal. But an inequality holds between them. See the chapter on series in Rudin's mathematical analysis book
Comment: See this classic [example](https://math.stackexchange.com/a/2395131/1085900).
Comment: If $a_{2n}=\frac1{n!}$ and $a_{2n+1}=1,$ the ratio $\limsup$ is $+\infty,$ but $\limsup \sqrt[n]{a_n}=1.$
Comment: The first sentence of your "proof" should give you a hint: "Suppose all $a_n$ are non-zero". What if they're not? Just consider the sequence $0,1,0,1,0,1,\cdots$. Then one limit is not defined and the other is obviously $1$.
Comment: Not correct, see above comments
Answer: The two lim sups are not equal. The flaw in your proof is that the assertion
$$s-\varepsilon < \underset{m\geq n}{\text{sup}}\left | \frac{a_{m+1}}{a_{m}} \right |<s+\varepsilon \qquad\forall n>N$$
does not imply
$$ s-\varepsilon < \left | \frac{a_{n+1}}{a_{n}} \right |<s+\varepsilon
\qquad\forall n>N.$$
A counterexample is
$$a_n=\begin{cases} 1&\text{$n$ odd}\\2&\text{$n$ even}\end{cases}.$$ With this sequence, $\sup_{m\ge n}|a_{m+1}/a_m|=2$ while the ratio $|a_{n+1}/a_n|$ oscillates between $\frac12$ and $2$. (And  $\limsup |a_{n+1}/a_n|=2$ while $\limsup |a_n|^{1/n}=1$.)
Comment: If I replace the flaw by:

Suppose $a_n \neq 0$, and $s=\lim\left | \frac{a_{n+1}}{a_n} \right | \neq 0$. For any $\varepsilon >0$, there exists $N\in \mathbb{N}$ such that $n>N$ $\Rightarrow s-\varepsilon < \left | \frac{a_{n+1}}{a_{n}} \right |N$, $s-\varepsilon \leq  \underset{m\geq n}{\text{sup}}\left | \frac{a_{m+1}}{a_{m}} \right |\leq s+\varepsilon$.

Then the original article can be corrected into a proof of the new statement $\lim \left | \frac{a_{n+1}}{a_n} \right |=\limsup \left | {a_n} \right |^{1/n}$, right?
Comment: But the new statement $\lim |a_{n+1}/a_n|=\limsup |a_n|^{1/n}$ is not true; the counterexample shows that the LHS limit need not exist.
Comment: But what if $\lim|a_{n+1}/a_n|$ does exist? Then the statement would be true right? If this limit exists, then the radius of convergence of the power series $\sum a_nx^n$ has the radius of convergence $1/\lim|a_{n+1}/a_n|$, which should be consistent with the Cauchy-Hadamard formula.
Comment: Do you mean only the following is true: If $\lim|a_{n+1}/a_n|$ exists, then it must be equal to $\limsup|a_n|^{1/n}$.
Comment: Yes. See https://math.stackexchange.com/q/814500/215011 and https://math.stackexchange.com/q/69386/215011