Mobify carousel Infinite slider

Question: I am using Mobify carousel. I want to make it as Infite slider.
To do this I change JS code by
if (newIndex < 1) {
    newIndex = length;
} else if (newIndex > this._length) {
    newIndex = 1;
}

But when I reached at last image then click on next it goes to first image by right to left. I want to make it Left to right for last image and right to left for first image. and it work as a Infinite loop
Comment: And it isnt?  I mean, what is length at the point in time you set the `newIndex` and is it going into the correct conditional?
Comment: length is depends upon number of image.
Comment: I think you are going to need to get me some more information.  I will create a quick example though to resolve this.
Answer: I had resolved this for you, I will show you my test case... and then i will show you what i did to adjust it for you.
var len = 6;
for (var i = 0; i < 100; i++){
  console.log("value:", Number(i%len));
}

this shows just a loop, iterating over something of size 6, and resetting it back to 0, a continual loop forward.  Similarly, in the other direction.
var len = 6;
for (var i = 100; i >= 0; i--){
  console.log("value:", Number(i%len));
}

So you can sort of get mod to work forward.  for reverse, -1 would not mod with len to loop back to the end, so you could say:
var len = this._length;
newIndex%=len;
if(newIndex < 0){
  newIndex = len;
}

if there is an issue with len, then it means there is an issue with this._length which you defined.  You need to make sure you understand that when there is an array of items, say: 6.... their indices are actually 0 through 5.
That could be a secondary issue as per your question.

Mobify carousel Infinite slider


Moving objects on the stage

Question: Let's say I have 5 objects in an array and I move all them along x-axis like this:
vx = 5;

for (i:int = 0; i < objects.length; i++)
{
 objects[i].x += vx;
}

I would like to make this.
If any object from array 'objects' hit PointA, move all objects from that array to left side, for example set vx *= -1;
I can make only this:
for (i:int = 0; i < objects.length; i++)
{
 // move right
 objects[i].x += vx;

 if (objects[i].hitTest(PointA))
 {
  // move left
  vx *= -1;
 }
}

This will change object's direction, but I need to wait all objets hit PointA.
How to change the direction of all objects in array, if any of them hit PointA?
Comment: It looks like you want to change direction once **any** of your objects arrives at your destination, correct?  You're not looking to reset them all to their origins instantly, but rather, continue incrementally moving them in reverse once one reaches PointA?
Answer: I don't know action script but you should set a boolean outside the for loop, like bGoingRight
Check that this is true and move objects right, if its false move the objects left. When you pass the hitTest you should changed the boolean to false.
Rough Example
  var bGoRight:Boolean = true;

  for (i:int = 0; i < objects.length; i++)
  {
    if(bGoRight)
    {
    // move right
    objects[i].x += vx;
    }
    else
    {
     // move left
     vx *= -1;
    }

    if (objects[i].hitTest(PointA))
    {
     // if any object hit the point, set the flag to move left
     bGoRight = false;
    }
 }

Comment: I see now what you are talking about JMG, I cannot belive it could be done so easy :) Thank you everyone guys, now I can move objects left and right very easy.
Comment: Im not sure if you understand my question.
Comment: I can easy make if object1 hit pointA move object1 to left, then if object2 hit PointA move object2 to left and so on... But how to make if object1 hit PointA, move all other objects to left, not just object1?
Comment: All objects will go left if the bGoRight is set to false because you will check that when you draw them. So when an object hits PointA just switch bGoRight from true to false.
Comment: Please give me an code example, cause it does not make sense to me at all.
Comment: There you go I gave an example
Comment: could you please clarify what your trying to do? So far it sounds like you have five movie clips going in a line towards a point. Then what? I'd be glad to help you out if you can help me make sense of your question.
Answer: So you'll need to check the objects that have already hit PointA, store them, then check if the updated storage count is equivalent to your objects array. Then when that case is satisfied you can change the vx variable. This could look something like this:
//set a variable for storing collided object references
//note: if you are doing this in the IDE remove the 'private' attribute
private var _contactList:Array = [];

for (i:int = 0; i < objects.length; i++)
{
     // move right
     objects[i].x += vx;

     if (objects[i].hitTest(PointA))
     {
          if( contactList.length == objects.length ) {
             // move left
             vx *= -1;
             //clear our contact list
             contactList.length = 0;
           }
           else if ( noContact( objects[i] ) ) {
               contactList.push( objects[i] );
           }
     }
}

Then the function in the else if statement noContact(), again if you are doing this in the IDE you will need to remove the private attribute.
private function noContact( obj:* ):Boolean {
    if ( contactList.indexOf( obj ) != -1 ) {
        return false;
    }
    return true;
}

Another way you can do this is like this (a boolean way as stated in the other answer), but is reliant on your storage setup correct:
//set this variable for directionRight (boolean)
private var directionRight:Boolean = true;

for (i:int = 0; i < objects.length; i++)
{
     // move right
     objects[i].x += vx;

     if (objects[i].hitTest(PointA))
     {
          //we are moving to the right, object[i] is the last object
          if( i == objects.length-1 && directionRight ) {
             // move left
             directionRight = !directionRight;
             vx *= -1;
           }
           else if ( i == 0 && !directionRight ) ) {
               // move right
               directionRight = !directionRight;
               vx *= -1;
           }
     }
}

Moving objects on the stage


R-Select rows that meet specific criteria across hundreds of columns in R

Question: I have a dataframe that looks as follows but consists of hundreds of rows and columns making conventional filtering in R a challenge.
A simplified image is shown below:
The rows represent values from a test and the columns represent different treatments
How do I select all rows(i.e., tests) that have values between -0.5 and 1 for each "treatment" column and generate this as an output? Your thoughts are much appreciated!
Comment: Can you please provide a reprex? https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: Within the hyperlink image of a "dataframe" provided as an example, I would like to select the following entries (in row/column format) : test8/d1, tests15,16/d2, tests 4,6,16, 17, 18/d3, test18/d4, and test 3/d5. Hope this clarifies?
Comment: What do you mean by "select the entries"?  What do you want the result to look like?  Do you want a vector, a dataframe, or something else?  Do you want to retain any information about which columns or rows these values came from?
Comment: I'd make this dataset a long file, collapsing `d1` to `d5` to a single column called `d`, adding a `time` column with the values `1` to `5`. Then you can simply select the rows you want. If you're using the tidyverse, use 'tidy' data.
Comment: This is a most elegant solution and a terrific example of the power of tidy data. Thank you!!
Answer: Create Example Data:
<code>df <- data.frame(
    test = paste0("test", 1:18),
    d1 = c(rep(-57, 7), 0, rep(-99, 10)),
    d2 = c(rep(-4, 14), 1, 0.1, -99, -99),
    d3 = c(rep(-89, 3), 0.99, -47, 0.8, rep(-55, 8), -1.56, 0.1, 1, 0),
    d4 = c(rep(-99, 6), rep(-57, 5), 0.7, -3, -13, -99, 0.98, -99, 0.99),
    d5 = c(rep(-57, 2), 0.4, rep(-99, 14), -57),
    stringsAsFactors = FALSE
)
</code>
If you just need to grab the elements:
<code># get TRUE/FALSE matrix of whether element meets your criteria
meets_criteria <- sapply(df[,-1], function(x) x >= -0.5 & x <= 1)

