How to use docker container as a proxy?

Question: I have the following docker-compose:
version: '3'
services:
  mitmproxy:
    image: johnmccabe/mitmweb
    container_name: mitmproxy
    command: --cadir /ca --wiface 0.0.0.0
    restart: always
    ports:
        #- "8080:8080"
        - "8081:8081"

  python:
    image: python
    build: ./python-socks-example
    command: python3 /home/project/socks-example.py
    volumes:
      - ./python-socks-example:/home/project/
    depends_on:
       - mitmproxy
    container_name: python
    restart: always

I want my python HTTP requests to go through mitmproxy on the other container. Here's the python code:
import requests
import time

while(True):
    time.sleep(5)
    print("gonna connect")
    resp = requests.get('http://google.com',
                    proxies=dict(http='socks5://user:email@example.com:8080',
                                 https='socks5://user:firstname.lastname@example.com:8080'))
    print(resp)
    print("done")
    time.sleep(2)

How can I wire the network of python to go through mitmproxy container?
Answer: In your python code, you'll need to reference the other service.
The proxy URL should be updated to have the right hostname. Which is to say replacing server.com with the name of of the service offering whatever you're trying to connect to.
In this case, you'd replace server.com with mitmproxy.
Meaning your python code would look as such:
import requests
import time

while(True):
    time.sleep(5)
    print("gonna connect")
    resp = requests.get('http://google.com',
                    proxies=dict(http='socks5://user:pass@mitmproxy:8080',
                                 https='socks5://user:pass@mitmproxy:8080'))
    print(resp)
    print("done")
    time.sleep(2)

How to use docker container as a proxy?


attachMovie from loadVariablesNum

Question: I am loading a variable at frame 1with loadVariablesNum("text.txt", 0);. The variable is called dayDate and for this is example the value is 09.
I have a movieClip called d09 in my library that I would like to attach to an empty movieClip (instance name: myLoader) via the variable value.
I can load it the "normal" way like this myLoader.attachMovie("d09", "d09", 1);
But how do I get my variable-value into that statement? I've tried putting in the variable name (like myLoader.attachMovie("dayDate", "d09", 1);) but it just won't do what I need
Answer: I haven't used AS2 in a while so I'm not sure what those parameters to attachMovie mean. However I believe you'd want to construct the string "d09" like so: "d" + dayDate
So your code would look something like:
myLoader.attachMovie("d" + dayDate, "d09", 1);

(Incidentally, by "the value is 09" I'm guessing you mean datDate is the string "09". If you simply mean the number 9 then you'll have to add in the leading 0.)
Comment: Thanks - but this only worked after I installed a `gotoAndPlay(1)` in frame #2. Why is it that I cannot grab the variable at once?
Comment: Found a "swonking"-method at actionscript.org but the if/else run doesn't work... And I have and idea there are niftyer ways to stop process before the variable has loaded. Tips would be appreciated. Or maybe that's for another question.

attachMovie from loadVariablesNum


Multicolor Multiline TMemo

Question: Is it possible to configure Multicolor Multiline TMemo in Delphi XE2?.
When I am writing codes like :
procedure TForm1.BitBtn1Click(Sender: TObject);
var
  FirstVariable, SecondVariable, ThirdVariable :BOOL;
begin
  if FirstVariable then
    begin
      Memo1.Font.Color := clGreen;
      Memo1.Lines.Add('FirstVariable = True');
    end
  else if SecondVariable then
    begin
      Memo1.Font.Color := clBlue;
      Memo1.Lines.Add('SecondVariable = True');
    end
  else
    begin
      Memo1.Font.Color := clRed;
      Memo1.Lines.Add('ThirdVariable = True');
    end;
end;

font color for all the previously existing lines are getting changed according to condition of the variables.
Comment: Please remove `= true`.
Answer: No, it is not possible. But you can use a RICHEDIT control instead, e.g., the TRichEdit wrapper.
RichEdit1.SelAttributes.Color := clGreen;
RichEdit1.Lines.Add('First line.');

RichEdit1.SelAttributes.Color := clBlue;
RichEdit1.Lines.Add('Second line.');

RichEdit1.SelAttributes.Color := clRed;
RichEdit1.Lines.Add('Third line.');

Comment: I think that technically it is possible (haven't tried) by doing direct drawing to the canvas. However that's way more than is necessary, a rich edit is meant for this.

Multicolor Multiline TMemo


Como criar um método de soma em que o resultado apareça no campo edit text

Question: Estou criando uma aplicação e gostaria que o resultado da operação preço de custo mais percentual de lucro aparecesse no resultado preço de venda sendo que este último não poderá ser editado no momento de salvar os dados. Peço que sejam o mais específicos possíveis pois não tenho muita experiência. Obrigado.

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.os.Bundle;
 import android.text.Editable;
 import android.text.TextWatcher;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.Toast;
 import br.gestaoBd.BancoDeDados.ProdutoDao;
 import br.gestaoBd.Beans.Produto;

 public class CadProdutos extends Activity {

private ImageView imgView = null;
static final int SALVAR = 0, EXCLUIR = 1, LIMPAR = 2;
EditText edId, edDescricao, edPrecoDeCusto, edPercDeLucro, edPrecoDeVenda;
ProdutoDao prodDao;
Produto produto;
ImageView imgFoto;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.cad_produtos);
    edId = (EditText) findViewById(R.id.cadEdId);
    edDescricao = (EditText) findViewById(R.id.cadEdDescricao);
    edPrecoDeCusto = (EditText) findViewById(R.id.cadEdPrecoDeCusto);
    edPrecoDeCusto.addTextChangedListener(new MonetaryMask(edPrecoDeCusto));
    edPercDeLucro = (EditText) findViewById(R.id.cadEdPercDeLucro);
    edPrecoDeVenda = (EditText) findViewById(R.id.cadEdPrecoDeVenda);
    edPrecoDeVenda.addTextChangedListener(new MonetaryMask(edPrecoDeVenda));

    imgView = (ImageView) findViewById(R.id.imgFoto);

    Produto produtoRecebido = (Produto) getIntent().getSerializableExtra("Produto");
    if (produtoRecebido != null) {
        montaTela(produtoRecebido);
    } else {
        montaTela(new Produto());
    }

    Button btn1Salvar = (Button) findViewById(R.id.btSalvar);
    btn1Salvar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Produto pro = new Produto();
            pro.setId(Integer.valueOf(edId.getText().toString()));
            pro.setDescricao(edDescricao.getText().toString());
            pro.setPrecoDeCusto(MonetaryMask.stringMonetarioToDouble(edPrecoDeCusto.getText().toString()));
            pro.setPercDeLucro(Double.valueOf(edPercDeLucro.getText().toString()));
            pro.setPrecoDeVenda(MonetaryMask.stringMonetarioToDouble(edPrecoDeVenda.getText().toString()));

            if (pro.getId() > 0) {
                getProDao().alterar(pro);
            } else {
                getProDao().inserirProduto(pro);
            }
            ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                    ToastManager.INFORMATION);

        }
    });

    Button btnLimpar = (Button) findViewById(R.id.btLimpar);

    btnLimpar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            montaTela(new Produto());
        }
    });

    Button bt2Excluir = (Button) findViewById(R.id.bt2Excluir);
    bt2Excluir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final Produto pro = new Produto();
            pro.setId(Integer.valueOf(edId.getText().toString()));
            pro.setDescricao(edDescricao.getText().toString());
            pro.setPrecoDeCusto(Double.valueOf(edPrecoDeCusto.getText().toString()));
            pro.setPercDeLucro(Double.valueOf(edPercDeLucro.getText().toString()));
            pro.setPrecoDeVenda(Double.valueOf(edPrecoDeVenda.getText().toString()));

            AlertDialog.Builder builder = new AlertDialog.Builder(CadProdutos.this);
            builder.setTitle("Deseja Excluir?");
            builder.setMessage("O produto será deletado!");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    getProDao().excluir(pro);
                    montaTela(new Produto());
                    ToastManager.show(getBaseContext(), "Produto Excluído",
                            ToastManager.INFORMATION);

                }

            });

            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(CadProdutos.this, "Cancelado", Toast.LENGTH_LONG).show();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });
}

private void montaTela(Produto produto) {
    edId.setText(String.valueOf(produto.getId()));
    edDescricao.setText(produto.getDescricao());
    edPrecoDeCusto.setText(String.valueOf(produto.getPrecoDeCusto()));
    edPercDeLucro.setText(String.valueOf(produto.getPercDeLucro()));
    edPrecoDeVenda.setText(String.valueOf(produto.getPrecoDeVenda()));

}

public ProdutoDao getProDao() {
    if (prodDao == null) {
        prodDao = new ProdutoDao();
    }
    return prodDao;
}

public void tirarFoto(View view) {
    Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(i, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (data != null) {
        Bundle bundle = data.getExtras();

        if (bundle != null) {

            Bitmap bitmap = (Bitmap) bundle.get("data");

            imgView.setImageBitmap(bitmap);
        }
    }
  }
  }

Comment: Procure por TextWatcher.
Comment: Esse método seria chamado pelo *click* num botão ou de forma automática ao preencher os outros campos?
Comment: @ramaral A ideia era fazer automático ao preencher os campos..
Answer: Como você utiliza o TextWatcher para aplicar a máscara, sugiro utilizar o View.OnFocusChangeListener
Problema: Ele só irá funcionar quando o usuário tirar o foco de um dos campos!
Exemplo de implementação:
OnFocusChangeListener focusListener = new View.OnFocusChangeListener() {

    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus)
        {
        // Aqui você pega os valores dos campos, realiza a soma e adiciona no no outro campo
        }
    }
};

edPrecoDeCusto.setOnFocusChangeListener(focusListener);
edPrecoDeCusto.setOnFocusChangeListener(focusListener);

Observação: Não vou entrar no mérito do cálculo, apenas mostrar como se implementa o OnFocusChangeListener!


struggling to understand code written for me by my tutor, for arknoid/brickbreaker collision detection

Question: I asked a third year student to help me detect collisions for the game, I've tried understanding the order but the last 20 or so lines don't make much sense to me, would anyone by willing to make it a bit more cleaner?
Specifically I need to understand what the code means from the keyword "Where". Any improvements that can be made to the code would be appreciated.
UIElement upDownBlock = MyGrid.Children.Cast<Rectangle>().Where(i => (Grid.GetRow(i) == ballRow + vely) && (Grid.GetColumn(i) == ballColumn)).FirstOrDefault();
if (upDownBlock != null)
{
    vely = -vely;
    MyGrid.Children.Remove(upDownBlock);
}
UIElement leftRightBlock = MyGrid.Children.Cast<Rectangle>().Where(i => (Grid.GetColumn(i) == ballColumn + velx) && (Grid.GetRow(i) == ballRow)).FirstOrDefault();
if (leftRightBlock != null)
{
    velx = -velx;
    MyGrid.Children.Remove(leftRightBlock);
}

