how to raise event getche() from process.Popen() - does not monitor stdin

Question: I am launching a binary in windows using:
process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdin = subprocess.PIPE, stdout = ch.input)

ch.input comes from:

ch = InputStreamChunker('\n')
ch.daemon = True
ch.start()

which was a cool non blocking method of reading from stdout.  It was the accepted answer for this SO question:
How can I read all availably data from subprocess.Popen.stdout (non blocking)?
This is the bulk of my script that attempts to launch/monitor the process:
import subprocess
import time
from e import *
import msvcrt

ch = InputStreamChunker('\n')
ch.daemon = True
ch.start()

cmd = "C:\TEST.EXE"
process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdin = subprocess.PIPE, stdout = ch.input)
i = process.stdin
answers = []
waitforresults(ch, answers, expect = 5)
an = 1
for i in answers:
    print "ANSWER # " + str(an) + ":" + i.read()
    an= an+1

answers = []
time.sleep(5)
msvcrt.ungetch('s')
ch.flush()
waitforresults(ch, answers, expect = 1)
for a in answers:
    print a.getvalue()

process.terminate()
ch.stop()
del process, ch
print "DONE"

Anyway, I can read from the process using this method fine.  When I attempt to write to the process using:
i = process.stdin
i.write("s\n")
or
i.write("s")
The output is printed in the console window but not captured by the binary.  I took a look at the binary in IDA Pro and find that it's using a non standard method of capturing user input while it is running.
The process is an interactive cli tool that waits for S, R, P or Q (Status, Resume, Pause, Quit) ***and it captures the input withput the user hitting ente***r.  This is accomplished using getche().  I threw the binary at IDA Pro to confirm:
v7 = getche();
if ( (unsigned int)dword_41F060 > 1 )
  sub_4030A0(&unk_41C111, v5);
WaitForSingleObject((HANDLE)dword_41F040, 0xFFFFFFFFu);
if ( v7 == 113 )
{
  if ( dword_41F060 != 1 )
  {
    if ( dword_41F060 )
      dword_41F060 = 6;
  }
}
else
{
  if ( v7 <= 113 )
  {
    if ( v7 == 112 )
    {
      if ( dword_41F060 == 2 )
        QueryPerformanceCounter((LARGE_INTEGER *)&qword_41F128);
      dword_41F060 = 3;
      sub_4030A0("Paused", v5);
    }
  }
  else
  {
    if ( v7 == 114 )
    {
      if ( dword_41F060 == 3 )
      {
        QueryPerformanceFrequency((LARGE_INTEGER *)&v9);
        QueryPerformanceCounter((LARGE_INTEGER *)&v8);
        v3 = (double)(v8 - qword_41F128);
        LODWORD(v4) = sub_413FF0(v9, v10, 1000, 0);
        dbl_41F138 = v3 / (double)v4 + dbl_41F138;
      }
      dword_41F060 = 2;
      sub_4030A0("Resumed", v5);
    }
    else
    {
      if ( v7 == 115 )
        sub_40AFC0();
    }
  }
}

Does anyone know how to trigger this event? This looked promising: http://docs.python.org/library/msvcrt.html and I tried using:
msvcrt.ungetch("s")
"Cause the character char to be "pushed back" into the console buffer; it will be the next character read by getch() or getche()."
which DID push the letter "s" to the console but did not trigger my breakpoint on getche().  Hitting the letter S manually does work and does cause IDA pro to hit the breakpoint
halp? :)
EDIT:
I created two small windows console apps to demonstrate what works, what doesn't, and ensure my python is sane.
This first one I can NOT get to recognize input by writing to stdin, the second one I can.
#include "stdafx.h"
#include <conio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char response;
    printf("Enter \"s\":\n");
    response = _getch();
    printf("You entered %c\n", response);
    return 0;
}

can write to this one:
#include "stdafx.h"
#include <conio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char response [2];
    printf("Enter \"s\":\n");
    gets(response);
    printf("You entered %s", response);
    return 0;
}

EDIT 2
I've also tried:
    import subprocess
    import time
    from e import *
    import msvcrt
ch = InputStreamChunker('\n')
ch.daemon = True
ch.start()

cmd = ["test-getch.exe"]
process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdin = subprocess.PIPE, stdout = ch.input)
i = process.stdin
answers = []
msvcrt.putch('s')
ch.flush
waitforresults(ch, answers, expect = 1)
for answer in answers:
    print answer.getvalue()
i.close()
time.sleep(3)
#process.terminate()
ch.stop()
del process, ch
print "DONE"

Comment: have you tried `msvcrt.putch()`?
Comment: I have indeed tried..  "C:\code>C:\Python27\python.exe te.py
sMain talking: 0 answers received, expecting 1" ..... as you can see s gets pushed to the console but is not picked up by the text.exe
Comment: I'd ask `getche()` as a separated question using only plain `subprocess` functions (without `InputStreamChunker()` e.g., `Popen(..stdin=PIPE).communicate('s')`) and a simple C program. Add `Windows` tag.
Comment: ungetch() is for backing up a bit while *you* are reading a stream. It's usually only guaranteed to back up by one character, and it's not meant for output. You shouldn't have to go through all these contortions to write into a pipe, anyway. Have you tried setting `bufsize=0` in Popen?
Answer: Excerpts from MSDN:

These routines read and write on your console.
  The console I/O routines are not compatible with stream I/O or low-level I/O library routines.
  In the Windows operating systems, the output from these functions is always directed to the console and cannot be redirected.

So I see 2 possible options and both are not promising:

Create a pseudo Windows console and run your program from it. Then you will get your output there. (Analog of pty on UNIX)
Somehow get data from existing Windows console. Console2 http://sourceforge.net/projects/console/ is doing something like that.

I do not know how to do any of these things or if they are possible at all.
In any case I don't see any practical solution, basically saying that you are out of luck, in my opinion.


Qual a diferença de SOME, IN e ANY?

Question: Qual é a diferença de SOME, IN e ANY no MySql e quando devo usá-las?
Elas têm uma performance ruim se usadas muitas vezes no mesmo SELECT?
Answer: Conforme documentação oficial do MySQL
ANY

"retorna TRUE se a comparação for verdadeira para qualquer dos valores na coluna que a subquery retorna." Por exemplo:
SELECT s1 FROM t1 WHERE s1 > ANY (SELECT s1 FROM t2);

Suponha que existe uma linha na tabela t1com o valor 10. A expressão é verdadeira se a tabela t2 contiver (21, 14, 7)pois 10 > 7.

IN

Quando usado em uma subquery, a palavra IN é um apelido para = ANY. Assim, essas duas declarações são iguais:
SELECT s1 FROM t1 WHERE s1 = ANY (SELECT s1 FROM t2);
SELECT s1 FROM t1 WHERE s1 IN    (SELECT s1 FROM t2);

IN e = ANYnão são sinonimos quando usados com uma lista de expressões. IN pode receber uma lista de expressões, mas = ANY não pode.
mysql> SELECT 2 IN (0,3,5,7);
         -> 0
mysql> SELECT 'wefwf' IN ('wee','wefwf','weg');
         -> 1

SOME

A palavra SOME é um apelido para ANY. Assim, essas duas declarações são iguais:
SELECT s1 FROM t1 WHERE s1 <> ANY  (SELECT s1 FROM t2);
SELECT s1 FROM t1 WHERE s1 <> SOME (SELECT s1 FROM t2);

TL;DR

ANY / SOME -> Expressões iguais. Para uma condição qualquer, retorna TRUE se existe qualquer valor na subquery que a satisfaça.
IN-> Como ANY, porém limitado à expressões de igualdade (IN <-> = ANY). Além de uma subquery pode também receber uma lista de valores.
Comment: Amigo a sua resposta é mais completa, porém os exemplos não são tão intuitivos, ao menos para mim, mas mesmo assim +1, obrigado
Answer: ANY e SOME são sinônimos. Correlacionando de forma simples, ambas funcionam como um comando EXISTS.
Isso:
SELECT  *
FROM    mytable
WHERE   x <= ANY
        (
        SELECT  y
        FROM    othertable
        )

É o mesmo que isso:
SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   m.x <= o.y
        )

Com uma condição de igualdade em um campo Not-nullable, fica similar ao IN
Quanto a performace,esses comandos são considerados os mais lentos dentro do SQL, portanto evite utilizar muitos em uma query.
Comment: Excelente, +1. A documentação do [MySQL](https://dev.mysql.com/doc/refman/5.7/en/subquery-optimization-with-exists.html) dá bastante detalhes sobre como otimizar consultas com `IN`. Geralmente é possível extrair melhor performance com `EXISTS`, bem como facilitar a vida do otimizador quando você usa `NOT NULL` ou não precisa distinguir `NULL` de `FALSE`.

Qual a diferença de SOME, IN e ANY?


Unable to set bounds for AVCaptureVideoPreviewLayer

Question: I am having a hard time changing the bounds of AVCaptureVideoPreviewLayer. Whatever I do it always ends up in small size as shown below:

Here is my code:
override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.imageLayer.bounds = CGRect(x: 0, y: 0, width: 375, height: 100)
    }

    private func startLiveVideo() {

        session.sessionPreset = AVCaptureSession.Preset.photo
        let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)

        let deviceInput = try! AVCaptureDeviceInput(device: captureDevice!)
        let deviceOutput = AVCaptureVideoDataOutput()
        deviceOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
        deviceOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
        session.addInput(deviceInput)
        session.addOutput(deviceOutput)

        self.imageLayer = AVCaptureVideoPreviewLayer(session: session)
        imageLayer.frame = CGRect(x: 0, y: 0, width: 375, height: 100)
        self.imageView.layer.addSublayer(self.imageLayer)

        session.startRunning()
    }

SOLUTION:
self.imageLayer.videoGravity = .resizeAspectFill

Comment: I just posted a solution in the original question.
Answer: You can first assign width and height of imageView from Storyboard or by yourViewController 500 x 500 or whatsoever size you want.
imageLayer.frame = CGRect(x: 0, y: 0, width: self.imageView.frame.width, height: self.imageView.frame.height)

self.imageView.layer.addSublayer(self.imageLayer)


There is no field with exactly 6 elements

Question: I saw the related posts, and I tried a different proof. Please have a look.
Let $D$ be any field with $|D|=6$.
$|D|=6<\infty \Longrightarrow Char(D)\neq 0\Longrightarrow Char(D)=prime\ number$
From the theorem of Lagrange in $(D,+)$ we have that:
$$ord(1_R) \mid  |D| \Longrightarrow Char(D)\mid  |D|\Longrightarrow Char(D)\mid 6$$
So, $Char(D)=2$ or $3$.

$Char(D)=2$

$\forall x\in U(D):ord(x)=Char(D) \Longrightarrow ord(x)=2 \Longrightarrow 2x=0_D \Longrightarrow x=-x $ (*)
If $H= \{0_D, a,b,a+b\} $ from (*) $(H,+)\leq (D,+)$ and from Theorem Of Lagrange we have that $|H|\mid |D| \Longrightarrow4|6$, contradiction.

$Char(D)=3$

Can we find another additive subgroup of $(D,+)$ with 4 or 5 elements to work on the same say as above?
Answer: Here is a proof using your idea of looking at the additive group of $D$.
Since the additive group of $D$ is abelian and has order $6$, it must be $C_6$.
Let $g$ be a generator for the additive group of $D$, that is, an element of additive order $6$.
Then $0 = 6 \cdot g = (2 \cdot 1_D)(3 \cdot g)$. Since $3 \cdot g \ne 0$, we must gave $2 \cdot 1_D=0$ because $D$ is a domain.
In the same manner, $0 = 6 \cdot g = (3 \cdot 1_D)(2 \cdot g)$ implies $3 \cdot 1_D=0$.
But then $1_D = 3 \cdot 1_D - 2 \cdot 1_D = 0$ and $D$ is the zero ring.
Comment: Why $(D,+)$ = additive group with$ |D|=6$ implies that is $C_6$? And also we didn find an additive subgroup $H'$ of $D$ such that $|H'|\nmid |D|$
Comment: @Chris, there are only two groups of order $6$: $S_3$ and $C_6$.