# "extract" elements that meet your criteria; result is a vector
df[,-1][meets_criteria]
</code>
If you also want to keep the row/col values associated with the element
(this follows @thelatemail's approach in the comments above):
<code># reshape to long
dflong <- tidyr::gather(df, dvar, dvalue, d1:d5)

# subset to meet your criteria
dflong[dflong$dvalue >= -0.5 & dflong$dvalue <= 1, ]
</code>
Comment: Thank you Dan - This works (although I should have mentioned I needed to retain the "test" row name also in the final result).  The tidy solution by "thelatemail" solved the problem!
Comment: Thanks again Dan!


Galeria com skew que ocupe largura da página

Question: É assim, eu estou a tentar fazer no meu site uma seccao que tem 10 graus de skew, o intuito era que essa seccao ocupasse 100% da largura da pagina, mas quando faço skew ficam as margens provenientes do skew, como posso fazer com que esta galeria ocupe a largura da pagina toda?
HTML:

SEE YOUR TOP ARTISTS

CSS:
/* ------------------------ SECTION ARTISTS -------------------- */

.section-artists {
    padding: 0;
}

.artists-showcase {
    list-style: none;
    display: inline;
    width: 200%;
    height: 100%;

}

.artists-showcase li {
    display: block;
    transform: skewX(-10deg);
    float: left;
    width: 25%;
    height: 100%;
}

.artist-photo {
    width: 100%;
    height: 100%;
    margin:0;
    overflow: hidden;
    background-color: #000;

}

.artist-photo img {
    opacity: 0.7;
    width: 100%;
    height: auto;
    -webkit-transform: scale(1.15);
    transform: scale(1.15);
    -webkit-transition: opacity 0.5s, -webkit-transform 0.5s;
    transition: opacity 0.5s, -webkit-transform 0.5s;
    transition: transform 0.5s, opacity 0.5s;
    transition: transform 0.5s, opacity 0.5s, -webkit-transform 0.5s;

}

.artist-photo img:hover {
    opacity: 1;
    -webkit-transform: scale(1.03);
    transform: scale(1.03);
}

Gostaria que essa area branca selecionada desaparecesse....

Obrigado pessoal!
Comment: Cara está meio complicado de entende exatamente até ande vc gostaria que o skwed fosse... Teria como vc colocar uma imagem na pergunta de como vc queria que ficasse?
Comment: Imagem adicionada!
Obrigado!
Answer: Cara foi preciso ajustar algumas coisas na classe da  eu mudei ela de display:inline para display:inline-block, e coloquei a largura de 110% pra jogar o branco do skwed pra fora da tela e ajustei a margem colocando um valor  negativo a esquerda de -5% e ficou direitinho alinhada no centro com 5% pra fora de cada lado.
Veja o exemplo para entender melhor:
EDIT: Para a imagem não fazer o skew vc tem que fazer nela o efeito oposto ao do PAI, então se vc colocou skew -10 po pai tem que colocar skew 10 no filho (no caso na imagem). Veja no código que vc vai entender deixei comentado no CSS

    .section-artists {
        padding: 0;
    }

    .artists-showcase {
        list-style: none;
        display: inline-block;
        width: 110%;
        height: 100%;
        padding: 0;
        margin-left: -5%;
    }

    .artists-showcase li {
        display: block;
        transform: skewX(-10deg);
        float: left;
        width: 25%;
        height: 100%;
    }

    .artist-photo {
        width: 100%;
        height: 100%;
        margin:0;
        overflow: hidden;
        background-color: #000;
    }

    .artist-photo img {
        opacity: 0.7;
        width: 100%;
        height: auto;
        -webkit-transform: scale(1.18) skewX(10deg); /* reverte o skew para a imagem ficar reta */
        transform: scale(1.18) skewX(10deg);
        -webkit-transition: opacity 0.5s, -webkit-transform 0.5s;
        transition: opacity 0.5s, -webkit-transform 0.5s;
        transition: transform 0.5s, opacity 0.5s;
        transition: transform 0.5s, opacity 0.5s, -webkit-transform 0.5s;
    }

    .artist-photo img:hover {
        opacity: 1;
        -webkit-transform: scale(1.085) skewX(10deg);
        transform: scale(1.085) skewX(10deg);
    }

SEE YOUR TOP ARTISTS

Comment: Sim é isso mesmo amigo! Obrigado
Mas como faço para as imagens não ficarem distorcidas? Nesse caso so quero o container com skew, nao as imagens.

Obrigado!
Comment: @NelsonPacheco ajustei o código, leia a parde do **EDIT** para entender como corrigi o `skew` na imagem.
Comment: Muito obrigado amigo!


Laravel: Save to database from multidimensional array

Question: How can I save this multidimentional array to may database in laravel?
I have an array details. Which has a key that has dates. Each date has hours, late, overtime and status.
"details": {

      "2019-07-01": {

        "hours": {
          "hours": 3.67,
          "late": 0.33,
          "overtime": 0.83
        },
        "status": "pending"

      },

      "2019-07-02": {

        "hours": {
          "hours": 7.17,
          "late": 0.83,
          "overtime": 2.83
        },

        "status": "approved"

      }

}

In my database I have this columns:
date , hours , late , overtime , status
I want to get the key from details and store it to date with its hours, lates, overtime, status.
Result:
date         | hours   | late  | overtime   | status
------       | ------  | ------| ------     | ------
2019-07-01   | 3.67    | 0.33  | 0.83       | pending
2019-07-02   | 7.67    | 0.83  | 2.83       | approved

How can I store this from laravel to database?
Comment: Can you provide code from your controller what you tried?
Answer: You can try this:
foreach($details as $key => $value) {

    DB::table('your_table')->insert(
        [
            'date' => $key,
            'hours' => $value['hours']['hours'],
            'late' => $value['hours']['late'],
            'overtime' => $value['hours']['overtime'],
            'status' => $value['status']
        ]
    );
}

Comment: please upvote and accept the answer if it works for you


Compute $\lim_{x \to +\infty}{\frac{\log(a+be^x)}{\sqrt{a+bx^2}}}$

Question: Please help me do the following problem which is in the book Calculus by Tom M. Apostol (vol.1, 2nd edition, p.303, exercise 4.).

Compute $$\lim_{x \to +\infty}{\frac{\log(a+be^x)}{\sqrt{a+bx^2}}}$$ where $a$ and $b$ are positive constants.

L'Hospital's rule for $\infty/\infty$ is not allowed, but I can use the property:$$\lim_{x \to +\infty}{\frac{(\log x)^b}{x^a}}=0$$where $a$ and $b$ are positive constants.
My Attempt:
\begin{align}
\frac{\log(a+be^x)}{\sqrt{a+bx^2}}
&<\frac{\log(a+be^x)}{\sqrt{bx^2}}\\
&=b^{-1/2}\frac{\log(a+be^x)}{x}\\
&=b^{-1/2}\frac{\log(a+bt)}{\log t}\;\;\;\;\;\;\;(t=e^x)\\
\end{align}
then I can't go any more.
Thank you for helping.
Answer: For $b>0$ we obtain:
$$\lim_{x\rightarrow+\infty}\frac{\ln(a+be^x)}{\sqrt{a+bx^2}}=\lim_{x\rightarrow+\infty}\frac{x+\ln\left(\frac{a}{e^x}+b\right)}{\sqrt{a+bx^2}}=\lim_{x\rightarrow+\infty}\frac{1+\frac{\ln\left(\frac{a}{e^x}+b\right)}{x}}{\sqrt{\frac{a}{x^2}+b}}=\frac{1}{\sqrt{b}}$$
Answer: $\ln(a + be^x) \sim \ln(be^x), x \to \infty$ and $\sqrt{a + bx^2} \sim \sqrt{b}x, x \to \infty$ hence your lim is equal to $\frac{1}{\sqrt{b}}$
Answer: $$
\lim_{x\to\infty}\frac{\log(a+be^x)}{\sqrt{a+bx^2}}
=\lim_{x\to\infty}\frac{\log(e^x)+\log(ae^{-x}+b)}{\sqrt{a+bx^2}}
=\lim_{x\to\infty}\left(\frac{x}{\sqrt{a+bx^2}}+\frac{\log(ae^{-x}+b)}{\sqrt{a+bx^2}}\right)
=\lim_{x\to\infty}\left(\frac{x}{\sqrt{a+bx^2}}+\frac{\log(ae^{-x}+b)}{ae^{-x}}\cdot\frac{ae^{-x}}{\sqrt{a+bx^2}}\right)
=\lim_{x\to\infty}\left(\sqrt{\frac{x^2}{a+bx^2}}+\frac{\log(ae^{-x}+b)}{ae^{-x}}\cdot\frac{a}{e^x\sqrt{a+bx^2}}\right)=\sqrt{\frac{1}{b}}+b\cdot0=\frac{1}{\sqrt{b}}
$$


general solution to retry a promise in javascript

Question: I try to give out a general solution for retrying a promise. Below is my way and comes an error of "Uncaught (in promise)".
How can I fix this problem?
function tryAtMost(maxRetries, promise) {
  let tries = maxRetries

    return new Promise(function(resolve, reject) {
        promise.then((result) => {
        resolve(result)
      })
        .catch(err => {
            if (tries > 0) {
                console.log(`tries with ${tries}`)
          tryAtMost(--tries, promise);
        } else {
          reject(err)
        }
        })
    })
}

tryAtMost(3, promise).then(result => {
  console.log(result)
})
.catch(err => {
  console.log(err)
})

Comment: what makes you think it's gonna work the second time?
Answer: The reason for what you asked about is that you're missing a call to resolve in your catch:
.catch(err => {
    if (tries > 0) {
        console.log(`tries with ${tries}`);
        resolve(tryAtMost(--tries, promise)); // <=== ****
    }
    else {
        reject(err)
    }
})

...and so you're creating a promise that is never handled by anything, and so if it rejects, you'll get an unhandled rejection.

But, tryAtMost has a problem: It cannot work with the information you've given it, because it doesn't know what to try. You need to pass it an executor, not a promise, because it's the work of the executor that you need to retry. This also makes the function a lot simpler:
function tryAtMost(tries, executor) {
    --tries;
    return new Promise(executor)
        .catch(err => tries > 0 ? tryAtMost(tries, executor) : Promise.reject(err));
}

Use:
tryAtMost(4, (resolve, reject) => {
    // The thing to (re)try
});

Example:

function tryAtMost(tries, executor) {
  console.log(`trying, tries = ${tries}`);
  --tries;
  return new Promise(executor)
    .catch(err => tries > 0 ? tryAtMost(tries, executor) : Promise.reject(err));
}

tryAtMost(4, (resolve, reject) => {
  const val = Math.random();
  if (val < 0.3) {
    resolve(val);
  } else {
    reject(val);
  }
})
.then(result => console.log(result))
.catch(err => console.error(err));


Convergence of series defined by sequence

Question: Okay, so I'm ever so slightly stuck on a question that sounds as follows
Let $\{a_n\}_{n=1}^\infty$ be a sequence such that $a_n>0$ for all $n$ and $\sum_{n=1}^\infty a_n$ converges. Show that
$$\sum_{n=1}^N a_n^2 \leq \left(\sum_{n=1}^N a_n \right)^2$$  where $N\geq 1$ is a natural numbers. Use then this result to show that
$$\sum_{n=1}^\infty a_n^2$$ converges.
Okay, so at first when I was looking at the sums in part one of the question it immediately looked similar to the cauchy-schwarz special case where we let $b_i$=1 such that
$$\left(\sum_{i=1}^N a_i\right)^2 \leq N\sum_{i=1}^N a_i^2$$
But it seems like a "this ain't it chief" moment.
As for the last part of the tasken, given the result in the question preceeding it, I was thinking using the comparison tests could be doable, but I'm not really sure where to start.
If someone could push me in the right direction that would be great!
Also I tagged this question as real-analysis because I wasn't sure whether this kind of question would be dipping its toe into that world, so I'm sorry if this is the wrong tag.
Answer: We are using that for any $n$
$$a_1^2+a_2^2+\ldots+a_n^2 \le (a_1+a_2+\ldots+a_n)(a_1+a_2+\ldots+a_n)=\\=(a_1^2+a_2^2+\ldots+a_n^2)+(2a_1a_2+2a_1a_3+\ldots+2a_{n-1}a_n) $$
then $S_N=\sum_{n=1}^N a_n^2 $ coverges since it is increasing and bounded.
Answer: Proof by induction: $N=1$ is trivial. Let the inequality hold for $N$. Then
\begin{align*}
\left(\sum_{n=1}^{N+1}a_n\right)^2
&= \left(\sum_{n=1}^{N}a_n + a_N\right)^2 = \left(\sum_{n=1}^{N}a_n\right)^2 + 2a_N\sum_{n=1}^{N}a_n + a_N^2\\
&\ge\,\sum_{n=1}^{N}a_n^2 + 2a_N\sum_{n=1}^{N}a_n + a_N^2\,\ge\,\sum_{n=1}^{N}a_n^2 + a_N^2 = \sum_{n=1}^{N+1}a_n^2.
\end{align*}
To show that $\sum_na_n^2$ converges, use the proved inequality and the very definition of limits of series (and the continuity of $x\mapsto x^2$).


Send the id of a selected option value to the controller

Question: I have a select option witch contains labels selected from the database!
My problem is that I don't want to send the value of the label, I want to send its id.
here is my code :

Veuillez choisir un cycle :

                  Cycle:

                  <form method="post" accept-charset="utf-8" action="<?php echo site_url("filiere/filiere_add"); ?>">

                 <select name="cyc" id ="Select1" class="input-small">

                    <?php foreach($cycle as $row) {?>

                         <option><?php echo $row->libelle; ?></option>

                    <?php }?>
                </select>
                  </form>

                  <button class="btn btn-success" onclick="display()"> display</button>

The table contains Id and libelle , I want to display libelle in the select option form but i want to send its id to the controller!
Thank you.
Comment: I could not understand your question as well as your code. Can you make it more understandable?
Comment: i have a form that will send two values to the controller and this form will be send by jquery function, but actually I want to send 3 values, the third value is in another form, how can I send the three values???
Answer: This is, how you should send the ID's to the controller:
<option value="<?php echo $row->id; ?>"><?php echo $row->libelle; ?></option>

Answer:     <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

Veuillez choisir un cycle :

                      Cycle:

                      <form method="post" accept-charset="utf-8" action="<?php  echo site_url("filiere/filiere_add"); ?>">

                     <select name="cyc" id ="Select1" class="input-small">

                        <?php foreach($cycle as $row) {?>

                             <option value="<?php echo $row->id; ?>"><?php echo $row->libelle; ?></option>

                        <?php }?>
                    </select>
                      </form>

                      <button class="btn btn-success" onclick="display()"> display</button>

      <button class="btn btn-success" onclick="add_filiere()"> Ajouter une filiere</button>

                 Identifiant
          Libellé

          Action

                <?php foreach($filiere as $row){?>

                         <?php echo $row->id;?>
                         <?php echo $row->libelle;?>

                                    <button class="btn btn-warning" onclick="edit_filiere(<?php echo $row->id;?>)"></button>
                                    <button class="btn btn-danger" onclick="delete_filiere(<?php echo $row->id;?>)"></button>

                     <?php }?>

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

Départements

        <form action="#" id="form" class="form-horizontal">

              Identifiant

                <input name="i" placeholder="Identifiant" class="form-control" type="text">

              Libelle

                <input name="l" placeholder="Nom" class="form-control" type="text">

        </form>

            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>


The set of functions which map convergent series to convergent series

Question: Suppose $f$ is some real function with the above property, i.e.
if $\sum\limits_{n = 0}^\infty {x_n}$ converges, then $\sum\limits_{n = 0}^\infty {f(x_n)}$ also converges.
My question is: can anything interesting be said regarding the behavior of such a function close to $0$, other than the fact that $f(0)=0$?
Comment: A simple example: If $\sum x_n$ converges absolutely, then any $f(x) = O(x)$ has the desired property.
Comment: See also [$f$ such that $\sum a_n$ converges $\implies \sum f(a_n)$ converges](http://math.stackexchange.com/questions/1332433/f-such-that-sum-a-n-converges-implies-sum-fa-n-converges)
Comment: All I can think is that , if the space you're in is complete, uniformly-continuous functions take Cauchy sequences to Cauchy sequences. This allows a unique continuous extension for functions defined in dense subsets.And continuous alone is not enough for this last, as f(x)=1/(x-2^{1/2}) is an example.
Comment: Let me ask this: must $f$ be continuous at $0$?
Comment: I misread your question so deleted the comment I posted.
Comment: Are your spaces--initial and target--complete, or do you want a more general result for any spaces? From your f(0)=0, I assume your maps are from R to R?
Comment: Yes, $f$ goes from $\mathbb{R}$ to $\mathbb{R}$
Comment: Let me also mention that what I am primarily interested in, is whether this set of functions has some interesting universal property, such as being continuous at $0$, and if so, what the "best" such property is. For instance, can anyone come up with an example of a non-polynomial such $f$?
Answer: I'm quite late on this one, but I think the result is nice enough to be included here.
Definition A function $f : \mathbb R \to \mathbb R$ is said to be convergence-preserving (hereafter CP) if $\sum f(a_n)$ converges for every convergent series $\sum a_n$.
Theorem (Wildenberg): The CP functions are exactly the ones which are linear on some neighbourhood of $0$.
Proof (Smith): Clearly, whether $f$ is CP only depends on the restriction of $f$ on an arbitrary small neighbourhood of $0$. Since the linear functions are CP, the condition is clearly sufficient. Let's prove that it is also necessary.
We will prove two preliminary results.
Lemma 1: $f$ CP $\Rightarrow$ $f$ continuous at $0$.
Proof: Let's suppose that $f$ isn't continuous at 0. This implies that there exists a sequence $\epsilon_n \to 0$ and a positive real $\eta > 0$ such that $\forall n, |f(\epsilon_n)| \geq \eta$. But it is easy to extract a subsequence $\epsilon_{\phi(n)}$ such that $\sum \epsilon_{\phi(n)}$ converges (take $\phi$ such that $\epsilon_{\phi(n)} \leq 2^{-n}$, for instance). For such a subsequence, we still have that $|f(\epsilon_{\phi(n)})| \geq \eta$. This prevents $\sum f(\epsilon_{\phi(n)})$ to converge and, thus, $f$ to be CP, a contradiction.
Lemma 2: The function $(x, y) \mapsto f(x+y) + f(-x) + f(-y)$ vanishes on some neighbourhood of $0$.
Proof: If it didn't, one would be able to find sequences $x_n \to 0$ and $y_n \to 0$ s.t. $\forall n, f(x_n + y_n) + f(-x_n) + f(-y_n) \neq 0$. Up to some extraction, we can assume that $\delta_n = f(x_n + y_n) + f(-x_n) + f(-y_n)$ always has the same sign (let's say $\delta_n > 0$, for the sake of simplicity.)
Consider now the series $$\begin{array}{l@{}l}
(x_0 + y_0) &+ (-x_0) + (-y_0) +  \cdots + (x_0 + y_0) + (-x_0) + (-y_0)\\
& +(x_1 + y_1) + (-x_1) + (-y_1) +  \cdots + (x_1 + y_1) + (-x_1) + (-y_1)\\
&+\cdots\\
&+(x_n + y_n) + (-x_n) + (-y_n) +  \cdots + (x_n + y_n) + (-x_n) + (-y_n)+\cdots,
\end{array}$$
where every triplet of termes $(x_i+y_i) + (-x_i) + (-y_i)$ is repeated $M_i > 0$ times, for some integer $M_i > 0$.
Because $x_n \to 0$ and $y_n \to 0$ and the three terms $x_i + y_i, -x_i, -y_i$ add to 0, it is easy to see that this series is convergent, regardless of the choice of the $M_i$'s.
On the other hand, if we choose $M_i \geq \delta_i^{-1}$, the image of our series by $f$ is $$\begin{array}{l@{}l}
f(x_0 + y_0) &+ f(-x_0) + f(-y_0) +  \cdots + f(x_0 + y_0) + f(-x_0) + f(-y_0)\\
& +f(x_1 + y_1) + f(-x_1) + f(-y_1) +  \cdots + f(x_1 + y_1) + f(-x_1) + f(-y_1)\\
&+\cdots\\
&+f(x_n + y_n) + f(-x_n) + f(-y_n) +  \cdots + f(x_n + y_n) + f(-x_n) + f(-y_n)+\cdots,
\end{array}$$
which diverges, for every line adds to $M_i \delta_i > 1$. Again, this in direct contradiction with the CPness of $f$.
If we apply the result of lemma 2 with $y = 0$, we get that $f(-x) = -f(x)$. So we can rewrite lemma 2 in the following way:
$\exists \eta > 0 : \forall x, y \in (-\eta, \eta), f(x+y) = f(x) + f(y)$.
This property and the continuity at 0 imply first the continuity on the whole of $(-\eta, \eta)$ and it is then not hard to adapt the classical proof to show that $f$ is linear on $(-\eta, \eta)$. Q.E.D.
Comment: Do you mean, in applying lemma 2, that $f(-x)=-f(x)$? Hard to see how you'd get $f(x)=-x$.
Comment: Great answer! Thank you.
Comment: You're absolutely right, of course. I fixed it.
Answer: If $f$ is not continuous at $0$, then we can find a sequence $x_n$ that converges to $0$ but $f(x_n)$ doesn't converge to $0$. First get a subsequence $y_n$ of $x_n$ with $|f( y_n)| > r$ for some $r>0$. Next choose some subsequence $z_n$ of $y_n$ so that
$\sum z_n$ converges. However the series $\sum f(z_n)$ diverges and it follows that $f$ is continuous at $0$.
Comment: Ok, next question: must $f$ be differentiable at $0$?
Answer: Answer to the next question: no.
Let $f\colon\mathbb{R}\to\mathbb{R}$ be defined by
$$
f(x)=\begin{cases}
n\,x & \text{if } x=2^{-n}, n\in\mathbb{N},\\
x & \text{otherwise.}
\end{cases}
$$
Then $\lim_{x\to0}f(x)=f(0)=0$, $f$ transforms convergent series in convergent series, but $f(x)/x$ is not bounded in any open set containing $0$. In particular $f$ is not differentiable at $x=0$. This example can be modified to make $f$ continuous.
Proof.
Let $\sum_{k=1}^\infty x_k$ be a convergent series. Let $I=\{k\in\mathbb{N}:x_k=2^{-n}\text{ for some }n\in\mathbb{N}\}$. For each $k\in I$ let $n_k\in\mathbb{N}$ be such that $x_k=2^{-n_k}$. Then
$$
\sum_{k=1}^\infty f(x_k)=\sum_{k\in I} n_k\,2^{-n_k}+\sum_{n\not\in I} x_n.
$$
The series $\sum_{k\in I} n_k\,2^{-n_k}$ is convergent. It is enough to show that also $\sum_{n\not\in I} x_n$ is convergent. This follows from the equality
$$
\sum_{n=1}^\infty x_n=\sum_{n\in I} x_n+\sum_{n\not\in I} x_n
$$
and the fact that $\sum_{n=1}^\infty x_n$ is convergent and $\sum_{k\in I} x_n$ absolutely convergent.
The proof is wrong. $\sum_{k\in I} x_n$ may be divergent. Consider the series
$$
\frac12-\frac12+\frac14-\frac14+\frac14-\frac14+\frac18-\frac18+\frac18-\frac18+\frac18-\frac18+\frac18-\frac18+\dots
$$
It is convergent, since its partial sums are
$$
\frac12,0,\frac14,0,\frac14,0,\frac18,0,\frac18,0,\frac18,0,\frac18,0,\dots
$$
The transformed series is
$$
\frac12-\frac12+\frac24-\frac14+\frac24-\frac14+\frac38-\frac18+\frac38-\frac18+\frac38-\frac18+\frac38-\frac18+\dots
$$
whose partial sums are
$$
\frac12,0,\frac12,\frac14,\frac34,\frac12,\frac78,\frac34,\frac98,1,\frac{11}8,\frac54,\dots
$$
which grow without bound.

On the other hand, $f(x)=O(x)$, the condition in Antonio Vargas' comment, is not enough when one considers series of arbitrary sign. Let
$$
f(x)=\begin{cases}
x\cos\dfrac{\pi}{x} & \text{if } x\ne0,\\
0 & \text{if } x=0,
\end{cases}
\quad\text{so that }|f(x)|\le|x|.
$$
Let $x_n=\dfrac{(-1)^n}{n}$. Then $\sum_{n=1}^\infty x_n$ converges, but
$$
\sum_{n=1}^\infty f(x_n)=\sum_{n=1}^\infty\frac1n
$$
diverges.
Comment: Not sure $\sum\limits_{k\in I}n_k/2^{n_k}$ always converges. Consider $(x_i)_{i\geqslant1}$ such that every $x_i$ is a negative power of $2$ and assume that $x_i=1/2^k$ roughly $2^k/k^2$ times. Then $\sum\limits_{i\geqslant1}x_i\approx\sum\limits_{k\geqslant1}1/k^2$ converges but $\sum\limits_{i\geqslant1}f(x_i)\approx\sum\limits_{k\geqslant1}1/k$ diverges.
Comment: Aside from Didier's point above, are you certain you can split the series?
Comment: Can you please provide a short proof why $f$ sends convergent series to convergent series?
Comment: I have written the proof.


Difference between linq to entities and linq to sql

Question:
Possible Duplicate:
Entity Framework vs LINQ to SQL

What is the difference between linq to entities & linq to sql?
Why linq to entities came into picture?
Comment: Dupe: http://stackoverflow.com/questions/8676/entity-framework-vs-linq-to-sql
Answer: linq to sql is being discontinued.
linq to entities is MS's new thing and will be replacing their linq to sql stuff.
Comment: Hmm. Linq to Entities has nothing to do with Linq to SQL, except it uses the same Linq syntax. They're for completely different data access mechanisms.

It may be more accurate to say that Microsoft is investing more in Entity Framework than Linq to SQL, but even that's not completely clear.
Answer: Linq to SQL is for direct queries using SQL Server, regardless of using Entity Framework.
Linq to Entities is Linq used while using Microsoft's Entity Framework, regardless of db server.
Comment: LINQ to SQL also has support for practically any other database with dblinq (an open source, drop in assembly replacement) see http://dblinq.codeplex.com/.


Divisibility problem involving the floor function

Question: I am trying to prove the following:

$$2^{m+1}\mid\lfloor(1+\sqrt{3})^{2m+1} \rfloor$$ but $2^{m+2}\nmid\lfloor(1+\sqrt{3})^{2m+1} \rfloor$ for every natural number $m$.

I tried to use induction on $m$ but am not sure how to use the induction hypothesis. (The base case is easy to verify). Is there some other way to approach this problem?
Thanks.
Comment: Perhaps it will come in handy to know that $(1+\sqrt3)^{2m+1}+(1-\sqrt3)^{2m+1}$ is always an integer, and $(1-\sqrt3)^{2m+1}$ approaches zero quickly.
Answer: Consider the recurrence $x_0=2, x_1=20$ and $x_n=8x_{n-1}-4x_{n-2}$ for $n \geq 2$. It has characteristic polynomial $x^2-8x+4$, with roots $4 \pm 2\sqrt{3}=(1 \pm \sqrt{3})^2$, so $x_n=a(1+\sqrt{3})^{2n}+b(1-\sqrt{3})^{2n}$ for some contants $a, b$.
Using the values for $x_0, x_1$, we get:
$$2=a+b$$
$$20=a(1+\sqrt{3})^2+b(1-\sqrt{3})^2=4(a+b)+2\sqrt{3}(a-b)=8+2\sqrt{3}(a-b)$$
$$a-b=\frac{12}{2\sqrt{3}}=2\sqrt{3}$$
$$a=\frac{2+2\sqrt{3}}{2}=1+\sqrt{3}, b=\frac{2-2\sqrt{3}}{2}=1-\sqrt{3}$$
Therefore $x_n=(1+\sqrt{3})^{2n+1}+(1-\sqrt{3})^{2n+1}$. Note that $x_n$ is an integer, and $-1<(1-\sqrt{3})^{2n+1}<0$, so $\lfloor(1+\sqrt{3})^{2n+1}\rfloor=\lfloor x_n-(1-\sqrt{3})^{2n+1} \rfloor=x_n$.
The problem is thus equivalent to proving that $2^{n+1} \| x_n$. We proceed by induction.
When $n=0$, clearly $2^1 \|2=x_0$.
When $n=1$, clearly $2^2 \|20=x_1$.
Suppose that the statement holds for $0 \leq n \leq k, k \geq 1$. Then $2^{k} \|x_{k-1}$ and $2^{k+1}\|x_k$. Therefore $x_{k+1}=8x_k-4x_{k-1} \equiv 2^{k+2} \pmod{2^{k+3}}$, so $2^{k+2} \|x_{k+1}$.
We are thus done by induction.
Answer: A different approach in the language of elementary theory of algebraic numbers.
I abbreviate $\alpha=1+\sqrt3$ and $\overline{\alpha}=1-\sqrt3=-\alpha(2-\sqrt3)$
As observed by Gerry Myerson and Ivan Loh we have i) $-1<\overline{\alpha}<0$, and ii) $\alpha^{2m+1}+\overline{\alpha}^{2m+1}\in\mathbb{Z}$, so
$$x_m:=\lfloor(1+\sqrt{3})^{2m+1} \rfloor=\alpha^{2m+1}+\overline{\alpha}^{2m+1}=
\alpha^{2m+1}\left(1-(2-\sqrt3)^{2m+1}\right).\qquad(*)$$
I shall work in the ring $R=\mathbb{Z}[\sqrt3]=\{a+b\sqrt3\mid a,b\in\mathbb{Z}\}$. From algebraic number theory I use the facts that $R$ is a PID and that the prime $2$ ramifies in $R$ as $(2)=(\alpha)^2$. In other words $\alpha^2$ and $2$ are associates, as
$$
\alpha^2=4+2\sqrt3=2(2+\sqrt3)
$$
and $2+\sqrt3$ is a unit of $R$, because $(2+\sqrt3)(2-\sqrt3)=1$.
Let us consider the ideal $I=2R=(\alpha)^2\subset R$. As $I=2R$, it has four cosets in $R$: a useful set of representatives being $0,1,\sqrt3,1+\sqrt3$. We see that $2-\sqrt3\equiv\sqrt3\pmod{I}.$ As $\sqrt3^2=3\equiv1\pmod I$ we get that
$$
(2-\sqrt3)^{2m+1}\equiv\sqrt3\pmod I
$$
for all integers $m$. Plugging this into our equation $(*)$ we see that
$$
x_m=\alpha^{2m+1}q_m,
$$
where $q_m$ is an element of $R$ such that
$$
q_m\equiv 1+\sqrt3 \pmod I.
$$
So in the ring $R$ we have $\alpha\mid q_m$, but $\alpha^2\nmid q_m$.
Therefore $\alpha^{2m+2}$ is the highest power of $\alpha$ dividing $x_m$. As $\alpha^2$ and $2$ are associates, and we have unique factorization, this tells us that $2^{m+1}$ is the highest power of two dividing $x_m$.
Comment: Like an small survey.