any sort of help would be appreciated, game was created on a grid
Comment: What specifically do you need help understanding?
Comment: The UIElement conditions mainly, need to specifically understand what the code means from the keyword "where" and improvements that can be made on the code would be appreciated
Comment: You need to study up on LINQ. And your mentor needs to study good naming conventions. Basically the code in the where clause is run against the various list of rectangles, the code in th where clause validates to either true or false and the first rectangle that matches is returned, if none match a null is returned.
Comment: Theory aspect is focused on in our second year this year was purely basics and introduction. The description you gave out helped out a lot!!! everything now makes sense, thank you!
Answer: As I said in my comment, you need to learn linq and your mentor needs to use better naming.  Does this seem more understandable?
Rectangle upDownBlock = MyGrid.Children.Cast<Rectangle>()
                          .Where(rect => (Grid.GetRow(rect) == ballRow + vely) &&
                                         (Grid.GetColumn(rect) == ballColumn))
                         .FirstOrDefault();
if (upDownBlock != null)
{
    vely = -vely;
    MyGrid.Children.Remove((UIElement)upDownBlock);
}

Basically the code in the Where clause is run against the various lists of rectangles, it evaluates to either true or false and the first rectangle that matches (evaluates to true) is returned.
An improvement would be to replace the "Where" with "FirstOrDefault" in the various assignments. This does not increase performance as you might expect, lazy evaluation means that the Where clause only evaluates the items requested, and FirstOrDefault will stop asking it to evaluate items when it finds its first match.  But it makes it clearer earlier that you don't care about the whole list of rectangles, just the first one to match your criteria aka predicate.
Comment: @Sihle: for your future reference when you are the mentor. On the job working code barely trumps readable code, for tutoring the reverse is true. It's better to have readable code that is slightly wrong than unreadable code that is absolutely correct. Pseudo code doesn't even pretend to work, but it can show what needs to be done.
Comment: way better, I'll work LINQ as soon as possible, appreciate the help
Comment: I'll start putting that to practice now since this is only my first year, I now know what's it like for the other person to read unreadable code


Markov Chains for Hospital Stays

Question: Suppose I have the following problem:

Suppose you access to the hospital records: you have the history about how different patients passed through the different "stages" of the hospital (each row represents a unique patient).
A patient can enter the hospital, and then meets the triage nurse. From there, they are sent to an examination room. If the condition is not serious, they are discharged from the hospital. If the condition is serious, they are sent to a proper hospital ward where they are kept there until they are discharged. However, if the patient enters the hospital in a very serious condition, then they are immediately sent to a ward and then discharged.
I think that this problem can be modelled as a Markov Chain - either as a discrete time Markov Chain or as a continuous time Markov Chain. Using the available data, you can build a transition matrix which will describe the probabilities from moving between "states" (i.e. "stages") in the hospital. Once you have built the Markov Chain, you can calculate the probability the patient is in any of these "states" on the "n-th" day that they have entered the hospital.
I am interested in something slightly different: When you look at this data, naturally you will see that the hospital does not admit only one patient at a time and then accept the second patient after the first patient has been discharged (i.e. dedicate the hospital to serving one patient at a time) - this would be crazy. Naturally, the hospital serves many patients - there are times when more patients might be transitioning between certain "states", and other times when fewer patients are transitioning between other "states". Naturally, the hospital can be more or less busy, and this will ultimately affect the "speed" at which patients will pass through the different "stages".
Question: Can a Markov Chain be built in such a way that the transition probabilities are contingent on how many patients are in the hospital, how many patients are in each state and the rate at which they are transitioning?
For instance, when a new patient arrives, the analysis could say: seeing as they are currently 100 patients in the hospital, 20 patients are waiting to see the triage nurse and 50 are in the exam room - the Markov Chain estimates you will have to wait approximately  10 hours before you might have your own room in the hospital ward?
Is something like this possible? Would this require survival analysis methods?
Answer: I wouldn't make too much of a distinction between Markov models and survival models. Survival analysis models times to events as functions of covariates and times. In a multi-state survival model, the events are transitions to different states. A Markov chain imposes a lack of memory about states prior to the current one. Whether that lack of memory holds in your situation depends on your understanding of the subject matter.
The situation you describe seems to be quite amenable to a multi-state survival model. If you have data on "how many patients are in the hospital, how many patients are in each state and the rate at which they are transitioning," then those can be included in the model. The basic ideas are nicely outlined in the multi-state vignette of the R survival package. The complexity of this particular situation could require the more elaborate tools provided by the msm package, illustrated in its own vignette.

Markov Chains for Hospital Stays


Prevent root in linux from changing folder permissions in GPFS filessystem

Question: I have created a NFS export in a GPFS/SpectrumScale filesystem I created.  I have enabled AD based authentication with our domain.  Everything works.  The NFS export was created with NFS4.
The NFS export is mounted on some linux VMs.  The problem is that when a user runs sudo they can access all the folders and change permissions on files/folders regardless of what the ACL allows.
Is there a way to prevent root from overriding the ACL?
In GPFS I set the NFS export with ROOT_SQUASH thinking that would do it but I am still able to change permissions when I sudo with a test account that does not have domain admin rights.
Answer: Well, technically, if you do not enforce stronger security, then NFS by default will use auth_sys, where client simply tells NFS server which UID and GID to use, IOW no security. The best way to solve this issue is to export with sec=krb5 and enforce RPCSEC_GSS. You already have AD, which is kerberos server with LDAP. Check this link to see how to configure client and servers
Answer: It appears that ROOT_SQUASH hadn't yet propagated out.  I ran the following command a bit later and saw ROOT_SQUASH in the results:
mmnfs export list --nfsdefs /comp/zixf401/NFS

I then logged out of the Linux VM I was testing the NFS mount on and logged back in.  After running the sudo su command and then attempting to chmod 770 one of the folders in the NFS mount, I received a not permitted message as I had hoped for.


Fill the array in Matlab Script, only in one column

Question: How can I fill the array with values that user gave me, in one column need be from smaller to higher number, and in the second column need be from higher to smaller. Than display it. It needs looks like this for example:
tab
1 3
2 2
3 1
clear all;
close all;
a = input('give a value ');
n = input('give n value ');
for (x=1:n-a)
tab = ;
end

I really don't idea how to do this, can someone help?
Answer: Following your input statements, try something like this:
tab = [a:n; n:-1:a].';

Say n=3 and a=1, then you get the array you show in your question. For n=5 and a=2, you get what your comment requests.
Comment: Thank U! But almost, this need be that value between 2 and 5, for example
2 3 4 5 and other one 5 4 3 2   (dont know why i cannot put this vertical in answers)


Disable password age policy for admin on Windows Server

Question: By default on my SBS08, the Maximum password age is set to 1year.
I'd like to disable this particular parameter for Domain Admin, not the entire policy (Default Domain Policy).
Is that possible ?
Thanks.
Comment: Sounds like a really bad idea... I'm guessing you're using the domain admin account for services (which you should be creating service accounts for), or just don't want to ever change the most important password in your whole network.
Answer: This is how to do it: http://technet.microsoft.com/en-us/library/cc770842(WS.10).aspx
Comment: Or for those that don't follow links, that's linking to the step-by-step guide to Fine Grained Password Policies in AD. It is EXACTLY how you set password policies domain-wide, and still exempt your admin/utility users. Beats the pants off of the old way.


How do I execute this SQL query

Question: I'm trying to execute the following :
db_query('SELECT FROM_UNIXTIME(`created`, "%Y") as year, FROM_UNIXTIME(`created`, "%m") as month, FROM_UNIXTIME(`created`, "%d") as day FROM users ORDER BY `created`');

And because of the % sign the result is :
PDOException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '%Y' in 'field list'
I tried escaping the % with a double %% resulting in : PDOException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '%%Y' in 'field list'
Of course this query works in phpmyadmin
Help ?
Answer: PDO requires that you use single quotes, e.g.
db_query("SELECT FROM_UNIXTIME(`created`, '%Y') as year, FROM_UNIXTIME(`created`, '%m') as month, FROM_UNIXTIME(`created`, '%d') as day FROM users ORDER BY `created`");

Comment: it is waaay to early in the morning for fielding questions i guess :D

How do I execute this SQL query


Run batch as Admin (auto-elevate) and then de-elevate

Question: I have a script that runs in 2 parts. The first part requires admin access (updates HOSTS file and does some copying/overwriting). After that part finishes, I need to map a drive using the hostname alias the first part of the script updated.
I have figured out how to get the elevated privileges by using this SO Question. But mapping a drive (while in admin) maps a drive into the admin's session. I need to "de-elevate" back into user mode to run my second script.
This is a script I run at least once every day, and possibly multiple times per day. I am trying to create a solution that is just 1 .bat file, if possible. For reasons, the scripts are written in perl.
Things I have tried:

Using the runas /user:regular_user command (this does not work)
1 bat file Using CALL for the 2 batch files (This "works" but for some reason both run at the same time)
Running 2 bat files separately, and manually.
Searching SO, but I could not find admin->user instead only user->admin

TLDR: How do I de-elevate to user mode from admin mode in a batch file?
Answer: Your best bet is to use the best third party remote/local execution tool : Windows Sysinternals PSEXEC. You can supply credentials and accomplish what you need using PSEXEC! You can put PSEXEC commands into your batch file or vbs and have them run without a hitch. You can also call one command with PSEXEC elevated permission and the next without any elevation, while mixing credentials in a single unique batch file.
http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
Comment: Cool, this sounds promising. Thanks.
Answer: If you're using 2 batch files, call the batch ElevatedBatch.cmd with elevation by using Main.cmd (which continues doing unelevated things):
@ECHO OFF
START /WAIT ElevatedBatch.cmd %1 %2 %3 %4 %5 %6 %7 %8 %9
REM here you can do unelevated stuff:
ECHO Running unelevated now

The parameter /WAIT ensures that the script will wait until ElevatedBatch.cmd has ended. For ElevatedBatch.cmd  you can use a template like this one to elevate it.
Answer: Do first the non-elevated part, then elevate and continue.
Comment: I'm not sure if that's possible in the OP's scenario. OP says that he needs to update HOSTS file first, and then use new aliases to do the second part.


R.Java error - Android Developer Studio -Eclipse-

Question: I have a nasty problem with R.Java in Eclipse, when trying to add new images to a newly created folder on my Res (drawable). what could be the problem ? Nothing happens after cleaning the project...
Comment: could you post you error log?
Comment: Check this: http://stackoverflow.com/questions/885009/r-cannot-be-resolved-android-error it contains a lot of possible problems
Comment: post the logcat error or the error you are facing ?
Answer: Maybe you are using non-compliant names for your resources (like file with uppercase letters).
Please read the Android naming conventions.
Answer: Make sure the image you copy have all letters in the filename as smallcase . This could be one issue. File name: must contain only [a-z0-9_.]
Answer: I had faced many times same problem.
try the below steps. it could help you.
In Eclipse
 1. Enable Problems view by clicking,
