Mapa abre antes de pegar a posição do GPS

Question: Estou estudando programação para Andriod e me deparei uma característica que simplesmente não conheço nada, que é a ordem de execução as funções!   por favor , alguém poderia de dar uma luz?
Explico, no meu exemplo eu chamo a
 - API para comunicar com o GPS, (linha 90)
 - DEPOIS para efetivamente pegar a posição (latitude e longitude) (linha 103)
 - e então chamo o mapa ! (linha 210)
Mas não sei por que razão, ele abre o mapa ANTES de pegar a posição do GPS, ou seja, o mapa não tem posição pra abrir e da erro.

Como sou novata, não sei exatamente se fui clara... Espero que vocês
  me ajudem  a entender e a explicar. Cheguei ate aqui depois de muita
  pesquisa, mas empaquei, pois não sei como abrir o mapa DEPOIS da
  consulta da posição...

Eis o código quer estou trabalhando!
package jp.co.e_grid.rakuseki;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

//import java.util.concurrent.atomic.DoubleAccumulator;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import jp.co.e_grid.rakuseki.model.Report;

import static jp.co.e_grid.rakuseki.config.Constants.MAP_ZOOM;

/**
 * Created by ootaegd on 2016/12/16.
 */

public class PostPositionActivity extends AppCompatActivity
        implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {

    private GoogleMap map;
    private Marker marker = null;
    private LatLng locationLatLng;
    //private static final LatLng MATSUE = new LatLng(35.47222, 133.05056); //マーカ初期値
    //private LatLng locationLatLng = instantPosition;
    private float accuracy;
    //private static final LatLng instantPosition = new LatLng(35.3852243, 132.7339911);  //              izumo
    //private static final LatLng instantPosition = new LatLng(35.47222, 133.05056);      //マーカ初期値  matsue
    private String uuId;
    //private LatLng instantPosition;
    protected Realm realm;
    private TextView tvCoordinate;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_position);

        //前のactivityから渡されたデータを取得する
        Intent intent = getIntent();
        uuId = intent.getStringExtra("uuId");

        //realm設定
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(config);

        //toolbarを設定
        Toolbar toolbar = (Toolbar) findViewById(R.id.post_position_toolbar);
        toolbar.setTitle(getString(R.string.headPositionTitle));
        setSupportActionBar(toolbar);

        onBtnGpsClicked();
        nextViewActivity();

        //Fragment を取得
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        tvCoordinate = (TextView) findViewById(R.id.tv_coordinate);
        callConnection();
    }

    /**
     * Getting the Google GPS API OnLine.
     *(linha 90)
     */
    private synchronized void callConnection() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
        Log.e("--------MESSAGE--------"," API loaded 01");
    }

    /**
     * Getting the actual GPS position.
      *(linha 103)
     */
    @Override
    public void onConnected(Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location l = LocationServices
                .FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if(l != null){
            //tvCoordinate.setText(l.getLatitude()+" -- "+l.getLongitude()+"-----"+ l.getAccuracy());
            tvCoordinate.setText("Accuracy = "+ l.getAccuracy());
            accuracy = l.getAccuracy();
            Log.e("--------LOG--------", "latitude:  " + l.getLatitude());
            Log.e("--------LOG--------", "longitude: " + l.getLongitude());
            Log.e("--------LOG--------", "accuracy:  " + accuracy);
            // tvCoordinate.setText(" ||| "+l.getLatitude()+" ||| "+l.getLongitude()+" ||| ");
            // final LatLng instantPosition = new LatLng(35.3852243, 132.7339911); //izumo
            // final LatLng instantPosition = new LatLng(35.47222, 133.05056); // matsue
            locationLatLng = new LatLng(l.getLatitude(), l.getLongitude());
            //instantPosition = new LatLng(l.getLatitude(), l.getLongitude());
            Log.e("--------MESSAGE--------"," GPS get ok 02");
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    /**
     * 次の画面へ遷移する処理
     */
    private void nextViewActivity() {
        //位置情報ボタンを押された時の処理
        Button btnPost = (Button) findViewById(R.id.btnPost);
        btnPost.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //位置情報を追加する
                addReport();

                // 画面を起動
                Intent intent = new Intent();
                intent.setClassName("jp.co.e_grid.rakuseki", "jp.co.e_grid.rakuseki.PostConfirmationActivity");
                intent.putExtra("uuId",uuId);
                startActivity(intent);
            }
        });
    }

    /**
     * 現在地取得ボタンを押された時、現在地を取得する
     */
    private void onBtnGpsClicked() {
        Button btnPost = (Button) findViewById(R.id.btnLocation);
        btnPost.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //現在地取得
            }
        });
    }

    /**
     * GoogleMapを読み込む前に、オーバライドして処理を行う
     *
     * @param googleMap
     *(linha 210)
     */
    @Override
    public void onMapReady( GoogleMap googleMap ) {
        map = googleMap;

        Log.e("--------MESSAGE--------"," original get 03");
        // final LatLng instantPosition = new LatLng(35.3852243, 132.7339911); // izumo
        // final LatLng instantPosition = new LatLng(35.47222,   133.05056);   // matsue
        //locationLatLng = new LatLng(35.47222,   133.05056);   // matsue  //test
        setMarker(locationLatLng);

        // GoogleMapが押下された時の処理
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick( LatLng latLng ){
                // クリックされるたびにマーカが増えていく
                // 一つ前のマーカは削除する
                marker.remove();
                //Mapが押下されたらその位置にピンを立てる
                //緯度経度を取得
                locationLatLng = latLng;
                //ピンを立てる
                setMarker(locationLatLng);
            }
        });
    }

    /**
     * Markerを立てる関数
     *
     * @param lacation 緯度経度情報
     */
    private void setMarker(LatLng lacation){
        marker = map.addMarker(new MarkerOptions()
                .position(lacation)
                .title("報告場所")
                .draggable(false));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(lacation, MAP_ZOOM));
    }

    /**
     * 位置情報を追加する
     * @return プライマリキー
     */
    private void addReport(){

        realm = Realm.getDefaultInstance();
        //トランザクション開始
        realm.beginTransaction();

        //uuIdでターゲットを抽出
        Report report = realm.where(Report.class).equalTo("key",uuId).findFirst();
        //保存を行う
        report.setLat(Double.parseDouble(String.valueOf(locationLatLng.latitude)));
        report.setLon(Double.parseDouble(String.valueOf(locationLatLng.longitude)));
        report.setAccuracy(Double.parseDouble(String.valueOf(accuracy)));
        Log.e("--------MESSAGE--------", " Longitude 04 " + String.valueOf(report.getLon()));
        Log.e("--------MESSAGE--------", " Latitude 04 "  + String.valueOf(report.getLat()));
        Log.e("--------MESSAGE--------", " Accuracy 04 "  + String.valueOf(report.getAccuracy()));

        //トランザクション終了
        realm.commitTransaction();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

Comment: Coloca as linhas 90,103 e 210 destacadas.
Comment: @Taisbevalle, marquei as linhas, de inicio de cada funcao! por favor me diga se ficou melhor!
Comment: Sabe.. to achando que isso de "auto-didata" em java não vai rolar..... o bicho eh chucru.  Acho que vou ter que pagar pra aprender.
Comment: Assim fica melhor =)..Quando tiver alguma dúvida veja esse [Manual de como NÃO fazer perguntas](http://meta.pt.stackoverflow.com/q/5483/51124)
Comment: eu ja li este manual.. :(   ele ma da muita dor.... vou ler de novo... :(
Answer: A ordem da execução dos métodos é a ordem em que são chamados e não a ordem em que são declarados.
A ordem como está a fazer é pedir para ser criado o mapa e depois pedir para ser criado o serviço de localização:
...
//Cria o mapa
mapFragment.getMapAsync(this);

...
//Cria o serviço de localização
callConnection();

Eu utilizei pedir para ser criado, em vez de apenas criar, porque ambos os métodos retornam antes do mapa e do serviço serem criados, a criação é processada de forma assíncrona.
O facto dos métodos serem chamados naquela ordem não garante que o resultado de cada um dos processamentos termine na mesma ordem.
Normalmente os processamentos assíncronos recorrem a callbacks para informar o código chamador do resultado do processamento.
O método getMapAsync(), de MapFragment, usa uma implementação da interface OnMapReadyCallback, passada como argumento.
O método connect() usa implementações de GoogleApiClient.OnConnectionFailedListener e GoogleApiClient.ConnectionCallbacks, informadas ao construir o objecto GoogleApiClient.
Como não se sabe qual dos callbacks vai ser chamado primeiro, se onConnected() ou onMapReady(), é necessário (tentar)colocar o marker no mapa em ambos os métodos.
No método onConnected():
if(map != null){
    setMarker(locationLatLng);
}

No método onMapReady():
if(locationLatLng != null){
    setMarker(locationLatLng);
}

Comment: OBRIGADAAAAAA! nem sei como agradecer! Beijos a Portugal!


Como evitar bloqueio de requisições?

Question: Estou fazendo um projeto em ASP.NET MVC + IIS e percebi que ao fazer uma requisição à uma página com longa leitura no Banco de Dados (utilizando Entity Framework), se eu abrir outra janela e tentar acessar uma outra página qualquer do site (a Home por exemplo, que não tem nenhuma leitura e deveria abrir rapidamente), essa segunda requisição acaba esperando a primeira terminar para então exibir a página.
Estou preocupado com este tipo de bloqueio, pois quando o site estiver em produção pode acabar bloqueando a requisição de clientes e até gerando um timeout.
Não sei se isso é algum tipo de configuração que deva ser inserida no IIS ou na aplicação.
Se alguem puder me ajudar com a seguinte questão, agradeço.
PS: Não estou utilizando métodos assíncronos nas Controllers. Acredito que o método assíncrono evitaria só o congelamento da tela para o usuário, mas não interfere no bloqueio da requisições de outros clientes, mas como não tenho muito conhecimento em programação assíncrona, se eu estiver errado me corrijam.
Answer:
Não sei se isso é algum tipo de configuração que deva ser inserida no IIS ou na aplicação.

Você já se respondeu neste comentário aqui:

Não estou utilizando métodos assíncronos nas Controllers. Acredito que o método assíncrono evitaria só o congelamento da tela para o usuário, mas não interfere no bloqueio da requisições de outros clientes, mas como não tenho muito conhecimento em programação assíncrona, se eu estiver errado me corrijam.

Sim, o bloqueio ocorre porque o contexto não é preparado para thread-safety, então todas as operações são enfileiradas em modo síncrono.
Já em modo assíncrono, o Controller executa todas as instruções da Action que não necessitem da informação do banco, até chegar na execução de alguma interação com o contexto. Por exemplo:
var produtos = await db.Produtos.ToListAsync();

Neste caso, uma thread em alto nível (implementada por Task<T>) será criada para fazer a execução do banco de dados. Com isso, a Action não bloqueia a execução de outras Actions concorrentes.

Como evitar bloqueio de requisições?

Em resumo:

Atualizar sua solução para, no mínimo o .NET 4.5.2;
Usar o escopo assíncrono nas suas Actions:
public async Task<ActionResult> MinhaAction() { ... }

Ao chamar o contexto, envelopar a requisição de informação usando um método assíncrono (System.Data.Entity) e preparar o C# para desenvelopar o resultado da requisição usando await:
var produtos = await db.Produtos.ToListAsync();

Ao usar escopo transacional, indicar ao coordenador de transação que você está usando um fluxo assíncrono:
using System.Transactions;

using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    ...

    scope.Complete();
}

Comment: Perfeito cara, acho que essa dúvida vai ajudar muita gente também. Agradeço pela resposta.

Como evitar bloqueio de requisições?


How to set initial value in directive property

Question: In this plunker:
I have a attribute directive called myTrimmer that trims long text:
which works fine for static text

some longgggg texttttttttttttttt

but does not work for interpolated one:

{{myText}}

that means it takes empty string  instead of myText  at line
this.originalValue = this.el.nativeElement.innerHTML;
Here it is set property of directive:
  set myTrimmer(value: string) {
        this.originalValue = this.el.nativeElement.innerHTML;
        this.length = +value;
        if (+value < this.el.nativeElement.innerHTML.length)
            this.el.nativeElement.innerHTML = this.el.nativeElement.innerHTML.substring(0, value) + '...';
    }

Answer: I suppose that this way you need to wait AfterViewInit event like this:
export class MyTrimmer {
  myTrimmer: string;
  ngAfterViewInit() {
    this.originalValue = this.el.nativeElement.innerHTML;
    console.log(this.originalValue);
    this.length = +this.myTrimmer;
    if (+this.myTrimmer < this.el.nativeElement.innerHTML.length)
      this.el.nativeElement.innerHTML =
this.el.nativeElement.innerHTML.substring(0, this.myTrimmer) + '...';
  }
}

See also at this updated plunkr https://plnkr.co/edit/MccvTyQxSpcgO6Tj99QX?p=preview
Answer: Its because angular doesn't compiled {{myText}} yet. to let angular compile the {{myText}} you need to postpone the trimmer function. in order to do that you can use javascript setTimeout function like this:
set myTrimmer(value: string) {
  var myTrim = this;
  setTimeout(function(){
    myTrim .originalValue = myTrim .el.nativeElement.innerHTML;
    myTrim .length = +value;
    if (+value < myTrim .el.nativeElement.innerHTML.length)
        myTrim .el.nativeElement.innerHTML = myTrim .el.nativeElement.innerHTML.substring(0, value) + '...';
  });
}

edited Plunker
Answer: You could just use a "TrimPipe" like this:
{{myText | trim:10}}

The pipe code:
import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'trim'})
export class TrimPipe implements PipeTransform {
  transform(text: any, trimValue: number) {
    if (!text) {
      return '';
    }
    return text.substring(0, trimValue) + '...';
  }
}