casting *mut u8 to &[u8] without std

Question: I'm writing Rust code for WebAssembly to handle strings from JavaScript land.
Since WebAssembly has no real string type, I'm trying to pass a pointer to WebAssembly memory object which points to UTF-8 encoded string.
#[no_mangle]
pub extern "C" fn check(ptr: *mut u8, length: u32) -> u32 {
    unsafe {
        let buf: &[u8] = std::slice::from_raw_parts(ptr, length as usize);
        // do some operations on buf
        0
    }
}

It works fine, expect that I have to depend on the std crate, which bloats the final binary to about 600KB.
Is there any way to get rid of std::slice::from_raw_parts but still be able to cast a raw pointer to a slice?
Comment: @Shepmaster wasm-gc is helpful. It will shrink the binary down to about 248KB. But without std crate, the binary size can be shrink to 18KB, which contains ~17KB data and only ~1KB code.
Comment: @Boiethios Yeah, I'm aware of that. The last return statement was appended temporarily but forgot to strip return. Thanks.
Comment: *which bloats the final binary* — this sounds like a toolchain problem. Are you running wasm-gc?
Comment: The thing is, the ultimate amount of code that you use from `libcore` is the *exact same* that you use from `libstd`. `std::slice::from_raw_parts_mut` **is** `core::slice::from_raw_parts_mut`. Switching from one to the other *shouldn't* change anything. It really sounds like some piece of unused code or data isn't being properly removed.
Comment: @Shepmaster In fact, in order to get rid of `std`, I also add "#![no_std]" and its counterparts. Those code made a lot difference on the final binary.
Comment: I'm not sure you are following what I am saying. The code that your program is using is identical when using it through libstd and libcore. The fact that switching to libcore produces a different sized result **is a bug** because you aren't using any of the unique functionality of libstd. I just don't know where the bug is, it could be in Rust or it could be in the linker, or other toolchain components.
Comment: Unless you have forgotten to build your WASM code as a `cdylib`, in which case there's probably a lot of junk for the unused `main` function lying around.
Comment: @Shepmaster I do understand what you mean. But I have no clue why this is happening. I made a simplest example for this issue, in case you may want to reproduce it: https://github.com/liuyanghejerry/rust-wasm-size-bug
Answer: You cannot cast a raw pointer to a slice because in Rust, a slice is not a mere pointer, it is a pointer and a size (otherwise it could not be safe).
If you do not want to use std, you can use the core crate:
extern crate core;