Windows->ShowView->Problems
check the problem and solve.
 2. Remove R.java from gen folder of your eclipse try to build it again.
 3. Check for Import R in your project. sometime eclipse imports android.R instead of yourclassname.R
 4. Check for your XML file where sometimes id will not generate if you add it manually in xml file.
 5. Reopen the project.
Hope it helps.


how to collect items of a set which are the multiplication of another set

Question: I have stuck this problem: "Your function receives two sets of Int. Return a new set of elements in the first set that are multiples of the size of the second set."
It is from Hyperskill, and the code I created is not accepted although it correctly ran in IntelliJ. What can be the problem?
fun solution(first: Set<Int>, second: Set<Int>): Set<Int> {
    val tempSet = mutableSetOf<Int>()
    var finalSet = emptySet<Int>()
    var isDiv = false
    for (f in first) {
        for (s in second) {
            if(f % s == 0){
                isDiv = true
                if(s == second.last()){
                    tempSet.add(f)
                }
            } else { break }
        }
        isDiv = false
    }
    finalSet = tempSet
    return finalSet
}

Comment: It says "Wrong answer" but when you test it locally "it seems to work fine". That sounds as if you had misunderstood the requirements.
Comment: "elements in the first set that are multiples of the size of the second set." I don't see you checking the _size_ of the second set.
Comment: Also: "the code I created is not accepted" - what do you mean by "not accepted"? It failed to compile? It gave the wrong results? It ran too slowly? Please be more precise in your questions.
Comment: This is a good exercise that reminds you that when you are given a task, you need to pay proper attention to the wording. This is important in interview situations and at work. This exercise caught you out because you assumed the elements of the second set were important, but in fact you only need to know its size (so in a workplace situation, you might ask why don't we just pass an integer to the function instead).
Comment: Hyperskill has its own IDE where you can put your code and can check if it is ok. It gives a feedback of "Failed test #2 of 3. Wrong answer". But when I copy the code to my IDE, it  seems to work fine.
Comment: The question asks for multiples of the size of the second set, not multiples of elements from the second set. Your code looks at elements of the second set and not the size. Also, what's the point of your `finalSet` variable?
Comment: Thanks for helping, I misunderstood the question. I reconsidered it and Joffrey was right. Thanks again.
Answer: Going off of what the wording is, Values from the first set that are multiples of the Size of the second set it could be done like this?
Note: None of this has been tested***
fun solution(first: Set<Int>, secondSize: Int): Set<Int> {
    val mResult = mutableSetOf<Int>()
    // Loop through first set, checking if they are
    // multiples of second sets Size
    first.forEach { value ->
        if (value % secondSize == 0) {
            mResult.add(value)
        }
    }

    // Return the resulting set
    return mResult
}

Or, if you need to see if a value at each index is a multiple of any value within the second set like you're code is currently you can do it this way
fun solution(first: Set<Int>, second: Set<Int>): Set<Int> {
    val mResult = mutableSetOf<Int>()
    // Loop through first set
    first.forEach { value ->
        // Loop through second, checking each value against the value from first,
        // also check if resulting set already contains said value so we don't
        // end up with multiples of the same value
        second.ForEach {
            If (value % it == 0 && !mResult.contains(it)) {
                mResult.add(value)
            }
        }
    }

    // Return the resulting set
    return mResult
}

I typed this up on a phone so double check for typos. In case you're unfamiliar and for anyone else who may not know, kotlin has some nifty things you can take advantage of. I prefer to use .forEach when possible, it saves some typing and is way easier to read when you're looking back through code. If you ever need to know the index of the loop, you can use .forEachIndexed but this isn't available for everything. And you'll need to specify the name for the index and value like this:
mSomeList.forEachIndexed { index, value ->
    // Do something with index and value
}

Using mResult.contains(it) returns true if the list contains that value, seems clear enough. But adding a ! At the begining will basically make it return the opposite. This is the same concept as == and !=.


Definition of partial correlation

Question: Here (page 415) https://www.stat.cmu.edu/~larry/=sml/DAGs.pdf I found this definition:

which confuses me. I am used to see $E[*|Z]$ as a ($Z$-measurable) random variable and as far as I know the partial correlation is a deterministic scalar, as I understand from the Wikipedia article from example:
https://en.wikipedia.org/wiki/Partial_correlation
What is the meaning intended by the author ? Is this definition intended to be the same used by Wikipedia? (the text in the definition would suggest so...)
( in order to simplify things, let's consider X, Y and Z scalars for the moment )
Comment: @ttnphns The definition above in the original post is in the context of jointly normal $(X,Y,Z)$ and not in general (as I found in the linked document). In this special case, these are all formal conditional expectations and variances and the 'conditional correlation' between $X$ and $Y$, given $Z$, equals the usual partial correlation. This is what I understood anyway.
Comment: If $\rho_{X,Y\mid Z=z}$ is meaningful (possibly changing with $z$, i.e. a function of $z$) then $\rho_{X,Y\mid Z}$ is also meaningful (a function of $Z$).
Comment: Correlation does not have to be a scaler.  There are *[correlation matrices](https://en.wikipedia.org/wiki/Correlation#Correlation_matrices)* if $X$ and $Y$ are vectors.  But this is unaffected by whether $Z$ is a scalar or not
Comment: Thanks @Henry .  I updated my question. In the definition of Wikipedia for my understanding the partial correlation is a deterministic scalar if X, Y and Z are scalars r.v.. Let's consider this simple case for the moment. But E[X|Z] in this case is a scalar r.v. and not a deterministic scalar for my notation... I cannot reconcile these definitions at the moment...
Comment: $E[X\mid Z]$ is presumably a function of $Z$.  So if $Z$ is a random variable, then so too is  $E[X\mid Z]$
Comment: Exactly also up to my understanding E(X|Z) is a Z measurable r.v., therefore a function of Z. But this contradicts the definition of wikipedia (?)
Comment: The numerator is simply the formula of covariance between the residuals: residuals from regressing X by Z (expressed as "X|Z") and residuals from regressing Y by Z (expressed as "Y|Z").
Comment: @ttnphns Thanks, as you say "expressed as X|Z". Do you find that notation standard/statistically correct and compatible with https://en.wikipedia.org/wiki/Conditional_expectation ?
Comment: Well, I don't think about how much it is standard. But it is conceivable. Residuals or, more strictly speaking, errors, are a random variable which is left of r.v. X after conditioning it on r.v. Z. "Given" Z (i.e. letting X' to be the predicted X, aka "image of Z within X"), what is left of specifically X in X? It is the errors. Here, the notation expresses not the conditional expectation, but conditional variation.
Comment: @ttnphns your reasonings make sense. So what they do is borrowing the symbol to imply an other meaning. What is the definition of "conditional variation" ? Does it have a definition or is a loosely/unofficially defined term ?
Comment: It is transparent. r.v. = expectation + variation (about it). Only add word "conditional" which in our context means (knowing value of another r.v., which correlates with our r.v.).
Comment: I see but than in this case E(XY|Z) would suggest to regress XY over Z and take the expectation tof the residuals? ( sounds strange since in the standard definition we only regress X and Y over  Z  but not their product ...)
Comment: See the series of equivalent formulas of Covariance between X an Y in wikipedia.You'll find the product XY there. In our case, our variables, per notation chosen by the authors of the book, are X|Z and Y|Z, rather than X and Y.
Comment: Yes of course. Now that I am thinking E(X|Z) in this interpretation would be zero, because after a linear regression the sum of the residuals is zero. Further, I would than use the notation E((X|Z)(Y|Z)), if X|Z were used to indicate the residuals after regression. Anyway thanks for your contribution which probably goes very close to what the author had in mind, even if I still have to get it 100%...
Answer: Suppose you have a random vector $\boldsymbol X=(X_1,X_2,\ldots,X_p)$.
Consider the linear regression models
$$X_1=X_{1\cdot 34\ldots p}+ \varepsilon_{1\cdot 34\ldots p}$$
and
$$X_2=X_{2\cdot 34\ldots p}+ \varepsilon_{2\cdot 34\ldots p}$$
Here $X_{i\cdot 34\ldots p}$ is the part of $X_i$ explained by $(X_3,\ldots,X_p)$ and $\varepsilon_{i\cdot 34\ldots p}$ is the unexplained error, $i=1,2$. Unknown parameters in $X_{i\cdot 34\ldots p}$ are found subject to minimization of $E(\varepsilon_{i\cdot 34\ldots p}^2)$.
If $e_{i.34\ldots p}$ are the residuals corresponding to the models above, the (population) partial correlation between $X_1$ and $X_2$, eliminating the linear effect of $X_3,\ldots,X_p$, is defined to be
$$\rho_{12\cdot 34\ldots p}=\operatorname{Corr}(e_{1.34\ldots p},e_{2.34\ldots p}) $$
For some distributions like the multivariate normal, this correlation coincides with the correlation between $X_1$ and $X_2$, conditioned on $X_3,\ldots,X_p$. In fact, your linked document does assume multivariate normality of $\boldsymbol X$. To quote Wikipedia, "The partial correlation coincides with the conditional correlation if the random variables are jointly distributed as the multivariate normal, other elliptical, multivariate hypergeometric, multivariate negative hypergeometric, multinomial or Dirichlet distribution, but not in general otherwise."
Hence in these specific situations only, one can say
$$
\rho_{12\cdot 34\ldots p}=\rho_{(X_1,X_2)\mid X_3,\ldots,X_p}=\operatorname{Corr}((X_1,X_2) \mid X_3,\ldots,X_p) \tag{$\star$}
$$
When $\boldsymbol X$ is multivariate normal, this conditional correlation (i.e. the conditional covariance and the conditional variances) does not depend on $X_3,\ldots,X_p$. Note that  the conditional distribution of $(X_1,X_2)$ given $X_3,\ldots,X_p$ is bivariate normal. And you can see here that the dispersion matrix of this conditional distribution is free of $X_3,\ldots,X_p$ (hence non-random). Hence in this case, there is no ambiguity in the formula in your post.
The partial correlation is of course a scalar by definition. In fact, it is entirely based on the entries of the correlation matrix (or equivalently, the dispersion matrix) of $\boldsymbol X$.
Specifically, if $R=((\rho_{ij}))$ is the correlation matrix of $\boldsymbol X$, one can show that
$$\rho_{12\cdot 34\ldots p}=-\frac{R_{12}}{\sqrt{R_{11}}\sqrt{R_{22}}}\,,$$
where $R_{ij}$ is the cofactor of $\rho_{ij}$.
For $p=3$ (say), this reduces to
$$\rho_{12\cdot 3}=\frac{\rho_{12}-\rho_{13}\rho_{23}}{\sqrt{1-\rho_{13}^2}\sqrt{1-\rho_{23}^2}}$$
Related: Derivation of the formula for partial correlation coefficient of second order.
Comment: Thank you (+1). You say: "This is also sometimes called the correlation between X1 and X2, keeping X3,…,Xp 'fixed'". Isn't it better said that it is the correlation between X1 and X2 when subtracting from both X1 and X2 the part that can be predicted from  "X3,…,Xp" ? What sense does it have to say that "X3,…,Xp" are "fixed" ? (they vary no?)
Comment: I am not following here: "I can see (⋆) as a formal notation only if the entries of the dispersion matrix of the conditional distribution of (X1,X2) given X3,…,Xp are constants." "constants" with respect to what? You mean when the conditional distribution of (X1,X2) does not depend on the values of "X3,…,Xp"? (i.e. when (X1,X2) is independent of "X3,…,Xp"?)
Comment: I only mean when the conditional variances and conditional covariance (entries of the conditional dispersion matrix) do not depend on $X_3,\ldots,X_p$. Regarding your first comment, you are right and by 'fixed' I mean we are conditioning on them.
Comment: Ok so this would mean that in these cases $E[XY|Z]-E[X|Z]E[Y|Z]=E[(X-E[X|Z])(Y-E[Y|Z])|Z]$ does not depend on Z in conclusion? This is interesting (or should it be trivial?), and is exactly the numerator of the formula of my original post. But at least Var(X|Z) (in the denominator) will depend on Z also in the Gaussian case, or not?
Comment: Ah no maybe what does not depend on Z will be all the original formula with denominators included (so the correlation, not the covariance), as you wrote in your post...
Comment: @Thomas Neither $E[XY\mid Z]-E[X\mid Z]E[Y\mid Z]=\operatorname{Cov}((X,Y)\mid Z)$ (the "conditional covariance") nor the conditional variances in the denominator depend on $Z$ when $(X,Y,Z)$ is jointly normal. So in the normal case, the formula in your post is correct. I would try to clarify in an edit later.
Comment: Perfect thanks!

Definition of partial correlation


R studio time difference in mm/dd/yy hh:mm format

Question: I have tried many commands to find the time duration from all related commands considering the POSTX format, etc. however Rstudio keeps on outputting error messages. The examples state that a "-" works.
For example I have the two columns in a data frame.
And tried to find the time duration, with  commands such as.
image of code and output from parsed time
And calculating from the original data frame
image of code and output from original data frame
> dput(file1[, c("V8", "V9")])

structure(list(V8 = structure(1:19, .Label = c("4/6/2018 14:39",
"4/6/2018 15:04", "4/6/2018 15:09", "4/6/2018 15:28", "4/6/2018 15:56",
"4/6/2018 16:02", "4/6/2018 16:07", "4/6/2018 16:10", "4/6/2018 16:11",
"4/6/2018 16:27", "4/6/2018 16:41", "4/6/2018 16:43", "4/6/2018 16:57",
"4/6/2018 17:13", "4/6/2018 17:17", "4/6/2018 17:30", "4/6/2018 17:38",
"4/6/2018 17:47", "4/6/2018 17:52"), class = "factor"), V9 = structure(c(1L,
3L, 2L, 4L, 8L, 5L, 6L, 9L, 7L, 12L, 19L, 16L, 11L, 13L, 10L,
14L, 17L, 18L, 15L), .Label = c("4/6/2018 15:00", "4/6/2018 15:26",
"4/6/2018 15:32", "4/6/2018 16:01", "4/6/2018 16:10", "4/6/2018 16:12",
"4/6/2018 16:18", "4/6/2018 16:35", "4/6/2018 16:46", "4/6/2018 17:24",
"4/6/2018 17:37", "4/6/2018 17:38", "4/6/2018 17:46", "4/6/2018 18:24",
"4/6/2018 18:46", "4/6/2018 19:21", "4/6/2018 20:14", "4/6/2018 20:35",
"4/6/2018 21:44"), class = "factor")), .Names = c("V8", "V9"), class = "data.frame", row.names = c(NA,
-19L))

Comment: Please share some sample data. Don't post screenshots, use e.g. `dput`.
Comment: Can you post sample data? Please edit the question with the output of `dput(file1[, c("V8", "V9")])`.
Answer: Notice those two variables are factors, not dates (or even characters/strings).  Convert them to strings, and then to date-times.
ds$V8 <- strptime(as.character(ds$V8), format="%m/%d/%Y %H:%M")
ds$V9 <- strptime(as.character(ds$V9), format="%m/%d/%Y %H:%M")
difftime(ds$V9,  ds$V8, units="secs")

Result:
Time differences in secs
 [1]  1260  1680  1020  1980  2340   480   300  2160   420  4260 18180  9480
[13]  2400  1980   420  3240  9360 10080  3240

Note, thanks for following @Maurits Evers's and @Rui Barradas's advice and using dput().  Ideally those error messages are also represented as text, and not screenshots.


Easy way to "simulate" a drag-and-drop using JQuery?

Question: I have a web page that allows the user to drag elements into a droppable div. I'm using JQuery UI Draggable and Droppable. I would like to add the functionality that if you double-click on one of the draggable elements, it "simulates" a drag-and-drop of that element - i.e. it drags the element across the screen and drops it on the droppable div. This way the user has the option to drag and drop, or simply to double click. Is there any way to implement this easily? (If it's too much of a hassle I will probably just code the double click to execute the code and then pop up an alert that it was done.)
Answer: It is hard to develop something to you without piece of code, but here is an idea:
You could use .animate() function fired by your element "doubleclick" event to move your draggable elemtent to the drop zone.
Calculate target position should not be hard using .offset() functionalities.
Then, use the .animate() callback to execute the drop action.
Answer: I found a similar question here: jQuery: How Do I simulate Drag and Drop in Code?
and I solved using the solution proposed by Patrick McElhaney:
<code>    $(".mainpanel").droppable({
        drop: function (event, ui) {
            onDragAndDrop($(ui.draggable), $(event.target));
        }
    });

    button.dblclick(function () {
        onDragAndDrop($(this), $(".mainpanel"));
    });

    function onDragAndDrop(dragged, droppable) {
        // ...
    }
</code>


Localization events and messages in identityserver 3

Question: I am looking at options to localise events and error messages in. One option I found is IdentityServer3.Localization package. But I could not get details on how to bind this with Ids 3. Where should I keep the resource strings?
Answer: There is a ILocalizationService that you can implement and register in the DI system. Here are the docs: https://identityserver.github.io/Documentation/docsv2/advanced/localization.html. This is used for localizing all translatable strings.
If you want to localize the views, then that must be done via a custom view service: https://identityserver.github.io/Documentation/docsv2/advanced/customizingViews.html
Comment: is it possible to supply resource files as part of the host, like the way we can supply custom views in templates folder?
Comment: Updated the answer to add some info about views.
Comment: My implementation of ILocalizationService takes language locale. I need to inject instance of this service on each request.   var localizationService = new GlobalizedLocalizationService(new LocaleOptions { Locale = "cs-CZ" });
                options.Factory.LocalizationService = new Registration(resolver => localizationService); Where do i need to do this? Doing this on startup will always inject the same language
Comment: You can register a delegate in the DI system in IdSvr. Inside this delegate you can resolve the current OWIN environment service, from which you can build an OwinContext to understand the current request so you can generate the correct localization service to return. We have an example of that somewhere in our samples -- prolly the DI one.
Comment: I was not successful in doing this as I could not find a good example. Trying my luck with other folks who are having the same problem here : https://github.com/johnkors/IdentityServer3.Contrib.Localization/issues/50
Comment: Here's a sample, @Shetty.

https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/LocalizedMessages/LocalizedMessages/Startup.cs#L45


Do we have a simpler method for computing $\int_{-\infty}^{\infty} \frac{\ln \left(x^2+ax+b\right)}{1+x^2} d x$, where $b> \frac{a^2}{4} $?

Question: Background
After finding the exact value of the integral in my post, I start to investigate a similar integral
$$I(a):
 =\int_{-\infty}^{\infty} \frac{\ln \left(x^2+ax+b\right)}{1+x^2} d x=\int_{-\infty}^{\infty} \frac{\ln \left[\left(x+\frac{a}{2}\right)^2+\left(b-\frac{a^2}{4}\right)\right] d x}{1+x^2}$$
where $b> \frac{a^2}{4}.$

By Contour integration along the upper semi-circle
Using the fact that $\ln \left(x^2+y^2\right)=2 \operatorname{Re}(\ln (x+y i))$ to reduce the $x^2$ to $x$ and making the branch point of $\ln$ below the real axis, we change the integral into
$$
$$
\begin{aligned}
I(a) & =2 \operatorname{Re} \int_{-\infty}^{\infty} \frac{\ln \left(x+\frac{a}{2}+i \sqrt{b-\frac{a^2}{4}}\right)}{1+x^2} d x \\
& =2 \operatorname{Re}\left[2 \pi i \lim _{z \rightarrow i} \frac{\ln \left(z+\frac{a}{2}+i \sqrt{b-\frac{a^2}{4}}\right)}{z+i}\right] \\
& =2 \operatorname{Re}\left[2 \pi i \frac{\ln \left(i+\frac{a}{2}+i \sqrt{b-\frac{a^2}{4}}\right)}{2 i}\right] \\
& = \pi \ln \left(1+b+\sqrt{4 b^2-a^2}\right)
\end{aligned}
For example,
$$
\begin{aligned}& \int_{-\infty}^{\infty} \frac{\ln \left(x^2+x+\frac{1}{2}   \right)}{1+x^2} d x =\pi \ln \left(\frac{5}{2}\right) \\
& \int_{-\infty}^{\infty} \frac{\ln \left(x^2+x+1\right)}{1+x^2} d x =\pi \ln (2+\sqrt{3})
\end{aligned}
$$
Do we have a simpler method for computing $$\int_{-\infty}^{\infty} \frac{\ln \left(x^2+ax+b\right)}{1+x^2} d x,$$ where $b> \frac{a^2}{4}  $?
Comment: I guess, Feynmann's Technique (Differentiation under integral sign).
Comment: Good suggestion!
Answer: Consider, instead
\begin{align}
 &\int_{-\infty}^{\infty} \frac{\ln (x^2+2x\sqrt b \sin \theta+b)}{x^2+1} \ d x\\
=& \int_{-\infty}^{\infty}\bigg(\ln (x^2+b)+ \int_0^{\theta}\frac{2x\sqrt b \cos t}{x^2+2x\sqrt b \sin t+b} dt\bigg) \frac{dx}{x^2+1}\\
 =& \ 2\pi\ln(1+\sqrt b) -\int_0^{\theta}\frac{2\pi \sqrt b \sin t}{1+2\sqrt b \cos t+b} dt
= \overset{}{\pi}\ln \left(1+b+2\sqrt b \cos\theta\right)
\end{align}
and then set $a=2\sqrt b \sin \theta$ to obtain
\begin{align}
 &\int_{-\infty}^{\infty} \frac{\ln (x^2+ax+b)}{x^2+1} \ d x
= \pi \ln \left(1+b+\sqrt{4 b-a^2}\right)
\end{align}
Comment: Mr @Quanto, can you explain a bit on $…=\ 2\pi\ln(1+\sqrt b) -\int_0^{\theta}\frac{2\pi \sqrt b \sin t}{1+2\sqrt b \cos t+b} dt
= \overset{}{\pi}\ln \left(1+b+2\sqrt b \cos\theta\right)$?
Comment: @Lai $\int_0^{\theta}\frac{-2\pi\sqrt b \sin t}{1+2\sqrt b \cos t+b} dt=\pi \ln(1+2\sqrt b\cos\theta+b)\bigg|_0^{\theta}=\pi\ln\frac{1+2\sqrt b\cos\theta+b}{(1+\sqrt b)^2}
$
Comment: Sorry for misunderstanding!  I understand the last step but do not understand this step:$\int_{-\infty}^{\infty}\bigg(\ln (x^2+b)+ \int_0^{\theta}\frac{2x\sqrt b \cos t}{x^2+2x\sqrt b \sin t+b} dt\bigg) \frac{dx}{x^2+1}\\
 ????= 2\pi\ln(1+\sqrt b) -\int_0^{\theta}\frac{2\pi \sqrt b \sin t}{1+2\sqrt b \cos t+b} dt$
Comment: @Lai - perform partial fractionalization of $\frac x{(x^2+2x\sqrt b \sin t +b)(1+x^2)}$ and then integrate over $x$
Comment: Thank you very much.
Answer: Some thoughts: Can this trick work?
Let $c = \sqrt{b - a^2/4}$. Let
$$I(c) := \int_{-\infty}^{\infty} \frac{\ln \left[\left(x+\frac{a}{2}\right)^2+c^2\right] }{1+x^2}\,\mathrm{d} x.$$
We have
$$I'(c) = \int_{-\infty}^{\infty} \frac{2c}{(1+x^2)\left[\left(x+\frac{a}{2}\right)^2+c^2\right]}\,\mathrm{d} x
= \frac{8(c + 1)\pi}{a^2 + 4c^2 + 8c + 4}. \tag{1}$$
(Note: The antiderivative is an elementary function. )
Clearly, $\pi\ln(a^2 + 4c^2 + 8c + 4)$ is an antiderivative of $\frac{8(c + 1)\pi}{a^2 + 4c^2 + 8c + 4}$.
Thus, we have
$$\int_{-\infty}^{\infty} \frac{\ln \left[\left(x+\frac{a}{2}\right)^2+c^2\right] }{1+x^2}\,\mathrm{d} x = \pi\ln(a^2 + 4c^2 + 8c + 4) + C(a) \tag{2}$$
for some function $C(a)$.
Answer: Here is another method of computing the integral in question. It might not be a "simpler" method as you are asking and the semicircular contour method in your post is great, but I'm just writing this post for fun and for me to learn a new thing or two.
Let the given integral be $I$. Let $\displaystyle f(z)=\frac{\log\left(z^{2}+az+b\right)}{z^{2}+1}.$ Its poles are $i$ and $-i$, and its branch points are $z_1 := \displaystyle-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}$ and $\displaystyle z_2 := -\frac{a}{2}-\frac{i\sqrt{4b-a^{2}}}{2}$. But consider $z_1$ instead of $z_2$ since $z_1$ is the one the contour will enclose. Define $\displaystyle \operatorname{arg}(z-z_1) \in \left(\operatorname{arg}\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right),\operatorname{arg}\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right) + 2\pi\right)$ and $\displaystyle \operatorname{arg}(z-z_2) \in \left(-\operatorname{arg}\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right) - 2\pi,-\operatorname{arg}\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)\right)$.
Even though the branch point $z_1$ can be anywhere above the real axis, here is a visual of the contour with some fixed $a$ and $b$.