convert javascript variable value into PHP value

Question: Javascript:
function setitem(id, phpvalue){
                var data = {
                    Sub_category: $("#Subcategory").val()
                }
                var formsubmission = '<?php echo base_url().'index.php/AJAX/get_item'?>';
                $.ajax({
                    method: "POST",
                    url: formsubmission,
                    data: data,
                    success: function(response){
                      $("#Item_"+id).find('option').not(':first').remove();
                      $("#Item_"+id+" option:first").after(response);
                      $("#Item_"+id).prop("disabled", false);
                      var item_value = '<?php echo $Items["+phpvalue+"]["Item"]?>';
                      $("#Item_"+id).val('<?php echo $Items[0]["Item"]?>');
                      $("#Item_"+id).selectpicker('refresh');
                    }
                })
            }

Anyone can please tell me How can I use phpvalue as an array index?
Comment: Possible duplicate of [Passing javascript value to PHP](https://stackoverflow.com/questions/37086813/passing-javascript-value-to-php)
Comment: Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming)
Comment: in simple words you cannot do it that way - when the javascript is to be executed (and phpvalue exist), the php would have already run.
Comment: Can be achieved by converting php array to json then javascript array.
Answer: You want to use the PHP variable in your Javascript script so you don't want to convert javascript value to PHP but the opposite : convert php value to javascript like :
var formsubmission = <?php echo base_url() ?> + 'index.php/AJAX/get_item';

Answer: If you want to transfer a javascript variable to a php variable, there are 2 ways of doing the same.
Here's How
You can run an ajax request and then shoot an ajax request to your server and save the data into a variable using $_SESSION and then get the data back onto 'a php backed page' using the same session variable.
P.S. Make sure you wrap everything inside an if block because if the ajax request fails due to any reason,then you won't be very glad to have an unassigned php variable being used somewhere.


Weighting variables with high variance

Question: For context - I'm the data analyst for a start-up company that compares car lease deals.
I want to create an algorithm which uses weighted variables to rank the best deals based on various criteria.
One of the variables is the popularity of the vehicle, i.e. the number of orders received in the last X days, 90 in this case.
I take the % split of orders on each vehicle against the total, leaving a top-heavy distribution of 443 observations, with the 30 most popular models receiving the same number of orders as the 413 least popular.
I want to give higher weights to the most popular models, without making the rest irrelevant.

The STDEV = 54 and variance = 2,919. Mean = 26.8 and median = 6
What transformation could I apply to these values to bring them closer together, thus reducing the weight given to the variable when included in the algorithm? If more information is needed, let me know :) Thanks
Comment: I agree with @whuber in that your question could be more clear. Are you asking about how to capture each model's popularity (creating a new variable) or about how to weigh model popularity in your ranking algorithm? Or both? These are completely different problems.
Comment: "Statistical significance" and "rank" just don't go together because they are associated with *completely* different problems.  That leads me to wonder what you are really trying to accomplish.
Comment: @whuber I guess I need to learn the terminology before throwing it around. I think I just mean weight? as in I want to weight each vehicle based on its popularity, without nullifying the less popular vehicles - so that if a vehicle with 1 order in the last 3 months suddenly dropped in price it wouldn't be ignored solely based on popularity. I hope that makes sense
Comment: @AdriàLuz would I be wrong to suppose both approaches could solve my issue - that issue being the disproportionate weighting of vehicle model based on its popularity? could the new variable not be used in the ranking?
Answer: Continuing here from the comments discussion...
The way I see it, there are two different challenges that you'll need to tackle:

How do you capture / measure model popularity? That is, how do you create a metric that is higher for more popular models and lower for less popular ones?
How do you weigh model popularity in the ranking, relative to other relevant features (e.g. price)?