#[no_mangle]
pub extern "C" fn check(ptr: *mut u8, length: u32) -> u32 {
    unsafe {
        let buf: &mut [u8] = core::slice::from_raw_parts_mut(ptr, length as usize);
    }
    // do some operations on buf
    0
}

The core crate is the part of the std crate suitable for embedded, i.e. without all the stuff that needs some allocation.
Answer: It is possible to manually construct something similar to a slice, which is a fat pointer that consists of a thin pointer and a length. Then cast a pointer-to-this-construct to a pointer-to-slice.
This approach is not only unsafe, it also relies on Rust internals (memory layout of a slice) that are not guaranteed to remain stable between compiler version, or even systems I suppose. @Boiethios' answer is the way to go if you want to be sure that your code works correctly in the future. However, for educational purposes, the code below may still be interesting:
unsafe fn make_slice<'a>(ptr: *const u8, len: usize) -> &'a [u8] {
    // place pointer address and length in contiguous memory
    let x: [usize; 2] = [ptr as usize, len];

    // cast pointer to array as pointer to slice
    let slice_ptr = &x as * const _ as *const &[u8];

    // dereference pointer to slice, so we get a slice
    *slice_ptr
}

fn main() {
    let src: Vec<u8> = vec![1, 2, 3, 4, 5, 6];
    let raw_ptr = &src[1] as *const u8;

    unsafe {
        println!("{:?}", make_slice(raw_ptr, 3));  // [2, 3, 4]
    }
}

