String Replace Error in PowerShell

Question: In my PowerShell script I am getting an error that I dont understand.
The error is:
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

Invalid regular expression pattern:
Menu "User" {
   Button "EXDS" {
      Walk_Right "EXDS"
   }
}
.
At C:\test.ps1:7 char:18
+ ($output -replace <<<<  $target) | Set-Content "usermenuTest2.4d.new"
    + CategoryInfo          : InvalidOperation: (
Menu "User" {...do"
  }
}
:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

My script reads a file into a string (string A) then attempts to remove String A from another file. What does this error mean and how I can I fix it?
My code:
#set-executionpolicy Unrestricted -Force
#set-executionpolicy -scope LocalMachine -executionPolicy Unrestricted -force

$target=[IO.File]::ReadAllText(".\usermenuTest1.4d")
$output=[IO.File]::ReadAllText(".\usermenuTest2.4d")

($output -replace $target) | Set-Content "usermenuTest2.4d.new"

Answer: Try:
($output -replace [regex]::escape($target))

in the -replace $target is always evaluated as a regular expression.
In you case $target contains some regex special character and can't be parsed correctly then you need to escape all special characters. The [regex]::escape() .net method helps doing this job.
Answer: That's probably because $target is null (and so is $output).
.NET replaces the dot with the initial working directory in which PowerShell was started (usually either your home directory or systemroot). I'm guessing that usermenuTest1.4d is in a different directory, and you're running this script from that directory. ReadAllText is looking for the file in the initial directory and not finding it.
If you run $target=[IO.File]::ReadAllText(".\usermenuTest1.4d") at the command prompt in the directory in which usermenuTest1.4d is located, you'll see an error telling you that it couldn't find the file and showing you the full path it was looking for, which will be different than what you expected. Or, you could add the following line to your script to see which directory it will replace the dot with:
[environment]::currentdirectory

Any of the following should work:
$target = Get-Content .\usermenuTest1.4d | Out-String
$target = [IO.File]::ReadAllText("$pwd\usermenuTest1.4d")
$target = [IO.File]::ReadAllText((Resolve-Path usermenuTest1.4d))
[environment]::currentdirectory = $pwd
$target=[IO.File]::ReadAllText('.\usermenuTest1.4d')

The last one is unnecessarily cumbersome, but I put it in to help make it clear what's going on.
Of course, you should do the same when setting $output.
Comment: If `$target` or `$output` are `$null` no `InvalidRegularExpression`
 exception will be trhow. The error in not this.

String Replace Error in PowerShell


DIY Slider simple pagination

Question: I've been searching, but I cannot find anything about this in the documentation, unless I'm missing something. I'm using this simple DIY Slider http://jsfiddle.net/kGRRK/ and I want it to display the current slide.
Like this:3 of 5
Or this:- - X - -
Is there a simple line of code to place here to achieve this?
$(".slider").diyslider({
   width: "400px",
   height: "200px",
   display: 1,
   loop: false,
});

$(".current-slide")

// use buttons to change slide
$("#go-left").bind("click", function(){
    $(".slider").diyslider("move", "back");
});
$("#go-right").bind("click", function(){
    $(".slider").diyslider("move", "forth");
});

Comment: http://jsfiddle.net/pioul/ba5jh/? First link from Other live examples http://pioul.fr/jquery-diyslider?
Comment: Is this what you wanted ?http://jsfiddle.net/bj4yZ/493/
Comment: Thanks a bunch guys! @dreamweiver your version seems to work, but it adds one more slide to the counter than there actually is. I ended up with a code much simpler than I thought: http://jsfiddle.net/CGBVF/

So that's what I needed. Just out of curiosity is there any way to get the slides to display as "- - X - -" with the X marking the current slide?
Comment: @Pascal: i hope this is what you were expecting,http://jsfiddle.net/dreamweiver/CGBVF/3/
Comment: @dreamweiver Oh haha I might have explained myself wrongly, sorry for that! I meant like the first slide "X - - - -", second "- X - - -", third "- - X - -", etc. Each - represents a slide, then placing the X at the current slide.
Comment: I thought so, what would that serve :). anyway here you go ,http://jsfiddle.net/dreamweiver/CGBVF/18/
Comment: @dreamweiver you are my hero! Exactly how I meant, I was able to change the number to an X easily. My questions have been answered! Thanks very much.
Comment: @Pascal: Your welcome, lets do one more final thing, close this question :)
Answer: Try this way
HTML CODE:
<button id="go-left">«</button>
<button id="go-right">»</button>

Div #1

Div #2

Div #3

Div #4

Div #5

    of

JS CODE:
// hide the message when the slider ends moving, and update the counter

$(".slider").bind("moved.diyslider", function (event, slide, slideNumber) {
  slideNo = "";
  $("#counter .current-slide").text(slideNumber);
  curSlide = $("#counter .total-slides").text();
  index = 1;
  while (index <= curSlide) {
      if (index == slideNumber) slideNo += " " + slideNumber + " ";
      else slideNo += " - ";
      index++;
  }
  $(".cur-slide").text(slideNo);
});

// initialize the slider
$(".slider").diyslider({
   width: "400px",
   height: "200px",
   display: 1,
   loop: false,
   start: 1
});

//set the slider index initially to first slide
$(".cur-slide").text("1 - - - -");

// set the counter's slides count once the slider has been initialized
$("#counter .total-slides").text($(".slider").diyslider("getSlidesCount"));

// use buttons to change slide
$("#go-left").bind("click", function () {
  $(".slider").diyslider("move", "back");
});
$("#go-right").bind("click", function () {
  $(".slider").diyslider("move", "forth");
});

CSS:
div {
  color: #000;
  font-size: 30px;
  line-height: 1.5em;
  font-weight: bold;
}
div.a {
   background: red;
}
div.b {
   background: green;
}
div.c {
   background: orange;
}
div.d {
   background: black;
   color: #fff;
}
div.e {
  background: pink;
}
.slider {
  border: 3px solid #000;
}

LIVE DEMO:http://jsfiddle.net/dreamweiver/CGBVF/20/
Happy Coding :)

DIY Slider simple pagination


How to play dynamics marks on drums / snare