Como fazer a colisão do meu player com um tile na Unity 5?

Question: Preciso colocar colisões em alguns tiles estáticos para que o player não possa passar por eles. Tentei colocar um Box Collider 2D no player e no tile mas não está funcionando. Como resolvo isso da melhor maneira possível, de maneira que melhore a performance da Unity. (Vão existir muitos colliders)
Obs: Não quero scripts para isso.
Comment: Tente colocar o Box Collider apenas no tile, e no player vc usa um Rigidbody 2d, isso deve funcionar.
Comment: @JúlioNeto Não funcionou!
Answer: Para que haja colisão no seu caso, você deve atribuir um Collider no Tile e no player adicionar um RigiBody e também um Collider. Ressaltando que ambos os componentes devem ser do tipo 2D, do contrário não funcionará. Vale lembrar que você deve se atentar a que tamanho está o Collider, pois talvez não esteja circundando o objeto de forma correta.


Between spring mvc and spring boot which should I learn for web development

Question: I'm beginner to spring and i want to develop web application. Which should I study between spring mvc and spring boot?
Comment: https://docs.spring.io/spring/docs/current/spring-framework-reference/index.html
Answer: The answer is "both". :-)
More specifically: you learn web development by writing web services. Spring Boot makes it easy to get a Spring MVC service up and running quickly. The concepts you learn will map to non-Boot, even non-Spring, projects.
Answer: Spring boot uses spring-mvc under the hood (if you use the web dependency).
So better learn spring boot which will get you up and running quickly.
You will learn spring-mvc specific feature eventually if you keep going...
Answer: Spring Boot is a easier way to use Spring MVC, because you don't need to install dependency manager, container, configs are simpler, etc.
But I got your question and I suggest you to start with Spring Boot, because you will make things work easily, so you won't get frustrated in the beginning. If you feel the need to use only Spring mvc, try it in the future.
Go to https://start.spring.io/ to generate your first project.


Android edit text showing weird text

Question: I am new to android. I just created a simple application using Aynctask. Basically, it uses Asynctask to iterate through a loop and show the iteration number in the text box. I created both a edittext and a textview and bot shows some weird text. I try creating a toast, and the toast shows the same text correctly. Here is the source code:
package com.jeannius.me;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
    /** Called when the activity is first created. */
    int[] color1 = {0xFFe48701, 0xFFa5bc4e, 0xFF1b95d9, 0xFFcaca9e, 0xFF6693b0, 0xFFf05e27, 0xFF86d1e4,
            0xFFe4f9a0, 0xFFffd512, 0xFF75b000, 0xFF0662b0, 0xFFede8c6, 0xFFcc3300, 0xFFd1dfe7,
            0xFF52d4ca, 0xFFc5e05d, 0xFFe7c174, 0xFFfff797, 0xFFc5f68f, 0xFFbdf1e6, 0xFF9e987d,
            0xFFeb988d, 0xFF91c9e5, 0xFF93dc4a, 0xFFffb900, 0xFF9ebbcd, 0xFF009797, 0xFF0db2c2};

    TextView yyr;
    EditText ud;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         yyr = (TextView)findViewById(R.id.mytext);
         ud = (EditText)findViewById(R.id.edit);

        Button myb =(Button)findViewById(R.id.mybut);
        yyr.setTextColor(0xFFE48701);
        ud.setRawInputType(InputType.TYPE_CLASS_TEXT);

        myb.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                new mySyncTask().execute();
            }

        });

   }

    class mySyncTask extends AsyncTask< Void, Integer, Void>{

        String red;

        @Override
        protected Void doInBackground(Void... unused) {

            for(Integer j=0; j<5; j++){
              red = String.valueOf(j);
                publishProgress(j);
            SystemClock.sleep(3000);}
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Toast.makeText(getApplicationContext(), red.toString(), Toast.LENGTH_LONG).show();
        }

        protected void onProgressUpdate(Integer... values) {

            yyr.setText(String.valueOf(values));
            ud.setText(values.toString(), TextView.BufferType.EDITABLE);
            Toast.makeText(getApplicationContext(), red.toString(), Toast.LENGTH_SHORT).show();

        }

    }

}

Comment: in the toast you show red, in the text views you show values, why is that?
Comment: What exactly is the "weird" text?
Answer: values is an array.  Use it like this: String.valueOf( values[0] )

Android edit text showing weird text


Custom PDF template in Commerce Billy