(tested on playground with Rust Stable 1.26.2)
Comment: This is very interesting. Is there any document or origin of this approach that I can track later?
Comment: @liuyanghejerry The memory layout of slices is loosely described in [the book](https://doc.rust-lang.org/book/second-edition/ch04-03-slices.html#string-slices) (figure 4-6). Knowing that, the rest is just pointer mangling to reinterpret the meaning of stuff in memory.

casting *mut u8 to &[u8] without std


python global variable access: keep define in every functions?

Question: I have three functions that want to change a global variable and can't combine into one function, the way I know right now is keep define "global" keyword in each functions to be able to access global variable. Is there a better way to do the same thing with out keep redefining the global variable? for example:
    def fn1(self):
        global NUM
        NUM = 1
        print "fn1 = ",  NUM

    def fn2(self):
        global NUM
        NUM = 2
        print "fn2 = ",  NUM

    def fn3(self):
        global NUM
        NUM = 3
        print "fn3 = ",  NUM

NUM = 0
fn1(NUM)
fn2(NUM)
fn3(NUM)

Thank you
Comment: Make your functions take a value and return a value. Then you don't need a global variable at all.
Comment: Where is the rest of your class? Why not create a `self.num` (or `cls.num)` that all can access? Why not return the modified num aka `NUM = fn1(NUM)`? Where is the classinstance before `fn1`,`fn2`,`fn3`? Any "course of action" that we could suggest heavily depends on the code you have not yet shown. Please edit your question to a full [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) to avoid multiple low-quality answers / guesstimates that - in the end - do not really fit.
Comment: @Tom Dalton Yes, thanks.
Comment: @PatrickArtner I just want to get the general idea and I'm new to python. So might not have enough knowledge about how to write a  complete class. But you suggestion is right. Thanks.
Comment: Start with the tutorial: [Classes](https://docs.python.org/3/tutorial/classes.html)
Comment: Thanks @PatrickArtner
Answer: Why don't you define another function, which changes the value of the global variable with the argument provided as parameter. And call this in rest of your function. For example :
var=None

class A:

  def change(self,num):
     global var
     var = num

  def first(self,num):
    self.change(num)

  def second(self,num):
    self.change(num)

  def third(self,num):
    self.change(num)

a=A()

a.first(1)
print 'value of global variable',var

a.second(2)
print 'value of global variable',var

a.third(3)
print 'value of global variable',var

Otherwise, if the scope of your global variable is supposed to be confined within your class then declare it as a member of the class, and let the functions change it's value. For example :
class A:

  def __init__(self):
     self.var=None
     print "default = ",  self.var

  def first(self,num):
    self.var=num
    print "fn1 = ",  self.var

  def second(self,num):
    self.var=num
    print "fn2 = ",  self.var

  def third(self,num):
    self.var=num
    print "fn3 = ",  self.var

a=A()

a.first(1)
print 'value of variable',a.var

a.second(2)
print 'value of variable',a.var

a.third(3)
print 'value of variable',a.va

Comment: Thanks, this is what I need.
Comment: @YHS if you are satisfied with the answer then you can accept the answer by clicking on the tick button
Comment: I don't have enough reputation though. :P
Answer: You can make the global variable a mutable class and then mutate in place.
global_dict = {"data": 1}
global_list = [1]

class MutableInt:
    def __init__(self, value=1):
        self.value = value

global_int = MutableInt()

This works, but personally I wouldn't call that any better. With the global it is at least 100% clear that you change a global variable. Best would be to change your architecture to not need any global variables.
Answer: it seems like the function are part of a class , based on the self keyword , if so they all can access class variable without the need of global keyword, if they are not part of a class you can:
define  each function with a given parameter to the function and make that function return a value.
 def func1(param_1):
     #work on param_1
     return param_1


Negative Binomial Distribution Example.

Question: A company takes out an insurance policy to cover accidents that occur at its manufacturing plant. The probability that one or more accidents will occur during any given month is 3/5. The number of accidents that occur in any given month is independent of the number of accidents that occur in all other months. Calculate the probability that there will be at least four months in which no accidents occur before the fourth month in which at least one accident occurs.
Can anyone please solve this using the N-Binomial formula with X trials needed until the rth success and not with Y failures before rth success since the former is the way i learnt the formula. or both methods if that makes the explanation even clearer. Much thanks in advance.
Comment: I think they phrased it for confusing students even more.
probability of an accident = 3/5
r = 4?
Comment: do you guys think it's easier using negative binomial with failures till r success or total trials till r successes?
Answer: If we let $X$ represent the $NegBin(r,p)$, where $X$ is the number of trails until the $r$th success, where each success occurs with a probability $p$ , then if I understand your problem correctly, you want the probability $P(X > 4)$, or the probability it takes more than 4 months, for the first ($r = 1$) "success" (which is having a month where an accident occurs), which happens with a probability $p = \frac{3}{5}$.
In this case, we can solve for $P(X > 4)$ in two ways:

$P(X > 4) = 1 - P(X = 1) - P(X = 2) - P(X = 3) - P(X = 4)$
$P(X > 4) = P(X = 5) + P(X = 6) + ... $

You can calculate out the first method by hand and you get $\boxed{\frac{16}{625}}$
By the second method you get the following geometric sum: $(\frac{2}{5})^{4} * (\frac{3}{5}) + (\frac{2}{5})^{5} * (\frac{3}{5}) + (\frac{2}{5})^{6} * (\frac{3}{5}) + ... = \frac{(\frac{2}{5})^{4} * (\frac{3}{5})}{ 1 - \frac{2}{5}} = (\frac{2}{5})^{4} = \boxed{\frac{16}{625}}$
As you can see both methods yield the same answer.
Comment: Answer is 0.29. no i think it they want the probability that it takes at least 4 months of failure till 4 successes. So r=4 and if X= no.of months it takes 4 successes, X can equal 4 (0 failures), 5 (1 failure), 6 (2 failures), 7(3 failures), and so on. they want X to be greater or equal to 8 (4 failures). Wait I think i know how to tackle this now using P(X>=8)=1−P(X=4)-P(X=5)−P(X=6)−P(X=7) since the possible values of X start from 4,5,6,7,....
Comment: Ah sorry, I think I misunderstood the question @SyedBukhari.

Negative Binomial Distribution Example.


O que é código pythônico?

Question: Em programação Python é comum ouvir o termo pythônico (ou pythonic), veja:

SOpt: "Entendendo o modo pythônico de lidar com propriedades"
SOpt: "Passar parâmetros de forma pythônica"
Wikipedia: "Python (programming language)"
python.net: "Code Like a Pythonista: Idiomatic  Python"

O que significa o termo pythônico e o que diferencia um código não-pythônico de um código pythônico?
Comment: Relacionada: http://pt.stackoverflow.com/q/184238/41056
Answer: O que é Pythonico?
A expressão pythonico, originada no inglês, pythonic, é uma expressão vaga, isto é, sem um significado exato. Geralmente é utilizada para referenciar um código idiomático em Python. O termo ficou famoso e mundialmente utilizado principalmente pelo sucesso que o Python faz com algumas soluções extremamente simples. Já cheguei a ouvir citações dizendo: "se você não fez em uma linha de código, você fez errado". Claro que isso não é literal, mas expressa bem como é a abordagem da linguagem.
O que faz um código ser considerado pythonico?
Criado com Tim Peters, um BDFL da linguagem Python, e extremamente bem recebido pela comunidade, o grupo de 20 aforismos conhecido como The Zen of Python (PEP 20) é o ponto principal para definir se um código é idomático ou não. Definido pelo próprio Guido van Rossum, criador da linguagem, como a perfeita descrição da filosofia do Python, basta fazer um código consistente com todos os aforismos para ter um código idiomático. São eles:
(1) Beautiful is better than ugly.
Bonito é melhor que feio.
(2) Explicit is better than implicit.
Explícito é melhor que implícito.
(3) Simple is better than complex.
Simples é melhor que complexo.
(4) Complex is better than complicated.
Complexo é melhor que complicado.
(5) Flat is better than nested.
Plano é melhor do que aninhado.
(6) Sparse is better than dense.
Esparso é melhor que denso.
(7) Readability counts.
Legibilidade conta.
(8) Special cases aren't special enough to break the rules.
Casos especiais não são especiais o bastante para quebrar as regras.
(9) Although practicality beats purity.
Ainda que praticidade vença a pureza.
(10) Errors should never pass silently.
Erros nunca devem passar silenciosamente.
(11) Unless explicitly silenced.
A menos que sejam explicitamente silenciados - vide aforismo 2.
(12) In the face of ambiguity, refuse the temptation to guess.
Diante da ambiguidade, recuse a tentação de adivinhar.
(13) There should be one-- and preferably only one --obvious way to do it.
Deveria haver um — e preferencialmente só um — modo óbvio para fazer algo: o modo pythonico.
(14) Although that way may not be obvious at first unless you're Dutch.
Embora esse modo possa não ser óbvio a princípio a menos que você seja holandês.
(15) Now is better than never.
Agora é melhor que nunca.
(16) Although never is often better than right now.
Embora nunca frequentemente seja melhor que agora.
(17) If the implementation is hard to explain, it's a bad idea.
Se a implementação é difícil de explicar, é uma má ideia.
(18) If the implementation is easy to explain, it may be a good idea.
Se a implementação é fácil de explicar, pode ser uma boa ideia - mas não necessariamente.
(19) Namespaces are one honking great idea -- let's do more of those!
Namespaces são uma grande ideia — vamos ter mais dessas!

Se reparar, o aforismo 7 indica que legibilidade do código é algo importante. De fato, é, tanto que um dos principais itens levados em conta pelo Guido van Rossum ao criar a linguagem foi que o código devesse ser legível aos humanos na mesma facilidade que uma máquina conseguisse lê-lo. Isto é, as estruturas deveriam seguir uma organização que se aproximassem ao máximo da escrita cotidiana do desenvolvedor, utilizando os blocos de indentação para gerenciar contextos. A formatação do código é tão importante no Python que a principal Python Enhancement Proposals (PEP) é a que define o guia de estilos para códigos Python: PEP 8. E ninguém mais indicado que o próprio criador da linguagem para definir o que é melhor para ela, certo? O documento é relativamente longo e inviável transcrevê-lo aqui, mas isso não deve reduzir sua importância. Para facilitar, você pode instalar em seu editor algum componente relacionado ao Python Lint que provavelmente ele te guiará conforme todas as recomendações da PEP 8.
Exemplos
Segue abaixo uma lista de exemplos simples que são considerados e aceitos pela comunidade como pythonicos.

Permutar valores em variáveis
Outras linguagens:
int x = 1,
    y = 2,
    temp;

temp = x;
x = y;
y = temp;

Em Python:
x = 1
y = 2

x, y = y, x

O código funciona pois o que na verdade ocorre é um tratamento de tuplas. A sintaxe do lado direito, y, x, gera uma tupla de dois valores (tuple packing). Já a sintaxe do lado esquerdo faz o oposto (tuple unpacking), atribuindo cada posição da tupla à uma variável, fazendo com que x receba o valor de y e y o valor de x.
Declaração de switch?
Outras linguagens:
int num = 3;

switch (num) {
    case 0:
        ...
    case 1:
        ...
    case 2:
        ...
    default:
        ...
}

Não existe uma construção switch no Python. O modo pythônico de fazer é usando um dicionário.
opcoes = {
    1: uma_funcao_qualquer,
    2: outra_funcao_qualquer,
    3: mais_uma_funcao
}

E chamar a função assim:
opcoes[variavel_inteira]()

Desta forma, opcoes[variavel_inteira] retornará a respectiva função e será executada imediatamente devido aos () no final da linha.
Declaração de do .. while?
Para a validação de um valor de entrada do usuário, por exemplo, é comum que tenhamos que ficar pedindo um novo valor até que o mesmo seja válido. Em outras linguagens há a estrutura do..while, mas em Python não. Veja o exemplo para a leitura de um valor natural:
Outras linguagens:
int num;

do {
    scanf("%d", &num);
} while (num < 0);

Python:
while True:
    num = int(input())
    if num >= 0:
        break;

Ou seja, em Python cria-se um loop infinito com while True e internamente é verificado se a condição desejada foi satisfeita, encerrando o loop com break.
Percorrendo uma lista com chave/valor:
É bastante comum que tenhamos que percorrer uma lista de valores utilizando tanto a chave quando o valor desta lista. Algumas linguagens fornecem a estrutura foreach que retorna o par chave/valor, porém no Python, a estrutura for retorna apenas o valor.
Outras linguagens:
int seq[5] = {0, 1, 2, 3, 4};

for (int i = 0; i < 5; i++) {
    printf("%d, %d\n", i, seq[i]);
}

Python:
seq = [0, 1, 2, 3, 4]

for key, value in enumerate(seq):
    print(key, value)

O acesso ao par chave/valor é feito através da função enumerate, que retorna uma tupla de dois valores: o primeiro a chave e o segundo o valor. Dentro da estrutura do for é feito uma tuple unpacking para as variáveis key e value.
Testando Vazio/Nulo:

Em Python, toda e qualquer variável testada como booleano devolve False nos seguintes casos:

False
None
0, seja qual for o tipo numérico
Sequências vazias ('', (), [])
Mapeamentos vazios: {}
Instâncias de classes "vazias", cujas classes implementem ou __nonzero__() (e devolvam False) ou __len__() (e devolvam zero).

Isso é útil para testar sequências com valores vazios, falsos ou zerados:
for item in lista:
    if item: print(item)

Percorrer linhas de um arquivo
Python:
with open("/tmp/arquivo.txt") as file:
    for line in file:
        print(line) # line possui o conteúdo de cada linha

Para mais detalhes do with, leia Para que serve o with no Python?. A função nativa open retorna um generator que iterará sobre o arquivo, desta forma é possível utilizar o objeto diretamente em um laço de repetição, sem ter que armazenar o conteúdo inteiro do arquivo em memória.

Referências e leituras obrigatórias
[1] The Zen of Python: https://www.python.org/dev/peps/pep-0020/
[2] Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008/
Comment: Muito boa sua resposta, Anderson. Só acrescentar que o texto "The Zen of Python" também é uma PEP (Python Enhancement Proposal), é a PEP 20.
Comment: Eu costumo usar `if`/`elif`/`else` no lugar do switch.
Answer: A maneira "tradicional" - se é que eu posso chamar assim - de escrever um código da maneira que conhecemos pode ser simplificado usando Python, quando você olha a estrutura de um loop construído em Java ou C:
Em C por exemplo:
//aloca 1000 posições
int vetor[1000];

for( int i=0; i < 1000; i++) {
    vetor[i] = i;
}

É um for tradicional que preenche as 1000 posições do vetor conforme vai incrementando até o final. Esse código pode ser escrito em Python, certo?
Seguindo a mesma estrutura do C, em Python:
#aloca 1000 posições
vetor= [None] * 1000

for i in range(1000):
    vetor[i]=i

A grosso modo, Python é conhecido por ser uma linguagem de rápido desenvolvimento, como dizemos por aí: "rápido e rasteiro" quando você faz um for em Python da maneira que te mostrei, não está errado, ele funciona, mas não é considerado uma maneira pythônica, você esta desperdiçando as vantagens que a linguagem te dá. Você pode fazer isso de outra maneira, mais simples, mais rápido, mais prático, mais organizado, etc...
Veja o que é considerado uma maneira pythônica de fazer o mesmo for:
vetor = [i for i in range(1000)]

O que diferencia um código não-pythônico de um código dito pythônico?

Tá ai um exemplo prático, você aproveitou os artifícios da linguagem para fazer a mesma coisa em uma só linha, você está usando as vantagens da linguagem no seu código, se você olhar no wiki do Python, veja as prioridades da linguagem:

Prioriza a legibilidade do código sobre a velocidade ou
expressividade. Combina uma sintaxe concisa e clara.

Tá aí uma explicação menos teórica e mais prática :-)
Comment: Ótima explicação também, com um exemplo prático.
Comment: eu faria `vetor = list(range(1000))`
Comment: @JJoao a intenção não foi mostrar como criar um vetor de 0 até 1000, a intenção foi demonstrar como fazer um for(loop) de maneira Pythônica  ....
Comment: @ederwander, eu sei, eu sei. A tua resposta está optima (+1). Eu só comentava porque implicitamente à noção "pytónica" para mim há associada algo de comparativo, e de "não há uma solução mais pythónica que" :-)
Answer: As expressões idiomáticas de uma linguagem de programação são definidas por seus usuários. A comunidade Python concebeu e vem utilizando o adjetivo pythônico para descrever qualquer código que siga um estilo em particular. Os desenvolvedores Python preferem ser explícitos, escolhem o simples em vez do complicado e maximizam a legibilidade.
Quando você vem de outra linguagem de programação para o Python, querendo ou não, você vem com o sotaque das outras que aprendera, e passa a escrever seu código em Python como se fosse nelas.
Siga o Guia do Estilo PEP 8, que é o guia de estilo para formatar o código em Python. Você pode escrever o código em Python da maneira que bem entender, desde que a sintaxe seja válida. Contudo empregar um estilo consistente deixa seu código mais fácil de ler e distribuir.
Answer: Pythonico significa idiomático.
Código idiomático é aquele que é escrito usando as estruturas e convenções mais comuns de uma determinada linguagem.
Exemplo:
A maioria dos programadores Python escreve:
for elemento in minha_lista:
    #faca alguma coisa

Ao inves de:
   for i in range(0, len(minha_lista)):
       #faca alguma coisa

A idea de escrever código idiomatico é que as pessoas vão entender o seu trabalho mais facilmente.
Não existe uma pessoa ou entidade que define 100% o que é Python idiomatico, mas boa parte da maneira que as pessoas escrevem Python vem da:

Documentação Ofical
PEP-8 (Guia de Estilo Python)

O que é código pythônico?


Javascript não funciona em Webview

Question: Tenho este motor de busca simples, funciona em todos os navegadores, mesmo no chrome do android, mas não funciona em Webviews, alguma sugestão do que possa ser e se há algum outro código compatível que possa substituir este,Tem como fazer isso sem ser por javascript, usando target e action por exemplo, e como habilitar isso para webview??

<form align="center" method="GET">
        <input type="text" placeholder="Digite Sua Pergunta Aqui" autofocus name="query" size="50">
        <input  type="submit" onclick="myFunction()" value="Buscar">
    </form>

Comment: Você está habilitando o uso de JavaScript no WebView?
Comment: Qual o comportamento que espera? quer dizer, onde essa janela vai abrir? vai sair do app e ir para o navegador?
Comment: @ValdeirPsr no caso é o usuário que vai ter que habilitar isso?
Comment: @MiguelSilva Não, é o desenvolvedor. Para o JavaScript funcionar, é necessário o desenvolvedor atribuir o valor `true` no método `webView.setJavaScriptEnabled` (no caso do Android). E como você está usando `popup`, talvez haja seja por isso também (não cheguei a testar algo do tipo).
Comment: @DavidSchrammel é um app que abre uma página usando webview, quando o usuário digita a pergunta e clica em buscar ele abre outra página com o resultado da busca, só que webview ao invés de aparecer o campo de texto e o submit aparecem dois campos seguido do código java script assim:
`function myFunction() {
      var query = document.getElementsByName('query')[0];
      window.open("endereco_site" + query.value);
    }`
Comment: @ValdeirPsr entendi
Comment: Tem como fazer isso sem ser por javascript?
Comment: @MiguelSilva Utilizando *modal*
Answer: Creio que para ativar o Javascript tenha que definir o WebChromeClient:
webView.setWebChromeClient(new WebChromeClient());

E depois habilitar o JavaScript
webView.getSettings().setJavaScriptEnabled(true);

Exemplo:
package foo.bar.baz; //nome do seu pacote, isso é apenas um exemplo

import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity
{
    private WebView meuWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        meuWebView = (WebView) findViewById(R.id.webView); //Busca o seu webView (se estiver layout)
        meuWebView.getSettings().setJavaScriptEnabled(true);
        meuWebView.setWebChromeClient(new WebChromeClient());
    }
}