For 1., a simple approach would be to take the number of orders received by each model and do min-max normalization. This way, the most popular model would get a "popularity score" of 1 and the least popular model would get a "popularity score" of 0. Every other model would get a score between 0 and 1.
Solving 2. is potentially more complex, so I would need more details to be able to say anything useful. What other features do you want the ranking to take into consideration? It sounds like price might be one of those features and, based on what you've said, it seems like you believe that it should have more weight relative to the popularity of the model.
Mathematically:
$$r_i=w_1v_{i1}+w_2v_{i2}+\cdots+w_pv_{ip}$$
where $r_i$ is the ranking score for model $i$, $w_p$ is the weight for variable $p$, and $v_{ip}$ is model's $i$ actual value of the variable $p$. For example, a ranking algorithm that only considered model popularity and price might look something like this:
$$r_i=0.3\operatorname{popularity}_i-0.7\operatorname{price}_i$$
Then you could rank by $r_i$ in descending order. You can see that the real challenge is to work out how to properly define the weights.  In the past, I have used a combination of design of experiments and discrete choice modelling to find weights for ranking problems. Both are explained in this paper.
Comment: This is really useful, thank you for breaking it down. Could you recommend a guide, or if that's wishful thinking, some literature to help me better understand - and eventually implement - such weights?
Comment: @AlexMidmore In the past, I have used a combination of design of experiments and discrete choice modelling to find weights for ranking problems. Both are explained in [this paper](https://www.jstatsoft.org/index.php/jss/article/view/v050c02/v50c02.pdf).

Weighting variables with high variance


Jquery - Número SEM arredondamento

Question: Como posso deixar o resultado de uma conta com o resultado inteiro, sem arredondamento, ou seja toda vez que o jQuery executa o script ele retorna um valor e cada navegador arredonda de seu modo.
Quero uma forma de deixar o valor inteiro sem arredondamento para todas os navegadores como no exemplo:
Este é o valor real:
933 / 9 =  103.66666666666666666666666666667
No navegador:
933 / 9 = 103.766
Comment: Não será `103.667` no navegador? E 103.666...7 não é o valor real!!!
Answer: Uma opção seria forçar a quantidade de casas decimais com toFixed:
var num = (933 / 9).toFixed(20); // 103.66666666666667140362

Comment: Sem limite não existe nem sequer em papel! É uma dízima infinita https://pt.wikipedia.org/wiki/D%C3%ADzima_peri%C3%B3dica
Comment: Dessa forma limita os caracteres em 20, quero uma forma que não tenha limite.
Answer: Ja tentou usar parseFloat () ?
var num = parseFloat(933 / 9);

console.log (num) // 103.66666666666667

Ou você pode usar como Lucas C. disse mas com valor máximo, assim:
var num = (933 / 9).toFixed(100);
console.log (num); // 103.6666666666666714036182384006679058074951171875000000000000000000000000000000000000000000000000000000

Usando valor máximo da função toFixed (0 a 100).

Jquery - Número SEM arredondamento


What is the best way to harden a postfix null client on an exploited php webserver?

Question: We use postfix as a null client to send out mail from a php webserver via sendmail.  We host our incoming mail servers elsewhere and use a SPF record to authorise the server to send emails from our domain.  This all works.
Now I would like to harden postfix, specifically against exploited PHP scripts which are sending mail spam.  But the problem is that I want to allow emails to be sent to any valid address since I have customer web forms who need to be able to receive confirmation emails.  I realise this is damage limitation and there is only so much that is possible.
What things do people suggest for detecting/preventing this? or should I focus my efforts elsewhere.
Things I have thought of but not tried yet are:

To stop any emails being sent as FROM: domains I am not authorized to send from. I found how to configure this using smtpd_recipient_restrictions = check_sender_access Will this work with localhost sendmail?  Is it even worth it if the attacker knows mails only get sent with the correct FROM address?
To detect that a flood of emails is being sent by localhost and to shut it down and alert me via email. No idea how to do this or whether it's even possible.
Comment: Perhaps, using SMTP instead PHP `mail()` command will reduce attack vector and you can tune  the restriction via `smtpd_*_restrictions`. See also:  [Postfix + Php Mail() VS Postfix + SMTP](http://serverfault.com/questions/639622/postfix-php-mail-vs-postfix-smtp/649159#649159)
Answer: I suggest you move the mail server to a different machine and prevent the actual web server from communicating on port 25 with anything other than your mail server. That means even a custom spambot (which doesn't rely on any mail function and uses plain sockets) won't work.
On your mail server, create (virtual) user accounts for each one of your hosting customers so you can uniquely identify them, apply rate-limits and block them if they spam without blocking other users on the same server.
Finally install PolicyD and apply both per-customer rate-limits and spam checking of outgoing mail, to slow down the potential spammer and alert you if outgoing mail looks spammy.
Nothing is perfect of course but this set up will at the very least alert you if outbound mail looks like spam and will keep the spamming relatively slow due to rate limits until you investigate and (hopefully) nuke the entire hosting account.
Comment: @natxoasenjo of course, no actual local accounts. Virtual accounts are the way to go, and they can be backed by databases to integrate seamlessly with existing web hosting control panel/infrastructure.
Comment: +1 for the suggestion. I would however not create local accounts on the smtp server. Postifx has support for virtual users in databases or directories.


Same value keeps appearing in Javascript callback

Question: I have the following bit of code in Node.js.
function homeCallback(reply, twid) {
    var c = reply.length;

    for (var i = c - 1; i >= 0; i--) {
        var isRT;
        var tweet_id;

        if (reply[i].hasOwnProperty('retweeted_status')) {
            tweet_id = reply[i].retweeted_status.id_str;
            isRT = true;
        } else {
            tweet_id = reply[i].id_str;
            isRT = false;
        }

        console.log(tweet_id);
        var existsQ = "SELECT * FROM tweets WHERE tweet_id=" + connection.escape(tweet_id);

        connection.query(existsQ, function (err, rows) {
            console.log(tweet_id);
            //need to use tweet_id here
        });
    }
}

reply is a json response from a call to stauses/home_timeline of Twitter's API, connection is a mysql connection
If there are a couple of tweets in reply with ids of 11 and 12 I get an output like this:
11
12
12
12

Although I expect an output like this:
11
12
11
12

Comment: What is `c`? I don't see it defined anywhere?
Comment: oops I had deleted that line. Added it back.
Comment: Are you able to create a [jsFiddle](http://jsfiddle.net/) using this code to demonstrate?
Comment: I can't because of connection
Comment: Perhaps you could use some `canned` data to demonstrate.
Comment: [This](http://pastebin.com/9aZEtXCD) is an example of what reply can be.
Comment: There is nothing there?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/47684/discussion-between-jasjeev-singh-and-xotic750)
Comment: Sorry, can't. So here is a starting [jsFiddle](http://jsfiddle.net/Xotic750/hT8Z3/) with your function and the `canned` data you provided. Try filling in the rest of the details for us.
Comment: Except connection is an object of [this](https://github.com/felixge/node-mysql) Node js module. I don't know how to get that working in jsFiddle
Comment: So [here you go](http://jsfiddle.net/Xotic750/hT8Z3/2/) Is that the problem that you are having?
Comment: I am actually using twid in my actual function. I have posted a simplified version of my actual function.
Comment: Ok, but in your example it is not used. The question is, did my example demonstrate the issue that you are having?
Comment: Yes it did demonstrate the issue
Comment: Then you need to capture the variable in a closure. Lots of information here on SO. Here is one particular example that relates to your problem. http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
Comment: And now, does this [jsFiddle](http://jsfiddle.net/Xotic750/hT8Z3/3/) solve the problem? Is the output as you expect?
Comment: Yes! I'm going to test it in Node now.
Answer: The callback on connection.query() would execute asynchronously while local variable tweet_id scoped in the for-loop might get overwritten by next iteration.
Try to duplicate tweet_id inside a closure/function call.
(function(tid) {
        console.log(tid);
        var existsQ = "SELECT * FROM tweets WHERE tweet_id=" + connection.escape(tid);

        connection.query(existsQ, function (err, rows) {
            console.log(tid);
            //need to use tweet_id here
        });
})(tweet_id);

This is not ideal, but would give you some idea.


What is the advantage of Lambda Curry expression in C++?

Question: I have learned how to write the following lambda expression in C++ as.
auto addCurry = [](auto &a) {
    return [&a](auto &b) {
        return [&a, &b] (auto &c){
            return a+b+c;
        };
    };
};

std::cout << addCurry("how")("are")("you?") << std::cout;

I applied the above technique to concatenate string or to sum some numbers. I am wondering why I should refer the above lambda expression over a normal function or a normal in-line string concatenation as following?
auto my_function(auto &a, auto &b, auto &c) {
    return a + b + c;
}

std::string a = "aa", b="bb", c = "cc";
std::cout << my_function(a, b, c) << std::endl;

// or just...
std::string my_string = a + b + c;

// or just ...
int i = 1; j = 2; k = 3;
int my_i = i + j + k;

What is the advantage of the above lambda expression and when is it useful to apply in C++?
Comment: C++ doesn't have local functions, that's why.
Comment: Most likely, you shouldn't. Why do you think you should?
Comment: Because the online trainer said: prefer lambda expression as a local function of limited use. But he did not say why. That's why I wonder why lambda expression and not just a normal local function.
Answer: Currying and partial function application are useful any time you have to invoke a function (typically multiple times) with some of the arguments fixed.
There's even a library providing a facility to curry or partially apply "functions":
#include <iostream>
#include <boost/hana/functional/curry.hpp>
#include <functional>
#include <iterator>
#include <ostream>
#include <vector>

using namespace boost::hana;

constexpr auto plus = boost::hana::curry<2>(std::plus<>{});

int main() {
    std::vector<int> v{1,2,3,4};
    std::ostream_iterator<int> os(std::cout, ",");
    std::transform(v.begin(), v.end(), os, plus(3)); // prints 4,5,6,7,
}

Clearly you could have made the currying manually, as in your example,
constexpr auto plus = [](auto x){
    return [x](auto y){
        return x + y;
    };
};

but then you're just reinventing a small wheel named std::plus<>{}. Furthermore, you wouldn't be able to call it like plus(x,y), whereas you are if you curry it via hana::curry.
You could also just define
auto plus3(int x) {
    return x + 3;
}

and use
    std::transform(v.begin(), v.end(), os, plus3);

but where's "code reusability" gone?

Imho, getting a feel of the impressive importance of currying and partial function application is something that goes almost by necessity together with embracing at least a bit of functional programming.
Indeed, the purely functional programming language Haskell makes currying the default, in the sense that functions are curried by default:
twoPlusThree = 2 + 3 -- twoPlusThree is 5 (-- introduces a comment)
plus3 = (+ 3) -- we are applying the function + to just one argument
onePlusThree = plus3 1 -- onePlusThree is 4

Comment: "in many situations": can you at least name one ?
Comment: `apply a function repeatedly`? because  I cannot invoke a normal custom function as the fourth parameter of the `std::transorm()`function?
Comment: Yes, @OConnor, but how are you gonna pass to it at the same time `std::plus<>{}` and the number 3?
Comment: Thus, lambda expression is actually to be used as a closure function.
Comment: @OConnor, I don't know what you mean. As you can read [here](https://en.cppreference.com/w/cpp/language/lambda), a lambda _expression_ (i.e. the characters `[…](…){…}`, or `[…]<…>(…){…}` in C++20, or any other valid form shown in the linked) **constructs** a closure, which is **an unnamed function object**. Furthermore, there's no lambda expression at all in the first snippet in my answer.


Pegar somente dado ultimo mês usando R

Question: Preciso extrair os ultimos valores mensais da coluna 2 do dataframe ntnb45. Há alguma maneira direta para fazer isso no R?
library(GetTDData)
ntnb <- download.TD.data('NTN-B')
ntnb45 <- read.TD.files(dl.folder = 'TD Files',maturity = '150545')

Answer: Eu não sei se há uma função que faça isto diretamente, mas consegui construir um algoritmo que aparentemente resolveu o problema.
Em primeiro lugar, separei a coluna ref.date, que possui as datas em formato "yyyy-mm-dd", em outras três colunas. Uma coluna corresponde ao ano, uma coluna ao mês e outra ao dia. Chamei este resultado de datas:
datas <- strsplit(as.character(ntnb45$ref.date), split="-")
datas <- matrix(as.numeric(unlist(datas)), ncol=3, byrow=TRUE)

Estou exibindo o código em duas linhas para ser didático. É perfeitamente possível rodar este comando em uma linha apenas.
Com o data frame datas construído, basta que atentemos a um fato que ocorre quando o mês acaba. Sempre que o mês muda, o dia "zera". Ele não volta a zero literalmente, mas o valor do primeiro dia útil de um mês é um valor numérico menor do que o ultimo dia útil do mês anterior. Assim, basta encontrarmos os locais em que, na posição seguinte, os dias ficaram com valor numérico inferior ao da posição atual. Isto pode ser obtido através de uma primeira diferença:
index <- which(diff(datas[, 3]) < 0)

o que este comando faz é calcular as diferenças do tipo x[n+1]-x[n]. Se n for o valor numérico do dia do mês, este valor será sempre igual a 1, exceto quanto o mês muda. Ou seja, o vetor index possui todas as posições nas quais o mês atual mudou. Agora basta selecionar as minhas correspondentes no data frame original:
ntnb45.ultimo <- ntnb45[index, ]
head(ntnb45.ultimo)
  ref.date yield.bid price.bid   asset.code matur.date
190 2004-09-30    0.0906   1022.04 NTN-B 150545 2045-05-15
210 2004-10-29    0.0905   1033.15 NTN-B 150545 2045-05-15
230 2004-11-30    0.0905   1002.60 NTN-B 150545 2045-05-15
253 2004-12-31    0.0905   1018.52 NTN-B 150545 2045-05-15
22  2005-01-31    0.0903   1035.64 NTN-B 150545 2045-05-15
40  2005-02-28    0.0905   1045.57 NTN-B 150545 2045-05-15

Para obter os valores da coluna 2 apenas dos últimos dias do mês, basta rodar
ntnb45.ultimo[, 2]

Answer: Uma solução rápida e simples com o dplyr:
library(dplyr)
ultimos <- ntnb45 %>% group_by(anomes = format(ref.date, "%Y%m")) %>% filter(ref.date == max(ref.date))
ultimos

Source: local data frame [151 x 6]
Groups: anomes [151]

     ref.date yield.bid price.bid   asset.code matur.date anomes
       <date>     <dbl>     <dbl>        <chr>     <date>  <chr>
1  2004-09-30    0.0906   1022.04 NTN-B 150545 2045-05-15 200409
2  2004-10-29    0.0905   1033.15 NTN-B 150545 2045-05-15 200410
3  2004-11-30    0.0905   1002.60 NTN-B 150545 2045-05-15 200411
4  2004-12-31    0.0905   1018.52 NTN-B 150545 2045-05-15 200412
5  2005-01-31    0.0903   1035.64 NTN-B 150545 2045-05-15 200501
6  2005-02-28    0.0905   1045.57 NTN-B 150545 2045-05-15 200502
7  2005-03-31    0.0905   1059.98 NTN-B 150545 2045-05-15 200503
8  2005-04-29    0.0904   1076.44 NTN-B 150545 2045-05-15 200504
9  2005-05-31    0.0910   1039.66 NTN-B 150545 2045-05-15 200505
10 2005-06-30    0.0910   1049.90 NTN-B 150545 2045-05-15 200506
# ... with 141 more rows

Pegar somente dado ultimo mês usando R


Send and Recive Payments With Credit Cards Only

Question: We are Making a App in which We Take Payments from Customers and Give Them Points
same like Customer can give Points to Us and Take Payment . This is a Game
is there any payment Gate Way That Directly Paid Customer in his/her Credit Card
we want Payments Direct Credit Cards To  Credit Cards
we will take customer credit cards when he will signup or later when he will give us points for Payment
Any Suggestion will be Appreciated
Answer: For PayPal, look at the following.

DoReferenceTransaction - This will allow you to hit somebody's credit card to process an amount without authentication so long as you've done a prior Authorization or Sale using the same credit card.  So you could have people run an Authorization on their card just to ensure it's good and get a transaction ID that you can use in future DRT requests.
DoNonReferencedCredit - This will allow you to load funds onto a credit card without referencing any previous transaction (so it's different than a refund.)  Keep in mind that when you send somebody money this way you won't get refunded fees like you would if you used the actual RefundTransaction API, so you may want to consider that.

You'll want to go through the detailed documentation for Reference Transactions, of course, to get a good understanding of it.
You'll also need a Payments Pro account to be able to process credit cards directly and utilize these features.
If you happen to be working with PHP I'd recommend using my class library for PayPal.  It'll make the API calls very simple for you.
Comment: Nice Thanks .what about Stripe?
Comment: Stripe makes you wait 7 - 10 days (or more) for your money.  That could cause issues with what you're explaining you're trying to do I would think.
Comment: i read from stripe doc they transfer fund  only in USA any other cool payment gate way  that allow me to transfer funds through CC to CC?
Comment: are you sure we can transfer funds to customer?DoNonReferencedCredit  have nothing param to transfer
Comment: DNRC allows you to push funds to a credit card from your PayPal account.


Action of a group $G$ on copies of $G$

Question: Let $G$ be a group and $G^n$ be the direct product of $n$ copies of $G$. There is an action $\psi$ of $G$ on the set $G^n$ such that :
$\psi\left(g,(g_1,\;g_2,\ldots,\;g_n)\right) = \left(g_1 \cdot g \cdot g_1^{-1} \cdot g_1, \;g_1 \cdot g \cdot g_1^{-1} \cdot g_2, \ldots, \;g_1 \cdot g \cdot g_1^{-1} \cdot g_n\right)$
I'm studying this from scratch, but I'm sure this group action has already appeared somewhere. My question is therefore: has this kind of action already been studied, and if so, what was the context ?
Comment: Yes, that is better. It took me a while to even see that is is an action (you might want to remark that it is a right action, not a left action, since many will read action as meaning left action). I don't think I have seen this action before, though it may simply be that I have only seen it "disguised".
Comment: I am not sure I understand your notation. You don't seem to be acting on $n$-tuples but rather on products of $n$ elements.
Comment: My answer was developed by attempting to (dis)prove that it was an action in a less tedious manner. I've run into similar formulas before (without the left/right mix) when I had my group acting too soon or too late in a more complicated situation in group cohomology.
Comment: I am curious about how you came across this action.
Comment: @TobiasKildetoft : I was looking for a group action on $G^n$ which respects the intervals $g_1^{-1}g_2, g_1^{-1}g_3,...,g_1^{-1}g_n$ relative to $g_1$. Of course, the basic left action sending $(g_1,...,g_n)$ to $(gg_1,...,gg_n)$ is also valid.
Answer: Your action is more standard after relabeling the domain. Possibly you are dealing with more of a "projective" space, and chose the "wrong" way to make it look affine.
Consider the map $f:G^n \to G^n$ given by $f(g_1,g_2,\dots,g_n) = (g_1,g_1 g_2, \dots, g_1 g_n)$.
Then $f^{-1}:G^n \to G^n$ is given by $f^{-1}(g_1,g_2,\dots,g_n) = (g_1, g_1^{-1} g_2, \dots, g_1^{-1} g_n)$ and $\psi^f : G \to \operatorname{Sym}(G^n)$ is a right action given by:
$$\begin{align*}
\psi^f \left(g, \left(g_1,g_2,\dots,g_n \right)\right)
&= f^{-1}\left( \psi\left( g, f\left(g_1,g_2,\dots,g_n\right)\right)\right) \\
&= f^{-1}\left( \psi\left( g, \left(g_1,g_1 g_2, \dots, g_1 g_n\right)\right)\right) \\
&= f^{-1}\left( g_1g, g_1g g_2, \dots, g_1g g_n \right) \\
&= \left( g_1 g, g^{-1} g_2, \dots, g^{-1} g_n \right)
\end{align*}
$$
This is more or less the standard right action on $G^n$. In the first coordinate it is right-multiplication by $g$, and on the other coordinates it is left-multiplication by $g^{-1}$. Each is standard, but I guess it is not horribly common to use both at the same time.
Comment: Thanks for your answer. Could you precise what was your context (group cohomology or other...) in which you encountered such actions ? As explained in my comment above, I was looking for an action which preserves the intervals $g_1^{-1}g_i$.
Comment: $G^n$ was $V^n$ for $V$ and abelian group and $G$ acted on $V$, but actually $G$ was supposed to act on $V^n/\Delta$ where $\Delta=\{ (v,v,\dots,v) : v \in V \}$. It was like projective space, where you can divide by any coordinate (say $g_1$) to get an equivalent "vector". As far as I recall, it was fairly close to standard ideas for extensions of groups by abelian groups. I think I had a horrible formula when I divided by $g_1$, but a good formula when I divided by $g_1^g$, which required some re-indexing all around. The "bar resolution" versus the "reduced bar resolution" might be similar.

Action of a group $G$ on copies of $G$


SAS: Determine programmatically what machine SAS is running on

Question: I am trying to write a macro, but it accesses a path variable

on Windows, it may be C:\Temp
On Unix, it may be /tmp

How can I figure out programmatically  what type of machine my SAS is running on so I can assign to appropriate value to path?
Thanks!
Answer: %put _automatic_; is the first place you should go when looking for things like this - this shows all of the automatically defined macro variables, many of which define your working environment.
In this case, &SYSSCPL. gives the operating system (in my case X64_7PRO for windows 7 64 bit).  There is also &SYSHOSTNAME which is the computer's "name" (defined differently on various OSs).


Finding the absolute minimum of $f(x)=\frac{1}{x}\sin x$

Question: For the function $f(x)=\frac{1}{x}\sin x$, the domain is $\mathbb{R}-\left\{0\right\}$, but how do I analytically determine the range of the function? Since it's not $[-1,1]$.
Graph:
Comment: The function has a lot of local maxima and minima, so then how could you determine which one is the absolute maximum/minimum?
Comment: Can't you just determine the maxima and minima by taking the derivative?
Comment: You should search for the closest to zero point where the derivative is zero. This means the closest to zero solutions of $\tan (x) = x$.
Comment: I could do that, but how do you know that the absolute minimum is close to zero?
Comment: From your graphic
Comment: Oh I forget to mention, in this case I don't have access to the graph, all I got to work with is the function.
Comment: You'd have to solve $tan(x)=x$ analytically, which I believe is not possible. I'm not sure though.
Comment: I think that's possible using Taylor series, but I was wondering if there was another way...
Comment: What do you mean by " in this case I don't have access to the graph", you just post it
Comment: Yes, but in the course I am taking, we need to solve these kind of problems without using calculators that can draw graphs.
Comment: Just pretend you didn't see the graph :)
Answer: Hint: Let $f(x)={\displaystyle \sin x\over x}$. Note that $f(x)$ is an even function (its graph is symmetric about the $y$-axis). Note also that
$$|f(x)|<{1\over 2\pi} \qquad \mbox{ for } |x|>2\pi.$$
Now it remains to analyze only a couple of local extrema points with $|x|\le2\pi$ and confirm that the one with $x\approx4.49$ is indeed the global minimum, with $f(x)<-{1\over2\pi}$. (You will get two minimum points which are symmetric about the $y$-axis.)
Comment: how do we find those? By taking the derivative?
Comment: Yes. We analyze local extrema by taking the derivative, which is $f'(x)={x\cos x - \sin x\over x^2}$. Now we just find those $x$ where $f'(x)$ is zero, and determine which of them are indeed minima.
Comment: The function is $\frac{\sin(x)}{x}$. The derivative is $\frac{\cos(x)}{x}-\frac{\sin(x)}{x^2}=\frac{x\cos(x)-\sin(x)}{x^2}$, so the limit points are found at the solutions to $\tan(x)=x$ I have had trouble with this exact equation before.
Comment: Actually $\tan(x)=x$ has a unique solution in $(0, 2\pi)$
Comment: But there is no way to analytically solve tan(x) = x right?
Comment: I don't think so.
Comment: @Eugen In fact $\tan(x) =x$ has three solutions when $-2\pi<x<2\pi$. When you cannot solve analytically, do it numerically.
Comment: @Alex I don't think so, it's only x=4.49340945790906 in $(0, 2\pi)$
Comment: @Eugen You and I are both right. Three solutions in $(-2\pi,2\pi)$ while only one solution in $(0,2\pi)$.
Comment: I'll try to do it numerically, thank you guys!


What is ValueError: too many values to unpack (expected 2)?

Question: Im trying to convert midi files to csv, make changes, and then change back into midi. I wan to do this all in python using the py_midicsv module.
However, I run into an error when i try to follow the documentation on: https://github.com/timwedde/py_midicsv
#Convert back to csv
import py_midicsv
csv_string = py_midicsv.midi_to_csv("example.mid")
midi_object = py_midicsv.csv_to_midi(csv_string)

The code above is straight from the documentations but I run into the error:
ValueError                                Traceback (most recent call last)
<ipython-input-17-2cb6d586ec9e> in <module>
      1 #Convert back to csv
      2 import py_midicsv
----> 3 midi_object = py_midicsv.csv_to_midi(csv_string)

~/.local/lib/python3.6/site-packages/py_midicsv/csvmidi.py in parse(file)
     44             pattern.append(track)
     45         else:
---> 46             event = csv_to_midi_map[identifier](tr, time, identifier, line[3:])
     47             track.append(event)
     48     pattern.make_ticks_rel()

~/.local/lib/python3.6/site-packages/py_midicsv/csv_converters.py in to_AfterTouchEvent(track, time, identifier, line)
     24
     25 def to_AfterTouchEvent(track, time, identifier, line):
---> 26     cannel, value = map(int, line)
     27     return AfterTouchEvent(tick=time, channel=channel, value=value)
     28

ValueError: too many values to unpack (expected 2)

What does this error mean and how can I fix things?
Answer: cannel, value = map(int, line)

the problem is with this line.
you are trying to unpack this map object into 2 objects, but it consists of more than 2 object, so python don't know what to do with the rest of the values.
you will need to understand what this map object contains, and what data you need to get from it. try to print it and see what data it holds.
Comment: And "channel" (which is used in the next line) is misspelled, so this part of the code was obviously never tested.


Stack fails to compile under windows

Question: I have a rather troublesome bug preventing me to build a small haskell project of mine under Windows, which you can find here if you want to try to compile it.I am under cygwin64.
I'm using stack as a build helper, on the advice given on this post.
Now, the build is failing near at the end (which is rather frustrating after trying to do so for several hours).
Error message is the following:
setup.exe:
'C:\Users\Julien\AppData\Local\Programs\stack\x86_64-windows\ghc-8.0.2\bin\ghc-pkg.EXE'
exited with an error:
cairo-0.13.4.2: Warning: haddock-interfaces:
C:\cygwin64\tmp\stack11608\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\doc\html\cairo\cairo.haddock
doesn't exist or isn't a file
cairo-0.13.4.2: Warning: haddock-html:
C:\cygwin64\tmp\stack11608\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\doc\html\cairo
doesn't exist or isn't a directory
cairo-0.13.4.2: include-dirs: /usr/include/cairo is a relative path which
makes no sense (as there is nothing for it to be relative to). You can make
paths relative to the package database itself by using ${pkgroot}. (use
--force to override)
cairo-0.13.4.2: include-dirs: /usr/include/glib-2.0 is a relative path which
makes no sense (as there is nothing for it to be relative to). You can make
paths relative to the package database itself by using ${pkgroot}. (use
--force to override)
cairo-0.13.4.2: include-dirs: /usr/lib/glib-2.0/include is a relative path
which makes no sense (as there is nothing for it to be relative to). You can
make paths relative to the package database itself by using ${pkgroot}. (use
--force to override)
cairo-0.13.4.2: include-dirs: /usr/include/pixman-1 is a relative path which
makes no sense (as there is nothing for it to be relative to). You can make
paths relative to the package database itself by using ${pkgroot}. (use
--force to override)
cairo-0.13.4.2: include-dirs: /usr/include/freetype2 is a relative path which
makes no sense (as there is nothing for it to be relative to). You can make
paths relative to the package database itself by using ${pkgroot}. (use
--force to override)
cairo-0.13.4.2: include-dirs: /usr/include/libpng16 is a relative path which
makes no sense (as there is nothing for it to be relative to). You can make
paths relative to the package database itself by using ${pkgroot}. (use
--force to override)

--  While building custom Setup.hs for package glib-0.13.5.0 using:
  C:\cygwin64\tmp\stack11608\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\setup --builddir=.stack-work\dist\ca59d0ab build --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Logs have been written to: C:\cygwin64\home\Julien\syme-master\.stack-work\logs\glib-0.13.5.0.log

[1 of 2] Compiling Main             ( C:\cygwin64\tmp\stack11608\glib-0.13.5.0\Setup.hs, C:\cygwin64\tmp\stack11608\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\Main.o )
[2 of 2] Compiling StackSetupShim   ( C:\sr\setup-exe-src\setup-shim-Z6RU0evB.hs, C:\cygwin64\tmp\stack11608\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\StackSetupShim.o )
Linking C:\cygwin64\tmp\stack11608\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\setup.exe ...
Configuring glib-0.13.5.0...
Building glib-0.13.5.0...
In file included from C:/cygwin64/usr/include/glib/gtypes.h:34:0,
                 from C:/cygwin64/usr/include/glib/galloca.h:32,
                 from C:/cygwin64/usr/include/glib.h:30,
                 from C:/cygwin64/usr/include/gobject/gbinding.h:28,
                 from C:\cygwin64\home\Julien\syme-master\../../../usr/include\glib-object.h:23:
C:/cygwin64/usr/include/glib/gversionmacros.h:257:2: error: #error "GLIB_VERSION_MIN_REQUIRED must be >= GLIB_VERSION_2_26"
 #error "GLIB_VERSION_MIN_REQUIRED must be >= GLIB_VERSION_2_26"
  ^
Preprocessing library glib-0.13.5.0...
setup.exe: Error during preprocessing

The point is that according to cygwin installer, I have libglib2.0-devel version 2.52.3-1 installed. Is it the wrong version of glib2? Is there any conflict between other glib versions? If so, how can I make stack understand to check
where are the correct versions?
I must say that I messed up a bit by adding relative paths inside of the stack.yaml file, I don't know if it is troublesome or not.
Any help would be greatly appreciated.
UDPATE: As the comments suggested, I changed my project-local stack.yaml to add the follwing (took me a while to figure out how to write the path on windows)
extra-include-dirs: [c;\\cygwin64\\usr\\include]
extra-lib-dirs: [c;\\cygwin64\\lib]

Inside of those, I unzipped the libs provided by the link user2407038 provided in the comments. Now, the error message looks like this:
--  While building custom Setup.hs for package cairo-0.13.4.2 using:
  C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\setup\setup --builddir=.stack-work\dist\ca59d0ab build --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Logs have been written to: C:\cygwin64\home\Julien\syme-master\.stack-work\logs\cairo-0.13.4.2.log

[1 of 2] Compiling Main             ( C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\Setup.hs, C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\setup\Main.o )
[2 of 2] Compiling StackSetupShim   ( C:\sr\setup-exe-src\setup-shim-Z6RU0evB.hs, C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\setup\StackSetupShim.o )
Linking C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\.stack-work\dist\ca59d0ab\setup\setup.exe ...
Configuring cairo-0.13.4.2...
Building cairo-0.13.4.2...
C:\cygwin64\tmp\stack10676\cairo-0.13.4.2\cairo-gtk2hs.h:1:18: fatal error: cairo.h: No such file or directory
compilation terminated.
Preprocessing library cairo-0.13.4.2...
setup.exe: Error during preprocessing

-- While building custom Setup.hs for package glib-0.13.5.0 using:
C:\cygwin64\tmp\stack10676\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\setup --builddir=.stack-work\dist\ca59d0ab build --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Logs have been written to: C:\cygwin64\home\Julien\syme-master\.stack-work\logs\glib-0.13.5.0.log

[1 of 2] Compiling Main             ( C:\cygwin64\tmp\stack10676\glib-0.13.5.0\Setup.hs, C:\cygwin64\tmp\stack10676\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\Main.o )
[2 of 2] Compiling StackSetupShim   ( C:\sr\setup-exe-src\setup-shim-Z6RU0evB.hs, C:\cygwin64\tmp\stack10676\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\StackSetupShim.o )
Linking C:\cygwin64\tmp\stack10676\glib-0.13.5.0\.stack-work\dist\ca59d0ab\setup\setup.exe ...
Configuring glib-0.13.5.0...
Building glib-0.13.5.0...
Preprocessing library glib-0.13.5.0...
setup.exe: glib-object.h: File does not exist

Where can I find those headers?
Comment: You can't really use cygwin with GHC, because on Windows GHC will expect to be in a Windows environment. In particular, there's nothing you can do to get GHC to recognize the path `/usr/include/cairo` as a valid Windows path (because it isn't). You have to install the native versions of glib (same goes for any other dependancy) and make sure that GHC not using cygwin `gcc` (stack does a good job of doing so, typically). Also note that your build is not failing near the end, it's doing so basically right at the start (when building a dependency, not even your package).
Comment: [Here](https://github.com/winlibs/glib) is the glib source; if you feel adventurous you can try to build it yourself. Otherwise you have to find pre-built binaries somewhere on the internet (a quick google search turns up [this](https://ftp.gnome.org/pub/gnome/binaries/win32/glib/))
Comment: Those are (afaik) not relative paths, but Unix/Linux paths, and apparently the compiler can not make sense out of these.
Comment: @user2407038 by native package, you mean Windows package? Because I looked for an available version of glib for Windows and I did not found out any...
Comment: I would expect you could find detailed instructions for installing Stack from scratch on Windows. Did you dig around for those?
Comment: @user2407038 thanks, will try so.I have installed Stack with the Haskell platform for windows (https://www.haskell.org/platform/#windows)
Comment: FWIW, I can't say if this will address your particular problem, but so far, I've been running Stack exclusively from Git Bash on Windows, and I haven't run into problems with interoperability so far...
Answer: I would take a look at the windows install instructions for gtk2hs: https://wiki.haskell.org/Gtk2Hs/Installation#Windows
You can download the bundle directly (from https://www.gtk.org/download/windows.php), or install it using the pacman distributed with the platform-installed msys distro.
You should use the msys version or the independent version, not the cywin one, as ghc is built to work with msys, not cygwin.
Once that's done you should be able to, having set up your paths correctly, cabal install cairo.

Stack fails to compile under windows


S3 to cloudfront edge location vs cloudfront to end user transfer ratio

Question: We host videos in amazon S3 and use cloudfront to deliver them. Here is last months numbers:
4,2 TB total traffic from cloudfront to end user. 4 TB of this is in europe, the rest mainly in the US.
This cost us $512. All as expected.
In addition we have cost of transfer from S3 to edge locations of roughly 1 TB. = cost $115
This is 22,4% of the cost of transfer to the end user and 18% of the combined cost. What I wonder, is that normal? I feel it's a bit much.
We have 280 GB of video stored in S3, spread out on about 20000 videos. Most of our traffic is from videos that are fresh. The top 100 videos for that month was responsible for about 80% of the total traffic.
I just feel that maybe too many videos are unnecessarily downloaded at edge locations and sees few hits. And then they are removed and later it is requested again and we get another download to the edge server.

Is this ratio normal, or at least somewhat close to other people's experiences?
Can I somehow tell cloudfront to put a threshold or something before it starts caching the file? Like: don't cache this file until you see x downloads within a day close to your location.
If the above is not possible, is there other tips on how I could achieve the same. Don't serve lesser frequent accessed files through cloudfront, just go directly to S3. I feel this might be a problem since I use the streaming feature of cloudfront anyway.

I haven't changed the TTL, so I assume it's on the standard 24 hours. This doesn't change anything anyway if I increase it as cloudfront will not download the file again if it has not changed (they don't).
The problem is that the file goes out of cache.
Answer: I would serve the less popular videos straight off S3. YouTube doesn't start serving videos off their CDN until a video hits 300 views. I would track the time of the last x many views of videos storing a list in something like Redis, and if the the x'th last view was within a certain time frame, only then serve the video off CloudFront.
Comment: A good choice and probably the option we will go for. However the biggest downside to this is that serving the videos straight from S3 will not allow us to do RTMP streaming. Likely this is a fair tradeoff though, since most of our videos are short anyway. Maybe always use cloudfront for longer videos regardless of view count. The ability to skip withing long videos randomly is important.
Comment: What format are your videos? If you're serving MP4 and using FFmpeg to transcode them, using FFmpeg's qt-faststart on the video will allow seeking before the video has finished downloading. I serve MP4 straight off S3 without issue. :-)


Scheduling jobs in salesforce using customization

Question: How to schedule jobs in salesforce which run on daily basis using customization .
Her i should also be able to know the number of days remaining
Comment: Please clarify your question.  Do you want to know how to schedule jobs via Apex code?  What are you trying to customize?
Comment: i want to know whether it is possible to schedule jobs via built in customization.If not how do we do using apex code.Give me some example
Comment: I think you meant 'config' or 'configuration' instead of 'customization'
Answer: Yes, you can schedule Apex classes for execution using configuration only. Below is the screenshot of the screen that shows all the option you get. In order to get to this screen go to Setup > Develop > Apex Classes and click Schedule Apex button in the top of the list view.


Keycloak login and register actions not https

Question: I have nginx that will handle https, but the login and register forms of keycloak have http actions and I can't find a way to set them to https.
Making them to https in the browser works correctly.
There are two variables:
<code>{url.registrationUrl}
{url.loginAction}
</code>
Where are these values coming from?
EDIT:
I made a workaround
<code>{url.registrationUrl?replace('http', 'https')}
</code>
Comment: have you tried setting enable ssl option? Option is present in realm-settings
Comment: yes, but then I need to configure an ssl certificate for the keycloak server, which I already did for nginx, it just seems a bit awkward. I keycloak was running on different machine inside a private network things could have been way easier.
Answer: Use proxy-address-forwarding.

Forward the original schema in Nginx (server.conf)
proxy_set_header X-Forwarded-Proto $scheme;
Use this information in Keyclok (standalone/domain.xml)
proxy-address-forwarding=true in http-listener

https://www.keycloak.org/docs/latest/server_installation/index.html#identifying-client-ip-addresses


How to find the ports of all running PostgreSQL instances (as a non-root user)

Question: I have a monitoring script (running as an unprivileged user) that needs to check all instances of Postgres currently running on the same host (Ubuntu Linux 18.04). Is there an easy way to find all their port numbers?
I was thinking of listing all files matching /var/run/postgresql/.s.PGSQL.* but I'm not sure whether this is reliable or the easiest way.
Answer: An easy way with Debian/Ubuntu would be to use pg_lsclusters (as provided by the postgresql-common package).
This command lists the clusters with ports, statuses and other information:

$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
11  main    5433 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
12  main    5432 online postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

$ ports=$(pg_lsclusters --no-header | awk '{ print $3; }')

$ echo $ports
5433 5432
Comment: Perfect! That's just what I wanted.
Answer: May be something like this:
 ss -xpntl| grep postmaster

Comment: I would say, yes. It's not guaranteed, that socket files will be located in the */var/run* directory. With *ss -x* you can see open socket files independent from their location.
Comment: Thank you. `ss -xpntl |grep postgres` returns `u_strLISTEN 0       128              /var/run/postgresql/.s.PGSQL.5432 53007754                                          * 0` - but is this more reliable somehow than just looking for socket files in /var/run/postgresql ?


Finding a cubic polynomial whose zeroes are the same as collectively of two other quadratic polynomials.

Question: The question is:
Find a cubic polynomial $p(x)$ whose zeroes are the same as those collectively of polynomials $g(x) = 2x^2 - 9x + 4$ and $f(x) = 2x^2 + 3x - 2$. Given that $p(0)$ = 8.
I tried solving the question but I got a little confused at the "collectively" part and also on how to use the value of $p(0)$.
Using the quadratic formula, I calculated the roots of $g(x)$ as 4 and 1/2.
Similarly, the roots for $f(x)$ came out to be 1/2 and -2.
And then I added them up to get two roots of the cubic polynomial $p(x)$ as 9/2 and -3/2.
( because they said it's roots are same as those collectively of the two quadratic polynomials. )
I don't exactly know how to proceed after this.
Please explain. Thanks.
Comment: Thanks a lot. It worked for me. :)
Comment: When you collect the root, it means that the roots of $p(x)$ are the same as the roots of $f(x)$ and $g(x)$. Since they are $1/2$,$4$,$1/2$ and $-2$ and that $p(x)$ is cubic, then its roots are $1/2$,$4$ and $-2$.
Comment: You are welcome. I am always glad when I can help. I suppose that now you understand what we mean when we $collect$. Cheers :)
Comment: Yes, I know now. ;)
Answer: Hint
We have
$$p(x)=\lambda(x-4)(x+2)\left(x-\frac12\right)$$
where
$$p(0)=\lambda\times(-4)\times 2\times\left(-\frac12\right)$$
Comment: I didn't get why you put the lambda in there.
I managed to get the answer by writing $p(x) = (x - 4) (x + 2) (x - 1/2)$, which led me to the polynomial $2x^3 - 5x^2 - 14x + 8$.
Since after collecting the roots, the total number of roots was 3, I don't understand the relevance of giving the value of $p(0)$.
Can you please elaborate a little?
Comment: If $p(x)$ is a polynomial that has the roots $4,-2$ and $\frac12$ so what are the roots of $\lambda p(x)$?
Comment: But we have to calculate the roots of $p(x)$, not lamba $p(x)$, right? Or am I missing something?
Comment: For all $\lambda\ne0$, $\lambda p(x)$ has the same roots of $p(x)$ but there's only one polynomial that further has the condition $p(0)=8$ so we should find the adequate $\lambda$ that gives this condition.
Answer: We could try $$p(x)=f(x)g(x).$$ At least every root of $f$ or $g$ would then also be a root of $p$. However, this has degree four, not three. Fortunately, $f$ and $g$ have a root in common (found by explicitly determinig the roots or by computing their gcd with Euclid's algorithm), namely $x=\frac12$. So divide by the corresponding linear factor:
$$p(x)=\frac{f(x)g(x)}{x-\frac12} $$
Now the only porblem remaining is a scaling factor. Multiply with a suitable constant to ensure $p(0)=8$.
Comment: I think the calculation required to compute this would be long and error-prone. So, in my opinion, it would be better if we just calculate $p(x)$ as $(x - 4) (x + 2) (x - 1/2)$, since the total number of roots is 3 because "1/2" is common, as you rightly said.
Also, I don't get what you meant by a "scaling factor". Can you please explain?
Answer: It is also possible to work out the coefficients of the cubic polynomial without using the quadratic formula on the two given polynomials (although we'll find that we pick up all three roots along the way).  Since neither of the quadratic polynomials is a "binomial-square", we infer that the three roots of the cubic polynomial are distinct; we are also given the constant term for the cubic, so we have
$$ ax^3 + bx^2 + cx + 8 \ = \ a · (x-r)·(x-s)·(x-t) \ \ , $$
$$ 2x^2 - 9x + 4 \ = \ 2 · (x-r)·(x-s) \ \  , \ \ 2x^2 + 3x - 2 \ = \ 2 · (x-r)·(x-t) \ \ . $$
Viete's relations tell us that $ \ -arst \ = \ 8 \ \ , \ \ 2rs \ = \ 4 \ \ , \ \ 2rt \ = \ -2 \ \   $ (we will have further use for them shortly).
If we subtract one of the quadratic polynomials from the other (convenient here because the leading coefficients of both are the same), we have
$$ 2·(x-r)·(x-s) \ - \ 2·(x-r)·(x-t) \ \ = \ \ 2·(x-r)·[(x-s) \ - \ (x-t)] $$ $$ = \ \ 2·(x-r)·(t-s) $$
$$ \Rightarrow \ \ (2x^2 - 9x + 4) \ - \ (2x^2 + 3x - 2) \ = \ -12x + 6 \ = \ -12·\left(x - \frac12 \right) \ \ . $$
[This is related to the Euclidean algorithm technique mentioned by Hagen von Eitzen .]  We now know that the recurring zero is $ \ r  = \frac12 \ $ and the difference between the other zeroes is $ \ 2·(t-s) \ = \ -12 $ $ \Rightarrow \ t-s \ = \ -6 \ . $  (We don't end up using this difference directly, but we'll soon see that it is so.)
At this point, we have everything we need to find the three unknown coefficients:
$$ 2rs \ = \ 4 \ \ \Rightarrow \ \ rs \ = \ 2 \ \ \Rightarrow \ \  s \ = \ 4 \ \ , \ \ 2rt \ = \ -2 \ \ \Rightarrow \ \ rt \ = \ -1 \ \ \Rightarrow \ \  t \ = \ -2 \ \ , $$
$$ -arst \ = \ 8 \ \ \Rightarrow \ \ a · \left(\frac12 \right) · 4 · (-2) \ = \ -8 \ \ \Rightarrow \ \ a \ = \ 2 \ \ .  $$
Viete goes on to tell us that
$$ b \ = \ a·(-r-s-t) \ = \ 2  ·  \left(-\frac12 \ - \ 4 \ - \ [-2] \right) \ = \ -5 \ \ , $$
and
$$ c \ = \ a·(rs+rt+st) \ = \ 2 \ · \ \left(2 \ + \ [-1] \ - \ 4·[-2] \right) \ = \ -14 \ \ . $$
Our cubic polynomial is therefore $ \ 2x^2  -  5x^2  -  14x  +  8 \ \ . $  [Solving for zeroes by way of an online resource -- or the Rational Zeroes Theorem, synthetic division, and patience -- confirms this result.]
$$ \ \ $$
To elaborate on Hagen von Eitzen's approach, once we have found the common linear factor between the two quadratic polynomials, we can obtain the cubic polynomial from
$$ \frac{k \ · \ [2·(x-r)·(x-s)] \ · \ [2·(x-r)·(x-t)]}{(x - r)} \ \ = \  \ \frac{k \ · \ (2x^2 - 9x + 4)· (2x^2 + 3x - 2)}{\left(x - \frac12 \right)} \ \ ,  $$
where the common factor between the polynomials is found as discussed above and $ \ k \ $ has been referred to as a "scaling factor", which must be brought in to be sure that the given constant term of $ \ 8 \ $ is produced.  (The division by that monic linear factor does not affect the leading coefficient.) The cubic polynomial formed by this ratio must have the specified value for $ \ x = 0 \ \ ,  $ hence,
$$ \frac{k \ · \ (4)· (- 2)}{\left(- \frac12 \right)} \  = \ 8 \ \ \Rightarrow \ \ k \ = \ \frac12 \ ,  $$
We can now calculate (by hand or with on-line aid)
$$ \frac{\frac12 \ · \ (2x^2 - 9x + 4)· (2x^2 + 3x - 2)}{\left(x - \frac12 \right)} \ \ = \ \ \frac{2x^4 \ - \ 6x^3 \ - \ \frac{23}{2}x^2 \ + \ 15x \ - \ 4}{\left(x - \frac12 \right)} \ \ . $$
We then apply polynomial or synthetic division here (or software):
$$ 1/2 \ \ \ |  \ \ 2  \quad -6 \quad -23/2 \quad 15 \quad -4   $$
$$ \quad \quad \quad \quad 1 \quad \ \ -5/2 \quad -7 \quad \quad 4$$
$$ \quad \quad \quad   ---------------- $$
$$ \quad \quad   2 \quad -5 \quad \ -14 \quad \quad  8 \quad \quad | \ \ 0  $$
to yield the "reduced" polynomial, $ \ 2x^3  -  5x^2  -  14x  +  8 \ \ . $


How do I return HTML (the content type, not just the string) from a WebApi endpoint?

Question: This is an endpoint in ASP.NET WebApi2 where I want the content type returned as a HTML document.  This currently returns it as text/plain.
 public HttpResponseMessage GetHtmlPreview(int id, bool isHtml)
    {
        var msg = new HttpResponseMessage()
        {
            Content = new StringContent("<title>test</title>
TEST HTML STUFF HERE" + id + "
"),
        };
        return msg;
    }

I want it to return as text/html so it renders fine within an iFrame.
Comment: At this point you probably just want a standard MVC controller. - API controllers should be used to return data, not HTML.
Comment: yes, normally i would return from a MVC controller, but the way the current app is, this needs to be a GET hanging off the very same endpoint, so I needed to still use ApiController versus a new MvcController
Comment: Seems Fishy, Why would it NEED to be a GET from the same endpoint? Im not sure I am following you... sounds like a code smell
Answer: You could set the ContentType like so:
msg.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

I do agree with BenjaminPaul in that a View backed by your controller seems like a better approach here.
Comment: Yep, agreed.  For brownfield reasons, I still needed to add it to an existing endpoint.  Thanks, this worked.
Answer: I use this
public IResult Function()
{
    return Results.Text("your_html_string", contentType: "text/html");
}


How to convert UTC time into IST Time in mongoDB schema?

Question: i am placing date.now() in default section in database schema. but i get only UST time in mongodb. i need IST time. how to convert it?
my code
created at:
{
type:Date,
default:Date.now()
}

Comment: Date values in MongoDB are always any only stored as UTC time. Usually the client application is responsible to display it in local time.
Answer: You can convert in your code (python / java) and then store it in your DB. Best practice would be to store your data as UTC inside your DB and then handle conversion at the app layer.


How to automate the replacement of special characters in URLs?

Question: The standard behavior (*) for friendly URLs in Drupal is replacing special characters by a hyphen in the friendly URL.
For instance,  without any input from the user, versão becomes vers-o and  conteúdo becomes conte-do. However, we need the character to be replaced by their corresponding non-accent ASCII values, such as versao  and conteudo.
Currently, we manually edit the URL when creating content. Is there a way to automate it?

(*): I assume it's out-of-the-box behavior, but this Drupal instance had modules installed and configured by other persons, maybe it's not a default behavior.
Answer: Have a look at the Transliteration module. Here is a quote from its project page:

... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydoamin/poslednie-novosti-v-Ukraine-i-mire.
However, to actually make this work, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". Attention: this does not "fix" already created aliases (those need to be deleted and recreated).
Comment: I added the extra paragraph about the Pathauto module. Curious if that is how you can get it to work (also) ...
Comment: I installed and tested it. It works only for file names.
Comment: Seems like you got it to work, great! Thanks for accept also!
Comment: Yes, thanks A LOT for the tip! I really like it transliterates file names as well, it might prevent a lot of potential long-term issues with charsets and migrations =)
Answer: Are you referring to how Path Auto will create node paths? Regardless, there's good reason not to have extended characters in your URL:

The URI syntax has been designed with global transcription as one of
its main considerations.  A URI is a sequence of characters from a
very limited set: the letters of the basic Latin alphabet, digits,
and a few special characters.  A URI may be represented in a variety
of ways; e.g., ink on paper, pixels on a screen, or a sequence of
character encoding octets.  The interpretation of a URI depends only
on the characters used and not on how those characters are
represented in a network protocol.

You can alter how Path Auto generates it's paths found at /admin/config/search/path/patterns
Comment: I don't want extended chars in URLs. I want, for instance, `conteúdo` changed to `conteudo` instead of `conte-do`.


Jquery blockui with jquery 1.9.1

Question: I have used the plugin on 1.6 and it works fine.
When i try using jquery 1.9.1 i get an error:
Uncaught TypeError: Cannot read property 'msie' of undefined

On loading the 'blockui.js'
I cant find any reference on this, is it possible that blockui is not supported on jquery 1.9.1?
Answer: You should either include the jQuery migrate plugin, update the plugin to not use $.browser, or don't upgrade jQuery past 1.8.3.
$.browser was removed in version 1.9

From jQuery's Documentation:
Description: Contains flags for the useragent, read from
navigator.userAgent. This property was removed in jQuery 1.9 and is
available only through the jQuery.migrate plugin. Please try to use
feature detection instead.
Comment: I am not using $.browser, who said anything about it, I dont understand
Comment: is it a good idea not to use the latest version of jquery? do you know of any other blockui plugin avialible?
Comment: In many cases you will often need a newer version of jQuery to use a certain jQuery plugin - but in this case you need an older one so you win more than you loose. And I do not know of any other blockUI plugin I'm afraid.

Jquery blockui with jquery 1.9.1


Matching Wrapper+Canvas+Div to an Image's Size

Question: I'm using heatmap.js in Google Apps Script and I am trying to resize the heatmap canvas (where I can actually plot points) to fit an image. How can I change the javascript or styling to make this work?
CODE: https://jsfiddle.net/nateomardavis/51h2guL9/

The wrapper has a black border.
The heatmap div has a blue border.
The canvas has a red border.

How it Should Work: I should be able to mark the heatmap anywhere on the image. The wrapper, heatmap div and canvas should all be sized based on the size of the image.
How it Currently Works: I can only mark the heatmap inside the blue/black border. My javascript resizes the canvas to fit the image, but not the bounds of the heatmap.
What I've Tried: You can see in the fiddle how I've tried to change what the javascript is resizing (lines 88-90).I also thought about using the using the image as the background-image of the heatmap div but the sizing wasn't right and I wanted to be able to save the heatmap and image as one layer (for printing/saving). I also tried changing the size of the image (line 101) but anything above 55% would cut the image off.
The screenshot below is just for reference, but the full working code is in the fiddle. I have it all under HTML because that's how it works in Google Apps Script.

 <!DOCTYPE html>

    <base target="_top">

   <button class="clear">Clear</button>
   <button onclick="printPage()" class="print-btn no-print" style="">Print</button>

      <canvas id="canvas" class="canvas"></canvas>

Answer: After lots of tinkering, I was able to figure it out: https://jsfiddle.net/nateomardavis/p1kwrhmv

I used img and gave it a background-image with CSS.
I then set the heatmap layer to relative and the image layer to absolute using the solution HERE.
Last, I then set the image layer css using the method outlined HERE.
.heatmap {
  background-size: contain;
  background-repeat: no-repeat;
  width: 100%;
  height: 300%; /*if the image is bigger than screen, this is needed */
  position: relative;
}

.backgroundIMG {
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Soccer_Field_Transparant.svg/1200px-Soccer_Field_Transparant.svg.png');
  background-size: contain;
  background-repeat: no-repeat;
  position: absolute;
  width: 100%;
  height: 0;
  padding-top: 151.33%;
}


Venn diagram word problem

Question: In a group of 100, 50 are having an umbrella, 60 have a hat and 80 have sunglasses. 70 are such that they don't have both – an umbrella and a hat. Similarly 50 are such that they do not have both hat and sunglasses and 60 do not have both umbrellas and sunglasses. If there are 5 who do not own any  of the three items, find the number of people who own all three items.
I couldn't solve the question using 2 equations
those who wear exactly one of the three  -n (A ) + n (B ) + n (C ) - 2 (n (A ∩ B ) + n (B ∩ C ) + n (A ∩ C )) + 3 × n (A ∩ B ∩ C )
and the general formula to find the union -
n (A ) + n (B ) + n (C ) - n (A ∩ B ) - n (B ∩ C ) - n (A ∩ C ) .
I took the sum of 70 , 50 , 60 as the sum of those who wear exactly one of the three
and 95 as the union
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: I would always draw a diagram for a question like this. I find it rather easy to get confused.
Answer: Let $A$ be the set of people who own an umbrella, $B$ be the set of people who own a hat, and $C$ be the set of people who own sunglasses. We want to compute the number of people who own all three items, which is equal to $|A \cap B \cap C|.$
The Principle of Inclusion-Exclusion asserts
$$|A \cup B \cup C| = |A| + |B| + |C| - |A \cap B| - |B \cap C| - |A \cap C| + |A\cap B\cap C|. $$
Here, $|A| = 50, |B| = 60, $ and $|C| = 80$. Also, we know there are $70$ people who are not in the set $A \cap B$, which means that there are $100 - 70 = 30$ people in this set. Thus, $|A \cap B| = 30$. Using similar reasoning, we can find $|B \cap C| = 50$ and $|A \cap C| = 40$. Also, we know $|A \cup B \cup C| = 5$ for the reason you described. Therefore,
$$|A| + |B| + |C| - |A \cap B| - |B \cap C| - |A \cap C| + |A\cap B\cap C|  $$
$$5= 50 + 60 + 80 - 30 - 50 - 40 - |A \cap B \cap C|   $$
$$\implies |A \cap B \cap C| = \boxed{65} $$
Comment: Well the answer given for this particular problem is 25

Venn diagram word problem


Module release date and commit date?

Question: I can't understand somethings about commits.
For example, for the Webform module, in its project page it is written that last version is "7.x-3.15 2011-Dec-08," but in the commits page, it is written that there is commits to 7.x-3.15 in 25 February 2012.
I also checked the releases page; one of them has been released on December 2011, and another has been released on February 2012.
Does it mean that these versions were commited to git, but not released?
So it was an unstable version?
Is this usage common for Drupal module releases?
Answer: It is common in pretty much every software project. It makes no sense to release a new version for every single change unless it is critical enough (e.g. security fix). So releases are e.g done on a regular schedule (Drupal core does one every month now).
It is common practice to list the issues that where implemented/fixed as part a release in the release notes.
There are usually multiple commits every day on Drupal core, imagine there would be a new version every time.
What's somewhat uncommon with Webform is that it they don't list their development snapshot releases on the project page. Those are automatically updated twice a day if there have been any commits. In case of Webform, that snapshot still exists, but, according to the description, should only be used for testing recently fixed issues: http://drupal.org/node/730862.
The quality of development snapshots can heavily vary between projects so it's generally not recommended to use them. One exception for example is if you encounter a bug in a module then it often makes sense to test the snapshot first if there is a newer version than the last release.

Module release date and commit date?


Uniform convergence of a complex integral

Question: Let E a compact in the complex plane and U his complement that is connected.
Let μ a complex measure on the boundary of U.
I don't undestand why the integral of |1/(z-t)|dμ(t) in boundary of U converges in a.e in the plane. (hint:Fubini's theorem)
Thanks
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Hint: For $r>0,$ is
$$\int_{\{|z| < r\}}\int_{\partial U}\frac{1}{|\zeta - z|}\,d|\mu|(\zeta)\, dm_2(z) < \infty?$$
Here $m_2$ is Lebesgue measure on $\mathbb C.$
Comment: Form this fact there is absolute convergente in the plane?
Comment: Can you say why under the same ipothesis the integral ∫ log |(z-ζ)|dμ(ζ) on E converges absolutely a.e. in the plane?
Comment: @Giacomo Yes to both questions.


Send user's password in mail

Question: I want to send a reminder email to the users to log in to my website with their username and password. My mail script is ready with the login ID, but I don't know how to decrypt the user's password.
Can anyone tell me how should I get the password associated with a user account?
Answer: You cannot get the user's password from what Drupal saves in the database. Drupal doesn't encrypt the password and saves it in the database, but it saves in database the hash of the password, which is the value returned from a one-way function; this means that is not possible to calculate the value that originated the hash.
That is the reason why hashes are saved instead of the passwords: If somebody access the database used by a Drupal site, it is not possible to retrieve the passwords, and access that site as one of the users registered in that site. (It could still possible to find a word with the exact same hash; so far, collision attacks are shown possible in short time only with MD5.)
Drupal is able to send an email to reset a user's password, which is not what you are asking for, but it could be helpful if you want the users to reset their password after X months. In this case, you could be interested to the code used by _user_mail_notify().
<code>  // By default, we always notify except for canceled and blocked.
  $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
  $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
  if ($notify) {
    $params['account'] = $account;
    $language = $language ? $language : user_preferred_language($account);
    $mail = drupal_mail('user', $op, $account->mail, $language, $params);
    if ($op == 'register_pending_approval') {
      // If a user registered requiring admin approval, notify the admin, too.
      // We use the site default language for this.
      drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
    }
  }
</code>
Comment: Yes, it's normal security practice for all multi-user systems. Drupal uses one time login urls for reseting password. It means that users don't get their raw passwords, but get special link to login and set new one. One time login url can be found in token `[user:one-time-login-url]`.
Answer: Please! Don't do that!
Implementing a login system on a web application is easy.  Implementing a secure login system on a web application is a totally different matter. There are many aspects and details to consider, and Drupal does a fine job of dealing with just about all of those aspects out of the box.
Adding the feature you ask for would greatly reduce the security of your application.  If you can decrypt the passwords, you have just stripped your app of a very important security mesure.
Other answers explain workarounds, BetaRide's answer would do what you ask, but be aware I totally agree with his closing statement.
In a very general way, I would probably tackle this in more or less the following manner:
In a custom module

Implement hook_cron, this would builds an array  containing all emails that match the criteria of your choice.
Loop through the array and send the emails via drupal_mail. Do look into the function <code>_user_mail_notify()</code>  kiamlaluno linked to up above.

If user has never logged in, you may need to send a reset password mail (not sure here), possibly using a combination of drupal_mail and hook_mail_alter to customise either the registration or the reset password email to your taste.
Hope that helps, I know it is a bit sketchy as I have not implemented anything similar in my Drupal experience so far, I was just pumping out a few ideas on how one could notify users in a secure manner. There are many alternatives to having a plain-text password in the email.
Good-luck friend, cheers to you & happy new-year!
Comment: The first sentence of this answer needs to be emphasized in 16pt bold type, and is perhaps one of the few places in which the blink tag might've been appropriate.
Answer: You can use the AES encryption module to get readable passwords.
However there are very good reasons why passwords are not readable in standard Drupal. IMHO using the built in one way pw-recovery links is much more secure.
Answer: You can use Account Password Token Module to send password in mail

Experimental Project
This is a sandbox project, which contains experimental code for developer use only.
This small module provides user account password token for account E-mails settings. Site administrator allowed sending the password to user in bellow settings:-

Welcome (new user created by administrator)
Welcome (no approval required)
Account activation
Welcome (no approval required, password is set)
Password recovery

Send user's password in mail


What are these things

Question: I've been trying to understand the occurance in various scores of two instance of the same note with different durations, and I've tried looking up various things to see if I can find out what I am supposed to actually play. My working solution is to play the longest duration note, and ignore the other.
Today I found a score with some text that seemed to referred to them as "double stemmed" notes. Yeah! off to my ref books and the internet to look that up - but another dead end. I think it may have just been a coincidence in that piece.
Please can anyone tell me the name for this and possibly explain how the are meant to be interpreted and why?
Thanks so much.

So, to be clear, here are two versions of the first two bars of Heller's Etude in E minor Op.46 No 7. This is from a book of piano studies written for that instrument.

The top version is the original version
But there is a "dilemma" the pianist is asked to play the same note twice at the same time with different durations (First note second bar). Obviously that's impossible - sure I can play chords or multiple voices, but this feels like a musical nonsense phrase.
The second version plays the same, as far as I am aware, but does not share this problem?
Q: Why has Heller, who is undoubtedly doing the correct thing, taken this first (top) approach?

I also found pieces in which both the right hand and the left hand end on the same note; with it drawn on the LH and RH stave. So one hand presses the note, and the other hand presses the finger of the first hand.
Comment: Do you mean something akin to https://music.stackexchange.com/questions/33948/why-does-this-note-have-a-stem-pointing-up-and-another-pointing-down?
Comment: Yeah, that's it.No name is mentioned in the link, but at least the interpretation is clarified.
Comment: A possible name would be "double voicing"
Comment: Well that would be audible if I was using two instruments, but on a solo piano score? I still don't quite see why composers would complicate the score with it?
Comment: @JMLCarter, on a piano or guitar - instruments that can play chords - you can hold the first note for the full beat with one finger and then play the next two notes with your other fingers.
Comment: Sorry its not quite a duplicate. A refinement or derrivative, for sure.
Comment: I'd always prefer the second version since it shows the musical line properly. The first version might suggest a hiatus in the bass-line.
Answer: The notation is likely showing two voices in the music.  This can be played by holding the longer of the notes and moving the other voice when it is indicated. I'm assuming you're talking about something akin to:
Comment: Out if curiosity: what does the _40_ in your example refer to?
Comment: Not sure, grabbed it from wikimedia.

What are these things


Normal Distribution With Many Zero Values

Question: I have here a probability density function representing the amount of hours spent studying for a class final. Unsurprisingly, many of the students do not study for the final.

However, because so many students stack up on 0 hours studied, it appears that the curve extends into a negative domain, which is not possible because you can't study for negative hours.
Here are some questions:

How can one interpret the results for a curve like this?
Can values for probability, z-score, std, cdf, etc be reliably calculated?
Is there a way to transform this so that all values of the domain are greater than 0?
Comment: this isn't one of your questions, but you might find it interesting to look at zero inflated models, like maybe a zero inflated gamma. And I'm sure this isn't what you mean, but adding $1$ to every data point makes all values greater than 0... i suspect you really want to make it so you can apply standard normal-theory analyses?
Comment: Your curve contradicts your characterization of the data: there is no "stack" of zero hours.  Indeed, because the curve is continuously drawn and has unit area, it appears you intend us to interpret it as a *density* function.  As such, it assigns *zero* probability to the value $0.$
Comment: @whuber so in short you are saying that the area under this curve will still be equal to 1? I'm going to have to check this when I get the chance.
Comment: @tear728 did you check this?  A quick estimation (curve pretty much bisects a 60x0.030 bounding box, (60*0.03)/2 = 0.9 ~1) would suggest that it is likely true.
Answer: I think you might be better off treating this as a mixture of two distributions rather than trying to apply the standard normal-theory tools, so instead I'm going to outline a bit about the zero inflated Gamma distribution, including computing its first two moments, to give you a sense of how this goes. You could pretty easily swap the Gamma out for a different continuous distribution if you'd like (e.g. a Beta distribution scaled to be in $[0,100]$). Happy to add updates later if this is not helpful.
Let $Z_1,\dots,Z_n\stackrel{\text{iid}}\sim\text{Bern}(\theta)$ and consider  $X_1,\dots,X_n$ where
$$
X_i \vert Z_i \stackrel{\text{iid}}\sim \begin{cases}\Gamma(\alpha, \beta) & Z_i = 1 \\ 0 & Z_i = 0\end{cases}
$$
so each $X_i$ is a mixture of a point mass at $0$ with probability $1-\theta$ and a $\Gamma(\alpha,\beta)$ with probability $\theta$. We interpret this as $Z_i$ being a hidden latent variable that determines whether or not the student studies, and then $X_i$ is the observed value.
This is a bit formal but I'm going to mention it for the sake of completeness. $X_i$ does not have a pdf in the usual sense because it's neither discrete nor continuous, but if we consider the measure $\nu = \lambda + \delta_0$, i.e. the Lebesgue measure plus a point mass at $0$, then $\nu(A) = 0 \implies P_X(A) = 0$ for any measurable $A$ so we can get a pdf $f_X := \frac{\text dP_X}{\text d\nu}$ w.r.t. $\nu$.
But what does this pdf look like? We can work out the CDF $F$ using some rules of conditional probability.
$$
F(x) = P(X\leq x \cap Z = 0) + P(X\leq x \cap Z = 1) \\
= P(X\leq x | Z = 0)P(Z=0) + P(X\leq x | Z=1)P(Z=1) \\
= 1 \cdot (1 - \theta) + F_\Gamma(x; \alpha, \beta) \theta \\
= 1 - \theta + \theta F_\Gamma(x; \alpha, \beta)
$$
where $F_\Gamma$ denotes the CDF of an actual Gamma distribution.
So we want a function $f_X$ such that
$$
F(x) = \int_{[0, x]} f_X\,\text d\nu.
$$
Note that
$$
\int_{[0, x]} f_X\,\text d\nu = \int_{\{0\}} f_X\,\text d\delta_0 + \int_{(0, x)} f_X\,\text d\lambda \\
= f_X(0) + \int_{(0, x)} f_X\,\text d\lambda
$$
so I can take
$$
f_X(x) = 1 - \theta + \theta f_\Gamma(x; \alpha, \beta).
$$
Let's check that this is a valid pdf:
$$
\int_{[0,\infty)} f_X\,\text d\nu = 1 - \theta + \theta \int_0^\infty f_\Gamma \,\text d\lambda = 1
$$
so this is indeed a valid pdf (w.r.t. $\nu$).

Now I'll work out the first two moments of $X_i$.
$$
E(X_i) = \int_{[0,\infty)} x f_X(x)\,\text d\nu(x) \\
= 0 \cdot \int_{\{0\}} f_X\,\text d\delta_0 + \int_{(0,\infty)} x f_X(x)\,\text d\lambda(x) \\
= 0 + \theta \int_0^\infty x f_\Gamma(x) \,\text d\lambda(x)
= \frac{\theta\alpha}\beta := \mu < \infty.
$$
Next
$$
E(X_i^2) =  \int_{[0,\infty)} x^2 f_X(x)\,\text d\nu(x) \\
= 0 + \theta \int_0^\infty x^2 f_\Gamma(x)\,\text d\lambda(x) \\
= \frac{\theta\alpha(1 + \alpha)}{\beta^2}.
$$
This means
$$
\sigma^2 := E(X_i^2) - \mu^2 < \infty.
$$
At long last I have confirmed the following facts: we have a collection of iid RVs $X_1, X_2,\dots$ with finite means and variances, so we can happily apply the standard CLT to conclude
$$
\frac{\bar X_n - \mu_n}{\sqrt n} \stackrel{\text d}\to \mathcal N(0, \sigma^2).
$$
Now as for how good this is, you'll probably want to do some simulations. Also I'm not saying this is actually a good model.

I'll check my math with the following simulation:
theta <- .76
a <- 5.4
b <- 1.2
n <- 1e6

set.seed(42)
z <- rbinom(n, 1, theta)
x <- numeric(n)
x[z==1] <- rgamma(sum(z), shape=a, rate=b)

hist(x, main="Zero inflated Gamma simulations")

mean(x)
theta * a / b  # agrees

mean(x^2)
theta * a * (1 + a) / b^2  # agrees

Also note that I'm not using a KDE to show the distribution like (it looks like) you are. Those typically aren't appropriate for distributions that have a point mass like this. Plus if you're using one that puts a mini gaussian at each data point then it's implicitly assumed that the support is all of $\mathbb R$ so you can also get positive probability on impossible areas like you did.
If you choose to use this model and want to estimate the parameters, the EM algorithm is the usual way to go.
In this case though there's no doubt as to which class a particular $X_i$ belongs as if $X_i = 0$ then $Z_i = 0$ almost surely. So you can do
mean(x > 0)  # compare with theta

mu.x <- mean(x[x > 0])
s2.x <- var(x[x > 0])
(b.hat <- mu.x / s2.x)
(a.hat <- mu.x^2 / s2.x)

and these agree. But I have a massive sample size and $\theta$ isn't particularly close to $0$ or $1$ here so it's not impressive to be so accurate with this conditional approach.