By Cauchy's Residue Theorem, we get
$$2\pi i\operatorname{Res}(f(z),z=i) = \left(\int_{-R}^{R} + \int_{\Gamma} + \int_{\lambda_1} + \int_{\gamma} + \int_{\lambda_2}\right)f(z)dz.$$
It can be proved that the integrals over $\Gamma$ and $\gamma$ go to $0$ as $R \to \infty$ and $r \to 0$ (where $r$ is the radius of the little circle). Maybe in the future, I'll write an addendum proving those two statements.
Let $\lambda_1$ be the line segment that travels from the large circular arc $\Gamma$ to the small circular arc $\gamma$, and let $\lambda_2$ be the line segment that travels in the opposite direction. As long as we don't have the case where $a=0$ and $b=1$, we can proceed with the following calculation, whether $z_1$ is in the first quadrant, second quadrant, or on the imaginary axis:
$$
\begin{align}
& \lim_{\lambda_1 \to \Lambda}\int_{\lambda_1} f(z)dz + \lim_{\lambda_2 \to \Lambda}\int_{\lambda_2} f(z)dz \\
=& \lim_{\lambda_1 \to \Lambda}\int_{\lambda_1}\frac{dz}{1+z^2}\left(\log\left|z-z_{1}\right|+\log\left|z-z_{2}\right|+i\operatorname{arg}\left(z-z_{1}\right)+i\operatorname{arg}\left(z-z_{2}\right)\right) \\
&+\lim_{\lambda_2 \to \Lambda}\int_{\lambda_2}\frac{dz}{1+z^2}\left(\log\left|z-z_{1}\right|+\log\left|z-z_{2}\right|+i\operatorname{arg}\left(z-z_{1}\right)+i\operatorname{arg}\left(z-z_{2}\right)\right) \\
=& -\int_{\Lambda}\frac{dz}{1+z^2}\left(\log\left|z-z_{1}\right|+\log\left|z-z_{2}\right|+i\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2} + 2\pi\right)+i\operatorname{arg}\left(z-z_{2}\right)\right) \\
&+\int_{\Lambda}\frac{dz}{1+z^2}\left(\log\left|z-z_{1}\right|+\log\left|z-z_{2}\right|+i\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)+i\operatorname{arg}\left(z-z_{2}\right)\right) \\
=& -2\pi i\int_{z_{1}}^{i\infty}\frac{dz}{1+z^{2}} \\
=& -2\pi i \Big[\arctan(z)\Big]_{z_1}^{i\infty} \\
=& -2\pi i\left(\frac{\pi}{2}-\arctan\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)\right). \\
\end{align}
$$
For the case where $a=0$ and $b=1$, we can refer to this answer.
Next, we can calculate the residue at the simple pole $i$ as follows:
$$2\pi i\operatorname{Res}(f(z),z=i) = 2\pi i \lim_{z\to i} \frac{\left(z-i\right)\log\left(z^{2}+az+b\right)}{\left(z-i\right)\left(z+i\right)} = \pi\log\left(b-1+ai\right).$$
Going back to the keyhole contour, we can take the appropriate limits to make the other contributions go to $0$ and solve for $I$ as follows:
$$
\begin{align}
\pi\log\left(b-1+ai\right) &= I + 0 -2\pi i\left(\frac{\pi}{2}-\arctan\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)\right) + 0 \\
I &= 2\pi i\left(\frac{\pi}{2}-\arctan\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)\right) + \pi\log\left(b-1+ai\right). \\
\end{align}
$$
Taking the real part on both sides yields
$$
\begin{align}
\Re I &= \Re 2\pi i\left(\frac{\pi}{2}-\arctan\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right)\right) + \Re\pi\log\left(b-1+ai\right) \\
&= -\Re 2\pi i\arctan\left(-\frac{a}{2}+\frac{i\sqrt{4b-a^{2}}}{2}\right) + \Re\pi\left(\log\left|b-1+ai\right|+i\operatorname{arg}\left(b-1+ai\right)\right) \\
&= \pi\ln\left(1+b+\sqrt{4b-a^{2}}\right)
\end{align}
$$
where from the second-to-last line to the last line, we make a huge leap of calculations.