Como adicional, você perguntou:

Tem como fazer isso sem ser por javascript?

Tem sim, usando o target= e action= no form, por exemplo:
<form action="http://endereço" align="center" method="GET">
    <input type="text" placeholder="Digite Sua Pergunta Aqui" autofocus name="query" size="50">
    <input  type="submit" value="Buscar">
</form>

Comment: Muito Show, funcionou perfeitamente!
Comment: @MiguelSilva então tem que usar o `onCreateWindow` eu estou preparando um exemplo, eu não consegui criar um ainda (é que eu procuro sempre testar meus exemplos antes de postar) porque algumas coisas mudaram no meu trabalho e estou sobrecarregado :(
Comment: se eu usar um target="_blank" vai funcionar em webviews? ou terei problemas? me refiro a opção apenas com action e target
Comment: @MiguelSilva ah verdade, creio que não, eu vou me retratar e melhorar a pergunta, acho que para ambos casos será necessário implementar algo a mais. Vou testar e assim que possivel já retorno.
Comment: Testei e funcionou usando o `target`  e `action`, assim não precisa fazer alteração no APP. Obrigado.

Javascript não funciona em Webview


$f(\frac{x^2}{x+1}) = p(x)$

Question: Does there exist a rational function $f$ and a polynomial in $\mathbb{R}[x]$ so that:
$$f(\frac{x^2}{x+1}) = p(x)$$
Comment: Polynomials are defined at $x=-1$, so...
Answer: All such functions $f$ must be constant. Here's a proof.
Suppose $f$ and $p$ satisfy the conditions of the problem. We must then have: $$p(-1)=\lim_{x\to-1^+}p(x)=\lim_{x\to-1^+}f\left(\frac{x^2}{x+1}\right)=\lim_{x\to\infty}f\left(\frac{x^2}{x+1}\right)=\lim_{x\to\infty}p(x).$$ Since $p(x)$ tends to a finite value as $x\to\infty$, $p$ must be a constant polynomial. In particular, $f$ must be constant in the range of $\frac{x^2}{x+1}$, which is an infinite set, implying that $f$ must also be constant. This proves what we wanted. $\blacksquare$
Comment: Why the downvote?
Comment: URL. What an idea! But as it stands f is not defined at x=-1, hence cannot be a polynomial. Define f at x=-1 to be =  constant pol. =c , then OK.Hope this makes sense:)
Comment: @PeterSzilas You can do pretty much whatever at the point $x=-1$, if we ignore it altogether in the original problem redaction. My solution only really cares about what happens in its neighborhood ;)
Comment: Fine.The problem : one equates a continuos polynomial with a function that is not defined at x=-1. Assuming a continuos extension of f at x=-1, you show that it is impossible unless f=p=constant.

$f(\frac{x^2}{x+1}) = p(x)$


Cache that always returns immediate response?

Question: I have a web service that takes a while to build a response despite being tuned as best I can.
What I'd like is some sort of cache sitting in front of the service which would always return the last known value from the service, but at the same time pass the request back to the service to build an up to date response for the next request.
I'm aware of the limitations that this puts on the freshness of the data, but you can assume that I'm happy to live with that.
The technologies I'm using at present are python uwsgi via nginx, but that need not be a limit to any solution you might suggest.
Col
Answer: Assuming you want a reverse proxy you can use Varnish in saint mode or squid with stale-if-error directive.
If you want in-app cache, using memcached for example, just don't rely on storage expiry mechanism - store expiry with cached object array(cached_object=>object, expiry=>timestamp) and react if you encounter stale cache: increase expiry to now + a bit of time (to prevent dogpiling - multiple processes regenerating cache in parallel), use stale cache, initialize update.
Comment: That Memcache solution looks like I can make it work. Thanks, FYI NGinX has proxy_cache_use_stale which I get the impression might also have been usable, but couldn't quite figure out how. Cheers.
Comment: AFAIK all you need is `proxy_cache_use_stale updating;` and is should just work.