Question: Is there any rule / recommendation on how to play the notes dynamically, following the marks from ff to pp on a snare or other drums?
For example, if mf is hit from approximally 6 inches height, f would be at 8; ff would be the hardest stroke, and pp would be ghost notes, letting the stick drop from about 1 inch distance, etc.?
I'm currently following the Kleine Trommel (Snare Drum) book and am wondering how to approach the dynamics marks.
Comment: Drop height is irrelevant unless your sticks are in free-fall.  One would hope they aren't! :-)
Comment: @CarlWitthoft, would you mind to elaborate on that? I find the distance to be an important element. Still need to see a loud stroke from a 1 inch distance. :)
Comment: Drop distance is probably a good way to "calibrate" your dynamics as well as meter.   However, the stroke type as well as dynamic output depends on how much your muscles drive the stick and hold the contact time.   As an extreme counterexample, I've seen some rock drummers in famous bands hold a stick above their head & bring it down in a slow, exaggerated movement -- clearly the 4-foot "drop" doesn't create an fffff in this case.
Comment: @CarlWitthoft There is a dynamics technique for drums where the concept is that the sticks should be allowed to fall on the drums and the dynamics are controlled by how high you lift the stick before letting it fall. A positive consequence is you don't have to use muscles as much on the downstroke, a negative consequence is you have to predict/calculate the fall time so the stroke will land at the right time. It's not necessarily the right way to play but it's valuable to learn.
Answer: Dynamic are relative, rather than absolute. Several past questions have revealed interesting answers.It couldn't be portrayed in inches! Sticks, drums and the player himself would make that subjective, let alone the room and its acoustics!
It is down to the player to decide and play accordingly, but it's really good that you are aware of dynamics; so many other drummers are too: fff...
Comment: The volume level of the drummer's playing should *always* reflect that of the other players. I think pp/mf/fff etc., are somewhat like the 'tempo' signs - lento/andante/allegretto etc. They're merely guidelines to give a feel. When you start playing with others, the academic side of volume will hardly be considered, you'll hopefully match your volume and dynamics to what's happening at the given moment - provided you're using that skill that not all drummers have - listening - and I'm not being funny.
Comment: @Tim, I hope I get what you are saying. But to go a step further - if someone puts p on a sheet, then they expect you to play softly. But softly compared to what exactly? I'm pushing on a string here for the sake of getting that extra bit of knowledge and understanding.
Answer: ƒƒƒn is as loud as you can go, pppn is as quiet as you can go.
The distance the stick needs to travel to achieve either of these is irrelevant.
If you can make the guitarist blink from 3" off the skin, you've got one end of the scale.
If the audience thinks you stopped hitting the skins you reached the other.
Everything else is in between.
If you're playing with a single acoustic guitarist singer/songwriter & no-one has a mic then everything you do is going to be compressed towards the ppp end of the scale.
If you join 'Ultra-Mega-Killer-Death' as their new time-keeper, you may never need a p again [I'm sure I could have phrased that better]
If you ever break a stick, you're playing too hard, which is not the same as loud. Loud is technique, not aggression. Aggression may form part of the musical style, but if you're playing with a 30-piece jazz orchestra rather than mega-ultra-whoever-they-were... then you need technique.
I had 20 years out from playing drums. When i came back to it I was rusty as all heck. Not a beginner, but I couldn't do half what I thought I ought to be able to.
I honed back in over about 3 months [many solo rehearsals, long hours] & I found the thing that got me best into the old feel was just playing along to 'records'... CD, cassette, iPod, take your pick - using 2 methods.

With headphones - this way you can immerse yourself in the song you're playing & just enjoy it. If you crank the cans up loud enough to feel like a rock gig, you can hammer away to your heart's content.
With speakers - you need a sizeable rig to overpower a drum kit in a rehearsal room, so this is your opportunity to drop the levels & work as though you're a member of a living orchestration. You have to control your levels so you can still hear what the others are doing. You're still playing the same part, but you have to control your dynamics & not overpower what you're playing along to, or you'll no longer be able to hear sufficient of it to keep in time with a track that won't wait for you.
Answer: The answer I was looking for is more along the lines of what is described in Percussion Guide for the Beginning Band Student, Lesson Six: Dynamics / Height of Stick.
It states that there is a clear relationship between the stick height and dynamics. It is not the only method but it is the best one, and the easiest to start with.
Generally, playing forte is done from ~5 inches distance and piano from ~2 inches.
Another useful reference is John Riley's The Master Drummer, where he clearly states a relationship between the volume and the stick height.
Answer: There are certainly 'rules', as expounded in several methods such as the one @Alen Siljak quoted. They are a useful part of drum technique, but not the whole story.   You 'bounce' the stick off the drumhead.  But it's an 'assisted bounce', not just free-fall.


Term for a series of connected lines that never fully close to create a shape?

Question: In a design like the one below, the lines are proper lines without a defined width.
What I'd like to know is what would a construct like this be referred to as mathematically?
Because:

It's more than just a line, but
Though it resembles a shape, it doesn't close in on itself to become one
Answer: In Foundations of geometry Hilbert refers to these as broken lines. Take a look at the diagram for the hit for "broken lines" on page 10 of this translation.
They are also called "piecewise linear arcs/curves" or "polygonal chains".
I understand you were emphasizing the behaviors you wished to conclude when you mentioned having more than one path and the possibility of not closing. To be certain, I should note here that it would be totally fine to refer to a single line segment by any of these names too, or to such a thing that ends where it started by the same name. They would just be special cases. They aren't precluded.


Geometric multiplicity of an eigenvalue

Question: Geometric multiplicity of an eigenvalue of a matrix is the dimension of the corresponding eigenspace.  The algebraic multiplicity is its multiplicity as a root of the characteristic polynomial.
It is known that the geometric multiplicity of an eigenvalue cannot be greater than the algebraic multiplicity.  This fact can be shown easily using the Jordan normal form of a matrix.
I was wondering if there is a more elementary way to prove this fact, possibly longer but without using the Jordan normal form?  (This is an exercise in Kreyszig's book on functional analysis, and given the author's style, I suspect that he did not intend the solution to use Jordan form, because otherwise I guess he would have given a hint about that. But I might be wrong.)
Answer: You don't need the Jordan form: suppose the geometric multiplicity of $\lambda$ is $k$, and let $\gamma=\{\mathbf{v}_1,\ldots,\mathbf{v}_k\}$ be a basis for the corresponding eigenspace. Extend the basis $\gamma$ to a basis $\beta$ for $F^n$, and let $Q$ be the change-of-basis matrix. Then the characteristic polynomials of $A$ and $Q^{-1}AQ$ are the same. The upper left $k\times k$ block of $Q^{-1}AQ$ is simply $\lambda I_k$, and, the $(n-k)\times k$ block under it is all zeroes. So the characteristic polynomial of $Q^{-1}AQ$ is a multiple of $(\lambda - t)^k$ hence the algebraic multiplicity of $\lambda$ is at least $k$.
Comment: Seems like this is exactly what I was looking for. Thanks!

Geometric multiplicity of an eigenvalue


Proof ln(x) limit

Question: Goal: Prove that $ \lim_{x \to 0}\ln(x) = -\infty$.
Consider $x \in (0,1]$
Fix $n \in \mathbb{N}$
Examine $\ln(\frac{1}{2^{n}}) = \int\frac{1}{t} \leq U(\frac{1}{t},P)$
Where our partition $P$ is $P =${$\frac{1}{2^{n}},...,\frac{1}{8},\frac{1}{4},\frac{1}{2},1$}
Then $U(f(t),P) = \sum_{i=1}^{n}(\frac{1}{2^{i}}-\frac{1}{2^{i-1}})*2^{i-1}=-n\geq \ln(\frac{1}{2^{n}})\forall n \in \mathbb{N} $
Now fix $N \in \mathbb{N}$ and let $M $ be $M = \frac{1}{2^{2N+2}}$. We have that ln is strictly increasing which necessitates that $x < M$ and then $\ln(x) < \ln(M) = \ln(\frac{1}{2^{2N+1}}) \leq \ln(2^{-2(N+1)})=\frac{-2(N+1)}{2}=-N-1<-N $
Thus we can make $\ln(x)$ less than any $-N \in \mathbb{N}$ as $x \to 0$.
I wrote this similarly to a proof we did in class and I guess I'm wondering why we have free choice of $M$ is it just like a $\delta$ in this proof or no? I'm a bit unsure about this proof.
Comment: Why don't you just say that $\ln (\frac 1 {2^{n}})=-n\ln 2 \to -\infty$ and use monotonicity  of the function. I have no idea why you want to consider Riemann integrals.
Comment: We can't use that property of ln I guess @KaboMurphy
Comment: In your first line, you have $x \to \infty$. I assume you mean $x \to 0$ instead. Also, instead of non-positive integral powers of $2$, are you allowed to non-positive integral powers of $e$ instead? This will give the results of $\ln$ of these values to exactly be negative integers.
Comment: No sadly we don't know anything about e^x other than exp(x) is the inverse of ln. Also fixed the infinity haha. The only things we can use are "basic" definitions.@JohnOmielan
Comment: @Christheyankee If you know that $e^x$ is the inverse of $\ln(x)$, i.e., $\ln(e^x) = x$, then as long as you know that $e \gt 1$, you can use negative powers of $e$ directly to make your proof simpler, as I suggested in my earlier comment. Will this work for you, or am I missing something?
Comment: @JohnOmielan I don't think I'm grasping what you're hinting at. I'm sorry this is all new to me. Where would I apply this?
Comment: @Christheyankee I meant you could use a partition of $e^{-n}$ for integers $n \le 0$, with each value decreasing from $1$ to $0$ as $-n$ gets smaller. Then you would have that $\ln(e^{-n}) = -n$ would be a decreasing sequence of integers, with no lower bound. It's similar to what you did, but I believe it's simpler & more straight forward.
Answer: $\ln x$ is an  increasing function of $x$ for $x>0$  (see Footnote) so it suffices to show that $\ln (2^{-n})\to -\infty$ as natural number $n\to \infty$ (see Remark).
For $n\in \Bbb N$ we have $$(\bullet)\quad \ln (2^{-n})=\int_1^{2^{-n}}(1/t)dt=\sum_{j=0}^{n-1}\int_{2^{-j}}^{2^{-j-1}}(1/t)dt.$$ Now $2^{-j}<2^{-j-1},$ and when $t\in [2^{-j-1},2^{-j})$ we have $(1/t)>2^j.$ So $$\int_{2^{-j}}^{2^{-j-1}}(1/t)dt<\int_{2^{-j}}^{2^{-j-1}}(2^j)dt=$$ $$=(2^{-j-1}-2^{-j})(2^j)=-1/2.$$ Applying this to $(\bullet)$ we have $$\ln (2^{-n})<\sum_{j=0}^{n-1}(-1/2)=-n/2.$$
Footnote. If $0<x<y$ then $\int_x^y(1/t)dt>0 $, so $$\ln y=\int_1^y(1/t)dt=\int_1^x(1/t)dt+\int_x^y(1/t)dt>\int_1^x(1/t)dt=\ln x.$$
Remark. For $0<x<1$ let $V(x)$ be the largest $n\in \Bbb N\cup \{0\}$ such that $x\le2^{-n}$. Then $V(x)\to \infty$ as $x\to 0,$ and $\ln  x\le \ln (2^{-V(x)})\le -V(x)/2.$
Comment: This is like showing that $S(n)=\sum_{j=1}^n(1/j)\to \infty$ as $n\to \infty$.... E.g. $S(8)>1+(1/2)+(1/4+1/4)+(1/8+1/8+1/8+1/8)=5/2$, and in general, if $1 (n+2)/2.$

Proof ln(x) limit


How to make a call from manager api methog originate

Question: I am trying to make a call to a PSTN number using dahdi, but I am unable to originate it through originate command please tell me how to use this method in asterisk-java.
Answer: <code>AMI Example

Action: Originate
Channel: DAHDI/1/123456789 ;PSTN Channel
Context: default
Exten: 101
Priority: 1
Callerid: Asterisk Automatic Wardial

extensions.conf

[default]
exten => 101,1,Dial(SIP/101,45)
exten => 101,n,Hangup()

this context make a bridge between SIP/101 and DAHDI/1/123456789
</code>


If I flip a coin n times how many different combinations are there?

Question: For example if a coin is flipped 3 times I know how to calculate all the possible outcomes.
I don't understand how I reduce that count to only the combinations where the order doesn't matter.
I know there's 8 permutations but how do you reduce that count to 4? {HHH,TTT,HTT,THH}
I've tried thinking about the combinations formula with repetition, the product rule, the division rule.
Comment: If order doesn't matter, then you **only** need to know how many times you got say heads(or analogously tails cause *heads*+*tails*=number of toss). Of course you can choose this number to be from $0$ heads to be $3$ heads so you get $\binom{n+1}{1}=n+1.$
Comment: Phicar is referring to [combinations with repetition](https://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition).
Comment: If order doesn't count, then just focus on the number of tails you can get: that can be anywhere from $0$ to $n$, so there are $n+1$ different outcomes
Answer: If you toss a coin $n$ times, the number of heads obtained can arrange from $0$ to $n$.  Since all of the remaining tosses must be tails (excluding unlikely events such as the coin standing on its edge), there are $n + 1$ possible outcomes.
Answer: For more illustration , lets assume that we indicate both heads and tails with stars such as $"*"$ , and we determine whether they are heads or tails according to their position in terms of a bar such as $"|"$ .Lets say that the stars which are on the left side of bar are representing the tails and the stars which are on the right side of bar are representing the heads.
Lets assume that $n=2$ where $n$ is the number of flipping ,so we have $2$ stars and one bar , the all possible outcomes are

$**| = \text{2 tails}$

$*|* = \text{1 tail and 1 head}$

$|** = \text{2 heads}$

As you see , the whole matter is just arranging stars and the bar in a row with permutation with repetition , then each arrangement will give you each possible distributions of heads and tails.
Then , by the formula of permutation with repetition  , if there are $n$ objects (stars ) of one type  and there is only one object (bar) from another type , then their arrangements is $$\frac{(n+1)!}{n! 1!} =n+1$$
Comment: Thank you this makes a lot of sense. All the other answers did too. As an extension if I have 3 letters ABC and I want to find all the combinations again is the answer 10? I've used the 3 places with 2 bars  and the combinations with repetition formula. Also listed it out and I think it's correct.
Comment: @BenHarris you are welcome ! When we comes your extension , if you think all posible words using these $3$ letters , then answer is $3!=6$ , but if you think it like this main question , then the answer is $C(3+3-1,2)=C(5,2)=10$ ,yeah you are right !
Answer: It might be easier if you list the combinations in sequence according to how many tails there are:
$$ \{HHH, THH, TTH, TTT \}. $$
That is, start with all $H$s and then for each successive element of the set, change one $H$ to a $T$. When you finally have all $T$s you're done.
Note that this set shows $TTH$ where yours shows $HTT,$ but since order does not matter, these are the same combination.


validação no IF JQuery

Question: boa tarde,
tenho varias telas que fica escondida(fade), quando clicado em um botão ela aparece.

Tenho essas ID: animate, animateServico, animatePortifolio.
eu queria saber como fazer uma validação, para que, quando clicar em algum botão que tenha umas das ID ela faça os comandos.
exemplo: quando clicado no animate, quero que a tela ande X px, se clicado no animateServico a tela ande X px.
Answer: Pelo o que eu entendi, você quer adicionar o EventListener simultaneamente nos elementos que possuem os IDs: animate, animateServico, animatePortifolio.
Você pode fazer isso, simplesmente adicionando os outros IDs com uma vírgula ao selector, dessa forma:
$("#animate, #animateServico, #animatePortifolio").click(function() {
    //ação que você deseja
});

[Editado]
Diante do que você falou nos comentários, já contrariando minha própria afirmação, você pode usar a abordagem acima, manipulando com o próprio if, qual tela você deseja abrir.
Existem duas formas de abrir uma tela específica, de acordo com o elemento que foi clicado:
Forma 1
Você pode obter o id do elemento clicado, e assim, você elabora um bloco if, dessa forma:
$("#animate, #animateServico, #animatePortifolio").click(function(event) {
    //o "event" se faz necessário para obter-se o elemento clicado
    let targetId = event.target.id;
    if (targetId == "animate") {
        //ação 1
    } else if (targetId == "animateServico") {
        //ação 2
    } else if (targetId == "animatePortifolio") {
        //ação 3
    }
});

Forma 2
Você pode definir um data attribute, para logo depois obter o seu valor, e de acordo com o mesmo, abrir a tela desejada:

Espero ter ajudado!
Comment: mais desse jeito eu não teria o controle, pois todas as telas faria a mesma coisa ao mesmo tempo, para intender melhor, e o seguinte, tenho a tela principal com quatro opções, dependendo a opção que escolho a principal some e abre a tela que foi escolhida.
Comment: Então, nesse caso, você teria que usar o *selector* de forma específica para cada um, ou seja, você teria que usar o *selector* três vezes para abrir as janelas específicas de cada botão.
Comment: achei que teia um mode de simplificar isso com o if, muito obrigado pela ajuda.
Comment: Eu editei a resposta
Answer: Como o Gustavo colocou na resposta, use o .target para saber qual botão que disparou o evento:

$("#animate, #animateServico, #animatePortifolio").click(function(e){

   var id = e.target.id; // pega o id do botão

   if(id == "animate"){

      console.log("botão animate");

   }else if(id == "animateServico"){

      console.log("botão animateServiço");

   }else{

      console.log("botão animatePortifolio");

   }
});

<button id="animate">animate</button>
<button id="animateServico">animateServico</button>
<button id="animatePortifolio">animatePortifolio</button>

validação no IF JQuery


Valor incorreto do agg mean

Question: Preciso chegar no mesmo resultado da media, moda e mediana dessa tabela
Televisores/dia   Freq. absoluta
 0 |----- 20           5
 20|----- 40           25
 40|----- 60           40
 60|----- 80           15
 80|----- 100          10
100|----- 120          5

media=53 moda=50 mediana=50

A ideia é calcular a média de cada valor da primeira coluna e depois a frequência de cada um. Cheguei nesse resultado:
televisores = [*range(0, 120)]
frequencia = [5, 25, 40, 15, 10, 5]

df = pd.DataFrame({'televisores': televisores})

bins = pd.cut(df['televisores'], [0, 20, 40, 60, 80, 100, 120])
df = df.groupby(bins)['televisores'].agg(Media='mean')

df['Freq. absoluta'] = frequencia

count = [x for x,y in zip(df['Media'], df['Freq. absoluta']) for i in range(y)]

O problema é que a media retorna os valores com 0.5 a mais
    df
                 Media   Freq. absoluta
    televisores
    (0, 20]       10.5         5
    (20, 40]      30.5         25
    (40, 60]      50.5         40
    (60, 80]      70.5         15
    (80, 100]     90.5         10
    (100, 120]   110.0         5

    mean(count), mode(count), median(count)
      53.475       50.5         50.5

Queria entender o problema e saber se tem algum modo mais fácil de chegar no resultado.
Comment: Tentou usar `include_lowest=True` no cut? Independente disso. Acredito que seu resultado está certo, uma vez que vc usou o cut.
Answer: O script está fazendo o que deveria. Assumir que as médias estão erradas em 0.5 está errado.
Alguns pontos:

range(0, 120) irá criar uma lista iniciando em zero e terminando em 119.
pd.cut irá criar 6 intervalos onde, por padrão, tem o formato (x...y]. Onde o lado x é aberto e o lado y fechado. Para inverter use: right=False no cut
pd.cut não inclui o valor mais baixo. para fazê-lo use: include_lowest=True

Usando o cut, vc teria intervalos como
>>> import numpy as np
>>> for sdf in np.array_split(df, 6):
...     print(list(sdf.televisores))
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]

Perceba que
>>> mean([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
9.5

>>> mean([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
10

>>> mean([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])
10.5

Entretanto, caso vc use .loc:
>>> import pandas as pd
>>> import numpy as np
>>> from statistics import mean, median, mode

>>> televisores = [*range(0, 120)]
>>> frequencia = [5, 25, 40, 15, 10, 5]

>>> df = pd.DataFrame({'televisores': televisores})

>>> df.loc[0:20].mean()
televisores    10.0
dtype: float64
>>> df.loc[20:40].mean()
televisores    30.0
dtype: float64
>>> df.loc[40:60].mean()
televisores    50.0
dtype: float64
>>> df.loc[60:80].mean()
televisores    70.0
dtype: float64
>>> df.loc[80:100].mean()
televisores    90.0
dtype: float64

Embora vc receba as médias que você estava esperando, isso está errado. No caso acima, df.loc[0:20].mean() e df.loc[20:40].mean() usam o mesmo 20 para ambos cálculos de média.
Nota o .loc inclui os indices inicial e final no resultado
>>> df.loc[0:3]
   televisores
0            0
1            1
2            2
3            3

Comment: Ótima explicação! Contar o mesmo número em duas médias também não me parece correto, mas é o que foi pedido. Acabei me expressando mal ao dizer que a media estava errada, não sabia como contornar o problema dos intervalos, o mais próximo que cheguei foi arredondar com `.apply(np.floor).reset_index()` no groupby pra forçar o resultado. Utilizar o loc funcionou nesse e em todos os exercícios similares.

Valor incorreto do agg mean


Node.Js async iterator over stream pipeline

Question: I have the following pipeline:
readFile > parseCSV > otherProcess

The readFile is the standard Node.Js createReadStream, while the parseCSV is a Node.js transform stream (module link).
I want to iterate through a csv file line by line and handle a single line at the time. Therefore, streams and async iterator are a perfect match.
I have the following code which is working properly:
async function* readByLine(path, opt) {
  const readFileStream = fs.createReadStream(path);
  const csvParser = parse(opt);
  const parser = readFileStream.pipe(csvParser);
  for await (const record of parser) {
    yield record;
  }
}

I'm quite new to Node.Js streams, but I've read from many sources that the module stream.pipeline is preferred to the .pipe method of read streams.
How can I change the code above in order to use the stream.pipeline (actually the promise version got from util.promisify(pipeline)) and yielding one line at the time?
Answer: Adding to @eol's answer, I would recommend storing the promise and awaiting it after the async iteration.
const fs = require('fs');
const parse = require('csv-parse');
const stream = require('stream');

async function* readByLine(path, opt) {
    const readFileStream = fs.createReadStream(path);
    const csvParser = parse(opt);
    const promise = stream.promises.pipeline(readFileStream, csvParser);
    for await (const record of csvParser) {
        yield record;
    }
    await promise;
}

By calling await pipeline(...) before the loop, it will consume the whole stream before you can iterate from whatever is left in the buffer, which works by accident on small streams but is likely to break on larger (or infinite/lazy) streams.
The callback equivalent might make it more clear what's going on depending on where we await.
// await before iterating
stream.pipeline(a, b, err => {
  if (err) return callback(err)

  for await (const record of b) {
    // process record
  }

  callback()
}

// await after iterating
for await (const record of stream.pipeline(a, b, callback)) {
  // process record
}

Comment: For anyone as much a novice as myself, I recommend https://medium.com/@segersian/howto-async-generators-in-nodejs-c7f0851f9c02 to explain iteration using function generators.
Comment: I'm reading a csv file and need to turn each record into a postgres row after adding a column and checking it's not a dupe.  I prefer this example because it is more concise and the input file size is not a consideration.  But, I'm new to Node.  How is readByLine() invoked outside of its block to return a single record?  Is .next involved?  Where are errors handled?  I'd like to put it all into async.auto form.  Thanks for any help.
Comment: @viejo the function flow is different than "normal" functions because it's an [async iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) - .next() is called automatically by the `for await of` structure below
Comment: Thank you, Val.  I copied your upper code and called readByLine() but got back only "Object [AsyncGenerator] {}".  I'm sure there are missing parts to your example that are obvious to a knowledgeable person.
To make a functional program, do I have to place all of the record processing and database checking/adding logic where you have placed the line 'yield record;' ?  In other words, calling readByLine() multiple times will not produce one record after another sequentially?
Answer: You should actually be able to just pass both the fs-stream and the parser-stream to pipeline() and use your async iterator on the parser-stream:
const fs = require('fs');
const parse = require('csv-parse');
const stream = require('stream')
const util = require('util');
const pipeline = util.promisify(stream.pipeline);

async function* readByLine(path, opt) {
    const readFileStream = fs.createReadStream(path);
    const csvParser = parse(opt);
    await pipeline(readFileStream, csvParser);
    for await (const record of csvParser) {
        yield record;
    }
}

Comment: I'm really sorry, It works with the proper imports. I copied and pasted your code, but in mine I called `pipeline = util.promisify(stream.pipeline);` `pipelinePromise`, while `pipeline` was the stream pipeline function. I'll mark it as correct, thanks
Comment: With this I get the following error `[ERR_INVALID_CALLBACK]: Callback must be a function. Received Parser` at this line `await pipeline(readFileStream, csvParser);`. I didn't mention that I'm using typescript, but I think it should not change the problem
Comment: Weird, worked fine for me with node 14.x.x on debian - can't test it right now, but I'll have another look at it tomorrow.
Comment: If it can help, I'm running on macos with node 12.11
Comment: Also works fine for me on 12.11.0, are you sure you're using the same code as I did? Are the imports the same?


Como fazer deploy de um container Windows no Heroku?

Question: Estou tentando fazer o deployde um container Windows no Heroku porém estou tendo o seguinte erro:

image operating system "windows" cannot be used on this platform

No site do Heroku tenho a seguinte informação:

Develop with Docker, deploy to Heroku
Use Docker for local development on Windows, Linux, or Mac. When you're ready, just push your code and Dockerfile to build and deploy your Docker images to Heroku.

O que me leva a pensar que é possível realizar o deploy utilizando uma imagem Windows.
Meu Dockerfile é o seguinte:
FROM mcr.microsoft.com/dotnet/framework/aspnet:4.7.2-windowsservercore-ltsc2019
ARG source
WORKDIR /inetpub/wwwroot
COPY ${source:-obj/Docker/publish} .

E meu heroku.yml é o seguinte:
build:
  docker:
    web: swagger-aspnet-docker/Dockerfile
run:
  web: bundle exec puma -C config/puma.rb

Answer: O Heroku e a maioria dos servidores só fazem deploy de imagens com base no kernel linux por causa de limitações do Windows, quando ele diz em rodar no Windows e subir para o Heroku ele esta dizendo para você desenvolver em uma imagem base linux localmente e subir aplicação, o docker aproveita o kernel do SO, imagens de base Windows não conseguem utilizar o kernel do linux por isso não tem suporte, nesse caso você teria que contratar um servidor windows e instalar o docker para fazer o deploy nesta maquina
Comment: @Sorack Pela imagem, nota-se que estamos falando de uma aplicação ASP .NET 4.7, baseada em .NET Framework. O .NET Framework não suporta deployment no linux. Teria de portar pra Mono para poder validar.
Comment: E como eu poderia fazer pra subir esse servidor? Não tem como usar uma outra imagem que não seja `Windows`?
Comment: 1- Você pode contratar o serviço docker entreprase https://www.docker.com/products/windows-containers
Comment: 2 - Existem soluções da AWS https://aws.amazon.com/pt/windows/
Comment: 3 - Pode usar a própria plataforma da microsoft https://azure.microsoft.com/pt-br/services/kubernetes-service/docker/
Comment: existem diversas outras abordagens mas acredito que essas os similares serão as melhores pra você
Comment: isso que eu tentei explicar


Compiling Python to C using Cython

Question: I'm trying to compile python source code foo.py to C using cython.
In foo.py:
print "Hello World"

The command I'm running is cython foo.py.
The problem is that when compiling foo.c using gcc, I get the error:
undefined reference to 'main'.
Answer: when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object.
in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file.
please notice you'll need the python .so runtime libraries in order to run the exec.
Comment: See [Cython GitHub Wiki: Embedding Cython](https://github.com/cython/cython/wiki/EmbeddingCython).
Answer: Read the Cython documentation. This will also (hopefully) teach you what Cython is and what it isn't. Cython is for creating python extensions (not a general-purpose Python-to-C-compiler), which are shared objects/dlls. Dynamically loaded libraries don't have a main function like standalone programs, but compilers assume that they are ultimately linking an executable. You have to tell them otherwise via flags (-shared methinks, but again, refer to the Cython documentation) - or even better, don't compile yourself, use a setup.py for this (yet again, read the Cython documentation).
Comment: for me this answer resulted in compilation of a working extension. answer of RoeeK resolved the linking problem, but after Python failed to import with error `ImportError: dynamic module does not define init function`. thank you really much, I think would be nicer to write it with less lecturing style without assuming stupidity as the 3 rtfm suggests.
Comment: This answer would be perfect if it included a link to the [Cython docs](https://cython.readthedocs.io/en/latest/) and the [Cython FAQ](https://github.com/cython/cython/wiki/FAQ#how-can-i-run-doctests-in-cython-code-pyx-files).
Comment: Not a very helpful answer. It's basically a RTFM but wrong as proven by the accepted answer.
Answer: The usual way is to use distutils to compile the cython-generated file. This also gives you all the  include directories you need in a portable way.

Compiling Python to C using Cython


The rule of the 3 sigmas ---- how many times multiply the sigma to get 85%?

Question: $\sigma c=\sqrt{\overline{R}(\sigma S)^{2}+\overline{S^{2}}(\sigma R^{2})}$
where,
$\sigma c$ --- the buffer stock --- needed for maintaining the risk
of stockouts, is used by logistitians
$\overline{R}$ --- the mean of the reserves
$\overline{S^{2}}$ --- the mean of the production
$(\sigma S)^{2}$ --- the square of the std. deviation of the production
series
$(\sigma R^{2})$ --- the square of the std. deviation of the reserves
With this value of the stock buffer i am able to assure 84% of the
stockouts. If i wanted 97.6% of the cases i would calculate for the
value of 2 sigmas instead of one like in the equation. Now these percentages
are given values......but what if i wanted to have the stock buffer
to cover a custom percentage not only the cases where sigma is 1,
2 or 3....but 1.2 for example. The problem is i need to get how many
times i have to multiply the sigma in order to get 85% of the stockouts
covered by the possible stockouts.
Comment: Your values are obtained from the cumulative standard Normal distribution.  For instance, in `R` you can use `pnorm` by typing (say) `pnorm(1.2)`.  The answer you will get is 88.5%.  The function `qnorm` is the inverse; *e.g.*, `qnorm(0.85)` yields the answer 1.036: that's the multiplier to use for 85% coverage.
Answer: You could try using an application like the one here.  If you do, be sure to select "Up to Z" (it starts on "0 to Z" by default, which is not what you want) in the application window.  If you move the cursor to Z=1 or Z=2, you can easily verify that it reproduces the 84% and 97.6% (actually, it's 97.7%, I believe) values that you have already quoted.  Alternatively, to obtain more accurate values, you may also scroll further down in the link above, and they also provide a table where you can just read off the numbers that you need.
Comment: Thanks, i tried to find it by the CDF of normal distribution but is very hard, here is s.m.th more about this [link](http://math.stackexchange.com/questions/145087/how-to-calculate-the-integral-in-normal-distribution). Thanks a lot for the help you saved my day :)


asymptotic probability of at least $m$ unique numbers in selection of $k$ integers in range $1, \ldots, n$

Question: The starting point is the following:
Given the positive fractions $0 \lt c \le d \le 1$, what is the probability of getting at least $m=cn$ unique numbers when selecting $k=dn$ integers independently and uniformly from the range $[1,n]$?
In a related question, an exact answer for a fixed $m$ is given as a sum involving binomial coefficients:
https://math.stackexchange.com/a/1087968/471924
Instead of an exact answer, I would like to consider where $m$ is significantly smaller than the expectation value, and to discuss the asymptotics of the probability as $n$ increases without bound.
In particular I am looking for conditions on $c$ and $d$ that allow a statement like:
With probability $1-o(1)$ there are at least $cn$ unique numbers when randomly selecting $dn$ integers uniformly from the range $[1,n]$.
Is there someway to get from the exact results to conditions on $c,d$ which would make the above asymptotic statement true?
Answer: The number $Z_{dn} $ of unique numbers when selecting $dn$ numbers with replacement from $n$ is about $(1-e^{-d})n$ on average.  Moreover, the variance is of order $n$, so $Z_{dn} = (1-e^{-d})n + O_p(\sqrt{n})$.
It can be shown that the error of this approximation is asymptotically normal. Here is the idea. Let the numbers be drawn one by one. Denote by $T_k$ the time of $k$th unique number appearing. Then $T_k = G_1 + \dots + G_k$, where $G_k$ are independent with $G_k\simeq \mathrm{Geo}(\frac{n-k+1}{n})$. Despite they have different distribution, the CLT (e.g. in the Lindeberg form) can be applied for $k = cn$, $c\in(0,1)$. In order to deduce the asymptotic normality for $Z$ from here, notice that $\{Z_{m}\ge k\} = \{T_k\le m\}$.
TLDR: you have the desired statement for any $c<1-e^{-d}$.

Let $A_i = \{\text{the number $i$ is chosen}\}$. Then the expectation of $Z_{nd}$ is
$$
\mathrm{E}[Z_{nd}] = \mathrm{E}\Big[ \sum_{i=1}^{n} \mathbf{1}_{A_i}\Big] = \sum_{i=1}^n \left(1 - \mathrm{P}(A_i^c)\right) = n \left(1 - \Big(1-\frac1n\Big)^{nd}\right)\approx n (1-e^{-d}).
$$
Comment: Can you show how to deduce those facts? Or provide a reference for those facts so I can see how that is worked out? (in particular regarding the error of the approximation)
Comment: @JJMalone, the expectation part should not be a problem for you. Concerning the asymptotic normality, I gave some ideas. Unfortunately, no references for you. But currently my master student is writing a paper on this problem, it may be finished soon.
Comment: @zhoraster Maybe I'm just misunderstanding, but when selecting n integers with replacement from 1...n, a quick test in python seems to indicate I get roughly n/e numbers selected uniquely. Above it looks like you are claiming it is (1-1/e)n, which looks like you are calculating the opposite number (how many in that range are not selected exactly 1 time). Did I misunderstand something?
Comment: @BuddyJohn, see the edit and check your code.
Comment: @zhoraster Okay, I see. I interpreted "unique" differently.  I took it to mean making nd selections, and how many of the selections are unique (ie. the number was selected exactly one time). And rereading, that does not appear to be the intention.


ROSE (Random Over Sampling Examples) in python

Question: I am currently working on imbalanced data topic. And I found a function in R called ROSE (paper). I understand from a high level how the function works, unfortunately, I do not have a very strong background in statistics, therefore, I can't reproduce the algorithm in Python.
So my questions are; Can someone help me understands in depth how ROSE works? Or at least point me  towards a good reference to understand it in depth.
Secondly, a rough estimation on how hard would it be to reproduce it in python.
Much appreciate it!
Comment: Why is class imbalance such a problem? Much of statistics says otherwise.
https://stats.stackexchange.com/questions/357466/are-unbalanced-datasets-problematic-and-how-does-oversampling-purport-to-he
https://www.fharrell.com/post/class-damage/
https://www.fharrell.com/post/classification/
https://stats.stackexchange.com/a/359936/247274
https://stats.stackexchange.com/questions/464636/proper-scoring-rule-when-there-is-a-decision-to-make-e-g-spam-vs-ham-email
https://stats.stackexchange.com/questions/368949/example-when-using-accuracy-as-an-outcome-measure-will-lead-to-a-wrong-conclusio
Comment: Getting to the software issue, there is a Python library called RPy2 that lets you call R functions, kind of a reverse of "reticulate" in R.
Comment: Imbalance can be a problem for very small datasets, but otherwise it tends to be just an unequal misclassification costs problem and the imbalance is irrelevant.  The important thing to do is to know what criterion you actually want to optimise (e.g. what are the misclassification costs for each type of error, e.g. false-positive and false-negative).  Until you have decided that, you probably don't want to resample the data.
Answer: I saw your question 6 months later, so my answer may be useless, but I want to answer for users who find the answer later.
I'm not sure it's exactly the same with the ROSE package in R, but a python package imblearn implements the ROSE sampling.
The below is an excerpt from here: https://imbalanced-learn.org/stable/over_sampling.html

If repeating samples is an issue, the parameter shrinkage allows to create a smoothed bootstrap. However, the original data needs to be numerical. The shrinkage parameter controls the dispersion of the new generated samples. We show an example illustrate that the new samples are not overlapping anymore once using a smoothed bootstrap. This ways of generating smoothed bootstrap is also known a Random Over-Sampling Examples (ROSE) [MT14].

I don't know about the ROSE in depth, but the algorithm seems to perform over sampling with smoothing in a multivariate way (sampling dataset and smoothing each sample?). I hope someone who is familiar with this algorithm could explain in depth with another answer.
So, I think you can use the package instead of implementing the algorithm yourself, if you just want to use this sampling. Or, it would be helpful to check the source code of imblearn github directly.
https://github.com/scikit-learn-contrib/imbalanced-learn/blob/master/imblearn/over_sampling/_random_over_sampler.py


log4net smtp appender failing

Question: I have log4net configured as follows

<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

  <file value="Logs\\rolling.log" />

  <appendToFile value="true" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <rollingStyle value="Date" />
  <datePattern value=".yyyy-MM-dd'.log'" />
  <maximumFileSize value="10MB" />

  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="[%date{dd MMM yyyy HH:mm:ss fff}] [%5level] (%identity-%username) %message%newline" />
  </layout>
</appender>

<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
  <to value="***" />
  <from value="***" />
  <subject value="****" />
  <smtpHost value="localhost" />
  <bufferSize value="1" />
  <lossy value="true" />
  <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="ERROR"/>
  </evaluator>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="[%date{dd MMM yyyy HH:mm:ss fff}] [%5level] (%identity-%username) %message%newline" />
  </layout>
</appender>

<root>

  <level value="INFO" />
  <appender-ref ref="RollingFile" />
  <appender-ref ref="SmtpAppender" />
</root>

The rolling file appender works fine however the SMTP appender is failing with the following error
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::1]:25
What I find strange is that the square brackets in the end of the error do not contain the SMTP host from the config. I was expecting to see localhost there.
I am running this against smtp4dev on my local machine.
Thank you!
Answer: The [::1] notation is the IPV6 way of denoting the loopback address (the double colon notation simply hides 0 that don't add information to the address) so the message just tells you the appender is trying to reach the localhost.
Regarding the error itself, it may be due to an antivirus blocking access to the port you want to use, or to a firewall preventing the connection. Please check whether you have messages regarding blocked access on these applications.

log4net smtp appender failing


What is wrong with this code for the classic 'Subset Sum' problem?

Question: Problem Statement: Given a list of integers (nums) and an integer x, check if some (possibly all) elements from the list, when added, give x.
Solution:
int dp[20001];
int recurse(vector<int>& nums, int x, int i) {

    if (x == 0)
        return 1;

    if (i < 0 or x < 0)
        return 0;

    if (dp[x] != -1)
        return dp[x];

    return dp[x] = recurse(nums, x - nums[i], i - 1) or recurse(nums, x, i - 1);
}
bool canPartition(vector<int>& nums, int x) {

    memset(dp, -1, sizeof dp);
    return recurse(nums, x, nums.size() - 1);
}

Problem is with the last line. If I change the order of recursions, i.e., recurse(nums, x, i - 1) first and then recurse(nums, x - nums[i], i - 1), I get wrong result.
e.g., [1, 2, 3, 4, 5, 6, 7] -> False
I'm guessing it has something to do with apparently wrong values being put in dp array which then returns the same when looked up again. But please clarify further. Not able to see through it clearly.
PS: All elements of dp array are -1 initially.
Answer: Your dp array depends only on the value of x. But it should depend on both x and i.
As an example:
Suppose nums = [1, 2, 3, 13] and x=13.
Then recurse(nums, 13, 3) should return 1, but recurse(nums, 13, 2) should return 0. With your code, if you called recurse(nums, 13, 2) first then dp[13] would be assigned an incorrect result. If you had two separate entries dp[13][3] and dp[13][2] then there would be no issue.
Comment: https://prnt.sc/1r1a8ui

as you can see, it gives the desired result
Comment: @SaptarshiGanguly Yes, but if you called `recurse(nums, 13, 2)` followed by `recurse(nums, 13, 3)` then you'd get incorrect results.


Computation of Network Homophily / Heterogeneity

Question: I am quite confused about the calculation of network homophily in network analysis. Right now I am computing the homophily using the following function, which has been written and also described by the following URL: http://dappls.umasscreate.net/networks/calculating-network-homophily-part-1/. Well the definition of homophily in social science is "the tendency of individuals to associate and bond with similar others". In network analysis homophily is described as a process where similar nodes on a particular trait are more likely to form ties, which is quite the same as in social science right? My goal is to measure the homophily in a directed network to identify which group of actors are similar to each other.
Function
homophily <- function(graph, vertex.attr, attr.val=NULL,
                      prop=TRUE){
  #Assign names as vertex attributes for edgelist output#
  V(graph)$name <- vertex_attr(graph, vertex.attr)

  #Get the basic edgelist#
  ee <- get.data.frame(graph)

  #If not specifying on particular attribute value,
  #get percentage (prop=TRUE)#
  #or count (prop=FALSE) of all nodes tied with matching attribute#
  if(is.null(attr.val)){
    ifelse(prop==TRUE, sum(ee[, 1]==ee[, 2])/nrow(ee),
                       sum(ee[, 1]==ee[, 2]))

  #If not null, get proportion (prop=TRUE) or count (prop=FALSE) of#
  #edges among nodes with that particular node attribute value#
  } else {
    ifelse(prop==TRUE, sum(ee[,1]==attr.val &
     ee[, 2]==attr.val)/nrow(ee[ee[, 1]==attr.val|ee[ ,2] ==
       attr.val,]), sum(ee[,1]==attr.val & ee[,2]==attr.val))
  }
}

Sample Data
set.seed(5165)
#Random directed graph with 100 nodes and 30% chance of a tie#
gg <- random.graph.game(100, 0.3, "gnp", directed=TRUE)

#Randomly assign the node attribute (group numbers 0:3)#
V(gg)$group<-sample(1:5,100,replace=T)

Output
By applying the function on sample data I receive the following output, which means that 20% of the ties in the network are between actors in the same group. It is also possible to compute the homophily for a specific group in percentage.
homophily(graph = abc, vertex.attr = "group")
[1] 0.1971504

However I also noticed that the igraph package contains as well a homophily method called assortativity() described here. Executing this function gives completely different results, with the assortativity coefficient in a range(-1, 1). The assortativity coefficient is positive if similar vertices (based on some external property) tend to connect to each other, and negative otherwise.
library(igraph)
assortativity(abc, V(abc)$group, directed=TRUE)
[1] -0.02653782

Question
So right now I am quite confused, which of these methods is the right one to measure the homophily in a network, because both functions received different results. I also noticed that the igraph method does not support the calculation of particular groups. In my opinion I would rather go with the first one which is self-coded (not sure if there are some mistakes), because the interpretation makes more sense. So my question is, which of the following methods is the right one for measuring the homophily in a network? I mean if I want to know how heterogeneous or homogenous actors in a network communicate, I would rather choose the first technique. Both techniques measure homophily & receive different results, but right know I can not see any difference (advantage) which one will be used for any reason. The goal of this technique is to measure the homophily in a network by their proportion of all edges in a network.
Answer: The second one (igraph function) is correct.  The first one does not take into account the baseline probability that two people from the same group will be connected by random change.
Because your groups are randomly assigned---not due to a process of preferential in-group attachment---you should not expect a proper homophily measurement to show any homophily.
To see this, try using just 2 groups instead of 5, e.g.:
V(gg)$group<-sample(1:2,100,replace=T)

Note how the homphily then jumps to around 0.5, despite the tie-formation process being the same.  With the assortativity measure, it is around zero.
To see this even more strongly, use two groups of unequal sizes.  In a network with 90% of group 1 and 10% of group 2, people of group 1 are likely to be connected to each other by sheer chance:
V(gg)$group<-runif(100,0,1)>0.1

Homophily is now 0.8 despite people still connecting randomly.  With the assortativity measure, it is around zero.
For further reading and an explanation of the igraph measurement, see Chapter 4 from the classic book "Networks, Crowds, and Markets," which can be found at this URL: http://www.cs.cornell.edu/home/kleinber/networks-book/
One more thing to note about assortativity is that it is also more general; it can measure correlation in continuous variables, not just nominal group assignments.  For this reason, you should use "assortativity_nominal" to measure homophily for group labels as in your example.  (See the igraph help file on the function)  This is also why it can be negative:  it can show if people tend to avoid each other.
Update:
This answer does not depend on the underlying topology of the network.  For example:
set.seed(5165)
#Random directed "small world" graph with 100 nodes and 30% chance of a tie#
gg<-sample_smallworld(1, 100, 4, 0.3, loops=T)

#Randomly assign the node attribute (group numbers 0:5)#
V(gg)$group<-sample(1:5,100,replace=T)

homophily(graph = gg, vertex.attr = "group")
[1] 0.225
assortativity_nominal(gg, factor(V(gg)$group), directed=T)
[1] 0.0251419

Comment: On Small Worlds:  You are conflating the topology of the edges with node-attribute homophily.  You could have a "random" (Erdos-Renyi / Poisson graph) network that shows homophily---i.e., in which node attributes are not assigned randomly.  If you started with a random small-world network in the code example above, you'd still have no homophily because node attributes are assigned randomly.  Whether or not Twitter in particular shows homophily is an empirical question, not a theoretical question.
Comment: On the Krackhardt E/I index and the Coleman homophily index:  these are two different indices.  However, both of them are similar in that they measure in-group tendences *for a particular group.*  The homophily/assortativity measure you give in your question measures it for the network as a whole, considering all groups therein.
Comment: Thank you for your detailed explanation to this topic. I have to question about your statements. In this example a random network is choosen, where groups are randomly assigned, what about small world network for example a network of tweets by twitter? Is there any difference in this, I mean in most of the cases these groups would not be randomly assigned right? Another question is based on the E-I Index, which I tried to compute (based on probability), I thought the Krackhardts and Colesman computation is for measuring the homophily in a network?
Comment: Added small-world example.


computing Moore-Penrose pseudoinverse when SVD computation does not converge

Question: I am writing a routine to return the Moore-Penrose inverse of a rectangular matrix.
Currently am computing the Moore-Penrose inverse using SVD, i.e., if the SVD is given by $A = \sum_{i=1}^r \lambda_i u_i v_i^T$, with $\lambda_i > 0 $ then $A^{+} =  \sum_{i=1}^{r} \frac{1}{\lambda_i} v_i u_i^T$. However, if SVD computation does not converge, I will have to throw an exception, I would prefer to compute the pseudo-inverse using some non-iterative method.
I have come across the formula that $A^{+} = H(H^2)^-A^T$, where $H=A^TA$ and $(H^2)^-$ is any generalized inverse of $H^2$, and I can compute a generalized inverse using elementary row operations, this does provide a way. However, I am not fond of this method because $H^2$'s condition number is $A$'s condition number raised to the fourth power.
Do I have any other alternative?
Comment: When does SVD not converge? I haven't encountered any cases where SVD doesn't converge.
Comment: Unfortunately OP has not been able to share an example of a matrix that chokes SVD...
Answer: You can compute a complete orthogonal decomposition using two QR decompositions.  See http://www.netlib.org/lapack/lug/node43.html


Mudar a cor do site em um clique de botão!

Question: Boas pessoal!
Eu tenho um botão com 5 botões, ao clicar nesses botões, a cor do site vai mudar, eu estava a fazer esse processo a alterar a cor em Javascript, mas não acho muito viável... Qual a melhor maneira de fazer isso? Fazer 5 cópias do documento css original mudando assim só as cores e fazendo trigger com js?
Qual será a melhor maneira de fazer isso, pessoal?
Comment: mudança permanente?
Comment: Sim, pelo menos até ao utilizador voltar a clicar noutro botao para mudar para outra cor, ou até o utilizador fazer refresh À pagina.
Comment: Então não é permanete, vc pode simplesmente usar `Jquery` e mudar quando clicar, quando atualizar ela volta ao normal
Comment: Muito obrigado.
Comment: Vou postar um exemplo
Answer: Acho que o melhor a se fazer seria criar classes para cada cor (ex: dark, light, default) e quando clicar no botão altera apenas a classe do elemento pai, o resto ja esta definido dentro.
ex:

var dark = document.getElementById('btnDark');
var light = document.getElementById('btnLight');
var initial = document.getElementById('btnInitial');
var body = document.querySelector('body');
dark.onclick = function(){
 body.className = "dark";
}

light.onclick = function(){
 body.className = "light";
}

initial.onclick = function(){
 body.className = "";
}
.dark{
background:#000;
color:#fff;
}

.light{
background:#fff;
color:#4b4b4b;
}

Lorem Ipsum é simplesmente

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica.

  <button id="btnDark">Dark</button>
  <button id="btnLight">Light</button>
  <button id="btnInitial">Default</button>

Utilize o sass para criar as classes, facilitaria muito mais.
PS: No exemplo acima não usei nenhuma biblioteca.
Comment: Boa ideia!
Obrigado!
Answer: Com Jquery:
<button id="red">Vermelho</button>
<button id="green">Verde</button>
<button id="blue">Azul</button>

Comment: Fiz isso, mas o problema que estu a a ter agora é que, tenho um titulo h2, esse h2 tem um after pseudo element, como mudo a cor do pseudo element do h2 com jquery?
Comment: @NelsonPacheco Não é possível. O que você pode fazer é criar um código CSS, por exemplo: `.your_class::after { /* Your Code */  }` e depois utilizar `addClass` ou `toggle` para alterar o CSS.


How to represent binary relations?

Question: Basically, Im not sure how to to evaluate if a ∧ b is a function, injective, reflexive etc. I can evaluate these properties if Its a real function e.g. f(x) = x+2 as I can just look at the graph/test these properties using numbers. But I have no idea how to represent "a ∧ b" as a graph/in a relationship diagram. To reiterate, I understand the definitions of injective, reflexive etc, I just dont know how to apply them to binary relations.
Answer: Try $\;\;\text{graph} \;(C) = \{(a, b) \in \mathbb Z \times \mathbb Z\mid C(a, b) = T\},\;$ where the binary relation is $"\land$" $\;$ and so $aCb \iff a\land b = T$
$ (T\land T) = T, \quad (T \land F) =  F, \quad (F\land T) = F$,  $  (F\land F) = F $
So $C = \{(T,T)\}$
Note that the relation $\text{graph}C = \{(a, b)= (T, T)\}$, (because $a\land b$ is true only when $a =b= T$.  Clearly, Since we need a = b = T, $a C a =T$, and $b C b = T$.  So the relation is reflexive. It is also symmetric, since $(a, b) = (T, T) = (b, a)$
Comment: I tried to use the notation you used in your post.
Answer: I do not see the problem. You can view $\wedge$ as function
$$
\wedge : \{0,1\}^2 \to \{0,1\}
$$
and verify it is a function (it is single valued at each point). It is not injective, as
$$
\wedge(t,f) = \wedge(f,t) = f
$$
so several arguments point to the same value.
To see if it is reflexive, you have to view it as relation:
$$
\wedge(t,t) = t \iff t \wedge t \\
\wedge(f,f) = f \iff \neg (f \wedge f)
$$
so it is not reflexive. Etc. A table could be:
$$
\begin{array}{r|rr}
x \wedge y & f & t \\
\hline
f &  - & - \\
t &  - & \surd
\end{array}
$$
Comment: The OP is struggling with the binary operation $\land$", as in  $\;\;a \land b$

How to represent binary relations?


How to maintain Struts2 Session

Question: I am using Struts2 in my application. In my application I have one login form and one main page. On successful login, I call main page and inside that main page I have called another action. Up to this all is working fine and page is also display after successful login but when I press F5 or click on browser refresh button it will give me login page but I want the same page on which I fire F5 or refresh button. How can I achieve this, my struts.xml is as follow..
...
<action name="mytable" class="MyDataTable">

        <result name="success" type="json"/>
        <result name="error">messages.jsp</result>

    </action>
    <action name="edit" class="MyEditAction">

        <result name="input" type="json"></result>
        <result name="success" type="json"></result>
        <result name="error">messages.jsp</result>

    </action>
    <action name="Login" class="LoginAction">

        <result name="input">login.jsp</result>
        <result name="success">main.jsp</result>
        <result name="error">messages.jsp</result>

    </action>
    <action name="Logout" class="LogoutAction">
        <result name="success">login.jsp</result>
    </action>

...
After login I call main.jsp and from main.jsp I am calling mytable action. After showing me the main page the address bar of browser still shows me the Login action
So please help me how can I maintain session.
Comment: your question is not clear to me, how you doing login and how to storing logged in user?
Answer: First of all, you must consider using a security framework. I recommend using Spring Security. There is A LOT that you can do wrong implementing security all by yourself. This will make sure users are properly authenticated and will guard you from many attacks. From the code you give us, it doesn't seem that you have this in place.
For your scenario, you want to use the so-called Post/Redirect/Get pattern. This pattern will make sure that the browser is redirected to a GET url, after doing a post. This will make sure that the user does not submit a form twice. It also makes sure that the browseris pointed to the new url.
To do this in Struts2, you must use the Redirect Action Result. An example is also worked-out here.
In your case this would be something like:
...
<action name="Login" class="LoginAction">

    <result name="input">login.jsp</result>
    <result name="success" type="redirect">
        <param name="actionName">displaySalesOrder</param>
        <param name="namespace">/yournamespace</param>
    </result>
    <result name="error">messages.jsp</result>

</action>

<action name="main" class="MainAction">
    <result name="success">main.jsp</result>
</action>
...

Comment: For current versions of Struts2, the type should be redirectAction. Also, note that the type "redirect" would also work here.

How to maintain Struts2 Session


Any solution to use two different $base_url's for drupal 7

Question: Any solution to use two different $base_url's for drupal 7. What i need to do is when i log to my site using IP/VPN, $base_url should be xxxx.xxxx.xxxx.xxxx and without any vpn connections $base_url should be aaaa.aaaa.aaaa.aaa. Any solutions? I'm Using Drupal 7.54
Answer: Rather than trying to change the base_url manually you might be better using something like https://www.drupal.org/project/domain or Drupal's language translation system and having 2 domains setup and the content shared for both domains.
So they effectively will look and act the same but the base url for drupal will be whatever the user is currently on. Then you could use these modules inbuilt hooks if you wanted to force a user ontop a specific domain based on their IP or whatever


Communication between two different network id

Question: How can two hosts with different network-id communicate with each other?
10.17.101.16 /24 needs to communicate with 10.17.102.16 /24
I was able to make communication by changing them to same network-id by changing subnet mask. But is it the only way to make communication possible?
Answer: If they're on the same segment then changing the subnet will work but it brings the question of whether that segment was subnetted correctly in the first place.
If they're on different segments then you needs something like a router or layer-3-switch to perform routing.
Comment: If the case is like two nodes are connected to two different switch and the switches are interconnected, will it be on same segment?
Comment: If there's nothing in between and they're 'dumb' switches then yes.
Comment: Ok. can u plse elaborate the 'segment was subnetted properly' part...
Comment: well there are reasons why one segment might be subnetted (i.e. 10.17.101.x and 10.17.102.x) but they're usually pretty advanced cases. Usually you'd only have one subnet per segment for regular basic networks.
Answer: Either the communication needs to be in the same subnet or you need to pass communication through a router.
You can make the subnet bigger if 255 addresses is not enough for you, ie /23 or /22.
Otherwise you need a box that has an interface on both subnets and is configured to route traffic between the two.  http://en.wikipedia.org/wiki/Router
Comment: Ok. I better go off with making my subnet bigger as I am planning not to use routers. Thanks for the reply


Is html or php header needed for gzip?

Question: I use gzip module of nginx to compress documents. When gzip is enabled nginx will automatically send content-ending of gzip with HTTP headers, right?
Without adding any PHP header header() or HTML meta http-equiv, this works perfectly. However, I have seen on online tutorial for adding header for gzip whether by PHP or HTML meta to assist browser to process gzipped data.
Is it really needed? Since I was not sure if this is needed on some conduction (that I am not testing), I asked this question for further clarification of the issue.
Answer: Nginx compresses data on mime type. For static files it uses the mime.types file for this but for data from a backend you do need to set the mime type unless the default is already text/html or you've added the default to the types of be compressed. See http://wiki.nginx.org/HttpGzipModule#gzip_types
Comment: Nginx will automatically add the gzip header.
Comment: If nginx is compressing it then it will make sure the response is properly formatted. You don't need to do anything at all on PHP side.
Comment: Yes, it compress text/html (by default), and without HTML or PHP header it successfully send gzip header. My question is whether I need to add gzip meta or header too? or nginx does this automatically?
Comment: Then adding PHP header is useless, right?

Is html or php header needed for gzip?


Test Explorer do Visual Studio não encontra os testes

Question: Estou com uma dificuldade no Visual Studio 2013, o Test Explorer não está carregando os testes em momento nenhum, seja após o Build, seja através do Run Tests / CTRL+R, T. Alguém tem alguma pista do que possa ser?
Possuo os seguintes pacotes instalados através do NuGet: xUnit.net,xUnit.net: Runners, Fluent Assertions, e o teste abaixo como exemplo:
using Xunit;
namespace Registro
{
    public class CadastroValidoRecebido
    {
        [Fact]
        public void Usuario_Adicionado_Ao_Sistema()
        {

        }
    }
}

Segui acertos de diversos links, o que mais pareceu promissor foram as alterações de arquitetura de processador informada no link abaixo, mas o Test Explorer continua sem localizar os testes.
https://stackoverflow.com/questions/13533259/why-does-visual-studio-2012-not-find-my-tests
Answer: Pelo que me lembro, o Visual Studio não reconhece testes de terceiros (ou seja, que não sejam MSTest) de forma automática, necessitando da instalação de pacotes adicionais ao mesmo.
Dê uma olhada neste para o xunit (não tenho certeza se é este, mas testa ai por favor):
xUnit.net runner for Visual Studio 2012 and 2013
Você também pode tentar o Resharper... é pago, mas eu sou absolutamente fã da ferramenta. Pelo que li sobre ele, suporta o xunit via plugins.
Comment: Olá, Miguel. Obrigado pela resposta, erroneamente pensei que o `xUnit.net: Runners` (https://www.nuget.org/packages/xunit.runners/1.9.2) seria o plug-in que faria funcionar no Visual Studio 2013, após instalar esse informado por você os testes apareceram.
Comment: No meu caso os testes estavam escritos com NUnit 2.0, e por isso tive que adicionar a extensão correspondente de "runner" ao Visual Studio.
Answer: Com a versão mais recente do xUnit.Net já é possível, de acordo com a documentação (http://xunit.github.io/docs/running-tests-in-vs.html) é necessário instalar via nuget o pacote xunit.runner.visualstudio
Com isso o xUnit é integrado com o Test Explorer


Understanding probabilistic Borel-Cantelli Lemma "Corollary" in Royden and Fitzpatrick

Question: The Borel-Cantelli Lemma in Royden and Fitzpatrick's "Real Analysis" seems to be a sort of "corollary" of the non-probabilistic ones I see online.
It says:
"Let $(E_k)_{k=1}^{\infty}$ be a countable collection of measurable sets for which $\sum_{k=1}^{\infty} m(E_k) < \infty$. Then almost all x $\epsilon \ \mathbb{R}$ belong to at most finitely many of the $E_k$'s"
I don't get three things:

"Then almost all x $\in \ \mathbb{R}$ belong to at most finitely many of the $E_k$'s"

What does that mean? Since the Borel-Cantelli Lemma comes after the "almost everywhere" definition, I guess: $\exists \ Z \ \subset \mathbb{R}$ s.t. $m(Z) = 0$ and $\forall x \ \in \ \mathbb{R} \setminus Z$, x belongs to $(E_{j}, E_{j+1}, E_{l}, ..., E_{m})$.

In the proof, one can see the $m(\limsup \ E_k) = 0$ part, stated as $m(\cap_{n=1}^{\infty} [\cup_{k=n}^{\infty} E_k]) = 0$. For some reason, $m(\cap_{n=1}^{\infty} [\cup_{k=n}^{\infty} E_k]) = 0$ implies that "Therefore almost all x $\in \ \mathbb{R}$ fail to belong to $\cap_{n=1}^{\infty} [\cup_{k=n}^{\infty} E_k]$ and therefore belong to at most finitely many $E_k$'s"

Okay, why? What is the contradiction if almost all $x \epsilon \ \mathbb{R}$ belong to all the $E_k$'s? Or a countably infinite subcollection?

What is the significance of this? Why not just state the Borel-Cantelli Lemma as "Let $(E_k)_{k=1}^{\infty}$ be a countable collection of measurable sets for which $\sum_{k=1}^{\infty} m(E_k) < \infty$. $m(\cap_{n=1}^{\infty} [\cup_{k=n}^{\infty} E_k]) = 0$"?
Answer:
I think you're getting a little mixed up (just think about your formulation, intuitively it seems false), but I agree that the conclusion is rather vaguely stated. Let me cite E. Stein's book Real Analysis, in which he poses the Borel-Cantelli lemma as Exercise 16, Chapter 1:

Suppose $\{E_k\}$ is a countable family of measurable subsets of $\mathbb{R}^n$ and that $$\sum_{k=1}^\infty m(E_k)<\infty.$$ Let $$E = \{x\in\mathbb{R}^n: x\in E_k~\text{for infinitely many}~k\} = \limsup_{k\to\infty} E_k.$$
  Then $E$ is measurable, and $m(E)=0$.

You can (check this!) write $E = \cap_{n=1}^\infty \cup_{k=n}^\infty E_k$, so if this set is measure zero then almost every $x$ fails to belong to $E$. But if $x$ fails to belong to $E$, then it means precisely that $x$ is contained in at most finitely many $E_k$. This is the desired conclusion, so we're done!
We could state it like that, but no one would know what it means. For its intuitive interpretation, the probabilistic version is very helpful. If you read the $E_k$-s as events and $m(E_k)$ as the probability of the event $E_k$ occurring, then $E$ is the event that infinitely many of the events $E_k$ occur simultaneously. The Borel-Cantelli lemma says that under a suitable decay condition on the probabilities of $E_k$ (namely convergence in the infinite series), the probability of the event $E$ is zero. Believable enough, I think. For its significance, it is an example of a zero-one law: the probability of infinitely many events occurring together is zero. Zero-one laws are of significant interest to probabilists; the page at http://en.wikipedia.org/wiki/Borel-Cantelli_lemma will mention other examples, some related.
Comment: Well, just think about what $E^C$ must be: if $E = \{x\in\mathbb{R}^n: \exists~\text{infinitely many}~E_k~\text{such that}~x\in E_k\}$, then just negate the appropriate quantifiers and you get exactly what I claimed.
Comment: "But if x fails to belong to E, then it means precisely that x is contained in at most finitely many $E_k$"

Why?
Comment: Also I seem to have completely forgotten that math is extremely theoretical and abstract and often has no significance unless applied like in the probabilistic interpretation. XD
Comment: You could also write $E$ as  $\{x : f(x) < \infty \}$ where $f(x) = \sum_{n=1}^\infty \chi_{E_n}(x)$.


Flask nginx proxy fix duplicates headers

Question: I have a flask server deployed with nginx and gunicorn. I read this and have nginx setup to set these headers and have the werkzeug middleware proxy fix in place. Now the headers coming in on flask have the right ip addresses and hosts and stuff. Except for 1 small problem. The headers show up as duplicates separated by commas. Here's what I see when printing request.headers.
Host: site.com,site.com
X-Real-Ip: 12.345.67.898,12.345.67.898
X-Forwarded-For: 12.345.67.898,12.345.67.898
X-Forwarded-Proto: https,https

These headers, are the ones that nginx overrides. Why do they all repeat. They are repeated and divided by a comma. How can I fix this behavior?
I have the nginx config and the werkzeug middleware proxy fix done exactly is in the example.
Here's my nginx config more or less.
server {
    # dont worry about ssl, certbot handles that
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name site.com www.site.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/site.sock;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Comment: Have you tried redirecting all the HTTP traffic to HTTPS?
Comment: i literally said in a comment that certbot handles ssl that isn't the problem
Comment: What is in the file `proxy_params`?
Comment: oh wow. just checked. it contains the same proxy_set_header that i already was setting. so i was setting them twice. that explains it thanks.
Answer: Richard Smith solved this problem. And that was the include proxy_params; line. I cat /etc/nginc/proxy_params and it contained the exact proxy_set_header lines that where already included. Bassically it set those headers twice. I have to either delete the include proxy_params line or delete the manual proxy_set_header lines.


Summing max & min of a list

Question: I'm working on a homework problem that takes a list of comma separated values, converts them to a list, then sums the max & min from said list.
def max_min_sum():
    user_input = input("Please enter a comma seperated list of numbers")
    input_as_a_list = user_input.split(",")
    input_as_numbers = map(float, input_as_a_list)
    print(sum((min(input_as_numbers))+(max(input_as_numbers, default = 0))))
max_min_sum()

Now I'm getting this error:
TypeError: 'float' object is not iterable

I have also tried:
def max_min_sum():
    user_input = input("Please enter a comma seperated list of numbers")
    input_as_a_list = user_input.split(",")
    input_as_numbers = map(float, input_as_a_list)
    print((min(input_as_numbers) + max(input_as_numbers, default = 0)))
max_min_sum()

But now it's just giving me the min value.
Comment: I tried that but now it's just giving me the min value. Here's the updated code.

    def max_min_sum():
        user_input = input("Please enter a comma seperated list of numbers")
        input_as_a_list = user_input.split(",")
        input_as_numbers = map(float, input_as_a_list)
        print((min(input_as_numbers) + max(input_as_numbers, default = 0)))

    max_min_sum()
Answer: You've at least 2 errors in your code, see this fix with the comments:
def max_min_sum():
    user_input = input("Please enter a comma seperated list of numbers")
    input_as_a_list = user_input.split(",")
    # map returns a generator, so you need to consume the output first
    # Or, you'll endup with max == 0
    # Or, better using a list comprehension
    # input_as_numbers = [float(elm) for elm in input_as_a_list]
    input_as_numbers = list(map(float, input_as_a_list))
    # No need to use sum, you're already using + operator
    print(min(input_as_numbers)) + max(input_as_numbers, default = 0))

max_min_sum()

Summing max & min of a list


Adding Exterior Physic Engine Library to new Project in Java (JBox2D)

Question: I want to import JBox2D libraries into a new project, im new to using exterior libraries so my doubts will seem really stupid but oh well, thats how you learn.
So i kind of followed the tutorial in JBox2D website and i made it this far:

You can see i have the JBox2D trunk (i didnt quite understood what a trunk is...) I believe they are all Maven projects, and my goal is to be able to use the engine's libraries in the PhysicTest project you can see opened.
(Probabily stupidly) Im trying to import as you can see in the image and its not working, so i ask your help to solve such a simple problem that is not so simple for me ^^
Answer: You need to import those projects into your project.  Go to your project properties, build path, and then click on the libraries tab.  There you can add the jbox2d libraries to your PhysicTest project.


Dois toques no ListView - Xamarim Forms

Question: É possível ter UM toque para certa função (hoje tenho para selecionar um item utilizando ItemTapped) e DOIS toques no mesmo ListView para fazer outra função?
Não consegui essa informação no site da Microsoft e em nenhuma outra fonte.
Meu XAML:

                <ListView x:Name="lstCompra"
                          BackgroundColor="Aqua"
                          SeparatorColor="DodgerBlue"
                          ItemTapped="Compra_OnItemTapped"
                          HasUnevenRows="True"
                          Margin="10, 0, 10, 10">

                    <ListView.ItemTemplate>

                        <DataTemplate>
                            <ViewCell>
                                <Grid Margin="2">

                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto" />
                                    </Grid.RowDefinitions>

                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>

                                    <StackLayout Grid.Row="0"
                                                     Grid.Column="0"
                                                     Orientation="Horizontal">

                                    </StackLayout>

                                    <StackLayout Grid.Row="0"
                                                     Grid.Column="1"
                                                     Orientation="Horizontal">

                                    </StackLayout>

                                </Grid>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>

Meu C#:
//Selecionando item da lista
        private void Compra_OnItemTapped(object sender, ItemTappedEventArgs e)
        {
            solicita = (sender as ListView).SelectedItem as SolicitarCompra;
        }

Estou tentando testar o que me foi passado pelo @AmadeuAntunes e não tenho conseguido (sou bem novo na programação), dá erro nessa linha btnClick.Clicked += (sender, e) =>.
O erro:

O XAML:
        <StackLayout>
            <Button Text="Teste"
                    Clicked="Btn_Teste"
                    x:Name="btnClick"/>
        </StackLayout>

O código:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Teste
{
    public partial class MainPage : ContentPage
    {
        int ButtonCount = 0;

        public MainPage()
        {
            InitializeComponent();
        }

        void Btn_Teste(object sender, EventArgs e)
        {
            btnClick.Clicked += (sender, e) =>
            {

                if (ButtonCount < 1)
                {
                    TimeSpan tt = new TimeSpan(0, 0, 1);
                    Device.StartTimer(tt, TestHandleFunc);
                }
                ButtonCount++;
            };

            bool TestHandleFunc()
            {
                if (ButtonCount > 1)
                {
                    //Your action for Double Click here
                    DisplayAlert("", "Two Clicks", "OK");
                }
                else
                {
                    //Your action for Single Click here
                    DisplayAlert("", "One Click", "OK");
                }
                ButtonCount = 0;
                return false;
            }
        }
    }
}

Comment: mostre o código
Comment: Adicionado o código @LeandroAngelo
Comment: Você está aprendendo ou trabalhando com Xamarim?
Comment: Os dois, estou aprendendo no trabalho rs. A minha prática tem sido num app real.
Answer: Eu usaria:
Da primeira vez que faz ItemTapped acciona um "timer" quando voltar a clicar novamente pára o "timer" e chama outro método que até pode chamar de Cliqueduplo

1º TapGestureRecognizer  - começar um "timer"
2º TapGestureRecognizer Pára o "timer" e invoca outro método chamado doupleTapped

Algo assim
     btnClick.Clicked += (sender, e) =>
                {
                    if (ButtonCount < 1)
                    {
                        TimeSpan tt = new TimeSpan(0, 0, 1);
                        Device.StartTimer(tt, TestHandleFunc);
                    }
                    ButtonCount++;
                };

bool TestHandleFunc()
        {
            if (ButtonCount > 1)
            {
            //Your action for Double Click here
                DisplayAlert("", "Two Clicks", "OK");
            }
            else
            {
            //Your action for Single Click here
                DisplayAlert("", "One Click", "OK");
            }
            ButtonCount = 0;
            return false;
        }

Comment: Adicionado o retorno do teste na minha postagem, se puder conferir agradeço.
Comment: Dessa forma não parece ser a melhor opção depois de termos visto sobre o TapGesture aqui na empresa, estamos tentando adaptá-lo no sistema. Mas agradeço pela opção colocada.

Dois toques no ListView - Xamarim Forms


flask+nginx+gunicorn redirect error

Question: I am trying to use flask + gunicorn + nginx to set up a web app. It's ok by running the script, but it has some little problem in nginx.
In the hello.py, it should redirect to index after submit a form. In my local test, the index address is http://127.0.0.1:8080 and everything goes well.
With the server of nginx and gunicorn, when a submit the form, it will redirect to http://192.168.1.108/ instead of http://192.168.1.108:1025/. 192.168.1.108 here is my local ip.
code redirect to index.html in hello.py, the cody is clone from flasky。
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_script import Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from werkzeug.contrib.fixers import ProxyFix

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

if __name__ == '__main__':
    manager.run()

setting in the nginx:
worker_processes  2;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    server {
        listen       1025;
        server_name  127.0.0.1:8080;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://127.0.0.1:8080;   # gunicorn host address
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

Running gunicorn bygunicorn -w 2 -b 127.0.0.1:8080 manage:app.
I think there is something wrong in the nginx configue.
Answer: I suspect that your issue is that nginx is not passing the port along with the Host header to gunicorn, so that your app thinks it's running on the default port instead of 8080. Try chaning your first proxy_set_header in nginx to this:
proxy_set_header Host $host:$server_port;

flask+nginx+gunicorn redirect error


Adding manual inputs to Google Fit

Question: Is it possible to send manual inputs(distance walked/run) to Google Fit?
My intention is to make a simple app which can pass the the user entered number of steps or miles walked into Google Fit.
So that user can enter his own readings from other fitness devices which did not have Google Fit integration.
Answer: Yes look at working with Fitness History, you can manually intput data using the History API
Answer: Yes you can do that by following code. Detail description you will find here
<code> Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    cal.add(Calendar.MINUTE, 0);
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.MINUTE, -50);
    long startTime = cal.getTimeInMillis();

    // Create a data source
    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(activity)
            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .setStreamName(TAG + " - step count")
            .setType(DataSource.TYPE_RAW)
            .build();

    // Create a data set
    DataSet dataSet = DataSet.create(dataSource);
    DataPoint dataPoint = dataSet.createDataPoint()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
    dataPoint.getValue(Field.FIELD_STEPS).setInt((int) steps);
    dataSet.add(dataPoint);

    DataUpdateRequest request = new DataUpdateRequest.Builder()
            .setDataSet(dataSet)
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
            .build();

    com.google.android.gms.common.api.Status updateStatus =
            Fitness.HistoryApi.updateData(mApiClient, request)
                    .await(1, TimeUnit.MINUTES);
</code>

Adding manual inputs to Google Fit


How many rolls of sum of 6d6 for an expectation of 90% chance of hitting three consecutive 6d6 totals each less than or equal to each other?

Question: each Roll is the sum of six six-sided dice ( therefore a value of 6 to 36).  How many times would I have to roll (and take the sum of 6d6) before I would have a 90% expectation of seeing three 6d6 sums that are sequentially less than or equal to each other.
Example...roll 1 is 27. Roll 2 is 30. Roll 3 is 17. Roll 4 is 15.  Roll 5 is 14.
Rolls 3, 4, and 5 are consecutive in the series and each <= the previous roll sum.
I know all of the possible outcomes for every 6d6, and can find the likelihood of rolling each value.  So I assume for any value of my current roll r ( the sum of 6d6 ), I would add up the probabilities of rolling every number <= r.  Then....I don't know.  Thank you!
Comment: Sorry, to clarify...I roll 6d6 and total the values of the six dice.  I continue to roll six dice, tracking the total for each set of six.  I'm trying to find how many rolls to be 90% likely of hitting a sequence of three 6d6 totals that are less than or equal to each other in sequence....not necessarily related to the original roll total.
Comment: Could you please explain what you mean by "in a row," given you state you roll all six dice at once?  What do you mean by "less than or equal to each other" when describing a set of *three* values??
Comment: Are you referring to the *totals* of 6d6? Thus, the $i$-th roll consists of rolling 6d6 and recording the total as $x_i$, and you are asking how many such rolls you need to do to have a 90% chance that there exists an $i$ with $x_i\geq x_{i+}\geq x_{i+2}$?
Answer: TL;DR: 11 (possibly 10). Plus 2.
I got this by simulation, and to be honest, I think a closed formula will be quite painful to derive. Here is my thinking. Note that if the first three rolls already satisfy the condition, then I will record this as stopping after step 1, so if you are interested in the total number and would count this as step 3, you need to add 2 to all numbers below.
First, we can quite easily derive the probability mass function (PMF) $(p_k)$ for the sum of 6d6 by convolution. In R:
n_dice <- 6
probs <- rep(1/6,6)
for ( ii in 2:n_dice ) probs <- convolve(probs,rep(1/6,6),type="open")
names(probs) <- n_dice:(6*n_dice)

Now, it's not overly hard to derive the probability that the first three roll totals $R_1, R_2, R_3$ fulfill your condition, i.e., the probability $q_1$ that your dice rolling stops after 1 step:
$$ \begin{align*}
q_1 = \; & P(R_1\geq R_2\geq R_3) \\
= \; & \sum_{k=6}^{36} P(R_1\geq k)P(R_2=k)P(R_3\leq k) \\
= \; & \sum_{k=6}^{36}\bigg(\sum_{j=k}^{36}p_j\bigg)p_k\bigg(\sum_{j=6}^k p_j\bigg) \\
\approx \; & 0.2016245.
\end{align*} $$
In R:
q_1 <- sum(sapply(seq_along(probs),function(kk)sum(probs[kk:length(probs)])*probs[kk]*sum(probs[1:kk])))

We can still find the probability $q_2$ that you stop after the second step:
$$ \begin{align*}
q_2 = \; & P(R_1< R_2\geq R_3\geq R_4) \\
= \; & \sum_{k=6}^{36} P(R_1<R_2)P(R_2\geq k)P(R_3=k)P(R_4\leq k) \\
= \; & \sum_{k=6}^{36}\bigg(\sum_{j=k}^{36}\Big(\sum_{i=6}^{j-1}p_i\Big)p_j\bigg)p_k\bigg(\sum_{j=6}^k p_j\bigg) \\
\approx \; & 0.1409793.
\end{align*} $$
In R again:
q_2 <- 0
for ( kk in 6:length(probs) ) {
    q_2 <- q_2 +
        sum(sapply(kk:length(probs),function(jj)sum(probs[1:(jj-1)])*probs[jj])) *
        probs[kk] *
        sum(probs[1:kk])
}
q_2

Interestingly, the precise same calculation gives us $q_3$, since the condition to stop at step 3 is $R_2<R_3\geq R_4\geq R_5$, and $R_1$ doesn't matter. So since all rolls are iid,
$$ q_3 = P(R_2<R_3\geq R_4\geq R_5) = P(R_1< R_2\geq R_3\geq R_4) = q_2 \approx 0.1409793. $$
Unfortunately, the problem starts about here. To calculate $q_4$, we have to get a handle on why the rolling didn't stop in steps 1-3. We know that $R_3<R_4\geq R_5\geq R_6$ (because we are stopping in step 4), but this relationship imposes a condition on our previous rolls: given this condition, the third roll is more likely to be lower, and since we didn't stop in step 1, this changes the conditional distributions of $R_1$ and $R_2$. The cases get complicated quickly.
So unless you are happy with a stopping probability $<q_1+q_2+q_3\approx 0.483583$ (for which the formulas above give the exact probabilities), the best you can do is likely to simulate. Here is a simulation of the stopping probabilities in R:
n_sims <- 1e6
results <- rep(0,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
    setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
    set.seed(ii)
    roll_1 <- sum(sample(1:6,n_dice,replace=TRUE))
    roll_2 <- sum(sample(1:6,n_dice,replace=TRUE))
    roll_3 <- sum(sample(1:6,n_dice,replace=TRUE))
    counter <- 1
    while ( roll_1<roll_2 | roll_2<roll_3 ) {
        roll_1 <- roll_2
        roll_2 <- roll_3
        roll_3 <- sum(sample(1:6,n_dice,replace=TRUE))
        counter <- counter+1
    }
    results[ii] <- counter
}
close(pb)
hist(results,breaks=seq(0.5,max(results)+0.5),col="grey",freq=FALSE)

Note how the first three tabulated frequencies are close to the $q_1, q_2, q_3$ we calculated above:
> table(results)/n_sims
results
       1        2        3        4        5        6        7        8        9       10       11       12       13       14       15       16       17       18       19       20       21       22       23       24       25       26
0.201307 0.140820 0.141095 0.104467 0.087303 0.066984 0.053460 0.042390 0.033982 0.026595 0.021161 0.016777 0.013222 0.010485 0.008337 0.006501 0.005204 0.004071 0.003291 0.002639 0.002096 0.001638 0.001300 0.001002 0.000833 0.000668
      27       28       29       30       31       32       33       34       35       36       37       38       39       40       41       42       43       44       45       46       47       48       49       50       51       52
0.000500 0.000372 0.000298 0.000217 0.000204 0.000156 0.000124 0.000110 0.000072 0.000068 0.000047 0.000040 0.000036 0.000027 0.000024 0.000019 0.000009 0.000013 0.000005 0.000005 0.000007 0.000006 0.000002 0.000002 0.000002 0.000001
      53       54       58       61       66       69
0.000001 0.000001 0.000001 0.000001 0.000001 0.000001

Finally, to get the number you are looking for, we look at the cumulative frequencies and note where this exceeds 90%:
> cumsum(table(results)/n_sims)
       1        2        3        4        5        6        7        8        9       10       11       12       13       14       15       16       17       18       19       20       21       22       23       24       25       26
0.201307 0.342127 0.483222 0.587689 0.674992 0.741976 0.795436 0.837826 0.871808 0.898403 0.919564 0.936341 0.949563 0.960048 0.968385 0.974886 0.980090 0.984161 0.987452 0.990091 0.992187 0.993825 0.995125 0.996127 0.996960 0.997628
      27       28       29       30       31       32       33       34       35       36       37       38       39       40       41       42       43       44       45       46       47       48       49       50       51       52
0.998128 0.998500 0.998798 0.999015 0.999219 0.999375 0.999499 0.999609 0.999681 0.999749 0.999796 0.999836 0.999872 0.999899 0.999923 0.999942 0.999951 0.999964 0.999969 0.999974 0.999981 0.999987 0.999989 0.999991 0.999993 0.999994
      53       54       58       61       66       69
0.999995 0.999996 0.999997 0.999998 0.999999 1.000000

So our result is 11 (but because of sampling variability, there is a small chance that it's actually 10).
Comment: (+1) You need to add $2$ to your answers because you aren't counting the first two rolls.  For confirmation of your answer, note that a slight overestimate can be obtained by assuming each roll is a uniform random value in $[0,1],$ for which an exact solution can be found (giving $15$ as the upper bound).
Comment: @whuber: thanks, good points. I edited the +2 in.