CDF of the function of a random variable

Question: I haven't been able to find useful information on this. I was just wondering what would be the distribution of a function of a random variable.
For example, what would be the distribution of the $c\, X^{(1/k)}$ where $c$ is a constant and $X$ is $\sim\text{exp}(1)$?
Thank You
Comment: This looks like routine bookwork. Is this for some class?
Comment: Or are you interested in the general approach to such problems?
Comment: I have given one simple approach that works on the example problem.
Answer: We can find the cdf of invertible transformations of r.v.s using elementary methods:
Assume for the moment that $g$ is a monotonic increasing transformation (monotonic decreasing can be handled similarly if you take care about the direction of the inequality; non-invertible transformations need to be dealt with more carefully, generally by splitting the transformation up into invertible sections)
Let $Y=g(X)$
$F_Y(y)= P(Y\leq y) = P(g(X)\leq y) = P(X\leq g^{-1}(y)) = F_X( g^{-1}(y))$
If you also need the density, you can take the derivative.
If you follow this through on your example, you get a well known cdf and density
There's also a formula for calculating the density more directly (which you can derive from the above argument), but you don't really need it here.


Is there any objective evidence that different keys "feel different" or have different moods?

Question: In an advertisement in YouTube for composer Danny Elfman's master class viewable here the composer says:

When somebody starts talking about "this should be in such and such a key because such a key feels that way", that's bulls--t. You can turn any key into anything you want.