What is the equation of these coordinate points

Question: (2,2)
(3,6)
(4,24)
(5,120)
(6,720)
(7,5040)
I input all of these points into my calculator and ran every working equation none of which fits the equation. These equations include: Linear(obviously not), quadratic (also obviously not), cubic, quartic, natural log, exponential and power regressions none of which seem to fit. Any ideas?
Comment: There are 130 such sequences considering that the first term is $(2,2)$ but none if we let it be $(2,1)$, see [OEIS](http://oeis.org/search?q=6%2C+24%2C+120%2C+720%2C+5040&sort=&language=english&go=Search).
Comment: Hint: Factorial function.  Or else you can drag in the Gamma function.
Comment: Should be $(2,2)$
Comment: I suspect that first point should be $(2,2)$; currently all pairs but the first are of the form $(n,n!)$.
Comment: There are infinitely many such sequences (though not necessarily interesting ones): Take the sequence to be points $(n, P(n))$ for $n = 2, \dots, 7$ for suitable polynomials $P$ of arbitrarily large degree.
Comment: You are all right, the point should definitely be (2,2)
Answer: This is the Gamma Function, the continuous version of the factorial.
http://en.wikipedia.org/wiki/Factorial#The_Gamma_and_Pi_functions
Comment: Why is the Gamma function necessary here? The arguments are integers, and all but the first are of the form $(n,n!).$
Comment: @Semiclassical He is looking for a function to connect these points. You need the Gamma function because it is continuous.
Comment: Well, it depends on what the domain of the $x$-coordinate is. But I see your point, since the OP doesn't clarify that issue at all.
Comment: So basically there is no equation where only x and y are involved, wow that's pretty interesting. I'd never even heard of "n!" thanks for response.


How to set up sshd so that it never asks for a password for a specific user?

Question: I have a dedicated system account named "git" that is managed by gitlab/gitolite. Users connecting to this account always use SSH keys, "git" user doesn't have a password. If users connect without a SSH key or with a mis-configured key, they get confused by being asked for a password. I'm looking for a way how to set up the server so that in such a case it doesn't ask for a password and instead it displays some kind of user-friendly message ("Your key is missing or invalid" etc.) and drops the connection. Is it possible, either in sshd configuration, or in some other way (PAM perhaps)?
Note that I'm not asking how to set up public/private password-less connections. Just how to prevent the server asking for a password for a single specific user.
(I understand that such setup reveals to a potential attacker that user "git" exists in the system. But since "git" has no password and an attacker can easily determine its existence anyway, I consider it only a low risk.)
Answer: You can disable password logins for that specific user. You can't provide a specific message, but at least they won't be prompted for a password. Add the following in /etc/ssh/sshd_config:
Match user git
    PasswordAuthentication no
    ChallengeResponseAuthentication no

Comment: I had to remove `UsePAM no` because the server complained it's not allowed inside `Match`, but otherwise it does exactly what I wanted. Thanks.


Como escrever essa query usando linq lambda em c#

Question: A query que eu tenho q passar pra lamba é a seguinte:
select * from Linguagem inner join Cadastro on Lin_ID=Cad_IDLinguagem and Cad_Situation=0

só coonsegui fazer até a parte da junção mas o where não sei em que parte entra:
return odb.Linguagem.Join(odb.Cadastro, l => l.Lin_ID, c => c.Cad_IDLinguagem, (l, c) => l).ToList();

Desde já muito obrigado.
Answer: Ola, tente algo assim:
odb.Linguagem.Join(odb.Cadastro,
                     l => l.Lin_ID,
                     c => c.Cad_IDLinguagem,
                     (l, c) => l)
             .Where(x => x.PROPRIEDADE == VERIFICAÇÃO)
         ).ToList();


Arabic font issue in windows form application using C#

Question: I am using resource file for Arabic Conversion in Windows form...It's all are working Perfectly but Problem with Buttons and Form Text not showing Proper letter........instead of that it showing small small box
Arabic Character not comming Properly
Comment: A small rectangle means that the operating system doesn't have a font that can display the character.  That could be because it doesn't have a font available that can display Arabic glyphs.  Or it could mean that you not converting text properly, fairly unlikely if you use resources properly.  Pretty important that you test localization on an Arabic version of Windows.  Which of course always has the required font.
Comment: But Sir Arabic text displaying in Label , It is not displaying for Buttons and Form Text.......
Answer: This will be an encoding issue, you will have to set your encodings to UTF8 as the standard ASCII encoding does not support Arabic characters.
http://msdn.microsoft.com/en-us/library/xbx3z216(v=vs.110).aspx
Comment: Cultureinfo ci=new Cultureinfo("ar-AE")
Comment: How to set encoding ?
Comment: I'll need some more information on how you created and saved your resource file and how you are setting your text from the resource file onto the control.
Comment: Also don't forget CurrentUICulture
Answer: Go to control panel->Religon n language setting->language->check the first script checkbox->install the script by using xp cd


Linksys SRW2024 switching/backplane capacity

Question: I have one of these switches. Its switching capacity is rated as 48Gbps non-blocking, which I suppose is a "marketing trick" made of 24-port 1Gbps on full-duplex. If I understand correctly this means I can load all 24 ports and expect 1Gbps per port. Well, this is not the case.
How to find out the real switching capacity?
Thanks
Edit: How to find out if the switch can sustain full load (48Gbps)?
Answer: That's exactly what it means, all ports can transmit inbound and outbound at 1Gbps - i.e. 24 x (1+1) = 48.
Comment: Because they either have either more and/or faster ports or are capable of taking more of these.
Comment: Then why some enterprise switches have 144Gbps switching capacity?
Comment: Some Cisco switches are also stackable and the big backplane is good for future grow.


How to override Drupal.ajax.prototype.beforeSend?

Question: I need to add my own little if's and checks in 3 functions inside
misc/ajax.js (
  Drupal.ajax.prototype.beforeSend,
  Drupal.ajax.prototype.success,
  Drupal.ajax.prototype.error
)

How can I override them in my module? I can't find a manual and it's not in Examples for Developers. Sorry if it seems a dumb question, but I'm a php developer - I can work with js, but I'm not so fluent with it.

Can I simply write it in my module's js file?
If 2 or 3 modules needs to modify them, how to avoid conflicts?
Answer: This might be a better way:
(function ($) {
  // Drupal's core beforeSend function
  var beforeSend = Drupal.ajax.prototype.beforeSend;
  // Add a trigger when beforeSend fires.
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    beforeSend.call(this, xmlhttprequest, options);
    $(document).trigger('beforeSend');
  }
})(jQuery);

https://www.drupal.org/node/1372840
Answer: Drupal.ajax.prototype.beforeSend and the others are just variables that happen to have functions assigned to them. As long as your code appears in the page build after the original function implementations, you you should be able to just override what's already there:
(function($) {
  // In mymodule.js, which appears after ajax.js in the page build
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    // Replacement code.
  }
})(jQuery);