Question: I have installed Commerce Billy module on my website.
Then upon ordering I get this PDF with this layout.
But I want to change the table displayed, because I've created some custom fields in it and I want to display it also in the table.
Any help will be greatly appreciated.
Answer: This table is actually the rendered view 'Line items (Commerce Line Item)' which is created in code by Drupal Commerce. So all you have to do is to modify this view to your needs.
To further customize the display of your invoice, you can make a copy of css/pdf.css and themes/commerce_order--commerce_order--pdf.tpl.php located in commerce_billy_pdf folder into your custom theme and experiment.
Comment: Great answer. Small note, the folder name in the billy module folder is now `template` not `theme`. Do you know how to preview the template as HTML before it's passed to the PDF generator? If you do I've [asked that as a follow-up question here](http://drupal.stackexchange.com/questions/214447/how-to-view-and-inspect-a-commerce-billy-invoice-pdf-template-as-html-before-it)
Comment: Any idea on the preprocess function for this theme registered under billy ?
Answer: If you'd like to display field output from custom fields, the simplest way is to put tokens in one of the admin/commerce/config/billy-invoice/pdf text areas.
I regularly place the pdf footer text in the commerce_order--commerce_order--pdf.tpl.php and use the footer text area to place text and tokens like Customer ID: [current-user:field-customer-id] and do the styling and placement via CSS.

Custom PDF template in Commerce Billy


Coldfusion - Loading order for CFIDE scripts

Question: I have a Coldfusion page that includes a number of javascript files and css files in the header, as well as a number of CFIDE/scripts that are included by Coldfusion in the header (eg cfform.js and cfajax.js).
I have been told that to help speed up page loading and for a smoother page load, that css
files should be loaded prior to script files. In my header, I have made sure that all script
files are included below css files however the CFIDE/Script files included by coldfusion always appear at the top and I can't seem to find a way to prevent this.
If someone knows how to accomplish this, it would be appreciated. Thanks.
My pages currently load (if not already in cache) very "staggered" like, bits and pieces at a time..so any other suggestions to improve that would also be very much appreciated..
Comment: Unless you don't use any of the cfide scripts, which a lot of people on this site recommend, that situation is probably beyond your control.
Answer: Which web server are you using and are you an administrator?  If so, I use ColdFusion 8, 9 & 10 with IIS and have started using IISpeed (A Google PageSpeed port) to manage organization, location, caching, consolidation, deferring, minification of JS & CSS resources. (This will even optimize the unoptimized CFIDE production code that Adobe ships.)
http://www.iispeed.com/
https://developers.google.com/speed/pagespeed/
The PageSpeed module allows me to focus on the code and let an automated process take over the optimization using best practices.
I can easily control what is optimized by using the "iispeed.config" file in the root of the website and adding CFHeader tags to enable & choose which filters to apply:
https://developers.google.com/speed/pagespeed/module/experiment
If you want to use ColdFusion to do everything, you could try using CFStatic, but it won't provide you as much benefit as using PageSpeed:
http://cfstatic.riaforge.org/
To do comparison testing, use the Visual Comparison tool at WebPageTest.org and test different browsers as well as mobile. (PageSpeed can generate WebP images for Chrome on-the-fly.):
http://www.webpagetest.org/video/
Comment: Wow thanks for all of that James. I am using Coldfusion 10 and do have administrator access. It will take me bit of time to chew through all of the info/options you have provided although I am definitely leaning towards using iispeed. Thank for that.


How can I rename file extensions to another extension type, on another directory?

Question: I'm attempting to rename all files with the file extension of ".ACH" to ".TXT" on another directory.
I used the below batch file on my local machine and it works like a charm:
@Echo Off
CD C:\Users\jonsmith\OneDrive\PC\jonsmith-PC\Desktop\TestingBatch Rename
forfiles /S /M *.ACH /C "cmd /c rename @file @fname.TXT"

However, when I attempt to use the same syntax on the server, nothing happens:
@Echo Off
CD D:\AP\ACHTest Rename
forfiles /S /M *.ACH /C "cmd /c rename @file @fname.TXT"

I'm not understanding what I'm doing wrong, but something tells me it's how I'm using the CD command.
Comment: Replace `cd` by `cd /D` to also change to the drive, or use `forfiles`' `/P` option to specify the root directory. *N. B.:* Use a standard `for` loop rather than `forfiles`: `for /R "D:\AP\ACHTest Rename" %%I in ("*.ach") do rename "%%~I" "%%~nI.txt"`…
Comment: @aschipfl that was perfect!
Comment: Always glad to be of service! Please do not include solutions in your question, please post an answer instead! You can even accept your own answer then…
Answer: I don't want to force Batch, so I have an easier way.
Inside file1.ach:
Hello

Inside file2.ach:
Hi

Code:
del file1.ach
del file2.ach

Current directory:
echo Hello >>file1.txt
echo Hi >>file2.txt

Different directory:
echo Hello >>D:\MyWork\TestRename\file1.txt
echo Hi >>D:\MyWork\TestRename\file2.txt

Easy, without forcing anything.
Comment: Hm - what do you do when the files have hundred or thousands of lines?


Probability that a randomly selected bit string of length 15 is a palindrome

Question: Question: what is the probability that a randomly selected bit string of length $15$ is a palindrome?
My partial solution is that I know the $15$ length is "$10001010100001$". That's all I know. Can someone help me find and understand the solution?
Comment: If you pick the first bit, how many bits are left free to set to any value?  (It's not 14.)
Answer: Well you know that you need the first 7 bits to match the last 7 bits for the string to be a palindrome.
First thing to think about is how many ways can we arrange 7 bits?
Answer: $$2\times2\times2\times2\times2\times2\times2=2^7$$
However, don't forget that the $8^{th}$ bit can be either a 1 or a 0. So if the $8^{th}$ bit is a 1 that cuts the number of combinations in half (i.e., $2^7/2$) and similarly if the $8^{th}$ bit is a 0.
Now, we want to know what the probability that a randomly selected bit string of length 15 is a palindrome. For convenience, define the event $E$ as the case that a string of length 15 is a palindrome. Well, we have the following:
\begin{align*}
Pr(E) = Pr(&\text{First 7 bits} = \text{Last 7 bits and the } 8^{th} \text{ bit = 1}\text{ or }\\
&\text{First 7 bits} = \text{Last 7 bits and the } 8^{th} \text{ bit = 0})\\
=Pr(&\text{First 7 bits} = \text{Last 7 bits and the } 8^{th} \text{ bit = 1})+\\
&\text{First 7 bits} = \text{Last 7 bits and the } 8^{th} \text{ bit = 0})\\
=&\frac{1}{2^7/2}+\frac{1}{2^7/2}\\
=&\frac{1}{2^7}
\end{align*}
Comment: @calculus, check out my answer for a different way to think about it.
Answer: A palindrome is a string that reads the same backwards as forwards.   Basically, that's symmetry.
So you want the probability that the last $7$ digits are exactly the same as the first $7$ digits, though in reverse order.
Answer: Hint:
You can calculate all ways of arrangement of $0$ and $1$ for the first $7$ places.  The last $7$ places have to be ordered mirror imaged. Thus they have not be regarded. Then regard that at the 8th place of the string can be a $1$ or a $0$.
Answer: For every first 7 bits you need last 7 bits to match in a defined way.
First 7 bits can be arbitrary. So the answer is 1/(2^7)
In general answer is 1/(2^floor(stringlength/2))
Comment: You have forgotten to regard the 8th bit.
Comment: Dude.. It will always match. Might as well it didn't exist.
Comment: Try on a small example and see.
Comment: $01010$ is different from $01110$ and you have to count both.
Comment: You are not getting it. For both string sizes 2 and 3, answer is 1/2.
Comment: You are right I´m not getting it. But your answer is right. Therefore your arguements should be right.
Comment: @calculus, the 8th bit doesn't need to be regarded as the palindrome dual of the 8th bit is the 8th bit. The probability that the 8th bit will be the same as the 8th bit is $1$.
Comment: @GrahamKemp It is another way of thinking than I do, but now I understand it and I do agree. I have counted all possible of arrangements of the first 8 digits and  have divided this number by the number of all possible arrangements of the 15 digit string:$\frac{2^8}{2^{15}}=\frac{1}{2^7}$. Thank you guys for clarifying.
Comment: can I use the above solution @calculus?
Comment: @guest11 Yes you can. Why not ?
Answer: For a string of length $n$, the probability of finding a palindromic string should simply be the number of possible palindromic combinations divided by the number of total possible combinations.
For both an even and odd string of length $n$, the total combinations is simply $2^n$. The number of palindrome combinations, however, depends on whether the string is even or odd.
For even, only the first $\frac{n}{2}$ elements of the string are free (the remainder are determined once the first $\frac{n}{2}$ are selected) and so the probability is
EVEN string: $\frac{1}{2^{n/2}}$
For odd, the first $\frac{n+1}{2}$ are free since the middle digit is along the line of symmetry. So, the probability in this case is,
ODD string: $\frac{1}{2^{(n-1)/2}}$
Note that the even case  is equivalent to the odd case + 1.
So, your string of length 15 being a palindrome has the same probability of a string of length 14:
$\frac{1}{2^7}$


Hiding a field title label of a field collections field?

Question: I have created several fields using the field collection module, but I cannot hide one of the field labels (within a collection). I've tried it in the UI and I've tried hiding it programmatically with hook_form_alter, but it continues to be displayed.
Is their a 'trick' to hiding the field labels created by this module? Thanks.
Comment: Hmm. Im using field collection right now, and as a quick test I have gone to Structure > Field COllections, then manage display, and I am able to select 'hidden' from the label column and hide all labels. What field are you trying to hide a label for?
Comment: Check out this simplytest.me site: http://s90fe10aa72ce1a6.s3.simplytest.me/node#overlay=admin/structure/field-collections/field-test/display (u: admin p: admin) and see if you can hide the 'Example' label. Thanks.
Comment: It still displays at: http://s90fe10aa72ce1a6.s3.simplytest.me/node#overlay=node/add/page, no?
Comment: Ah, are you trying to hide it from the admin pages?
Comment: http://s90fe10aa72ce1a6.s3.simplytest.me/test is an example with "Example" label hidden
Comment: My 30mins ran out on the site. Here's a new link. I want to hide the label 'Example' in 'TEST': http://sef5878073f425de.s3.simplytest.me/node#overlay=node/add/page. Thanks.
Comment: Well, the admin says it's hidden, but it's not: http://sef5878073f425de.s3.simplytest.me/node#overlay=admin/structure/field-collections/field-test/display.
Comment: That's the admin side label. All default options built into field UI are set to hide labels for the published node. To hide the admin side label, you can either re-name the field to something better, use CSS in a sub theme of your admin theme to hide it, or use hook_form_alter in your admin sub themes template folder to render the field with no label.
Comment: Doesn't hide labels on the page either, and `hook_form_alter` does not hide it either.
Comment: Look at this page where I have added 5 values into that field collection. On the rendered node, all "example" labels are hidden. http://sef5878073f425de.s3.simplytest.me/test
Comment: Sorry, the 30mins rans out. Can you quickly create again here, so I can see what you did: http://se51af703797a9ad.s3.simplytest.me/. Thanks.
Answer: After our discussion, these are the steps to clear the labels from a published node field collection field.

Head to Structure > Field Collections > Manage Display (For your collection)
Under the label column, make sure all select boxes are set to "Hidden".
Next, head to Structure > Content Types > Your Content Type > Manage Display (For your collection)
Same as before, Under the label column, make sure all select boxes are set to "Hidden".

This wont hide the labels in the admin node/add/yourcontenttype page, but when you save the node, and look at the published page, the labels will be gone.
To remove the edit, delete and add links, Structure > Content Types > Your Content Type > Manage Display and click the settings icon on your field collection field. Then simply delete the edit, delete and add text from the text fields. Click update. Then save the content type.
Comment: Thanks for your help. I understand what you are saying, but, unfortunately, it is the labels in the (admin) form that I need to hide. I see what I was trying will only hide the labels in the displayed node.
Comment: OK, in that case, just grab the class of the containing div, and use a simple display:none; in CSS for that label. You will need to either add this in your admin themes CSS (which would get wiped in an update), or create a quick sub theme for your admin theme.
Comment: Yea, it looks like that may be my only option. Always a last resort, but still it does the job.
Comment: Yeah, that's what I would do, especially to save time. Unless the client is paying by the hour! :-P
Answer: Inside hook_form_alter make #title_display = 'invisible'.
$form['your_field_name']['#title_display'] = 'invisible';

Comment: #title_display not works for field_collection items


Twitter login page comes up even though user denies to give access to Twitter from App

Question: When I am trying to login to my App in iOS 11 using Twitter, sometimes I am getting an alertview-style popup saying " wants to open twitter", with the options "cancel" and "open". If I tap on "open", it is the normal login flow for twitter.
However, if I tap on cancel, then what I want is for the whole login attempt to be cancelled. Instead, the app redirects me to the webview which opens twitter login page and again I need to cancel that dismiss the page saying "Error during login". Could anyone able to simulate it?
Comment: Could you paste your code, please?
Answer: Looks like it might be related to a known issue that Twitter is trying to fix? See https://twittercommunity.com/t/bug-twitter-kit-ios-3-0-4-login-sometimes-fails-to-redirect-back-to-host-app/89618/24


Will Team Foundation Version Control ignore the git folder?

Question: I have a Visual Studio project that I am going to add to our companies TFVC.  I will be doing so from inside Visual Studio.  I use git from the command line while I'm developing.  When I add my Visual Studio project to TFVC will my git folder be ignored and not added to TFVC?  I don't want to clutter up TFS with my micro iterations.
Answer: If you're on TFS 2017 (and maybe 2015) you can have both TFVC and Git repositories in the same project.
The other way would be to use a .tfignore file to ignore the .git folder https://blogs.msdn.microsoft.com/dstfs/2016/01/29/tfignore-usage-in-team-foundation-server/


Discrete random variables are defined on a countable probability space. All examples I found are either finite spaces or something like all integers

Question: I wonder if a discrete random variable could be defined on the set {1, 2, 1+1/2, 1-1/2, 2+1/2, 2-1/2, 1+1/3, 1-1/3, 2+1/3, 2-1/3, 1+1/4, ...} i.e on a countable set with 2 accumulation points (or even only 1). In this example there would be no way to order the jump points by magnitude. Kalbfleisch and Prentice are using this ordering implicitly in their book "The statistical analysis of failure time series" when explaining the probability function in chapter 1.2.2 with the 2 bullets at the end. They don't explicitly restrict the discrete case to sets w/o accumulation points
Comment: Definitions are made incredibly generally, for good reason.  Yes, you can have any probability space you want... including the situation you ask about.  Just be warned that you can not have a uniform distribution on a countably infinite space thanks to the $\sigma$-summability requirements in the definition/axioms of probability spaces.
Answer: You absolutely can, and it's pretty simple to do so.
If your support set $A$ is countable, then there exists a bijection $f: \mathbb{N} \rightarrow A$. So then all you need to do is construct a random variable $Y$ on the natural numbers, and then your random variable is just $X = f(Y)$.
Comment: That's fully agreed. But I think there is no bijection which maintains the order of N in the A of my example. And that's exactly my problem. In failure time or survival analysis, there are failures or deaths at some time point after start of the observation, and for some analyses these time points must be ordered to see when what percentage of the sample under consideration failed or died. So I conclude in this context accumulation points of A, if any, can only be a single one at the end of the time interval under consideration, to which A converges monotonically


Trouble setting up chef-client on a vagrant

Question: I've been using opscode chef for remote configuration and I wanted to test my chef scripts locally, so I started working on setting up a vagrant box. But, I can't seem to get my vagrant boxes to register. I get errors like the ones listed here: https://gist.github.com/2961246
My Vagrantfile looks like this:
Vagrant::Config.run do |config|
  config.vm.box = "lucid32"

  config.vm.forward_port 80, 8080

  config.vm.provision :chef_client do |chef|
   chef.chef_server_url = "https://api.opscode.com/organizations/pinedesk"
   chef.validation_key_path = ".chef/pinedesk-validator.pem"
   chef.validation_client_name = "pinedesk-validator"
   chef.node_name = "vagrant"
   chef.provisioning_path = "/etc/chef"
   chef.log_level = :debug

   chef.add_role "base"
  end
end

And my .chef folder has these:
dsummersl.pem
knife.rb
pinedesk-validator.pem
vagrant.pem

Chef appears appears to register a new client, and then gets an HTTP 401 when creating the node. Any pointers?
Answer: It appears you are trying to register a new client by a name that already exists.
If you run knife client list you should see a client name that matches your vagrant vm's host name
Assuming the hostname is 'vagrant' you could run this:
for foo in client node ; do knife $foo delete vagrant -y ; done
then run vagrant up or vagrant provision
You will probably want to delete the client and node after every vagrant destroy
Comment: Cassiano Leal's [vagrant-butcher](https://github.com/cassianoleal/vagrant-butcher) [gem](https://rubygems.org/gems/vagrant-butcher) ensures that nodes and clients associated with your Vagrant VMs are deleted when the VMs are destroyed.
Comment: Is there a way not to delete client, but reuse an existing one?


Signing a firefox add-on with Mozilla api and download signed xpi

Question: I'm using the Mozilla API to upload an add-on and signing it (following this
guide).
After uploading the add-on, I receive the first answer from the api as a json, that looks like that. From that response, I'm taking the url field and accessing it (result), that way I can see the status of my add-on signing.
The thing that I don't get, is why although the add-on is marked as signed for my understanding (active, passed_review, processed, reviewd, valid are all set to true), the xpi file (result.files[0].download_url) is marked as signed=false.
Does anyone knows why is that? How can I get my xpi signed and download it?
Maybe it has to do with the warnings I have on the add-on? (although they're marked as fine).
The curl commands I'm executing.
Thanks,
Ariel.
P.S - Can't use jpm cause It's not the add-ons format we currently have.
Comment: is your addon listed on AMO?
Answer: I also used the API to sign and download non-sdk addon - https://github.com/Noitidart/Chrome-Store-Foxified/blob/ee3ad5486fa1539b88670f30e66fe277ec6d8afd/bootstrap.js#L208-L215
I think the signed means physically passed review and got signed that way. Not auto-signed.
Don't worry your addon is signed.
Comment: according to the [signing documentation](http://olympia.readthedocs.org/en/latest/topics/api/signing.html) it should be true. And actually it's not really signed, I've figured out the problem - I had problems in my install.rdf
Answer: I believe that behavior resulted from a bad install.rdf configuration. I had a wrong targetApplication id (firefox, thunderbird, etc..), and when I fixed that and tried again it worked, and I got signed=true.
I also opened an issue about it in the github project of https://addons.mozilla.org
P.S - From jpm v1.0.5 it is possible to sign a non-SDK (Xul, WebExtensions) add-on with the jpm tool (github):
jpm sign --api-key <key> --api-secret <secret> --xpi <filePath.xpi> (works great!)


Show that all eigenvalues of the matrix $AB$ are real

Question:
Suppose that the matrices $A, B \in \Bbb R^{n \times n}$ are symmetric and that $A$ is also non-negative definite. Show that all eigenvalues of the matrix $AB$ are real.

I haven't find this question on StackMath. Suppose that $A$ and $B$ are two $n \times n$ real symmetric matrices and $A$ is also non-negative definite. Let $\lambda$ be an eigenvalue of $AB$, and let $v$ be a corresponding eigenvector. Then $ABv = \lambda v$, so $v$ is also an eigenvector of $A$ with eigenvalue $\lambda/B$. Since $A$ is non-negative definite, all of its eigenvalues are non-negative.
Now how to approach? Please help.
Comment: *"...so $v$ is also an eigenvector of $A$ with eigenvalue $\lambda/B$"*. This is ridiculous.
Answer: Hints:

If the use of matrix square root is allowed, consider the relationship between $AB$ and $A^{1/2}BA^{1/2}$.
Without using matrix square root: let $\lambda$ be any eigenvalue of $AB$ over $\mathbb C$ and let $x$ be a corresponding eigenvector. Then $\langle Bx,ABx\rangle=\lambda\langle Bx,x\rangle$. The result follows immediately if $\langle Bx,x\rangle\ne0$. If $\langle Bx,x\rangle=0$ instead, show that $ABx=0$.


Is there a value to show how fragmented is a group?

Question: I would like to know if there is a way to calculate a number that can show how fragmented is a group?
It should be something like "variance of categorical data"?
For example I want to see how fragmented is Android/iOS in terms of OS version. The number would be high for Android, where there are a lot of versions, and the usage percentage of each version is small. For iOS, the number would be small, since there is a dominant usage percentage of one version.
Answer: There are many different measures of variability of a categorical variable, see e.g. Wikipedia's list .
A frequently used one is Simpson's index of diversity (aka Herfindahl index). It equals the sum of squared relative frequencies of the categories. As such, it estimates the probability that two randomly chosen iOS users have the same version.
Comment: Thanks! Simpson's index of diversity is what I'm looking for! Is there a way to tell if the largest segment is significantly dominant?


Como Pegar uma lista de json de uma Api em JAVA?

Question: Eu tenho o seguinte retorno de uma api {"type":"champion","version":"7.10.1","data":{"89":{"id":89,"key":"Leona","name":"Leona","title":"a Alvorada Radiante"},"110":{"id":110,"key":"Varus","name":"Varus","title":"a Flecha da Vingança"}
Estou começando agora a consumir mas não estou conseguindo. Pesquisei sobre como pegar esse tipo de lista  mas ainda sim não estou conseguindo, é um pouco estranho porque tem uma array dentro da outra. Podem me dar um auxilio de como eu posso prosseguir?
Comment: https://pt.stackoverflow.com/a/6050/28595
Comment: Esse já é o retorno da API? Já fez a requisição e obteve isso de resultado?
Comment: Esse é o resultado já
Comment: Consegue adicionar a sua pergunta como tu faz a requisição?
Comment: @JeffersonSchmitt, para deixar aqui um pouco mais correto o sentido das palavras : um objeto json (como o que você mandou) é um mapeamento de chave valor. Uma lista é uma coleção de valores, como `['a', 'b', 'c']`
Answer: Recomendo o uso da biblioteca chamada Jackson, é muito boa para fazer esse tipo de conversão em objetos java.
Se você usa maven, pode importar a seguinte biblioteca:
<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0.pr3</version>
</dependency>

Caso não use, importe o seguinte jar na sua aplicação:
http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.9.0.pr3/jackson-databind-2.9.0.pr3.jar

Segue uma exemplo funcional da leitura do json:
Crie uma classe chamada Champion com os seguintes dados:
import java.util.Map;

public class Champion {

    private String type;
    private String version;
    private Map<Integer, DadosChampion> data;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public Map<Integer, DadosChampion> getData() {
        return data;
    }

    public void setData(Map<Integer, DadosChampion> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Champion [type=" + type + ", version=" + version + ", data=" + data + "]";
    }
}

Crie outra classe chamada DadosChampion com os seguintes dados:
public class DadosChampion {

    private Integer id;
    private String key;
    private String name;
    private String title;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Por fim, crie uma última classe chamada Principal com os seguintes dados:
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Principal {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String json = "{\"type\":\"champion\",\"version\":\"7.10.1\",\"data\":{\"89\":{\"id\":89,\"key\":\"Leona\",\"name\":\"Leona\",\"title\":\"a Alvorada Radiante\"},\"110\":{\"id\":110,\"key\":\"Varus\",\"name\":\"Varus\",\"title\":\"a Flecha da Vingança\"}}}";

        ObjectMapper mapper = new ObjectMapper();
        Champion champion = mapper.readValue(json, Champion.class);

        System.out.println("Tipo: " + champion.getType());
        System.out.println("Versão: " + champion.getVersion());

        System.out.println();

        System.out.println("Dados do champion:");
        System.out.println("---------------");

        for (DadosChampion dadosChampion : champion.getData().values()) {
            System.out.println("ID: " + dadosChampion.getId());
            System.out.println("KEY: " + dadosChampion.getKey());
            System.out.println("NOME: " + dadosChampion.getName());
            System.out.println("Title: " + dadosChampion.getTitle());
            System.out.println("---------------");
        }

        System.out.println();
        System.out.println("OUTRA FORMA DE PERCORRER: ");
        for (Map.Entry<Integer, DadosChampion> dadosChampion : champion.getData().entrySet()) {
            System.out.println("ID INDICE: " + dadosChampion.getKey());
            System.out.println("ID: " + dadosChampion.getValue().getId());
            System.out.println("KEY: " + dadosChampion.getValue().getKey());
            System.out.println("NOME: " + dadosChampion.getValue().getName());
            System.out.println("Title: " + dadosChampion.getValue().getTitle());
            System.out.println("---------------");
        }
    }

}

A saída sera o seguinte:
Tipo: champion
Versão: 7.10.1

Dados do champion:
---------------
ID: 89
KEY: Leona
NOME: Leona
Title: a Alvorada Radiante
---------------
ID: 110
KEY: Varus
NOME: Varus
Title: a Flecha da Vingança
---------------

Abraços.
Comment: Valeu mesmo diego , funcionou certinho , uma unica observação é que  tive que baixar o jacksonall porque deu  esse erro:
"error: cannot access JsonProcessingException"
pesquisando no stack gringo explicou  o pessoal que teve esse mesmo erro usou o all e funcionou , comigo também então vou deixar o link aqui também http://www.java2s.com/Code/Jar/j/Downloadjacksonall199jar.htm
Comment: @JeffersonSchmitt Certo.. obrigado pelo feedback, alterei o link para esse  jar.

Uma observação, caso vc queira alterar o nome dos seus atributo da classe java, vc pode. Basta apenas colocar a propridade @JsonProperty("label") acima do seu atributos e especificar qual propriedade do json ela se refere.

Mais detalhes em https://github.com/FasterXML/jackson-docs

Att
Comment: Uma duvida o que seria esse toString() ?,  Caso eu queria fazer com outro json que tenha mais um desse mesmo tipo data por exemplo um tipo tem o "type":,"version": , depois tem uma lista chamada "basic:{...}" e depois o "data:{...}" eu adicionaria mais um map? como eu poderia fazer ?
Comment: O toString retorna uma representação do objeto em forma de String. Se vc executar o método toString ele não vai mostrar a referência do objeto e sim o conteúdo dele em forma de String.

Depende da estrutura do json, vc criaria uma classe Basic e dentro dela criaria o data. Se vai ser um Map ou não depende da estrutura do json.

Depois vc cria um objeto da classe Basic dentro da classae Champion.

Se tiver um exemplo do json que vc está em dúvida coloca aqui que te mostro com exemplos.
Comment: Fiz um pastebin exemplificando pastebin.com/wSrwMkGV tem vários um dentro do outro, como ficaria ? Exemplo eu tenho ali um "basic" depois  o image , stats ,gold,rune e por ultimo o data, eu precisaria fazer um map de todos eles ? sendo que eu preciso apenas do data. como posso fazer ?
Comment: @JeffersonSchmitt Acima da declaração da classe vc pode adicionar a propriedade @JsonIgnoreProperties(ignoreUnknown = true) que ela vai ignorar os campos que não estão na sua classe e estão no json.

Classe Item:
https://pastebin.com/BXXXqN9K

Classe DadosItem:
https://pastebin.com/wwxPujLB

Classe Principal:
https://pastebin.com/FwYZDH5H

Vai ser necessário atualizar os imports das classes.
Comment: Eu tinha comentado sobre o @jsonignore mas não enviou para cá mas essas outras propriedades eu não tinha feito , funcionou tudo tranquilo , valeu mesmo pela ajuda , eu não teria conseguido sem essa força. Abraços
Comment: @JeffersonSchmitt
As outras propriedades não são obrigatórias, mas com elas vc consegue colocar o nome que quiser no atributo da sua classe e mapear qual valor do json seu atributo ira pegar.


Finding the radius with chord length

Question: I'm struggling to find the radius of the circle in the image (the only other given length is the length between B and the right angle below, which is 5). Is it even possible to get the radius without knowing any other dimensions? Or is there a way to find it? I've tried to use Pythagoras but without knowing the length of the side of the triangle going towards O, it was hard to find it.
Comment: Where have the 2.8s come from in your diagram?
Comment: It was given in the problem, where they asked to get the angle that I marked as theta.
Comment: Just to clarify then, everything in the diagram you provided is from the question itself?
Comment: Yes I think so.The only information that I didn't put was 5 m (between point B and the right angle below it).
Comment: Well I'm almost done, just need to find the angle PBO, if you have any ideas
Answer: There is no way to find $\theta$ or the radius from the given data. To see why, imagine to move point $P$ to the left on the horizontal line and let $O$ be the center of circle $ABP$: all given lengths would stay the same, but $r$ and $\theta$ would change.
Comment: This seems to be the problem posed by Regiomontanus. It has sense if he wants the radius for the greatest visual angle.
Comment: Thank you for reminding me of that.The angle of course is maximum when the radius is minimum, that is when the circle is tangent to the base line ($r=7,8$ m).
Comment: Does that mean that the radius would be 7 or 8 m when the angle is maximized?
Comment: Sorry, I should have written $r=7.8$ m. That is: when the circle is tangent, the radius is equal to the distance of $O$ from the baseline.

Finding the radius with chord length


Insert a  tag programmatically (VB.NET)

Question: I'm trying to dynamically add results to this display and I simply want to put a break tag after a label to start putting information on the next line.  For some reason, Using a literal isn't working for me.  Is there a better way to do this or should I just use tables?
Dim break As LiteralControl
break = New LiteralControl("
")
divListenerInfo.Controls.Add(break)

That's part of the code that I'm attempting to use.

Let me clarify what I said:
It's not working as in the line break isn't showing up on the webpage.  It's compiling fine and there is nothing wrong with the code.  It just doesn't show up in the html for some odd reason.
Comment: Why not add another label, or append the previous label.txt with a break?
Comment: I don't know VB.NET, but break is a reserved word in C#. Are you getting a compiler warning for using it?
Comment: madcolor: Not a bad idea.

Out Into Space: Nope.
Comment: I would take a look at my answer, while a label will work it is a bit of a hack.  The proper control to use is the HtmlGenericControl as it was built for situations just like this.
Answer: The proper control to use is the HtmlGenericControl.
Dim br As New HtmlGenericControl("br")

You can use the HtmlGenericControl to render any HTML element you wish, simply pass the element's tag name as a single argument to the constructor.
Comment: Cool!  Was not aware of the HtmlGenericControl previously.  Thx.
Comment: This isn't working either.  The break tag appear nowhere in the html.
Comment: It sounds like any new controls you create are not being added to the ControlCollection of the Page itself.  You ought to verify that the control itself is actually being added.
Comment: Only 2 of the 10 "br" controls are being added.  I step through and it hits all 10 of them.  Any ideas as to why they aren't being shown in the actual html?
Comment: It is hard to say without seeing more code - that does sounds really strange though.
Comment: HtmlGenericControl("br") will render as
LiteralControl("") is what you want to use.  If it's not rendering, there is an issue somewhere else in your code.
Comment: how exactly can I use put this in a line in my html file? thanks
Answer: Why not just use another label, or append the
 to the previous label.txt?
Comment: Voted Andrew +1, as I believe he has a cleaner more appropriate solution.
Answer: If the added  is the last element in the container div, you can not see any difference.
you can try :
Dim breakTag As LiteralControl
breakTag= New LiteralControl("
 ")
divListenerInfo.Controls.Add(breakTag)

to see the break.
But I think you should first add a dummy text into this Literal and search for it in your page if it's added. because your code looks fine.
Comment: I put some generic text in the LiteralControl and it only shows up 2 of 10 times in the html. Any clue as to why that is?  I stepped through it and the line of code is getting hit, but nothing results of it.
Answer:
I know this is reviving an old post but I didn't see any clear answer and I finally figured it out for my own application. Hope it helps someone else!
In my application  I tried to create the control once and add it again wherever I needed it. The control would only be created once per parent.
You need to create a new control every time you need it!
So this:
divListenerInfo.Controls.Add(New LiteralControl("<br />"))
divListenerInfo.Controls.Add(New LiteralControl("<br />"))

Instead of this
Dim breakTag As LiteralControl
breakTag= New LiteralControl("<br />")
divListenerInfo.Controls.Add(breakTag)
divListenerInfo.Controls.Add(breakTag)

Answer: I'm not sure if break is a reserve word also in vb.net so try
Dim newline = New LiteralControl("
")

or
newline.Text="
";

Comment: I changed the variable name to make sure, and it didnt change anything.
Answer: I would try stepping through the code with a debugger to make sure the line gets hit, also  triple-check that divListenerInfo is the right control.
Answer: I think you are using a panel or placeholder.
vb.net or C# .net syntax:
divListenerInfo.Controls.Add(New LiteralControl("
"))

Comment: I doubt leaving the "/" out is going to change much, and may break his page... or did you maybe answer before reading the whole page?

Insert a  tag programmatically (VB.NET)


Conditional probability of failure of a lamp

Question: Let Tbe the random variable of the lifetime(in years) of an LED lamp.The lifetime
                              $Pr[T>t]=100/t^2$ for $t>10$
a. please find $Pr[T\le3]$ ,and the expected value of T
b. Find the conditional probability of failure in the next year for a working LED lamp that is now t years old for each $t>10$
for a.question,well, i cant solve it,i have been thinked that $Pr[T>t]=1-Pt[T\le t]$,then differential it to let it become pdf,and i can know the expected value.  but the t  still have to bigger than 10,$t>10$,so is question wrong?or does there  someway to solve it?
for b.question,i think Pr[broken next year|have been worked for more than 10 yeasrs],that is,$[(100/t^2)\times[1-(100/(t+1)^2)]]/(100/t^2) $ for$t>10$, is my ideal wrong?
Answer: For a, as you have $Pr(T \gt 10)=1$ you also have it for any lower $T$ because it has to be nonincreasing with $t$.  The question could have been more clear, but maybe this is what you were supposed to realize.  For b you are supposed to comput the chance the lamp fails in the next year, given that it has survived so far.  So for $t=15$ you are given that it has not failed by year $15$.  Without the condition, the chance that a lamp fails in year $15$ is $\frac {100}{15^2}-\frac {100}{16^2}$ where the first term is the chance that it survives the first $15$ years and the second is the chance it does not survive $16$
Comment: $Pr(T>t)=1−Pr(T\le t)$,so $P[T\le 3]=1−Pr[T>3]=1−100/9$ it is obviously wrong
Comment: @蕭仰恩 Indeed $\Pr(T\leq 3)=1-100/9$ is wrong because, in fact, $\Pr(T>3)=1$ .  The complete expression for this tail distribution is $$\Pr(T>t) =\begin{cases} 100/t^2 &:& t>10 \\ 1 &:& t\leq 10\end{cases}$$ Thus...
Comment: thx for answering a.,however,is my ideal for b.wrong?i understand the way  u think for b,but,i still dont know if my ideal for b were wrong,where did i think wrong?$[(100/t^2)×[1−(100/(t+1)^2)]]$ means he worked for more than 10 years and die,$1−(100/(t+1)^2)$, next year  ;$(100/t^2)$ means  worked for more than 10 years
Comment: @蕭仰恩 That is $\tfrac{\Pr(T>t)\times\big(1-\Pr(T>t+1)\big)}{\Pr(T>t)}$, which is simply $\Pr(T\leq t+1)$ and not at all for what you were asked.  Hint: the events $\{T\leq t+1\}$ and $\{T>t\}$ are not independent, so multiplication is inapplicable.  However, $\{T>t+1\}\subseteq \{T>t\}$, so....
Answer:
for a. question,well, i cant solve it,i have been thinked that $\Pr[T>t]=1−\Pr[T≤t]$,then differential it to let it become pdf, and i can know the expected value. but the t still have to bigger than 10,$t>10$,so is question wrong? or does there someway to solve it?

The complete tail distribution function should be $\Pr(T>t) =\begin{cases} 100/t^2 &:& t>10 \\ 1 &:& t\leq 10\end{cases}$
Then $\Pr(T\leq 3) = 0$.
For the expectation, use that for strictly non-negative integer random variables, $$\begin{align}
\mathsf E(X) &= \sum_{k=1}^\infty k\,\Pr(X=k)
\\ & = \sum_{k=1}^\infty\sum_{x=0}^{k-1}\Pr(X=k)
\\ & = \sum_{x=0}^\infty\sum_{k=x+1}^\infty \Pr(X=k)
\\ & = \sum_{x=0}^\infty \Pr(X> x)
\end{align}$$
And in particular $\mathsf E(T) = 11 +\sum\limits_{t=11}^\infty \Pr(T>t)$

for b.question,i think Pr[broken next year|have been worked for more than 10 yeasrs],that is,$[(100/t^2)×[1−(100/(t+1)^2)]]/(100/t^2)$ for $t>10$, is my ideal wrong?

Yes, it is wrong; but almost okay.
That is $\frac{\Pr(T>t)\times\big(1-\Pr(T>t+1)\big)}{\Pr(T>t)}$, which is simply $\Pr(T\leq t+1)$ and not at all for what you were asked.
You want to find the conditional probability that the device fails on or before $t+1$ given that it hasn't failed by $t$.
$\Pr(T\leq t+1\mid T>t) = \dfrac{\Pr(t<T\leq t+1)}{\Pr (T>t)} = \dfrac{\bbox[white]{\color{white}{\Pr(T>t)-\Pr(T> t+1)}}}{\Pr (T>t)}$
Hint: The events $\{T>t\}$ and $\{T>t+1\}$ are not independent, so the product rule is inapplicable, but $\{T>t+1\}\subseteq \{T>t\}$, so...


Is the last digit of $2^{2^{n-1}(2^n-1)}-1$ always $5$ for $n >3$?

Question: Is the last digit of $2^{2^{n-1}(2^n-1)}-1$ always $5$ for $n >3$?
I did modification to the Mersenne numbers (Even perfect numbers) foruma I put that formual to be the power of 2 have got  : $2^{2^{n-1}(2^n-1)}-1$ , Now for some values of $n >3$ that i have tried i have got the produced integer with last digit equal $5$ like this example, Now to do more $n$ or so large to conjecture that it is beyond of current tecknology , Really am interesting to prove that if it is true ?
Comment: $2^{4k}-1$ has last digit $5$, of course.
Comment: I did not say that the Mersenne numbers are congruent $0$ modulo $4$. But the **exponent** is $2^{n-1}(2^n-1)=4k$ for all $n>3$.
Comment: are all of mersenne numbers =0 mod 4 ? I think no
Comment: What @DietrichBurde said can be seen by induction as $$2^{4k+4}-2^{4k}= 15\cdot 2^{4k}\equiv 15\cdot 6 = 80\equiv0 \pmod{10}$$
Comment: @zeraouliarafik The existence of Mersenne primes proves that there are mersenne primes which are not equal to $0$ modulo $4$
Answer: Since $N=2^{2^{n-1}(2^n-1)}-1$ is odd, it is enough to show $5\mid N$, and the conclusion follows. But since $2^4 \equiv 1 \pmod 5$, we have $2^{2^{n-1}(2^n-1)}-1=(2^4)^{2^{n-3}(2^n-1)}-1\equiv 1-1=0\pmod {5}$ and we are done.
Answer: We start from.the sequence:
$$2\;\;4\;\;8\;\;16\;\;32\;\;64\;\;128\;\;256\;\;512\;\;1024\;\;2048\;\;4096$$
In particular, we are interested in the power of $2$ such that their last digit is $6$. This occours when $e\equiv0\mod 4$, in fact:
$$2^e\equiv 6 \mod 10 \leftrightarrow e=4n, n\in N$$
Now, to show that $2^{2^{n-1}(2^n-1)}-1\equiv 5 \mod 10$, we need to show that:
$$2^{n-1}(2^n-1)\equiv 0\mod 4$$
Let $n=3+k, k\in N_0$, we have:
$$2^{3+k-1}(2^{3+k}-1)=2^2\cdot2^k\cdot(2^{3+k}-1)=4\cdot(2^{3+k}-1)$$
We are in the form $4a \mod 4$, where $a=(2^{n}-1)$, so:
$$2^{n-1}(2^n-1)\equiv 0\mod 4, \forall n\in N, n>3$$
Note that this proprety holds also for $n=3$ because in that case, we can pick up a $2^2=4$ and so all the expression is congruent to $0$ modulo $4$.
Comment: @zeraoulia rafik: if this answer has been useful, maybe a $1$ or a favourite answer?


Why does drupal commerce create an empty order for every anonymous user?

Question: Drupal Commmerce is creating an empty order for every single anonymous user in my website (over 13000 in just a few hours).
Users on my website have no direct access to the shopping basket, nor do they have any means of adding products to the cart, since for the moment, I'm only planning to use the Drupal Commerce functionality for specific users (i.e. I will create a product in the backend, then send the URL to the customer).
It doesn't seem right that so many orders are created for users who don't even have the shopping basket block in their page.
Why does this happen?
Is there a way to prevent it?
You can see in the screenshot how the empty-basket orders are being created for every anonymous user, this is slowing down the site!
Comment: Are you sure that urls are not public?

Not having the shopping basket block available does not means that they can not access the specific url of the product variation or product display and then click under add to cart
Comment: @GianniDiFalco Those URLs (as of now, only 1) are only accessible by direct access.  However, when a person just loads the frontpage, an empty order is created ...
Comment: Yep that's pretty standard in my experience. The 'culprit' is `commerce_cart_order_id()`, which can be called from a multitude of places. If you have the cart block active, for example, it will be called during the build process for all users
Comment: @Clive so this is standard behaviour? Should I just let the orders table be vastly populated?  I have seen a clear decrease in performance.
Answer: There's nothing in core Drupal Commerce that would create an empty order for every anonymous session. Core Commerce will only create an order when an anonymous user adds a product to the shopping cart. This means some other module must be creating those orders for every session. I'd look to your contributed modules, especially if any are facilitating adding products to the cart via links instead of forms.
Comment: You are absolutely right! I found out the culprit was module [Commerce Marketplace](http://www.drupal.org/project/commerce_marketplace), which I've disabled for the moment.
Answer: As long the users click on the cart link that is a normal behavior. Why ? The far I'm concern Drupal Commerce assign an unique order id for each user. This can help you to determine when the user leave your site before they did not make the purchase. In addition, if the user leave and comeback this is going to keep the all the order information where they left out last time.


Running Apple Script on hidden safari window

Question: I am running apple script.
My problem is that i am opening a safari window using apple script.
After that I am hiding it using script
tell application "System Events" to tell process "Safari" to set visible to false
Now I want that my leftover script should run on that safari window which is hidden, but when i hide safari window then the focus to the safari is lost and the script starts running on the application that has focus instead of safari window.
Can we do this? Please tell the solution if we can.Any help is appreciated.
Thanks.
Comment: Use a 'tell application "Safari" - block to talk to Safari.app -
Comment: Can you give me an example.
Comment: Basically it's this: put all the code that belongs to Safari in a 'tell application "Safari" ... [ your code ] end tell - block.
Answer: What are you trying to do with the window? If I hide Safari with an open window, I can still access the window using the normal tell block, like
tell application "Safari"
    set bounds of window 1 to {111, 222, 777, 666}
end tell

with no problem. But perhaps you are using System Events, which may not be necessary (and possibly bad practice) but it depends on what you're trying to do. Check Safari's dictionary, and post example code.
Comment: This is hiding all the safari windows. I want that my apple script should run on hidden safari window.
Comment: Please update your question to explain how you are hiding a single window. It is not very clear hence you are not getting the answers you are looking for
Answer: try this
tell application "System Events" to set visible of process "Safari" to false

Comment: This apple script is not running on hidden safari window, its running in the any other application window that is focused. I want it to run on hidden safari window.
Answer: This worked for me:
tell application "Safari"
activate
delay 1
tell application "System Events" to set visible of process "Safari" to false


Probability of at least one random number out of 3 being greater than 3 other random numbers?

Question: $$\{?,?,?\mid?,?,?\}$$
There are 6 random numbers (drawn from arbitrarily large pool). What is the probability that biggest number lies in second half? Answer is $1/2$ but I tried to solve it with combination. Can you show me where I went wrong?
I thought, for one particular number in second half, the probability that it is greater than all three points in first half is $1/8$ and likewise probability that it is not greater than all three points in first half is $7/8$, so
$${3 \choose 1}  \left(\frac18\right)^1 \left(\frac78\right)^2$$ is probability that only of them is bigger than first half
$${3 \choose 2} \left(\frac18\right)^2 \left(\frac78\right)^1$$ is probability that two of them are bigger than first half
$${3 \choose 3} \left(\frac18\right)^3 \left(\frac78\right)^0$$ is probability that all three of them are bigger than first half
Total is $\dfrac{169}{512}$ not $\dfrac{256}{512}$. So what is my mistake?
Edit: I think I figured out, biggest number, rank 6 must be in second half; so I can choose other two numbers
(5 choose 2) different ways * 3! configuration for right side * also 3! configuration for left side;
divided by 6! equals to 1/2. now i can generalize it to solve secretary problem, : )
Comment: I think my argument is not correct but suppose that the 6 randomly drawn numbers are $\{a_1,\dots,a_6 \}$. Suppose $a_1$ is the largest of them. Then $a_1$ can be placed in 2 baskets in 2 ways and $a_1$ can be placed in basket 2 in 1 way. So the probability is $1/2$.
Comment: yes, argument is wrong but i want to know exactly where it is wrong. I am really stuck in this basic :) question. i know answer is 1/2 with simple logic
Comment: I meant my argument. :)
Comment: Hahaha. Easy to answer. Hard to justify. Um, all the numbers have an equal chance of being the biggest number...the biggest number is either in one or the other...damn idk :)) I'd like to know the explanation too!
Comment: I don'see the definition of "random number drawn from an arbitrarily large pool." Please, explain.
Comment: well pick random a number uniformly from 1 to 1 trillion, for example, so probability that numbers being equal is so small
Answer: Your problem is that the probability that the fourth number is greater than the preceding three is not $\frac 18$, it is $\frac 14$.  Your calculation of $\frac 18$ assumes that the fourth number being greater than the first and the fourth number being greater than the second are independent.  They are not.  If the fourth number is large, it has a good chance of being greater than any of the first three.
Comment: thank you, it is interestingly so, i had written a small script and it confirms it. but how can i show it with formula? thanks again
Comment: I don't think there is a graceful way in the approach you describe.  There are too many correlations between the chances that one number in the second set is greater than all the first three and the chances for another.  If the six numbers are distinct, you can just change them into $1$ through $6$ by using their ranks and you have a permutation of the numbers.
Comment: Thank you, i solved with your hint
Answer: The probability is $1/2$. Here is a possible explanation.
Let's suppose we have two groups containing three random numbers each.
Group 1: $\{x_1,x_2,x_3\}$
Group 2: $\{x_4,x_5,x_6\}$
Assume that these numbers are uniformly distributed and in [0,1]. All the random variables are also independent of each other.
\begin{equation}
p_x(X) = \left\{\begin{array}{rl}
1, & \textrm{if $X \in [0,1]$}\\
0, & \textrm{otherwise}
\end{array}\right.
\end{equation}
Defining $z_1 = \max(x_1,x_2,x_3)$ and $z_2 = \max(x_4,x_5,x_6)$, we want to obtain $P(z_2 > z_1)$.
This probability can be obtained by integrating the joint density $p_{z_1z_2}(Z_1,Z_2)$ of the random variables $z_1,z_2$, over the region where $z_2 > z_1$. Since $z_1$ and $z_2$ are independent because all the $x$ are independent, we have that $p_{z_1z_2}(Z_1,Z_2)=p_{z_1}(Z_1)p_{z_2}(Z_2)$.
The density $p_{z_1}(Z_1)$ is obtained by deriving the cdf $F_{z_1}(Z_1)$:
\begin{eqnarray*}
p_{z_1}(Z_1) &=& \frac{d}{dZ_1}\,F_{z_1}(Z_1) = \frac{d}{dZ_1}\,P(z_1 \le Z_1) \\ \\
&=& \frac{d}{dZ_1}\,P(\max(x_1,x_2,x_3) \le Z_1) \\
&=& \frac{d}{dZ_1}\,P(x_1 \le Z_1, x_2 \le Z_1, x_3 \le Z_1) \\
&=& \frac{d}{dZ_1}\,P(x_1 \le Z_1)P(x_2 \le Z_1)P(x_3 \le Z_1) \\
&=& \frac{d}{dZ_1}\,Z_1^3 = 3Z_1^2, \quad \textrm{for $Z_1 \in [0,1]$}.
\end{eqnarray*}
The same procedure is used for $z_2$ and we obtain $p_{z_2}(Z_2) = 3Z_2^2$, for $Z_2 \in [0,1]$.
The joint density is:
\begin{equation}
p_{z_1z_2}(Z_1,Z_2) = \left\{\begin{array}{rl}
9Z_1^2Z_2^2, & \textrm{if $(Z_1,Z_2) \in [0,1] \times [0,1]$}\\
0, & \textrm{otherwise}
\end{array}\right.
\end{equation}
We now can obtain the desired probability $P(z_2>z_1)$:
\begin{eqnarray*}
P(z_2 > z_1) &=& \int_{0}^{1}\int_{0}^{Z_2}p_{z_1z_2}(Z_1,Z_2)\,dZ_1dZ_2 \\
 &=& 9\int_{0}^{1} Z_2^2\int_{0}^{Z_2}Z_1^2\,dZ_1dZ_2 \\
 &=& 3\int_{0}^{1} Z_2^5dZ_2 \\
 &=& \frac{1}{2}\,Z_2^6\bigg|_0^1 = 1/2.
\end{eqnarray*}
Comment: This is much more complicated than using the symmetry of the situation.  I think OP wanted to know why his calculation was not correct.
Answer: If none of the numbers in the pool are equal, then the fact that six numbers are drawn from the pool is irrelevant.  You are just dealing with six numbers, none of which are equal to any of the others.  Since we are dealing with a set of six (an even number) numbers, then each number is either above the median or below it.  So no need to do combinations or anything else fancy.  The question you are asking is the same as asking what the probability of picking a red ball is from a set of 3 red balls and 3 blue balls.
Comment: I think OP had understood this, but wanted to know why his detailed procedure failed.
Answer: We are given a nonatomic probability measure $P$ on ${\Bbb R}$, which on account of independence induces a probability measure $P^\otimes$ on ${\mathbb R}^6$. If $P$ can be realized as a probability density $x \mapsto f_X(x)$ then $P^\otimes$ is realized by
$$P^\otimes (A)=\int _A f_X(x_1)\cdot\ldots\cdot f_X(x_6)\>{\rm d}(x)\ .$$
Let
$$A:=\bigl\{x\in{\Bbb R}^6\>|\>\max\{x_1,x_2,x_3\}\geq\max\{x_4,x_5,x_6\}\bigr\}\ ,$$
and let $A'$ be the complement of $A$, defined by $\max\{x_1,x_2,x_3\}\leq\max\{x_4,x_5,x_6\}$. Then $P(A)=P(A')={1\over2}$ on account of symmetry. (Of course we knew this all along.)
Answer: If the numbers cannot be equal (if they can be equal the largest has to be defined with care), and are all equally likely, then proceed as follows.
Any collection of six numbers is equally likely - if they are chosen from $n$ possibilities the number of choices is $\binom n6$.
There are 6! possible arrangements of each possible six. Of these $5!$ have the largest number in the first place (and the same for the second, third etc). So the number of arrangements with the largest number in the first half is $3\cdot 5! \cdot \binom n6$. The number of arrangements with the largest number in the second half is the same.
Comment: thank you, i solved myself just around this time, but thank you


Does smtpfailedrecipientsexception work for CC and BCC

Question: I'm trying to get my head round the System.Net.Mail class but I'm having trouble finding decent documentation.
First query - Say I have an email with a CC and a BCC email, do I need to catch SmtpFailedRecipientsException instead of SmtpFailedRecipientException (note the singlular Recipient) or is it intended for sending to multiple TO recipients?
Second query - when I iterate through the exceptions using the method below, will the inner exceptions relate to the email addresses that have failed, such as the BCC but not the TO or CC. If this is the case will the resend then go to all 3 again?
<code>    static void CheckExceptionAndResend(SmtpFailedRecipientsException ex, SmtpClient client, MailMessage message)
    {
        var status = ex.StatusCode;

        for (int i = 0; i < ex.InnerExceptions.Length; i++)
        {
            if (status == SmtpStatusCode.MailboxBusy ||
                status == SmtpStatusCode.MailboxUnavailable ||
                status == SmtpStatusCode.TransactionFailed)
            {
                System.Threading.Thread.Sleep(3000);
                client.Send(message);
            }
            else
            {
                // TODO: Log delivery failure
            }
        }
    }
</code>
All advice appreciated. Thanks in advance.
Answer: I don't know and can't answer your 1st query but to answer the 2nd one, if you are not sending the message anywhere except in this method, I don't understand how the message will be sent again or twice to the recipients..
But if you are sending the message using the smtpclient instance before this method gets invoked because of an exception, then yes, the message gets delievered again to all 3 i.e. TO, BCC and CC, not just to the failed recipients..
Comment: Yes, there is a method that calls client.Send() then calls the method shown on SmtpFailedRecipientsException exception. You have answered the second part. It seems logical because the message is never 'rebuilt', just resent.
Comment: Also, it seems that exceptions will only be thrown for local email addresses, therefore, if I'm sending out emails to users rather than my own internal admin, no exception will be caught.
Comment: @dotnetnoob that is true if you are in intranet because your smtp client instance is initialized with the value of your intranet's smtp mailing host which can only detect failures of local mail addresses, not others..
Answer: For your 1st query, have a look at the source code for SmtpTransport.SendMail(), which is called by SmtpClient.Send().  If only one recipient (regardless of To, CC, or BCC) is rejected, the resulting exception will be SmtpFailedRecipientException, but if more than one is rejected, it'll be SmtpFailedRecipientsException.  Inconveniently, I believe this means you'd need to try to catch both types.


What is a formula to find the permutation of $r$ objects given that there are $n$ total object and out of them $n_1$ and $n_2$ are indistinguishable?

Question: The question is I've $n$ the total number of objects, out of them I've to find the permutation of $r$ objects given that $r < n$. It's also given that there $m$ and $t$ are indistinguishable objects in $n$ such that $m+t=n$. What will be the formula to find the permutation in such a case?
As an example, we've $8$ marbles out of which $5$ are red and $3$ and blue, and the number of objects we have to choose is $2$. The permutation we know would be equal to $4$. But I don't don't the formula to evaluate this value of $4$.
Answer: One way is dividing it into cases, eg for the numerical example, either you can have 2 red, 2 blue, or 1 red + 1 blue in two ordered  ways
But this sort of computation quickly becomes very tedious.
So here is a way you can use where a lot of cases may arise.
We know that when we multiply polynomials in $x$, the indices of $x$ get added up.
And we also know that if one type, eg, $M$ occurs, say, $k$ times in the extracted letters, we need to divide the permutations by $k!$
Using these two ideas, we can represent each letter as a polynomial of x, the indices representing the number of times a letter can occur. You can regard $x's$ as only  placeholders for the number of times a letter can occur.
Putting it all together, for a somewhat more complex example, $4$ letter permutations of PINEAPPLE  (I,N,A,L occur once each, E occurs twice, P occurs thrice), Remember that $P$, for example, may occur $0,1,2,\; or\; 3$ times
find  $4!$ times the coefficient of $x^4$ in the expression $(x^0+x^1)(x^0+x^1)(x^0+x^1)(x^0+x^1)(x^0+x^1+\frac{x^2}{2!})(x^0+x^1+\frac{x^2}{2!}+\frac{x^3}{3!})$
where the successive terms in parentheses are for $I,N,A,L,E,P$
which of course would normally be written as
$4!(1+x)^4(1+x+\frac{x^2}{2!})(1+x+\frac{x^2}{2!}+\frac{x^3}{3!})$
and gives an  answer of $626$
You may like to countercheck by the case by case approach, eg

$4$ singles: $\binom64*4! = 360$

$2$ singles and a double: $\binom43\binom21\frac{4!}{2!} = 240$

$1$ single, $1$ triple: $\binom51\frac{4!}{3!} = 20$

$2$ doubles: $\binom 22\frac{4!}{2!2!} = 6$

PS
The second approach is called the generating function approach, which for the moment you can understand simply the way it has been explained for use in the type of permutations you have asked for
Comment: Thank you so much. The answer was very helpful
Comment: Glad to be of help ! $\;\;$ :)


Page not found when trying to access custom module

Question: I've followed this post and made a custom module but when I try to access it from url domain.com/module/method I get 404?
Am I missing something?
Path (URL) to call custom module function
Answer: So much could be going wrong from a finger fudge standpoint here, so just make sure you have something very similar to this going on:
For example, in quick.info:
name = quick module
core = 6.x
description = quick module
package = quick package

In quick.module:
<?php

function quick_menu() {

  $items = array();
  $items['quick/hello'] = array( // change to the url you want
    'title' => 'Quick Hello',
    'type' => MENU_CALLBACK,
    'page callback' => 'quick_hello',
    'access arguments' => array('access content'),
  );

  return $items;
}

function quick_hello() {

  $content='Hello. Thank you for surfing over to ' . $_GET['q'];
  return $content;
}

Obviously make sure your module is enabled and not so obviously that all caches are cleared, but past that, the most important piece of the above is the 'quick/hello' when it comes to page found/not found :)
Comment: Thnx it was the caches.....


Filling in a new column based on a condition in a data frame

Question: I want to add a new column in my data frame so that for each row if LOC == 1 then V is equal to the value given for V1; if LOC==2 then V is equal to the value given for V2. Here is an example:
df <-
LOC   V1   V2
 1    0.5  0.7
 1    0.5  0.7
 2    0.5  0.7
 1    0.6  0.8

Result should be:
df <-
 LOC   V1   V2   V
 1    0.5  0.7   0.5
 1    0.5  0.7   0.5
 2    0.5  0.7   0.7
 1    0.6  0.8   0.6

I need help on how to do that in R.
Answer: Use matrix indexing:
idx <- cbind(seq_len(nrow(dat)), dat$LOC)
#      row  col
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    1
#[3,]    3    2
#[4,]    4    1

dat[-1][idx]
#[1] 0.5 0.5 0.7 0.6

Comment: Thank you. But is there an easier way where I can added it to the data frame that I have?
Comment: @daragh - `dat$V <- dat[-1][idx]` and you're done. I'm not sure what is difficult about that.
Answer: If LOC only contains 1 or 2 then this will work
 df$V <- ifelse(df$LOC == 1, df$V1, df$V2)

Comment: It's a good solution for 2 groups, but will quickly become complex if you have >2 columns.
Comment: @thelatemail, agreed. I like your approach, sub-setting with matrices is always fun!


After a key rotation do I still need the old key to sign the update of the app?

Question: I have read here, https://source.android.com/docs/security/features/apksigning/v3, and here https://www.xda-developers.com/apk-signature-scheme-v3-key-rotation/, that I rotate keys with the V3 signing and be able to sign the apk with another key.
Do I still need the old key to sign it? Or signing it with the new key is enough?
Answer: In short, signed with new key is enough.
I did below key rotation steps on Android 13 emulator and Pixel 5 (not work on Android 10 Emulator)
below steps for you reference
create 3 key store owen1.jks, owen2.jks and owen3.jks
keytool -keystore owen1.jks -genkey -alias owen1 -keyalg rsa
keytool -keystore owen2.jks -genkey -alias owen2 -keyalg rsa
keytool -keystore owen3.jks -genkey -alias owen3 -keyalg rsa

create rotation lineage file
apksigner rotate --out SigningCertificateLineage.owen1.owen2 --old-signer --ks owen1.jks --new-signer --ks owen2.jks
apksigner rotate --out SigningCertificateLineage.owen2.owen3 --old-signer --ks owen2.jks --new-signer --ks owen3.jks

sign serial.apk with each jks
apksigner sign --ks owen1.jks --in serial.apk --out serial.SignedOwen1.apk
apksigner sign --ks owen2.jks --in serial.apk --out serial.SignedOwen2.apk
apksigner sign --ks owen3.jks --in serial.apk --out serial.SignedOwen3.apk

sign serial.apk with rotation data
apksigner sign --ks owen1.jks --next-signer --ks owen2.jks --lineage SigningCertificateLineage.owen1.owen2 --in serial.apk --out serial.rotate.owen1.owen2.apk
apksigner sign --ks owen2.jks --next-signer --ks owen3.jks --lineage SigningCertificateLineage.owen2.owen3 --in serial.apk --out serial.rotate.owen2.owen3.apk

then let's try the rotation as below steps
[0] 12/29 15:41:51 owenwen@dell:~/jks$ adb install serial.SignedOwen1.apk
Performing Incremental Install
Serving...
All files should be loaded. Notifying the device.
Success
Install command complete in 931 ms

[0] 12/29 15:42:42 owenwen@dell:~/jks$ adb install serial.rotate.owen1.owen2.apk
Performing Incremental Install
Serving...
All files should be loaded. Notifying the device.
Success
Install command complete in 629 ms

[0] 12/29 15:42:52 owenwen@dell:~/jks$ adb install serial.SignedOwen2.apk
Performing Incremental Install
Serving...
All files should be loaded. Notifying the device.
Success
Install command complete in 467 ms

[0] 12/29 15:42:59 owenwen@dell:~/jks$ adb install serial.rotate.owen2.owen3.apk
Performing Incremental Install
Serving...
All files should be loaded. Notifying the device.
Success
Install command complete in 570 ms

[0] 12/29 15:43:05 owenwen@dell:~/jks$ adb install serial.SignedOwen3.apk
Performing Incremental Install
Serving...
All files should be loaded. Notifying the device.
Success
Install command complete in 728 ms

[0] 12/29 15:43:10 owenwen@dell:~/jks$ adb install serial.SignedOwen1.apk
Performing Incremental Install
Serving...
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Existing package com.sample.app signatures do not match newer version; ignoring!]
Performing Streamed Install
adb: failed to install serial.SignedOwen1.apk: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Existing package com.sample.app signatures do not match newer version; ignoring!]

[1] 12/29 15:43:14 owenwen@dell:~/jks$ adb shell getprop | grep fingerprint
[ro.bootimage.build.fingerprint]: [google/redfin/redfin:13/TQ1A.221205.011/9244662:user/release-keys]

Comment: Thank you very much, @Wenchichin.
Did yo manage to make it work on Google play store?


Como capturar o innerHTML de um documentFragment via Javascript?

Question: O documentFragmentque é criado utilizando o método document.createDocumentFragment() não contém as propriedades innerHTML e outerHTML igual elementos derivados de HTMLElement tem.
Mas preciso pegar o conteúdo do fragmento em formato de string. Porém não posso simplesmente dar um appendChild do fragmento em outro elemento pra ter o innerHTML, pois isso deixaria a instancia do fragmento vazia uma vez que seu conteúdo seria transportado pra outro elemento.
Preciso extrair o HTML em forma de string do fragmento sem alterá-lo.
Answer: Use apenas: frag.querySelector('*').innerHTML
O asterísco seleciona qualquer primeiro objeto DOM achado dentro do fragmento, que no caso é a raiz, e ai então, com o objeto DOM raiz nas mãos é possível usar innerHTML, ou o outerHTML se for o caso.
EDIT
No caso de seu fragmento conter múltiplos elementos raízes, então use querySelectorAll:
var conteudo = "";
var all = frag.querySelectorAll('*');
    for (var i = 0; i < all.length; i++)
        if (!all[i].parentElement)
            conteudo += all[i].outerHTML;

// mostrando o output na página
$("#output").text($("#output").text() + conteudo);

querySelectorAll é bem suportado nos browsers:
http://caniuse.com/queryselector
EDIT 2: Uma solução mais performática usando querySelector ao invés de querySelectorAll:
var conteudo = "";
var current = frag.querySelector('*');
while (current) {
    conteudo += current.outerHTML + "\n";
    current = current.nextSibling;
}

EDIT 3: como as opções anteriores não funcionaram no IE8, continuei procurando até achar a seguinte alternativa (que funciona em todos os browsers que eu testei):
var conteudo = "";
var rootNodes = frag.childNodes;
for (var i = 0; i < rootNodes.length; i++)
    conteudo += rootNodes[i].outerHTML;

Comment: Obrigado Miguel, realmente a ultima foi a mesma coisa que eu acabei fazendo pra resolver esse caso, então a resposta está correta, o legal das edições é que ficou uma base de conhecimento para os proximos que tiverem esta mesma dúvida. =) Novamente obrigado!
Comment: Atualizei a resposta para múltiplos elementos raízes.
Comment: `querySelectorAll` garante a ordem dos elementos? Pq se ele garantir provavelmente essa solução esta solução serve ao meu propósito.
Comment: Poxa vida, ele está selecionando também os filhos... vou ver se tem como selecionar só os elementos raiz sem os filhos.
Comment: Miguel acho que se juntar a sua resposta com o bfavaretto, seria a solução mais correta, agora não sei pra quem dar como solução da questão...
Comment: Acho que `querySelectorAll('*')` vai pegar todos os elementos dentro do fragment, não só as raízes.
Comment: Código corrigido, agora só as raízes serão selecionadas.
Comment: Eu excluí os não raízes manualmente, dentro do for... não sei se isso é bom para performance.
Comment: Agora sim, uma solução que não é ruim de performance: usar `querySelector('*')` e depois usar `nextSibling` e ir concatenando o outerHTML. Dessa forma, inclusive, a ordenação fica mais garantida... é a ordem de inserção dos elementos no fragmento.
Comment: Milésima edição... =) Foi mal por tantas edições pessoal.
Comment: O método do edit 2 é bem eficiente, 3x mais rápido que o meu: http://jsperf.com/documentfragment-innerhtml
Answer: Considerando seus requisitos, parece que a única maneira seria clonar cada filho do fragmento:
function fragHtml(frag) {
    var div = document.createElement('div');
    for(var i=0; i<frag.children.length; i++) {
        div.appendChild(frag.children[i].cloneNode(true));
    }
    return div.innerHTML;
}