This is something that I've long suspected, and hearing someone who's recognized as "good at" intuiting how music sounds to the general public carries at least some weight.
Question: Has anyone put this to the test in some objective way? Is there any objective evidence that different keys "feel different" or can impart different moods or feelings?
I suppose subjects would have to be sorted in to those with and without perfect pitch to check for subconscious bias; if you definitely know what key a passage is in, you may potentially be influenced by that knowledge.
note: A test of this is also challenging because as a passage played on various instruments or voices is transposed through its register the sound will change slowly, so a test for a key-dependent effect might compare nearby keys in order to minimize those effects.
Comment: iI's better to accompany down votes with a bit of advice one how the question might be improved.
Comment: On the one hand, this related question - https://music.stackexchange.com/questions/93292/why-do-i-hear-characters-to-keys-in-equal-temperament - implies that different keys evoke so many different emotions as to may as well not "feel different" on average at all. On the other hand, different instruments have very different ranges, and that will likely contribute to any differences in "feel" keys have.
Comment: Another related question: [Psychology Of Key Preferences](https://music.stackexchange.com/questions/78628/psychology-of-key-preferences)
Comment: I believe that the current way that pianos are tuned, while aiming to approximate equal temperament, is not literally equal temperament... since, in part, the tuner listens for the "beats" between strings (which would lead to some sort of absolute temperament)... but/and makes compromises, to move toward equal temperament. :)
Comment: @uhoh, yes, someone could ask what piano tuners actually do. There might be more than one approach! But I do vaguely recall some amazing explanations from a trust-worthy piano tuner from decades ago... Overwhelming...
Comment: @paulgarrett Interesting! Well certainly there are procedures for tuning pianos that involve beat counting that can provide equal temperament (I'd read up on it when for three weeks 50 years ago my answer to "what do you want to do when you grow up?" was "piano tuner"; but I don't know how many tuners are actually counting beats. I wonder if tuners use a combination of "perfect pitch" and "perfect beats"? :-) I think this has the makings of a good Music SE question somehow if it's not been addressed before already.
Comment: @paulgarrett hmm... now I'm starting to perhaps understand your point; if pianos consistently deviate slightly from equal temperament, then that could be one way that they would "sound different", apart from the absolute shift in registry. Yes I see.
Answer: There are other questions here that have dealt with this topic.  Basically, there are good reasons why historically certain keys sounded different from others, due to the fact that unequal temperaments were more common, and thus some keys would sound more "in-tune" than others.  These aspects of tuning often influenced the choices of genres for writing music in particular keys, so different keys developed associations with emotions or extra-musical characters (e.g., some keys were considered appropriate for "martial" or military type music, often because military instruments were pitched in them, so marches were often written in them).
That last bit is still potentially an issue today: many instruments are still pitched in standard keys, which means they are easier to play (and easier to play in-tune) in some keys than in others.  Modern instruments are mostly equipped with various keys and slides and such to help correct for the problems of playing in less-common keys, but there may still be subtle variance in tone, say, for brass instruments playing in a key they are pitched in vs. a key that is a half-step away (which will require much more tuning adjustments, will potentially change the tone slightly by using more valves, etc.).  For string instruments, one might consider that sharp keys often take advantage of open strings, which alters the sound.  And unless you're talking about truly professional violinist, their ability to play in a key in tune with many flats compared to their ability to play in a key with a few sharps will vary significantly.
So, from a practical standpoint on many instruments, it certainly does "feel different" to play in different keys.  Does it therefore also create a different mood?  No, not necessarily.  But differences in tuning and tone can make a difference, and this was part of the historical origin of the characters of the keys, back when most instruments were quite difficult to play in all possible keys, and various keys would in fact sound quite different due to these practical performance issues.
As for today, the effects are relatively small, and if you're dealing with professional players, asking them to play the same piece in G major or G-flat major or F major isn't going to make much difference.  However, if you're dealing with amateur ensembles, there are potential significant differences to asking a group to play in G major vs. G-flat major, and some of those will come out in the sound of various instruments or in the fluidity with which instrumentalists are able to play.
But as for moods and "feelings" associated with specific keys?  These were always a bit of a convention, created through associations that built up over decades of composers using certain keys for certain purposes.  There's nothing inherent in the sound of different keys that conveys those specific moods.
(The one exception, I suppose, would be for some people with perfect pitch who experience different types of synesthesia.  I once knew someone who had a very acute sense of perfect pitch but also had developed very particular associations with keys, including moods, colors, etc.)
Comment: @PeterJ: Well, it could be a couple things.  (1) Even people without perfect pitch can have a very good sense of pitch for pieces they know well.  It may be that the piece played in G sounds "off" to you for some difficult-to-describe reason.  (2) The Gb Impromptu lies in a very particular place on black keys on piano, and although I've never played it transposed to G, I can imagine it creates a lot of reconfiguration of hand position, which might influence how you play it in subtle ways.
Comment: @PeterJ -- One other way to test your hypothesis: Does "baroque pitch" bother you? Many recent recordings of baroque and even classical music tend to be pitched at A=415Hz, about a half step lower. I've listened to many recordings of the same pieces at both pitch levels and never noticed a shift in their "resonance or power." Try doing the same, if you haven't. If you don't notice a difference, it suggests that any difference is keys is due to performance effects (e.g., fingerings, changes in instrument resonance, etc.) rather than something inherent in the absolute pitch of the sound.
Comment: There's also the "feel" that certain keys are for easy-to-play music, which is backed up by the statistically significantly larger percentage of pieces in low difficulty levels with those keys (at least for concert band, where loads of Grade 0.5-1.5 pieces are in B flat major because little kids don't learn how to play most accidentals until later--I believe the same applies for piano music and C major, but it's harder to back that up simply by mass listening to that oeuvre).
Comment: Nice answer. Still. I have heard the Schubert Impromptu in Gb played in G a few times and it doesn't have the same resonance or power, which makes me wonder.  . .
Comment: @Athanasius - All good points. I'm not convinced there's not some absolute difference.but it's hard to tell.  .
Answer: Elfman is both right and wrong.
With respect to traditional music, he is very wrong.
Suppose an instrument is tuned to a specific key, not with equal temperaments.
A tune played in the instrument's key will sound different than the same tune played in a different key.
For instance, using the diatonic scale,
if an instrument is tuned to the key of "C", the interval between "do" and "re" will have a frequency ratio of 1.125 (9/8).
If the same tune is played on that same instrument in the key of "D",
that same "do-re" interval will have a frequency ratio of 1.111 (10/9), which will sound significantly different.
Classical composers were well aware of this difference and made use of it.
That's why their works often include the key in their titles.
Bach's Toccata and Fugue in D Minor would sound very wrong if played in any other key.

Bach knew very well what the various keys sound like in meantone temperaments, and in well temperaments. Organs he played were in various versions of meantone, as a standard. (And some still are.) Other wind instruments were also designed to use those specific twelve notes: A-B-C-D-E-F-G, F#-C#-G#, Bb-Eb. The other notes were by design not as well in tune in the temperaments in practical use. Composers understood this. This was practical musical knowledge.
  Temperament — Bach Cantatas Web Site

But since that time, instruments and music have changed, losing the tonality that defined classical music.
In some ways this is a great loss (no more associated mood), but in other ways it is a win (any tune can be played on any instrument, or sung in any key).
Pianos, and many modern instruments, especially synthesizers, are tuned with
equal temperament,
in which the interval between any two adjacent notes, including semitones, has a ratio of the twelfth root of 2.
Using this system the interval between "do" and "re" will be 1.0593781, an approximation of the 1.125 and 1.111 of the diatonic scale.
In fact, every whole tone difference will have that same ratio.
A piece written in equal temperament will sound exactly the same regardless of what key it is played in.
And today, almost all music is written that way; it has no tonality.
So that is what Danny Elfman was referring to when he said "You can turn any key into anything you want.".
Answer: There's no evidence that I'm aware of that in an equal temperament world different keys have intrinsically distinct characters, in the sense that Bb major would relate to a different range of emotions than C major.
I guess I find it a bit surprising that you find Elfman's statement noteworthy - It seems fairly intuitive that with most people possessing only relative pitch, and in an equal temperament world, there wouldn't be any intrinsic correlation between home note and emotion.
In a given body of work, you might nevertheless still find correlations between particular keys and particular 'feels'. One reason might be the tuning of particular instruments - the standard tuning of the guitar could lead to a large number of songs in blues/rock tonality being written in E or A, for example.
I assume that when he says "You can turn any key into anything you want", he doesn't mean that C major has the same range of subjective feelings as C minor - rather that he's just talking about the home note. If he's stating that there's no significance whatever in major/minor, that would be a surprising statement.
Answer: If you play a folk song in D flat major instead of D major on a fiddle, it sounds like crap since all the resonances are off and lots of drones don't work.  Even if you discount the tremendous added technical difficulty which "should not" make a difference to a perfect soloist but of course does.
Not every instrument is a piano in modern equidistant tuning.
Most wind instruments have compromise tunings combining perfect intervals and valve combinations.  Not every wind instrument is a trombone.
Fretted string instruments with fixed frets are commonly based on equidistant tuning, but chord voicing and fingering still depends on the tuning, and the tuning again will often be a compromise different from equidistant tuning, making some chords have better qualities than others.
When you are doing your composition work at the piano or on synthesizers or on MIDI expanders with less than per-note sampling, it is easy to forget that most orchestral instruments are not working from a continuum of semitones and sound samples but from a limited number of co-dependent oscillators employed in various constellations and mechanical vibration modes that may take a variety of skills and effort to coax into different keys.
A brass ensemble will have several chords that sound awful because of the way the different compromises for the tuning of notes of various different instruments interact.  Good players can adjust the intonation of single notes, but you don't get to adjust every note in a fast passage.
But if your main listening tool is a MIDI expander, indeed hitting the transpose button will not magically shift moods unless you have come to culturally associate certain moods with certain keys and recognize them reliably even in partly synthesized sounds.
Answer: This is the question, that I had been asking myself for quite some time, and though I am by no means a professional musician and do NOT have a perfect pitch I still think that the key is to some extent important.
I would not argue that a half-tone change will make the music sound different for me, but the large differences will sound differently. The reason is that instruments of the orchestra have their ranges (which are much less than that of pianoforte) and they actually sound differently in different regions and changing the key by a fifth up I would lose the sound that I had (e.g. violin would get too squeaky and horn less heroic).
So for me, if I compose something there will be a range of keys, where it sounds right, and the range where it sounds worse.
Answer: As someone who has perfect pitch, it's always seemed to me that every key, and I'm assuming you're not talking about different modes, every key has a different inflection or tone to me.
For example, I've always felt songs that are written in D major to be uplifting or more grand, and I couldn't really give you a reason as to why. In contrast, a song that's written in C major, in most cases, will bore me for some reason. Possibly, it could depend on what I'm used to and how many songs I've heard written in that particular key.
Often, a comparison to hearing pitches is seeing colors. Someone could love the pitch Db in the way they love the color red. And maybe, everyone has this happen to them no matter what way they hear pitches. I hope this answer helps to answer your question.
Comment: Yes it does help, thank you! Like I mentioned in the question: "I suppose subjects would have to be sorted in to those with and without perfect pitch to check for subconscious bias..." Since you *a priori* know the key, one can't rule out bias (subconscious or otherwise); perhaps the first few things you heard in D major were more uplifting, or perhaps statistically music written in D major is more uplifting than average. I have read somewhere that usually people with perfect pitch have generally spent time in front of a piano early on, so one could start by checking stats of that repertoire.
Answer: From a biological standpoint, I'd argue that it would be very odd if all keys were exactly identical to the average human brain.  If you think about what's happening physiologically, sound waves are triggering certain cascades of neurons in the audio cortex, and the neurons triggered by the key of G major aren't going to be the exact same neurons as those triggered by C major.  Many of them will overlap, but some will be unique to each key--otherwise we wouldn't be able to tell a difference between keys.  Simply recognizing that there must be a neurological difference implies that how a key is experienced internally would be different as well. However, it may be such a minor difference that it is unnoticeable, and/or the "noise" of perception introduced by individual brains probably overwhelms any average difference that brains in general might experience between the keys.  At the very least, we can say that mood/tone differences due to chord progressions compared to differences due to key are close to negligible.  Doesn't mean there are no differences between keys, only that they are overwhelmed by noise and other factors.  Still, I'd say the burden of proof is on those who claim there is NO difference.  To me, the null-hypothesis would imply the opposite.
Comment: I agree with the necessity of the null-hypothesis here. Also, I don't understand all these answers saying there's no difference, or that it's just the tuning or instrument - I transpose songs in my DAW all the time, and each key gives a VERY significant emotional adjustment ime. I'm kinda floored no one else is chirping up about this tbh.


How to open modelproj in Visual Studio 2022 Community Edition?

Question: What workload/component needs to be installed in order for Visual Studio 2022 Community Edition to open existing .modelproj?
I have installed everything under the Code Tools group