Comment: Correct, this practice is usually referred to as ['monkey patching'](http://en.wikipedia.org/wiki/Monkey_patch) and it's not an exact science unfortunately
Comment: So, I'm doing it the right way, but that leaves my doubt - each module must take care to be the last one updating them on the page that needs it's changes, right? No way to prevent accidental modifications by others?
Comment: Oh. I was so sure there is some clean, safe, clever way I just cannot find due to my lack of js skill... I wouldn't asked if I knew. But I think I'll leave this question for future users looking for that nonexistent safe way.
Comment: Using other frameworks (Require.js, AngularJS, anything else that tries to bring Dependency Injection to Javascript) there are more satisfying ways of achieving the same results, but with plain 'ol JS/jQuery not so much. Your method is the best that I know of on top of Drupal


Why I'm getting undefined while assigning a function call to a variable even when it is a synchronous call?

Question: I have a piece of code as this :

function imp(user) {
  return console.log("user", user)
}

var msg = imp("Jenny")

console.log("msg", msg)

I'm getting an output as this :
user //for user log
undefined // for msg log

However I expect this undefined if the code was async, for example a setTimeout call inside the imp function as :
function imp(user) {
  setTimeout(() => {
    console.log("inside the timeout for ", user)
  }, 3000)
}

But since the very top code is sync, then still why it logs undefined ?
Isn't that equal to simply assigning a new variable (msg) to a function call?
Thanks for reading
Comment: exactly. the return value of `console.log(...)` is undefined.
Comment: @anshul: What value do you *expect* `msg` to have and why?
Comment: `return console.log` will return undefined
Comment: Please read [Does every Javascript function have to return a value?](https://stackoverflow.com/questions/17337064/does-every-javascript-function-have-to-return-a-value)
Comment: functions return by default `undefined` if you dont use the `return` keyword
Comment: @anshul: If you want `msg` to be the `imp` function then it would be: `var msg = imp;`  You're *invoking* the function.
Comment: @anshul: Are you looking for this?:  `var msg = () => imp("Jenny");` ?
Comment: @anshul: Because, again, you are *invoking* the function.  That's what using parentheses after a function name does.  When you call `imp("Jenny")` you invoke the `imp` function and pass it the parameter `"Jenny"`.  If you're not expecting this to invoke the function then why do you expect `console.log("msg", msg)` to invoke the `console.log` function and not just return a reference to the `console.log` function?  Why would you expect that using parentheses does one thing in one case and another thing in another case?  Invoking a function is basic JavaScript syntax...
Comment: why is that? It also returns undefined even I just do console.log without the return keyword
Comment: but even when I'm not using the return keyword?
Comment: @David I want it to either return the function signature itself if I'm logging just `msg` or call the function with the `console.log(...)` inside it when I'm calling as `msg()`
Comment: @bill.gates So I believe that's a tricky slope here, if I don't use return keyword, then it would log undefined, if I do then console.log returns undefined by default?
Comment: @David Yes, exactly that's what i'm trying to do, but instead passing a user value as well as - `var msg = imp("Jenny")`
Comment: console.log returns undefined https://developer.mozilla.org/en-US/docs/Web/API/Console/log?retiredLocale=de#return_value
Comment: @David yes, the same functionality as arrow signature, but can't we do it without an arrow function? It's just simply assigning a function call with params to a new variable
Comment: @David I understood, Thanks for the description. So If I do - `var msg = imp;` & later do `msg('jenny')` then it would invoke the function correct? Please put the comment as an answer. I would tick it off if you like.
Answer: The issue is the return of the console.log(), a console.log() returns undefined and not the message it just logged.
https://developer.mozilla.org/en-US/docs/Web/API/console/log


"Allow multiple selection" not available in exposed filters

Question: I'm having trouble making some options appear as checkboxes in an exposed view form.
The problem is that the "Allow multiple selection" option is not available in the filter.

How can i make it visible. "Allow multiple selection" option.
Comment: Is this about D5?
Comment: I had the same issue. Found the solution here: [https://www.drupal.org/project/views/issues/2995086](https://www.drupal.org/project/views/issues/2995086)
Answer: You can go for Better Exposed Filters module.

The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.
Comment: You have to change the "Exposed form style" under Advanced section and then in the Advanced > Exposed Form Style > settings exactly for the exposed filter you can select to use Display as "Checkboxes / Radio buttons" - checkboxes would be if the "Allow multiple selections" is checked (this time under Filter criteria > exact filter )
Comment: I installed BEF module also even that open is not coming.
Comment: Have you checked the BEF settings present in view advance section.
Comment: Everything i selected in BEF settings but the problem is Allow multiple selections is not appearing in filter setting.
Answer: You Can use the Better Exposed Filters for the filters.
Follow the Screenshots
Comment: I have done all the steps but still no changes
Comment: Have you checked the Allow Multiple selections option under the filtered field?
Comment: Its coming fine in
Content: Type (= Bank Blog)
but i want that in
Content: Blog Type (exposed) | Settings
Comment: What is blog type?
Is it a content type?
Comment: Yes blog type is my content type,
Comment: Sorry blog type is my content type field, what is refer taxonomy term.
Comment: I do not understand what I'm supposed to see on all these screenprints. Please EDIT your answer to explain what the purpose of each of these screens is. E.g., about your 3rd screenprint: that has dozens of options, which ones of them are important in the context of what you're trying to explain with that screenprint?


Relationship between Ideals and subgroups ??

Question: I am just wondering if Product of two Ideals is again an Ideal.
Let $I$ and $J$ be ideal of Ring, then is $IJ=\{ij: i\in I, j\in J\}$ still an ideal?
Answer: No, $\{\,ij\mid i\in I, j\in J\,\}$ generates an ideal, which the smallest ideal that contains these product, and can be described as the set of all finite sums of such products.
In case of principal ideals, generated by $a$ and $b$, the product is again a principal ideal, generated by $ab$.
Comment: @Nancy: That's right.
Comment: Thanks, Is ideal a subgroup under addition?


Find PDF of the x coordinate of a randomly chosen point on a circle of radius R - why is my approach wrong?

Question: I know the correct solution to this, but I am trying to understand why my approach is wrong.
Let P be a point that is randomly chosen from circle with radius R. My approach is the following:
Point P is a distance $d$ from the origin and is at an angle $\theta$ with the horizontal, where $d$ is uniformly distributed on $(0,R)$ and $\theta$ is uniformly distributed on $(0,2\pi)$. $d$ and $\theta$ are independent.
What we're interested in is the distribution of $X = d*cos(\theta)$, where the densities of $d$ and $\theta$ are $f_d(d) = 1/R$ and $f_\theta(\theta) = 1/2\pi$
Let $Y = cos(\theta)$, $F_Y(y) = P(Y<y) = P(cos(\theta) <y) = P(\theta <cos^{-1}(y)) = cos^{-1}(y)$
Therefore the density $f_y(y) = dF_y(y)/dy = -1/\sqrt {1 - y^2}$
What we want is the density $f_X(x)$. Because $d$ and $\theta$ are independent in the expression $X = d*cos(\theta) = d*Y$, then you would expect $f_X(x) = f_d(d)*f_Y(y) = -1/(R*\sqrt {1 - y^2})$
But this is the wrong answer. Where's my mistake?
Comment: When you say "circle", you seem to include the part inside, i.e. a disk.  Negative densities  seem unlikely.  $d$ may not be uniformly distributed
Comment: the density functions are

$$f_d(d)=\frac{1}{R}1_{]0,R[}(d)$$

$$f_{\theta}(\theta)=\frac{1}{2\pi}1_{]0,2\pi[}(\theta)$$

Also,
the function $arccos$ is not a bijection from $]-1,1[$ to $]0,2\pi[$
Answer: If you take a point uniformly on a circle, then $\theta$ is uniformly distributed, but d is not.
You have to assume that every elemental area $r * dr * d\theta$ has equal probability of being chosen.
Answer: $d$ is not uniformly distributed over $(0,R)$. Indeed, $d\leq t$ is equivalent to point is in the sircle with radius $t$, and cdf of $d$ is
$$
F_d(t)=\mathbb P(d\leq t) = \frac{\pi t^2}{\pi R^2}=\frac{t^2}{R^2}, 0<t<R.
$$
So, pdf of $d$ is
$$
f_d(t)=\frac{2t}{R^2}, 0<t<R.
$$


Creating a web service client from WSDL in java

Question: I have been searching for days on this, and finally figured I'd ask.  I'm new to java in general, and newer to web service functionality, so I'm struggling quite a bit.  I'm surprised I haven't found a step by step guide on this in all of the examples I've found on the net, but I'm sure there is something somewhere.  All I need to do is import a WSDL document into Java (done), and be able to invoke the web service from my class, send it a string, and have it return a response.  When I first import the WSDL into the project, there are several errors that exist.  The main one seems to be that it requires an interface named similar to the proxy class that was generated.  So I've done that, but other errors are in there as well.  Is it normal that you have to create code within the generated classes and do your own thing in there, or should the WSDL be more formatted and precise so that it's just plug and play?  I thought from a project I did years ago, that it was pretty much plug and play and you could just do import it and do String response = myService.call(String myString); and have it return a response just by referencing the classes generated by the WSDL.  Does anyone have any ideas where a beginner could learn how to invoke a web service based on a WSDL file?  I mean from square one, like what you need to import, where you need to get the .jar file references from (if needed), etc.  Just for reference, I am including the WSDL below.  Thanks for any insight!
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://listeners.webtools.integrator.myserver.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://listeners.webtools.integrator.myserver.com">
<wsdl:documentation>MYListener</wsdl:documentation>
<wsdl:types>
  <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://listeners.webtools.integrator.myserver.com">
    <xs:element name="processMessage">
      <xs:complexType>
        <xs:sequence>
          <xs:element minOccurs="0" name="inputMessage" nillable="true" type="xs:string"/>
        </xs:sequence>
      </xs:complexType>
   </xs:element>
                        <xs:element minOccurs="0" name="return"
                         nillable="true" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>
</wsdl:types>

<wsdl:message name="processMessageRequest">
    <wsdl:part name="parameters" element="ns:processMessage"/>
</wsdl:message>
<wsdl:message name="processMessageResponse">
    <wsdl:part name="parameters" element="ns:processMessageResponse"/>
</wsdl:message>
<wsdl:portType name="MYListenerPortType">
    <wsdl:operation name="processMessage">
        <wsdl:input message="ns:processMessageRequest"
         wsaw:Action="urn:processMessage"/>
        <wsdl:output message="ns:processMessageResponse"
         wsaw:Action="urn:processMessageResponse"/>
    </wsdl:operation>
</wsdl:portType>
<wsdl:binding name="MYListenerSoap11Binding"
 type="ns:MYListenerPortType">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
     style="document"/>
    <wsdl:operation name="processMessage">
        <soap:operation soapAction="urn:processMessage"
         style="document"/>
        <wsdl:input>
            <soap:body use="literal"/>
        </wsdl:input>
        <wsdl:output>
            <soap:body use="literal"/>
        </wsdl:output>
    </wsdl:operation>
</wsdl:binding>
<wsdl:binding name="MYListenerSoap12Binding"
 type="ns:MYListenerPortType">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"
     style="document"/>
    <wsdl:operation name="processMessage">
        <soap12:operation soapAction="urn:processMessage"
         style="document"/>
        <wsdl:input>
            <soap12:body use="literal"/>
        </wsdl:input>
        <wsdl:output>
            <soap12:body use="literal"/>
        </wsdl:output>
    </wsdl:operation>
</wsdl:binding>

<wsdl:binding name="MYListenerHttpBinding" type="ns:MYListenerPortType">
    <http:binding verb="POST"/>
    <wsdl:operation name="processMessage">
        <http:operation location="processMessage"/>
        <wsdl:input>
            <mime:content type="application/xml" part="parameters"/>
        </wsdl:input>
        <wsdl:output>
            <mime:content type="application/xml" part="parameters"/>
        </wsdl:output>
    </wsdl:operation>
</wsdl:binding>
<wsdl:service name="MYListener">
    <wsdl:port name="MYListenerHttpSoap11Endpoint"
     binding="ns:MYListenerSoap11Binding">
        <soap:address location="http://10.221.55.206:20043/axis2/services/MYListener.MYListenerHttpSoap11Endpoint/"/>
    </wsdl:port>
    <wsdl:port name="MYListenerHttpSoap12Endpoint" binding="ns:MYListenerSoap12Binding">
        <soap12:address location="http://10.221.55.206:20043/axis2/services/MYListener.MYListenerHttpSoap12Endpoint/"/>
    </wsdl:port>
    <wsdl:port name="MYListenerHttpEndpoint" binding="ns:MYListenerHttpBinding">
        <http:address location="http://10.221.55.206:20043/axis2/services/MYListener.MYListenerHttpEndpoint/"/>
    </wsdl:port>
</wsdl:service>

Answer: You can use wsimport tool to generate all artifacts, and then organize them manually. Or simpler, install NetBeans and use its option "Generate Web service client from wsdl". It will put all files at correct places and generate jax-ws-catalog.xml file. More info here:
https://netbeans.org/kb/docs/websvc/client.html#creatingtheclient
HTH.
Comment: Thanks for the response.  I've actually created this several times, and looked at some other internal examples.  The problem is my background is AS400 RPG.  I've managed to create the classes from the WSDL, but it created a proxy class, which references the actual class from the WSDL.  I assume I have to create that class myself, but I figured it would have done it automatically.  I will follow the example from this document and see how it goes.  I might have already tried it, as I've tried about a million different things already.  :)
Comment: @user1420914 Don't have experience with AS400 RPG, but your WSDL looks regular, so I don't think that you should encounter any problems by using this approach. NetBeans is a really great tool to deal with SOAP-based Web services. If you face any problems, post here and we will try to help.
Comment: For what it's worth, I just had the developers of the web service give me an example of how to connect to it, I just basically used their code.  It basically used the imports from org.apache.commons and functions to send the stuff.
Comment: @user1420914 Excellent, glad that you resolved the issue. For the future I strongly recommend using NetBeans for this purpose.


Why does all links of homepage redirects me to Xampp homepage ( Took backup from Godaddy )

Question: I took backup of SQL from Godaddy and copied all the data from my Godaddy hosting account through FTP.
I imported the SQL in my machine's mysql ( no issues ).
I copied the files to my htdocs/subdir1/drupalDIR/ and made changes in settings.php ( updated mysql connection details ).
Homepage is showed in a perfectly fine way but whenever I click on any link, it takes me to Xampp Homepage.
Perhaps it's a htaccess issue.
What should be the Rewrite rule to make it okay ?
Comment: Downloading a fresh copy of Drupal and looking at its .htaccess is the easiest way to see what the rewrite rules should be
Comment: That's what I did, I replaced the one I had with the new one. It works !
Answer: I tried copying the .htaccess file available inside the Drupal package and pasted into my htdocs drupal folder.
Works like charm till yet.