Comment: Bem interessante, mas acho que pra pegar a string, a melhor solução deve ser a junção da sua resposta com a do Miguel Angelo, pois a sua solução mantém a ordem dos elementos correta, só não precisaria clonar todos elementos pra pegar sua string...
Answer: A MDN refere o método:

element = documentframgment.querySelector(selectors);

Assim, um exemplo seria:
HTML

    Teste

JS
var frag = document.createDocumentFragment();
var teste = document.getElementById('test');
frag.appendChild(teste);
console.log(frag);       // #document-fragment
var conteudo = frag.querySelector('#test');
console.log(conteudo.innerHTML);   //  Teste

Exemplo
Answer: Uma sugestão seria mapear os nós e convertê-los para string:
function getFragmentHTML(fragment) {
  return Array.from(fragment.childNodes).map(item => item.innerHTML).join('');
}

Isso vai pegar todos os nós de um fragment, transformar em um array comum, converter cada entrada para o equivalente ao conteúdo html do item corrente, e retornar isso concatenado em uma string única. Como utilizamos childNodes, TEXT_NODES serão preservados, preservando assim a formatação original tbm.
Comment: Não votei na sua resposta, mas posso explicar os negativos. Quando a pergunta e essas respostas foram escritas não existiam o elemento HTM [`


Understanding the Wolfram Demonstration "Distance of a Point to a Polygon"

Question: I've recently came across a neat Wolfram Demonstration script by Jaime Rangel-Mondragon that calculates the minimum distance from a point to an arbitrary convex or non-convex polygon:
http://demonstrations.wolfram.com/DistanceOfAPointToAPolygon/
Here's the basic script that computes point-to-polygon distances:
dis[{a_, b_}, p_] := Module[{pz, az, bz, z},
  If[a == b, {a, Norm[p - a]},
   {pz, az, bz} = Map[First[#] + I Last[#] &, {p, a, b}];
   z = (pz - az)/(bz - az);
   If[Not[0 <= Re[z] <= 1], d1 = Norm[p - a]; d2 = Norm[p - b];
    If[d1 < d2, {a, d1}, {b, d2}],
    {a + Re[z] (b - a), Norm[Im[z] (b - a)]}]]]

p = {1, 1};
poli = {{-3, -3}, {0, -1}, {3, -1}, {3, 3}, {0, 1}, {-2, 1}};

f = Map[dis[#, p] &, Partition[poli, 2, 1, 1]];
{closestPointOnPolygon, distPointToPolygon} = First[Sort[f, Last[#1] <= Last[#2] &]]

Where we provide two inputs, the first being an arbitrary two-dimensional point p, and the second being a 2D polygon poli.  This then yields two outputs, closestPointOnPolygon and distPointToPolygon (or c and d, respectively, in the author's original notation).
I read through the source code, and looked through the notes, however, I'm still not sure if I understand what the author is doing.  Would anyone here be able to provide a higher level description of what the author is doing?
Answer: The main part is dis[{a_, b_}, p_] which finds the distance from point $p$ to the line segment $[a,b]$. It does so with complex arithmetics, by using a complex linear transformation that sends $a$ to $0$ and $b$ to $1$. Let $p'$ be the image of $p$ under this transformation. $\DeclareMathOperator{\re}{Re}$

If   $\re p'<0$, then $0$ is the closest  point to $p'$. Hence $a$ is the closest  point to $p$.
If   $\re p'>0$ is greater than $1$, then $1$ is the closest point to $p'$. Hence $b$ is the closest point to $p$.
Otherwise,   $\re p'$ is the closest point on $[0,1]$ to $p'$. From here one determines the closest point on $[a,b]$ to $p$.

The very last line applies the above to every side of the polygon, and takes the smallest distance.
Important: this algorithm  returns the distance to the boundary of polygon, not to the polygon itself. If $p$ is outside of the polygon, there is no difference. But if $p$ is inside the polygon, the algorithm returns a positive number (distance to the boundary) instead of $0$.


If f+g in L2 then so are f and g

Question: Is it true that if f+g is a function in L2(R)  then f and g must be in L2(R)?
Does it also hold true for the multiplication of f and g?
Comment: It is, however, true if $f,g \ge 0$.
Comment: Not at all. Let $h$ not be in $L^2$ and use $h+(-h) = 0$. For multiplication, let $f = g = 1/\sqrt{x}$ on the interval $[1,\infty)$.
Answer: Nope. $h+ (-h) \equiv 0 \in L^2(\mathbb R)$ for any $h$ and $1_{(-\infty, 0)} \cdot 1_{(0, \infty)} \equiv 0 \in L^2(\mathbb R)$.

If f+g in L2 then so are f and g


Download and/or View .pdf on the same page

Question: I am using IIS/asp.net and have a requirement to have two links side by side on the same page.  They both link to the same exact file, but with two different behaviors, one should view the file and the other should download the file.

I have seen some tips here on SO about forcing one behavior or the other through MIME types, or via Content-Disposition: attachment
But is there anyway to have this arrangement where both live on the same page?  I was hoping ideally to be able to add something to the link itself or to the href.
Thanks!
Comment: I did ask about Right Click-->Save As and they weren't interested ;)
Comment: posted my entire solution below.
Answer: If you want to force it you can do it on the server side.  I'm not sure if you are using webforms or mvc, but either way on the server side you can add something like this to the header:
Response.AddHeader("Content-Disposition", "attachment;filename=whatevernamehere.pdf");
That will force the browser to download as an attachment.  You only need to do this for the 'download' link and leave the 'view' link alone (to view it in the browser).
Hope that helps!
Answer: I ended up taking the advice I was given.  My entire solution is below.
My first step was to create a handler in the root of the site which I called fileDownload.ashx.
<%@ WebHandler Language="C#" Class="fileDownload" %>
using System;
using System.Web;

public class fileDownload : System.Web.IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        HttpResponse r = context.Response;
        string fileName = context.Request.QueryString["file"];
        r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        r.ContentType = "application/octet-stream";
        r.WriteFile(context.Server.MapPath(fileName));
    }
    public bool IsReusable { get { return false;}}
}

Next to update the links...

Thats it! There is a little postback flicker which I'd prefer there not to be, but it does what I need.  Thanks for the push Bald Programmer.
Comment: Note that that code will fail if your filename contains characters not allowed in an unquoted name, such as comma or whitespace.


Using micro average vs. macro average vs. normal versions of precision and recall for a binary classifier

Question: I have a logistic regression recommender model built on my data where I tried to predict one of two outcomes for each row. Let's call them success and fail. I'm using the cross_val_score function of SKLearn to do so. I was planning on just using precision and recall as performance measures, but saw the "micro" and "macro" options and decided to read up more and try those as well, but I'm confused by the results. For reference, I looked at this blog post, this SO question, and this paper.
While I think I understand the general concept, I'm confused by the results I'm getting, and which one is ideal for my use case. One important piece of background is that I have fewer success cases that fail. success makes up 25% of my dataset.
My understanding is that micro is a value that's closer to the performance of the model on the larger class (in this case, fail), while macro is for the smaller one (success). This makes sense. I'm trying to predict successes in this case, so the latter should be the better choice.
Here are the parts I don't get:
a) How do each of these compare to just regular precision / recall, in terms of representing the larger or smaller classes? Which of the three options is optimal for a case like this where I want to surface the smaller class but not the large one.
b) In some folds of my CV, I get 0 as the regular precision value, but none are 0 for micro and macro. How is that possible? If I get some true positives in the individual classes, shouldn't I always have some in the overall dataset as well? In general the regular precision and recall end up significantly lower than both types of averages.
Comment: Are you building a binary classifier (i.e. only two output classes)? Because then you can just use the regular precision and recall values. I like to create a visualization like this for binary classifiers: http://www.scikit-yb.org/en/latest/api/classifier/threshold.html
Answer: These micro and macro averaging techniques are typically made for situations with more than 2 classes. With two classes you would only compute precision, recall, F1 or whatever you are interested in (you tell us! We cannot know) with regard to almost always your minority class (since it almost always is the one you're interested in).
If these averaging techniques use arithmetic means (on the micro or macro level), the other non 0 value will make the average larger than 0 as in $(0 + 5)/2=2.5$. If they used geometric averages (which is very uncommon), then $\sqrt{0\times5}=0$


How to post to remote url on form submit

Question: We want to silently submit a Drupal6 form to a marketing partner, and redirect the user to page on our site.  Is this the correct syntax?
<code>function my_form_submit($form, &$form_state) {
  $form_state['action'] = url('http://example.com/?method=cSurveyWebservice.submit&mode=test');
  $form_state['redirect'] = array('campaign/thank-you');
}
</code>
Certainly it processes and redirects, although I'm not sure how to independently validate if the form is actually posted to the specified URL.
Answer: You can try something like this
<code>$request_url = 'http://your-url.com';
$request_headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$request_method = 'POST';
$request_retry = 2;
// form values you want to post
$form_values= array('apple' => 'red', 'banana' => 'yellow', 'pear' => 'green');
$data = http_build_query($fruits, '', '&');

// Send the request.
$response = drupal_http_request($request_url, $request_headers, $request_method, $data, $request_retry);

if ($response->code == 200) {
  $form_state['redirect'] = array('campaign/thank-you');
}
else {
drupal_set_message(t('There was a problem with your submission. Please try again later.'), 'error');
}
</code>
I haven't tried it but let me know if it works.
Comment: very nice, thanks.  I implemented in a submit handler, and added the following to include the form elements in the request:   '$skip_keys = array('submit', 'form_build_id', 'form_id');
  foreach ($form_state['values'] as $key => $value) {
    if (!in_array($key, $skip_keys)) {
     $form_values[$key] = $value;
    }'
Comment: @August1914 glad to hear it worked.


How to process an email thread with mailman

Question: If the person replying to a "ticket" is using a mail client such as gmail that reply will show a whole conversation thread when I do @message.body.decoded rather than the text that they typed.
Is there a way to extract just that portion of text?
Comment: only thing I can think of is to put for every message going out, and for a message going it to do a diff on the two.
Answer: Generally, the existing replies are formatted with a preceding >. One option is to extract lines that do not begin with that character.
So you look at the email as plain-text, you can extract it. Here is an example:
--f46d0basically0a0unique0id # Marks the start of content for this email
Content-Type: text/plain; charset=ISO-8859-1

Hello foo,

This is a message.

Regards,
Bar

>
> Original response
> is quoted like this
> What in included here
> depends on mail client
>

--f46d0basically0a0unique0id # Marks the end of content for this email

Comment: this looks like the most reasonably solution, except if contacts start using > in the start of their lines for no reason. but that's a tiny caveat.
Comment: I don't think this is the best solution because messages use `>` but also mix it with original messages in html.
Comment: I think I need to separate the first unique section, and then remove the `>`s
Comment: Yeah, its just a hacky work around. But I know for sure that GMail guys match it with last email's content.