Open Visual Studio 2022
Tools menu
Get tools and Features...
Individual Components tab
Code Tools group
Comment: Does this answer your question? [Visual Studio 2017 not opening .modelproj](https://stackoverflow.com/questions/42727430/visual-studio-2017-not-opening-modelproj)
Comment: I did the same thing in visual studio 2022 community edition but I couldn't open it
Answer: The workload component name is Microsoft.VisualStudio.Component.DependencyValidation.Enterprise. However, as you can probably see, this component is limited to enterprise editions of Visual Studio (just like code coverage).
It would be listed under the "Code Tools" section as "Live Dependency Validation".
Answer: I resoled it but going to View -> Terminal and then running
dotnet install android
dotnet install ios
dotnet install maccatalyst


Starting my career as i'm not a native english speaker

Question: i think this question is a little bit weird, but i wanted to ask it anyway.
i don't live in a country with its main language as English. so i learned it myself. my speaking is not good enough right now but i've come a long way.
you may say why not just sing(rap) in your own language, the point is i feel i can express my feelings better in English and also its a global language so my dream is to rap for worldwide not just for one specific country.
i have a few obstacles which i wanted to share with you and take any advice if you have:
1- i have no one around that i can talk English to. even if there was, they couldn't help me with my mistakes and improving my Accent. how can i overcome this? fluenting my rapping and learning American accent.
2- i read in internet that some rappers started going to local producers and showing them lyrics or some beats and... so they could work together. which doesn't work for me. 90% of here doesn't even understand Eng, so showing my lyrics to them doesn't make sense.
3- this is somehow connected to number2. i'm new to this field and i have no one(lets make it crystal clear :) "NO ONE") around me in music industry. how am i supposed to find a producer for example?! or a guy help me record song with his stuff cause i'm not sure i can afford a good mic or sth else to record myself.
4- how to tell the world i'm here! i created an Instagram account. trying to put some quotes of my favorite artists to gain some traction. but i think there must be better ways to do that.
5- there is no one in my country that i can sign an Eng rap deal. how am i supposed to grow without that?
-- if you know anyone with same problems that finally made it and became someone, it would be appreciated to share with me
Comment: perhaps if you told us your locale, we could assist more ? Personally I think your use of English is fine. I am much less fluent than you in the languages that I know.
Comment: To be successful as a rapper you don't need to speak perfectly English. There are enough native English speaking rappers! But your success could just lay in the fact that you have your own original pictures in mind, your own phrasing and accent, and even it is not perfect English people like me would love and estimate it!
Comment: @bigbadmouse i live in middle east, already know Persian, Arabics, English, and a little bit Germans language
Answer: To be successful as a rapper you don't need to speak perfectly English. There are enough native English speaking rappers! But your success could just lie in the fact that you have your own original pictures in mind, your own phrasing and accent, and even it is not perfect English people like me would love and estimate it! - But somehow you remind me of all the young boys who want to start a career as football players or all the girls who want become a model or "influencer". So I wouldn't start trying to look for producer but start your own  channel. Getting famous in this biz is harder than  to win the 6 in a lottery.
Example:
Müslüm is a Swiss entertainer with Turkish background and successful artist. He started his career when calling public offices like police center or journal offices and politicians etc.  asking silly funny question, recording the call and spreading on his youtube channel.
This video is criticizing  the doctors of medicine, the pharma industry the drug dealers  and he tells his song is the super vitamin.

here he is mocking about  a political party of the right corner that wants to send the migrants home.
Comment: First let me thank you so much for your answer.  so you advice me to create a channel and put my own raps there? Tnx OFC i'll do that. do u suggest me any other way in parallel for me to grow up my career?


5. Prove by induction on $n$ that $\sum\limits_{k=1}^n \frac k{k+1} \leq n - \frac1{n+1}$

Question: $\sum\limits_{k=1}^n \frac k{k+1} \leq n - \frac1{n+1}$
Base Case:
I did $n = 1$, so..
LHS-
$\sum \limits_{k=1}^n (k/(k+1)) = 1/(1+1) = 1/2 $
RHS-
$n-(1/(n+1)) = 1 - (1/(1+1)) = 1/2$
so LHS = RHS
Inductive case-
LHS for $n+1$
$\sum \limits_{k=1}^n (k/(k+1)) + ((n+1)/(n+2)) $
and then I think that you can use inductive hypothesis to change it to the form of
$$
(n - (1/(n+1)))  + ((n+1)/(n+2))
$$
now form here I tried multiplying it out and solving with some algebra but I kept hitting dead ends. If you could explain your steps and the reasoning behind them I would appreciate it.
Edit-
Am i on the right track with the following solution for the inductive case?
$\sum \limits_{k=1}^n (k/(k+1))
= \sum \limits_{k=1}^n (n - (1/(n+1)) + (n+1)/(n+2) $
then I think if i increase the denominator 1/(n+1) by 1 then it should become..
${}< n - 1/(n+2) + (n+1/n+2)$
${}< n - 1/(n+2)$
which is really close to the RHS of $n+1$ which is $n+1 - 1/(n+2)$... and since i did change the value of the denominator by 1 earlier, i feel like i should be able to add a 1 in now to make it equal. I'm not sure of the logic behind this though!
Comment: If you are in the $n+1$ case, then the RHS should be $n + 1 - 1 / (n + 1 + 1)$
Comment: Anyway, check the $n=2$ case.
Comment: How come you suggest to check n = 2? what lead you to that?
Comment: Well that was before you changed it to an inequality
Comment: Yea, sorry about that I realized that I had type the question wrong. You comment lead me to take another look at what I type. Does that change the process alot?
Comment: Yes, now you have to use the transitive property of $\le$, which is $a \le b \text{ and } b \le c \text{ then } a \le c$.
Comment: I'm not sure how that would work, if a is the LHS and c is the RHS what is b in this case? Am i on the right track with my edit at the bottom?
Answer: $$\begin{align}\sum_1^{n+1}\frac k{k+1}&\leq n-\frac 1{n+1}+\frac{n+1}{n+2}\\&=n-\frac 1{n+1}+1-\frac 1{n+2}\\&=(n+1)-\frac{2(n+2)-1}{(n+1)(n+2)}\\&=(n+1)-\frac 2{n+1}+\frac 1{(n+1)(n+2)}\\&\leq (n+1)-\frac 2{n+2}+\frac 1{n+2}=(n+1)-\frac 1{n+2}\end{align}$$
For the penultimate inequality, note that $n+1\lt n+2$, so $-\frac 1{n+1}\lt -\frac 1{n+2}$ and $(n+1)(n+2)\gt (n+2)$, so $\frac 1{(n+1)(n+2)}\lt\frac 1{n+2}$
Comment: Could you explain the second step please? I'm having trouble following the solution, since i'm fairly new to this. If i'm understanding this right  shouldn't at the top it be          -(n+1)/(n+2) since you would subtract from the lhs and rhs side?
Comment: @Brownie: it's just the inductive step: $$\sum_1^{n+1}\frac k{k+1}=\left(\sum_1^n\frac k{k+1}\right)+\frac{n+1}{n+2}\leq n-\frac 1{n+1}+\frac{n-1}{n-2}$$ where we apply the inductive hypothesis at the last step.
Answer: You are trying to prove that
$$\sum_{k = 1}^n \frac k {k+1} \le n - \frac{1}{n+1}$$
implies
$$\frac{n+1}{n+2} + \sum_{k = 1}^n \frac k {k+1} \le n+1 - \frac{1}{n+2}$$
So let
$$A = \sum_{k = 1}^n \frac k {k+1}$$
$$B = n - \frac{1}{n+1}$$
$$C = n+1 - \frac{1}{n+2} - \frac{n+1}{n+2}$$
And use $A \le B \text{ and } B \le C \text{ then } A \le C$
Answer: It might be useful to rearrange the LHS of the inequality before proving it:

$\sum_{k=1}^n \frac k{k+1} = \sum_{k=1}^n \frac {k+1-1}{k+1} = \sum_{k=1}^n \left(1-\frac{1}{k+1} \right) = n - \sum_{k=1}^n \frac {1}{k+1}$

Hence the inequality becomes
$$\sum\limits_{k=1}^n \frac k{k+1} \leq n - \frac1{n+1} \Leftrightarrow n - \sum_{k=1}^n \frac {1}{k+1} \leq n - \frac1{n+1}$$ $$\Leftrightarrow \boxed{\sum_{k=1}^n \frac {1}{k+1} \geq \frac1{n+1}}$$
Now, there isn't much left to prove.
Comment: This is a great solution, as a beginner its really easy for me to follow this! My one question is in your top line at the end, where you rearrange, what is the math behind you taking the 1 outside and it becomes n - the summation?
Comment: @Brownie : This is so because of the definition of the sum symbol you have \begin{eqnarray*}  \sum_{k=1}^n \left(1-\frac{1}{k+1} \right)
& =  &\underbrace{\left(1-\frac{1}{1+1} \right) + \cdots + \left(1-\frac{1}{n+1} \right)}_{n \: summands} \\
& = &\underbrace{\left(1+ \cdots +1 \right)}_{n\:summands} - \left(\frac{1}{1+1}+ \cdots +\frac{1}{n+1} \right) \\
& = & n - \sum_{k=1}^n \frac{1}{k+1}
\end{eqnarray*}


How to access kernel mode memory in user mode application in WinCe7

Question: I have written a direct show filter and a video decoder driver for Win CE 7. The filter is loaded in the user mode and the decoder driver is loaded in the kernel mode. The filter need memory to receive the input buffers and it allocates this memory by calling a video decoder driver function. The decoder driver allocates memory and returns its virtual address from kernel space (>2GB) because it is loaded in the kernel mode. But this memory is not accessible for the filter because it is loaded in the user mode.
By considering the above scenario, how can I make the memory allocated by the video decoder driver accessible for the filter?
Comment: Well, can you not allocate the buffers in user space and pass them to the video decoder driver to fill up?
Comment: Basically the video decoder driver needs a buffer from filter that contains an encoded data. The video decoder driver takes this buffer, decodes the data and send it back to the filter.
Answer: I'm not sure if this will help considering you're on Win CE 7, but in Windows 7, I have a driver that maps a kernel mode address to a user mode address before returning the resulting user-mode address to my application.
void *userSpaceAddr;

// Allocate the MDL describing our kernel memory
pmdl = IoAllocateMdl((PVOID)&my_heap_var,
                     (ULONG)size_of_my_heap_var,
                     FALSE,
                     FALSE,
                     NULL);
if(!pmdl) {
    DbgPrintEx(DPFLTR_IHVVIDEO_ID, DPFLTR_INFO_LEVEL, "Error on IoAllocateMdl. Returning from driver early.\n");
    return STATUS_INSUFFICIENT_RESOURCES;
}

MmBuildMdlForNonPagedPool(pmdl);

userSpaceAddr = (void *)MmMapLockedPagesSpecifyCache(pmdl, UserMode, MmWriteCombined, NULL, FALSE, LowPagePriority);

userSpaceAddris mapped to a user space virtual address in the process context that called the driver. You can then return userSpaceAddr to your application.
This hinges on the MmMapLockedPagesSpecifyCache function. MSDN doc here: http://msdn.microsoft.com/en-us/library/windows/hardware/ff554629(v=vs.85).aspx


GTK - Don't highlight buttons on select / hover

Question: I'm trying to write a kiosk GUI in ruby/gtk on ubuntu. I'm pretty fluent in ruby, but new to writing GUIs and not great with linux.
I'm using a touch screen, and am using our own images for buttons, e.g.
button_image = Gtk::Image.new(Gdk::Pixbuff.new "images/button_image.png")
@button = Gtk::Button.new
@button.add(button_image)
@button.set_relief(Gtk::RELIEF_NONE)

My issue is that when the buttons are pressed or remain selected (or hovered over, although this is less relevant with a touch screen), gtk shows fat, square borders around them. Obviously it's applying gtk's prelight / selected / active lighting to the buttons. I've tried changing the button properties in various ways, and also tryied hacking apart my theme, and while I can modify how the highlighting looks, I can't seem to completely get rid of it. Changing the color of the highlight via my theme is easy, but if I remove my setting there's still a default I can't get rid of.
Does anyone know if there's a way to stop it, or possibly make it transparent? Thanks in advance!
Answer: Sounds like you want to use exactly your image for the whole button, instead of putting an image inside the normal GtkButton - but still use all the normal behavior of the button.
The easiest way to do this is to just override the drawing.  If you are on gtk2, connect to the "expose-event" signal, do your drawing there, and return true so that the default handler doesn't get run.  If you are on gtk3, connect to the "draw" signal and do the same.
Comment: oh interesting -- haven't gotten that deep in before but I'll try it out, thank you for the suggestion
Answer: I tried meddling with the drawing as Federico suggested, but found that the most direct way to address this was instead to use an event box rather than a button. Event boxes accept clicks just like buttons, but don't respond to selecting, hovering, etc. In ruby, the code looks like this:
image = Gtk::Image.new("myfile.png")
event_box = Gtk::EventBox.new.add(image)
event_box.visible_window = false
event_box.signal_connect("button_press_event") do
  puts "Clicked."
end

Most of this is exactly like a button; the *visible_window* method, obviously, keeps the event box from being visible under the button image.


Can subdomains work without being registered in the DNS records/

Question: I have made a web-application on my localhost which provides a platform which gives different businesses their own page on that platform. Each business has it's own subdomain.
So,
business1.example.com
business2.example.com
business3.example.com
...
On my localhost, my code just interprets the URL as a string and extracts the subdomain part. If that subdomain is linked to a business in my database the page is served, otherwise a 404 is returned.
This works fine on my localhost. But can this also work on the internet?

There are an infinite amount of subdomains possible
sfkojfioej.example.com should work too as URL, but just return a 404.
The subdomains are not registered in the DNS-records.

Especially the last point bothers me. Is it possible to achieve this without registering each subdomain in the DNS records?
Answer:

The subdomains are not registered in the DNS-records.

Especially the last point bothers me. Is it possible to achieve this without registering each subdomain in the DNS records?

The sub domains must exist in DNS because otherwise people can't resolve them.
But  you don't need to explicitly create a DNS record for each subdomain, you can create a DNS wildcard record <code>*.example.com</code> which will be used for any subdomain that is not explicitly created.


Reverse GeoCoordinate Class gives Location Not found error

Question: i m using google Reverse Geocoding API in my app, i m succussfully able to get get coordinate using google geolocation API. Now i m trying to get Location Name from   Reverse Geocoding API , but always returns Location not found error
here is my code:

  Geocoder geocoder= new Geocoder(MainActivity.this, Locale.ENGLISH);

  if(geocoder.isPresent()){
          List<Address> list;
 try {
   list = geocoder.getFromLocation(37.42279, -122.08506,1);
    Address address = list.get(0);
    Log.d("this is working","thsi sis working");

          StringBuffer str = new StringBuffer();
          str.append("Name: " + address.getLocality() + "\n");
          str.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
          str.append("Admin Area: " + address.getAdminArea() + "\n");
          str.append("Country: " + address.getCountryName() + "\n");
          str.append("Country Code: " + address.getCountryCode() + "\n");;

          String strAddress = str.toString();
          JsonDatas.setText(strAddress);
           Log.d("Address", strAddress);
  }
    catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

i have several question

how google know that which app requested the API and how google determine of Quota that app. in google API developer Console, google gave Quota for app API
Why i m getting location not found error but searching on google map location is showing
do i need to add google Geocoder APi key into my app -  right now i m only Geolocation API key using for retrieve Coordinates

Please correct me if i m wrong, Please give suggestion so my code will work fine
thanks
Comment: 1. Depends on the api, but every request will cost quota. Typically, you'll need a key to access the api, which allows your usage to be track and identified. Other times, it may be through your IP.

2. Is it only a particular request or all requests?

3. You can use the Android Geocoder without an api key.
Comment: thanks for your information, i m getting location not found  error for every coordinate , i was using Geocoder api and i was not able to get the location from coordinats, can u please share any good link that have reverse api or google map v3 api android example @Andy
Answer: Make sure you have latest Google play library in your project. I am using this code and working for me.
 private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
        Context mContext;

        public ReverseGeocodingTask(Context context) {
            super();
            mContext = context;
        }

        // Finding address using reverse geocoding
        @Override
        protected String doInBackground(LatLng... params) {
            Geocoder geocoder = new Geocoder(mContext);
            double latitude = params[0].latitude;
            double longitude = params[0].longitude;
            List<Address> addresses = null;
            String addressText = "";

            try {

                addresses = geocoder.getFromLocation(latitude, longitude, 1);

                Thread.sleep(500);

                if (addresses != null && addresses.size() > 0) {

                    Address address = addresses.get(0);

                    addressText = String.format(
                            "%s",
                            address.getMaxAddressLineIndex() > 0 ? address
                                    .getAddressLine(1) : "", "", "");
                }
            } catch (IOException e) {
                e.printStackTrace();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return addressText;
        }

        @Override
        protected void onPostExecute(String addressText) {
        }
}

Where LatLng is Latitude and longitute, check this for doc.
and to use write down new ReverseGeocodingTask(this).execute(latlng); where you want to get data.
Make sure you are adding permission into your manifest file.
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />


Query using specifications gives error when ordering on joined column that is not in SELECT DISTINCT

Question: I get following error when doing a rather complicated query: for SELECT DISTINCT, ORDER BY expressions must appear in select list
In the query I need to find all distinct Requests that have an ExploitationSite that contains a search term in their dutch or french name. The result has to be ordered by the Activity's dutch name and limited to the first 10 for pagination.
To do this query I use the Page <T> findAll(Specification<T> spec, Pageable pageable) method of JpaSpecificationExecutor.
This will result in a SELECT DISTINCT query which has to be ORDERed BY a property that is not in SELECT. (details below)
I tried to fetch the activities eagerly in the hope it would place those differently in the SELECT. I did my best trying to get the DISTINCT in a subquery and then have the ORDER BY + LIMIT around that, but I did not succeed in that.
Has someone an idea how I can get this query to work?
The (simplified) Request entity
@Entity
@Table(name = "request_requests")
@History("Request")
public class Request extends EqualByStateObject {

    @GeneratedValue
    @Id
    private int id;

    @Embedded
    private RequestNumber requestNumber;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "fk_request")
    private List<ExploitationSite> exploitationSites = new ArrayList<>();

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(unique = true, name = "fk_activity")
    private Activity activity;

    ...
}

The Specification (I have to use distinct here because since a Request contains a List of ExploitationSites it was possible I got the same request multiple times back if multiple ExploitationSites contained the search term)
public class ExploitationSiteSpecification extends EqualByStateObject implements Specification<Request> {
    private final String exploitationSiteName;

    protected ExploitationSiteSpecification(String exploitationSiteName) {
        this.exploitationSiteName = exploitationSiteName;
    }

    @Override
    public Predicate toPredicate(Root<Request> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        query.distinct(true);
        ListJoin<Object, Object> exploitationSites = root.joinList("exploitationSites");
        return criteriaBuilder.or(
                criteriaBuilder.like(
                        criteriaBuilder.lower(exploitationSites.get("name").get("dutchName")), "%" + exploitationSiteName.toLowerCase() + "%"),
                criteriaBuilder.like(
                        criteriaBuilder.lower(exploitationSites.get("name").get("frenchName")), "%" + exploitationSiteName.toLowerCase() + "%")
        );
    }
}

The Pageable
public Pageable getPageable() {
    Sort sort = Sort.by(Sort.Order.asc("activity.name.dutchName"));

    PageRequest.of(0, 10, sort);
}

This results in a generated query like this one
select distinct request0_.id as id1_23_,
    request0_.fk_activity as fk_acti15_23_,
    request0_.request_number as request12_23_

from request_requests request0_
    inner join request_exploitation_sites exploitati1_ on request0_.id=exploitati1_.fk_request
    left outer join request_activity activity2_ on request0_.fk_activity=activity2_.id

where lower(exploitati1_.dutch_name) like $1
        or lower(exploitati1_.french_name) like $2

order by activity2_.dutch_name asc limit $3

which then gives the for SELECT DISTINCT, ORDER BY expressions must appear in select list error
Comment: You can multiselect the column for  distinct `query.multiselect(exploitationSites.get("id"),exploitationSites.get("name").get("dutchName")).distinct(true);`
Comment: You need to select `dutch_name` also to order by that column
Comment: I wish it was as easy as that, but it's difficult to change the query directly since it is automatically generated.
Comment: It looked promising, but it unfortunately did not change the generated query
Answer: Assuming you put the distinct because the join with exploitationSites would return multiple rows, the following two options would work without using distinct.

right after the join you could do an additional fetch

ListJoin<Object, Object> exploitationSites = root.joinList("exploitationSites");
root.fetch("exploitationSites")

this would result in hibernate to create an additional join of ExploitationSites as well as selecting additional columns
select request0_.id as id1_23_,
    request0_.fk_activity as fk_acti15_23_,
    request0_.request_number as request12_23_,
    exploitati3_.id as exploitati3_id,
    exploitati3_.name as exploitati3_name,
    ...

from request_requests request0_
    inner join request_exploitation_sites exploitati1_ on request0_.id=exploitati1_.fk_request
    left outer join request_activity activity2_ on request0_.fk_activity=activity2_.id
    inner join request_exploitation_sites exploitati3_ on request0_.id=exploitati3_.fk_request

where lower(exploitati1_.dutch_name) like $1
        or lower(exploitati1_.french_name) like $2

order by activity2_.dutch_name asc limit $3

use fetch in the first place and cast it to Join

Join<Object, Object> exploitationSites = (Join<Object, Object>) root.fetch("exploitationSites");

By casting the Fetch to a Join you can still use where clauses.
Note that this will also select additional columns, but won't do an additional join in the resulting query.

In both cases the fetch will result in a join fetch which hibernate internally will remove duplicates from the parent entity (see https://stackoverflow.com/a/51177569)