Jersey/Jackson @JsonIgnore on setter

Question: i have an class with the following annotations:
class A {
public Map<String,List<String>> references;

@JsonProperty
public Map<String,List<String>> getReferences() {
...
}

@JsonIgnore
public void setReferences(Map<String,List<String>>) {
}
...
}
}

What I try is to ignore the json on deserialization. But it doesn't work. Always when JSON String arrives the Jackson lib fill the references attribute. If I use only the @JsonIgnore annotation the getter doesn't work. Are there any solutions for this problem?
Thanks
Answer: As of Jackson 2.6, there is a new and improved way to define read-only and write-only properties, using JsonProperty#access() annotation. This is recommended over use of separate JsonIgnore and JsonProperty annotations.
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Map<String,List<String>> references;

Answer: I think there are two key pieces that should enable you to have "read-only collections" as desired. First, in addition to ignoring the setter, ensure that your field is also marked with @JsonIgnore:
class A {

  @JsonIgnore
  public Map<String,List<String>> references;

  @JsonProperty
  public Map<String,List<String>> getReferences() { ... }

  @JsonIgnore
  public void setReferences(Map<String,List<String>>) { ... }

}

Second, in order to prevent the getters from being used as setters, disable the USE_GETTERS_AS_SETTERS feature:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);

Comment: I foolishly ignored your first advice and doesn't marked the field as ignored, since it is private in my case. However, I needed to do that nevertheless, to get it working properly. Is this right or a misunderstanding on my side? If so, maybe it's worth pointing that out explicitly in your answer.
Answer: You have to make sure there is @JsonIgnore annotation on the field level as well as on the setter, and getter annotated with @JsonProperty.
public class Echo {

    @Null
    @JsonIgnore
    private String doNotDeserialise;

    private String echo;

    @JsonProperty
    public String getDoNotDeserialise() {
        return doNotDeserialise;
    }

    @JsonIgnore
    public void setDoNotDeserialise(String doNotDeserialise) {
        this.doNotDeserialise = doNotDeserialise;
    }

    public String getEcho() {
        return echo;
    }

    public void setEcho(String echo) {
        this.echo = echo;
    }
}

@Controller
public class EchoController {

@ResponseBody
@RequestMapping(value = "/echo", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
    public Echo echo(@RequestBody @Valid Echo echo) {
        if (StringUtils.isEmpty(echo.getDoNotDeserialise())) {
            echo.setDoNotDeserialise("Value is set by the server, not by the client!");
        }

        return echo;
    }
}

If you submit a JSON request with a "doNotDeserialise" value set to something, when JSON is deserialised to an object it will be set to null (if not I put a validation constraint on the field so it will error out)
If you set the "doNotDeserialise" value to something on the server then it will be correctly serialised to JSON and pushed to the client
Answer: I used @JsonIgnore on my getter and it didn't work and I couldn't configure the mapper (I was using Jackson Jaxrs providers). This worked for me:
@JsonIgnoreProperties(ignoreUnknown = true, value = { "actorsAsString",
    "writersAsString", "directorsAsString", "genresAsString" })

Answer: I can only think of a non-jackson solution, to use a base class that does not have references for the mapping and then cast to the actual class:
// expect a B on an incoming request
class B {
// ...
}

// after the data is read, cast to A which will have empty references
class A extends B {
public Map<String,List<String>> references;
}

Why do you even send the References if you don't want them?
Or is the incoming data out of your hands and you just want to avoid the mapping exception telling you that jackson cannot find a property to set for incoming references? For that we use a base class which all of our Json model classes inherit:
public abstract class JsonObject {

    @JsonAnySetter
    public void handleUnknown(String key, Object value) {

        // for us we log an error if we can't map but you can skip that
        Log log = LogFactory.getLog(String.class);
        log.error("Error mapping object of type: " + this.getClass().getName());
        log.error("Could not map key: \"" + key + "\" and value: \"" + "\"" + value.toString() + "\"");

    }

Then in the POJO you add @JsonIgnoreProperties so that incoming properties will get forwarded to handleUnknown()
@JsonIgnoreProperties
class A extends JsonObject {
    // no references if you don't need them
}

edit
This SO Thread describes how to use Mixins. This might be the solution, if you want to keep your structure exactly as it is, but I have not tried it.
Comment: That's right. The incoming data is not really in our hands. But the clients sends always references attribute in correct format so handleUnknown will never be called.
Comment: Ah, my bad, forgot a little pice of information. You need `@JsonIgnoreProperties` at the POJO if you want to ignore incoming data. I'll update my post. (PS: we use this to consume facebook's REST resource and all properties sent from facebook that are not contained in our POJO will just get logged and then we decide if we want to add them or not)
Comment: But references is in my POJO so it always matches to the setter
Comment: But why do you keep References in your POJO if you don't need it? Found another solution that might be applicable if you really want to keep your exact structure: http://stackoverflow.com/questions/7421474/how-can-i-tell-jackson-to-ignore-a-property-for-which-i-dont-have-control-over
Comment: Thanks for the link. I've tried mixins before and it works not for me. The challenge is getting the references property to Read-only state. So that I can send information to the client but ignore incoming changes on this property

Jersey/Jackson @JsonIgnore on setter


I gat a error due to the influence of migration that I wrote a long time ago

Question: I want to add new column 'piece_id' and I added it to Bucket table.
class AddPieceIdToBuckets < ActiveRecord::Migration
  def change
    add_column :buckets, :piece_id, :string
  end
end

class Bucket < ActiveRecord::Base
  validates :piece_id, presence: true
end

Also I need to validate piece_id. But Adding validation gives me the following error. I tried run migration without validation and then it passed.
undefined method `piece_id'

Although I do not have piece_id in migration I wrote in old days, I think that it is the influence that writing validation in the model. And I created several objects for migration I wrote before. Should I edit it?
    def change
        Bucket.reset_column_information
        Bucket.create(
              name: 'test_name',
              about: 'test',
         )
    end

Comment: does `piece_id` column present in table ?
Answer: I have been bitten by this many times, I no longer put any data changes, via models, in my migrations for this reason.
Since you can be confident that the old migration where you create a Bucket has already run you could remove that bit of code, or better still add piece_id to the attributes and give it a value so it passes when migrating from an empty database.
I now use rake db:seeds to create data, in db/seeds.rb I have:
require_relative "seeds/#{Rails.env}/all"

and a directory structure such as:

db/seeds/development/all.rb
db/seeds/production/all.rb

In development/all.rb I do require_relative '../production/all'.
I run rake db:seed as part of deployment, this works well, just have sure that the seeds are idempotent, so check the record does not exist already, or use active record methods like find_or_create_by.


Poisson regression or ANOVA, repeated measures or independent?

Question: I have been trying to figure out the best way to approach analysis of my data for a while now and I'm struggling to understand if a Poisson regression is correct and, embarrassingly, I'm not sure if my data are independent observations.
I have two data sets:
Firstly,
I have data from rows sown with 100 seeds each (n=6) with counts of seedlings recorded at different stages of seedling development (germinated, emerged etc, 6 stages). The same seeds/seedling were tracked over time. I want to know which stages have significantly different counts of seeds/seedlings.
Are these independent observations as they are different outcome variables (germinated, emerged etc)? Note: each time point can only be equal to or less than the preceding time point.
Should this be approached with a GLM with Poisson distribution or can it be a simple one-way ANOVA or a repeated measures ANOVA?
My second data set has data from 10 seeds per pot (n=6 pots) for two species, under 3 different treatments. There are four outcome variables (germinated, ungerminated etc) with the seeds proportioned into one of the four outcome variables (if 80% germinate, for example, then 10% could be ungerminated and 10% dead). This means quite a lot of 0's in some cases.
I have performed a Poisson regression in R to find significant differences between treatments for each outcome variable and it makes sense but I want to check that this is the best approach and meets the correct assumptions but, I'm confused..
Comment: I'm not sure if I replied in the right section or not (I replied to the below answer rather than my question?). Is there any more information I can give that might help anyone in answering my above question?
Answer: Welcome to this site, Scott!  It's a bit hard from your description to tease out what exactly is going on in your two studies.  You may need to revise your question and provide more specifics.
Your first study seems to involve different time points, although you don't share how many.  Are we talking about 3 time points or 20 time points, say? Also, you mention that counts are recorded at each time point but you don't explain what those counts represent (e.g., are they counts of seeds that germinated?), what entities they are recorded for and, most importantly, whether those entities are kept the same at each time point or they are different from one time point to another? Also, what do you mean by replicate rows?
Your research question for the first study needs to be stated more carefully: "I want to know which time points are significantly different (i.e. significantly less than the preceding time point).". I suspect what you really mean is that you want to know whether the expected/average value of your count outcome variable at time point $t$ is less than that at time point $t-1$?  (It's clear that the time points themselves are different from each other by virtue of how you chose them.)
If you measure the same entity over time with respect to a variable of interest, you can reasonably expect temporal correlation among the recorded values of that variable for that entity.  As an example, if you track the same seed over time and at each time point you record whether or not that seed germinated, the germination status values (yes or no) will likely be correlated over time.
Your second study needs more clarifications also. How many treatments are we talking about? Etc.
Comment: I Isabella, Thank you for your quick reply, I appreciate it a lot. I have updated my question and hope that provides more clarity. Apologies but my stats knowledge isn't great and count data has not been covered in courses I've done! Regarding "expected/average value of your count outcome variable at time point t is less than that at time point t−1", that sounds correct but I don't have the stats background to have written it that way. Please let me know if any more clarification is needed, Kind regards, Scott


How to install DSC on Azure Windows 2016 Nano Server deployed from Microsoft's image?

Question: All information I could find regarding DSC on Nano Server suggest the DSC should be added to the server image upon creation, e.g. Using DSC on Nano Server:

DSC on Nano Server is an optional package in the NanoServer\Packages folder of the Windows Server 2016 media. The package can be installed when you create a VHD for a Nano Server by specifying Microsoft-NanoServer-DSC-Package as the value of the Packages parameter of the New-NanoServerImage function.

Is there any way to add the DSC to an already existing system? Namely to the one deployed from 2016-Nano-Server image provided by Microsoft on Azure.
Answer: Copy the DSC cab file from 2016 install media onto the nano server, then use DISM to add it.
Dism.exe /online /Add-Package /PackagePath:c:\Microsoft-NanoServer-DSC-Package.cab

You can also try using the Install-NanoServerPackage powershell command but I've found it to be rather buggy at the moment.


Debugging multiple projects under VS2012 - Main project invokes a sub-project

Question: I have a solution that has 2 projects. The main one and the one that is called with CreateProcess() from the main program.
The main one is a win32 program and the second a console application. I use the win32 program to invoke the console app and have it do its thing. My problem is, I want to be able to debug the console app once it's invoked with CreateProcess.
How can I accomplish this? or Can I accomplish this?
I'm also a little confused with the Debugger API as I want Visual Studio to be the debugger, instead of me creating the debugger.
Comment: I'm sorry, I misunderstood your problem. I agree with Scott's answer then, nothing to add. Use DebugBreak();
Answer: Call DebugBreak(); at the start of the console process. When it hits that call you will be able to start a new instance of Visual Studio to debug the console process.


Listar itens de um objeto no Pug JS, com Node e Mongo

Question: Estou montando uma loja, utilizando Keystone JS, instalei as dependências Pug JS e MongoDB.
Criei tenho um model que está apontando para uma view, chamada Tour.JS
O problema é que eu não consegui listar de forma eficiente todos os itens que está no model do MongoDB.
var keystone = require('keystone');
var Types = keystone.Field.Types;

/**
 * User Tour
 * ==========
 */

 var Tour = new keystone.List('Tour', {
        autokey: { from: 'nome_do_passeio', path: 'key', unique: true, Singular:'Passeio', Plural: 'Passeios'},
 });

 Tour.add({
   nome_do_passeio: {type: String, label:"Nome do Passeio", initial:true},
   image: { type: Types.CloudinaryImage },
   category: { type: Types.Select, options: 'barco, vinícola', label:"Categoria", initial:true},
     custo: { type: Types.Money, format: '$0.0,00', label:"Valor", initial:true },
     data_do_passeio: { type: Types.Date, yearRange:(2000,2100), format: ('Do MMMM YYYY'), default: Date.now, label:"Data do Passeio", initial:true },
     descricao_passeio: {  type: Types.Html, wysiwyg: true, height: 200, label: "Descrição do Passeio"},
   incluido: {  type: Types.Html, wysiwyg: true, height: 200, label: "O que está incluído"},
   cidade: { type: String, required: false, index: true, label:"Cidade" }
 });

 Tour.defaultSort = Tour.data_do_passeio;
 Tour.defaultColumns = 'nome_do_passeio, custo, cidade, category, data_do_passeio';
 Tour.register();

E gostaria de listar todos os passeios que estão disponíveis no meu banco de dados.
Mas eu estou usando Pug JS, e não consegui listar de acordo com a quantidade de passeios disponíveis.
extends ../layouts/default

block content

    .container
        h1 Passeio
    .container.col-md-4.col-lg-4
        .row
            if !data.tour
                h2 Passeio inválido
            else
                each tr in data.tour
                    h2= nome_do_passeio

Tour.js em "routes/views"
var keystone = require('keystone');

exports = module.exports = function(req, res) {
  var view = new keystone.View(req, res);
  var locals = res.locals;

  // Set locals
  locals.section = 'store';
  locals.filters = {
    tour: req.params.tour
  }
  locals.data = {
    tour:[]
  }

view.on('init', function(next){
  var q = keystone.list('Tour').model.findOne({
    slug: locals.filters.tour
  });

  q.exec(function(err, result){
    locals.data.tour = result;
    next(err);
  });
});

  // Render View
  view.render('tour');
}

Com certeza estou fazendo algo errado, problema que não consegui até agora listar todos os passeios utilizando o Pug JS.
Tentei de uma nova forma.
- var qtd_nome_do_passeio = data.tour
each tr in qtd_nome_do_passeio
h2= JSON.stringify(data.tour.nome_do_passeio)

Mas ele imprimiu várias vezes "Passeio de Barco", que é o resultado do primeiro objeto do data.tour.nome_do_passeio, mas não imprimiu o próximo no loop.
Resultado do JSON.stringif do data.tour
{"_id":"59f76221da96af24235f06db","key":"passeio-de-barco","nome_do_passeio":"Passeio de Barco","__v":0,"category":"barco","cidade":"Florianópolis","custo":150,"descricao_passeio":"
On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment
","incluido":"
Teste
","data_do_passeio":"2017-10-30T03:00:00.000Z","image":{"public_id":"o59xhtyonz6jrwts18q3","version":1509386166,"signature":"f5d2343a70a9d1ae25781d5c2ced4934a1b3e4c3","width":800,"height":528,"format":"jpg","resource_type":"image","url":"http://res.cloudinary.com/keystone-demo/image/upload/v1509386166/o59xhtyonz6jrwts18q3.jpg","secure_url":"https://res.cloudinary.com/keystone-demo/image/upload/v1509386166/o59xhtyonz6jrwts18q3.jpg"}}

Comment: Genial!!! DEU CERTO! MUITO OBRIGADO MESMO!!!!
Comment: Ok, agora já está o JSON na pergunta. Esse json é só de um objeto, não há nada para iterar aí... isso é o resultado de `JSON.stringify(data.tour)`? Então no Node.js como passas o `data` para o Pug? podes mostrar como crias essa variável `data`?
Comment: Coloquei na pergunta o arquivo Tour.js em "routes/views".
Comment: Ok, e se colocares como estava e em ves de `.findOne` usares o `.find()`?
Answer: Usa .findOne( em vez de .findOne( no MongoDB e depois com essa array poder iterar assim:
each tr in data.tour
    h2= tr.nome_do_passeio
    p= tr.descricao_passeio
    p Custo: #{tr.custo}


Add configuration options for Views block under Structure > Blocks > configure

Question: I'm building a module that defines several blocks and provides custom options for those blocks via hook_block_configure(). Two of these blocks were built from scratch using hook_block_info() and their configuration options defined in hook_block_configure() display as intended. In other words, if you navigate to Structure > Blocks and click configure for either of these two blocks, the custom configuration options are displayed as intended.
The third block is a Views block, defined by hook_views_api() and hook_views_default_views(), and the hook_block_configure() hook doesn't trigger at all for this block. Navigating to Structure > Blocks and clicking on configure for this block just shows the default block configuration options.
What I would like to know is how to add custom configuration options for this Views block or a similar solution. Is there any way to register this block so that it will also listen in on the hook_block_configure() hook? Or is there maybe a different hook that would allow me to accomplish my goal? My Google-fu has yielded nothing.
Answer: To "add fields to the block configure pages for these two blocks" (as in your question), you should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
PS: this is a D7 module, integrated in core in D8 ...
Comment: Thanks Pierre I never had read about the inclusion of Bean in D8, this is a great notice.
Comment: To be honest, I only noticed that myself just recently. So if you've never used it (or seen it), hurry and start eperimenting with the D7 version already. Myself I first discovered it when deep-diving into the forena module, which basically allows creating blocks (using BEAN) that contain (tiny) "reports". Think of dashboards and things like that for this specific usecase ... The video tutorial in my answer will be sufficient to understand the power of thos BEAN module ...
Comment: I used the Bean module in one or two project, thanks for the info
Comment: @Pierre.Vriens, I appreciate your input with this module, but it doesn't quite accomplish what I need. I've edited my question to (hopefully) make my needs more clear.


a question on fourier transform in the complex domain

Question: This is from my homework: given $f\in L^1(R)$ and $f$ is compactly supported, show that

Fourier transform of $f$ , i.e $\hat{f(\zeta)}$ is $C^\infty$
$\hat{f}(\zeta)$ is analytic and entire by showing that the taylor series of   $\hat{f}$ at $\zeta = 0$ has infinite radius of convergence, and converges to $\hat{f}$

My attempt is:
For Part 1 since the domain is the real line, the support must be a closed interval and we can divide this interval into two parts: A where $|f|>0$ and B the rest. Then the integral over $|f|$ over A is less than $|f|^2$, while the integral over B is less that m(B), which is finite.
The I tried to show all derivatives are continuous by induction, but no success .
For base case , I tried to show $\hat{f}(\zeta)$ is continuous. That is, $\lim_{ h\to \infty}|\hat{f}(\zeta+h) - \hat{f}(\zeta)|=0$.  $|\hat{f}(\zeta+h) - \hat{f}(\zeta)|\leq \int|(e^{-i(\zeta+h)x}-e^{-i(\zeta)x})f(x)|dx \leq \int|e^{-ihx}-1||f(x)|dx$. I am stuck at this step and I guess power series would help to bound the RHS?
For induction step, assume $\hat{f}^n(\zeta)$ is continuous , let $|\hat{f}^{n+1}(\zeta+h) - \hat{f}^{n+1}(\zeta)|=D|\hat{f}^n(\zeta+h) - \hat{f}^n(\zeta)|$. I got trouble with putting D under integral sign and can't proceed..
For Part 2, I tried to bound $f$ with some $O(e^{ai})$ when $\zeta\to\infty$. Anyway I am totally lost from here. Could anyone show me how to do it and many thanks in advance.
Answer: Let me treat in $\mathbb{R}^{n}$ instead.According to the fourier-laplace transform $$\hat{f}(\xi)=\int{e^{-ix\cdot\xi}f(x)dx},\quad \xi\in\mathbb{C}^{n}$$
Since now $f\in L^{1}$ with compact support,apply the Cauchy-Riemann operator to $\hat{f}(\xi)$ and exchange with integral(this is allowed since f is compact supported) to find that $\hat{f}(\xi)$ is a entire analytic function.
BTW,the result still hoids if f is only a distribution with compact support(and the method is essentially the same),which has many applications in linear PDE.


single or multiple docker containers per host

Question: So we are in the phase of designing a pipeline for deploying our app to production.
We have 5 services that needs to talk each other, and currently using docker for developing.
We are studying CodePipeline (github + CodeBuild + EB) for deploying, but we have doubts if using Elastic Beanstalk for single container (i.e. 1 container running per host), or multiple (multiple containers running in the same hosts)
The only benefit I can see from using multicontainer is that is cost effective (more cheap to have a fleet of ec2 instance for all containers, than to have a whole fleet for running only 1 container).
Other than that, I can only see extra complexity added in multicontainers, due to the orchestration and task scheduling for managing multiple containers in multiple hosts.
So what is best practice? 1 container per host? or multiple container per host?
Comment: If you're only running one docker container per host you miss out on many of the benefits of containerization. Suggest you look a bit harder at managed container offerings such as ECS / EKS / Fargate.
Answer: Single Docker Beanstalk is great when you are just starting out with Docker. Its easy and familiar to use but wastes resources.
Multi-Docker is more advanced, and but basically follows all the same deployment practices of Single Docker and Beanstalk in general. Multi-Docker will provision an ECS cluster for you and launch task (not a service) on each instance. Beanstalk scripts monitor the state of the task and an upstart script is in charge of starting/stopping the task (it leverages ecs agent to do this). There really isn't any added complexity as Beanstalk takes care of all of that.
Each instance will only run 1 task, so tasks scale linearly with instances in the cluster, which makes it only slightly less wasteful than Single Docker, and will cost the same amount (assuming applications of equal size and scaling similarly). The only REAL benefit of Multi-Docker over Single Docker is being able to decouple parts of an application.
If you start using Multi-Docker, you will very quickly move on to ECS as it is all-around better for running containers. If you start with Single Docker, you will quickly get annoyed by the limitations of a single container, and either move on to Multi-Docker or ECS Native. My suggestion is just to skip Beanstalk altogether, or use Multi-Docker to get a feel and understanding of ECS before jumping ship like most people do.
tl;dr The best practice for running containers is setting up a cluster, not using Beanstalk.
p.s. Now with Fargate, you don't even have to manage a cluster at all.


nginx config with docker bad getway

Question: the error in terminal:
2023/07/31 09:30:16 [error] 23#23: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.21.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://192.168.21.3:9002/", host: "192.168.21.4:84"

2023/07/31 09:30:16 [error] 23#23: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.21.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://192.168.21.2:9003/", host: "192.168.21.4:84"
192.168.21.1 - - [31/Jul/2023:09:30:16 +0000] "GET / HTTP/1.1" 502 559 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/184.108.40.206 Safari/537.36"
2023/07/31 09:30:16 [error] 23#23: *3 no live upstreams while connecting to upstream, client: 192.168.21.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", upstream: "http://php-apps/favicon.ico", host: "192.168.21.4:84", referrer: "http://192.168.21.4:84/"
192.168.21.1 - - [31/Jul/2023:09:30:16 +0000] "GET /favicon.ico HTTP/1.1" 502 559 "http://192.168.21.4:84/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/184.108.40.206 Safari/537.36"

my nginx config :

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    access_log /var/log/nginx/access.log;

    # Load balancer configuration
    upstream php-apps {
        server php-app1:9002;
        server php-app2:9003;
    }

    server {
        listen 84;
        server_name localhost;

        location / {
            proxy_pass http://php-apps;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

app1.conf :
http {

    server {
        listen 9002;
        server_name php-app1;
        root /var/www/app1/html;

        index index.php;

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php$ {
            fastcgi_pass php-app1:9000;
            fastcgi_index index.php;
            fastcgi_param REQUEST_METHOD $request_method;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }

}

--------

app2.conf/

http {

    server {
        listen 9003;
        server_name php-app2;
        root /var/www/app2/html;

        index index.php;

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php$ {
            fastcgi_pass php-app2:9000;
            fastcgi_index index.php;
            fastcgi_param REQUEST_METHOD $request_method;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
}

my docker-compose :

version: '3'

services:
  nginx-lb:
    build:
      context: ./nginx
    ports:
      - "84:84"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/app1-config/app1.conf:/etc/nginx/conf.d/app1.conf
      - ./nginx/app2-config/app2.conf:/etc/nginx/conf.d/app2.conf
    depends_on:
      - php-app1
      - php-app2
    networks:
      my-test-network:
#        ipv4_address: 192.168.21.2
  php-app1:
    image: php:fpm
    volumes:
      - ./app1/html:/var/www/html
    ports:
      - "9002:9000"
    networks:
      my-test-network:
#       ipv4_address: 192.168.21.3
  php-app2:
    image: php:fpm
    volumes:
      - ./app2/html:/var/www/html
    ports:
      - "9003:9000"
    networks:
      my-test-network:
#        ipv4_address: 192.168.21.4
networks:
  my-test-network:
    driver: bridge
#    ipam:
#      config:
#       - subnet: 192.168.21.0/24

enter image description here
Comment: Can you access those apps on port `9002` and `9003`?
Comment: no i cant, may be i need nginx for each app not just nginx as load balancer
Comment: i mean there is a need for inginx image for each server and how i add it in docker compose
Answer: Please have a look at the following post: How to correctly link php-fpm and Nginx Docker containers?
Seems like you have to adjust your volumes in order to serve it correctly with nginx. So using - ./app1/html:/var/www/app1/html and - ./app2/html:/var/www/app2/html should work. Afterwards you should be able to access your applications on port 9002 and 9003. It might also work on port 84 already, but please check the other ports first.

I mean changing your docker-compose to look like this:
version: '3'

services:
  nginx-lb:
    build:
      context: ./nginx
    ports:
      - "84:84"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/app1-config/app1.conf:/etc/nginx/conf.d/app1.conf
      - ./nginx/app2-config/app2.conf:/etc/nginx/conf.d/app2.conf
    depends_on:
      - php-app1
      - php-app2
    networks:
      my-test-network:
#        ipv4_address: 192.168.21.2
  php-app1:
    image: php:fpm
    container_name: php-app1
    volumes:
      - ./app1/html:/var/www/app1/html
    ports:
      - "9002:9000"
    networks:
      my-test-network:
#       ipv4_address: 192.168.21.3
  php-app2:
    image: php:fpm
    container_name: php-app2
    volumes:
      - ./app2/html:/var/www/app2/html
    ports:
      - "9003:9000"
    networks:
      my-test-network:
#        ipv4_address: 192.168.21.4
networks:
  my-test-network:
    driver: bridge
#    ipam:
#      config:
#       - subnet: 192.168.21.0/24

Comment: do you mean in each container or in nginx-lb container
Comment: `2023/07/31 11:58:22 [warn] 1#1: conflicting server name "php-app2" on 0.0.0.0:9003, ignored
test2-nginx-1     | nginx: [warn] conflicting server name "php-app2" on 0.0.0.0:9003, ignored`
Comment: I edited my answer. But you indeed also need to change the server_name in you app1.conf and app2.conf. You should use `server_name localhost` or `server_name default_server` or `server_name _` depending on how you want to access it. If it's all running on your local computer you should use `server_name localhost`.
Comment: now it opens the nginx html file. not my apps. i changed my code as you mentioned
Comment: You mean the default nginx page with "Welcome to nginx"? On both port 9002 and 9003?
Comment: on 84 it opens the default nginx page
when i do host-ip:9002 or 9003 get me an error
Comment: Can you tell which error? On one side in browser and also in nginx logs?
Comment: Maybe you should also add the container name to your docker compose file like I updated above.
Comment: i do it, name the containers but the load balance not working. it just open the default nginx page or one of my app. but it does not balancing my two apps
Comment: So what is working currently? You can access your app on port 9002 and 9003 and also access it on port 84 but not load balanced (always requesting the same app)?

nginx config with docker bad getway


Is it unlawful or not-done to field between bowler and sight screen?

Question: In cricket, play usually stops temporarily when spectators or personnel walk or stand in front of the (live) sight screen. What about fielders? Should they move elsewhere on request?
Answer: The role of the sight screen is to help the batter see the ball at the start of its flight, as it leaves the bowlers hand. If you think about the angles involved, it is mainly the upper portion of the sight screen that is used, so a fielder standing in front of it would not block this view.
The problem with spectators is typically not that they are in front of the sight screen, but that they are moving in front of the sight screen. Humans are very tuned in to movement visually, so having someone move in the line of sight of the batter is distracting. Under the laws of cricket, fielders are not permitted to move laterally as the bowler is running is (they can move towards or away from the batsmen under Law 41.7, 41.8). Therefore, a fielder in front of the sight screen but stationary will not be distracting the batter. They probably wouldn't notice given that the Umpire and Bowler are also in the way.
Fielding directly in front of the sight screen would be a very poor field placement in any case.
Comment: "Neither long-on or long-off, but sort of floating between the two (And not quite deep enough): In most forms of cricket, an extremely unusual position; in the village game, however, an almost compulsory one, designed not so much to cover two distinct positions as to distract the batsman by having someone legitimately stand in front of the sightscreens - that is, where the sightscreens would usually be found in higher levels of the game. For this reason, if this fielder is sufficiently portly, his lilywhite-clad girth may well serve to assist the batsman, in which case he should be moved." :)
Comment: ^ From [here](http://www.espncricinfo.com/blogs/content/story/647171.html).
Answer: It is not unlawful to field between bowler and side screen. In fact there is a fielding position for that and it is called straight hit.

Usually the fielder is placed at an angle and I don't remember any captains using this fielding position. You can see all the rules here.
Comment: Helpful picture. However, I do not know of any law that prevents a fielder being placed directly behind the wicketkeeper, and, indeed, the picture in your answer shows just such a position, _long stop_. If there is a regulation that makes such a restriction in one-day games could you please provide a reference to the details of it?
Comment: I already have, but the Wikipedia page provided no citation for the assertion it makes, and therefore I don't see the basis for it.
Comment: I know that the Wikipedia page makes that quoted claim. What I am querying is where the Wikipedia article gets that information from. I have not been able to find any reference to support it in either the Laws of Cricket or the ICC Playing Conditions.
Comment: If there is no law or regulation that prohibits the captain from placing a fielder there, he/she is perfectly free to do so; whether he/she would want to do so is another matter (one reason might be to save 4 byes on a very fast outfield). Why would such a prohibition exist?
Comment: @ACB I think Wikipedia may very well be right on this, but _without_ the preceding "In **some** one-day matches:" (note the "some") the quote seems false. So, Wikipedia may be right, but I doubt that this part of your answer is right.
Comment: I suspect the origin of this confusion is that in ODI and T20 matches, there is a requirement that a certain number of players (the number varies in different circumstances) be not only inside 'the circle' but be in a subjectively defined 'catching position'. Having a player inside the circle, but directly behind the keeper would not be a catching position, and therefore not permitted if that player was being used as part of the quota. That's my best guess at the origin of the wiki quote, but there's certainly no specific prohibition, even though in practice it simply isn't used as a position.
Comment: Read the link mentioned as rules here.  It is mentioned there.
Comment: @Spinner, Try again. Or search for the above words I posted in answer. You should get it. I have edited the answer with same content.
Comment: Unfortunately not all details are available on the internet. Some things we have to learn from experience and by following cricket. This is just one of such instances. Let me know if you have ever seen a captain putting a fielder directly behind keeper. I remember Doulas Marillier(Mar 2002, Ind vs Zim) kept playing his famous scoop shot behind wicket keeper and captain could do nothing about it. http://www.youtube.com/watch?v=7BwE_49f2tA
Comment: One possible reason, I can think of, is this. It is a wicket keeper's job to make sure the ball wont go past him. Keeping someone as backup behind him is absurd and hence no point in allowing that. In any case I haven't seen that happening at all. Having said that, if you feel that this is absolutely wrong and I should remove that comment from answer, I can do it. It is anyways not related to the original question at all.
Comment: I agree with you that it makes little sense having a fielder there, and that a captain would not normally put someone there - as you say, it is the keeper's job. It would make more sense to have the fielder at _third man_ or _fine-leg_. However, the Laws do not prevent captains making absurd decisions. In the absence of any reference to the Laws or Playing Conditions, I don't think the Wikipedia claim can be justified; however, as you say, all this is unrelated to the original question!
Comment: @ACB The Wikipedia quote is preceded by "In some one-day matches:". I think you may include that in the quote in your answer, because without it it doesn't seem to be true generally.
Comment: From [here](http://www.espncricinfo.com/blogs/content/story/647171.html): "Long stop: [...] It should be borne in mind that this fielder is often a chuckling simpleton with next to no concentration span, hence the high bye count. On the plus side, he has the stamina and arm of Forrest Gump." :)
Comment: @Gugg I doubt it applies even in one-day matches. As your (humorous) link suggests, _long stop_ appears to be a perfectly legitimate position, contrary to what Wikipedia claims.
Comment: If wiki were that wrong, I doubt it will stay there just like that. Someone would have already corrected it. And from the above link which talks about village cricket, I don't think you can generalize it to all one day matches.
Comment: Anyways edited it. But I think this has nothing to do with the question. That was just a gentle comment I added.
Comment: I note that the Wikipedia quote in question was credited to an IP address rather than a user account, which may cast doubt on its reliability. @Bogdanovist That's a possibility; I'd have to look up the T20 regulations to confirm that.


How to get database credentials

Question: I am integrating code that implements its own extension of PHP's PDO class, in the same way that Drupal's DatabaseConnection does. So this code (which is various data models) needs to use this non-drupal PDO object.
This code needs DSN, username and password to access the default drupal database. I noted that $databases, defined in settings.php is not available: global $databases does not work to give me access to that data.
Is there a way to ask Drupal for this info or extract it from the default connection object?
Comment: I've posted an initial answer, but how are you you *integrating* this script?  Through a module?  A separate PHP file?
Answer: The following works perfectly for me in devel/php
global $databases;

dpm($databases);

It should return the full array of database information:
Comment: My bad, must have been doing something stupid, thank you!
Answer: As shown by Chapabu global $databases does work but it wont work if you are using a separate PHP file (not related to Drupal Codebase), if you want to use it like that you need to include settings.php file before.

How to get database credentials


Points of inflexion at circular points at infinity.

Question: According to the Wikipedia article on Cassini Ovals, a Cassini oval has double-points, which are also inflexion points, at circular points I and J at infinity.  I don't understand how to show that I and J are inflexion points.  Wikipedia references a very old text by Basset which makes the same claim.  Unfortunately, I was not able to find any "computational" support for this statement; only a general discussion about points of contact was given.  I am looking for an explanation or a good reference that I can use to understand this problem.  Thanks in advance!
Answer: The Wikipedia article on
Circular points at infinity
gives their homogeneous coordinates as
$$(x_0,y_0,z_0) = (1,\pm i,0). \tag{1}$$
The homogeneous equation for
Cassini ovals is
$$ P(x,y,z) := (x^2+y^2)^2 - 2 a^2 (x^2-y^2) z^2 + (a^4-b^4) z^4 = 0. \tag{2}$$
Verify for the circular points in equation $(1)$ that
$$ P(x_0,y_0,z_0) = 0. \tag{3}$$
As for inflection points, differentiate the equation $(2)$ taking partials to get
the equation of the tangent line at $\,(x_0,y_0,z_0).\,$ Namely,
$$ \frac14 dP(x,y,z) = x((x^2+y^2)-a^2z^2)dx +
y((x^2+y^2)+a^2z^2)dy + z(a^2(y^2-x^2)+(a^4-b^4)z^2)dz.\tag{4}$$
If we evaluate this equation $(4)$ with $\,x^2+y^2=z=0\,$ as
in equation $(1)$ it vanishes which verifies that there
is a double point at infinity.
Also equation $(4)$ is cubic in $\,x,y,z\,$ which verifies that
the circular points are also inflection points of the curve.


Calculating the expectation of the supremum of absolute value of a Brownian motion

Question: I got a Brownian motion $B(t)$ that starts in $0$ and want to calculate the expectated value of the supremum on the interval $[0,1]$ of the absolute value of it, i.e.
$E \left (\sup \limits_{t \in [0,1]}  |B(t) | \right )$.
I found some information on this question in this thread.
Here user3371583 posted in the comment chain that the expected value in the case of the interval $[0,1]$ should be $\sqrt{\frac{\pi}{8}}$ and he explained how he got to this result in the same post, but I cant seem to get it done.
What I got so far is this:
$E \left (\sup \limits_{t \in [0,1]}  |B(t) | \right ) = \int_0^\infty P(\sup \limits_{t \in [0,1]}  |B(t) | \geq y )  dy $
$ =  \int_0^\infty \sum_{k=-\infty}^\infty (-1)^k \text{sign}((2k+1) y) \text{Erfc} \left ( \frac{\vert (2k+1) y \vert }{\sqrt{2}}  \right ) dy $.
Here Erfc is the error function:
$\text{Erfc}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \, dt$
Now the post mentions splitting the series up into a series over negative $k$ and one over positive (nonnegative I guess) $k$, so that I get
$= \int_0^\infty \sum_{k=-\infty}^{-1} (-1)^k \text{sign}((2k+1) y) \text{Erfc} \left ( \frac{\vert (2k+1) y \vert }{\sqrt{2}}  \right ) dy $
$ + \int_0^\infty \sum_{k=0}^\infty (-1)^k \text{sign}((2k+1) y) \text{Erfc} \left ( \frac{\vert (2k+1) y \vert }{\sqrt{2}}  \right ) dy  $
and now the next step seems to be using a change of variable to see that both terms are actually equal, but I cannot verify this. The first term is
$\int_0^\infty \sum_{k=1}^{\infty} (-1)^{-k} \text{sign}((2(-k)+1) y) \text{Erfc} \left ( \frac{\vert ((2(-k)+1) y \vert }{\sqrt{2}}  \right ) dy $
$= \int_0^\infty \sum_{k=1}^{\infty} (-1)^{k} \text{sign}((2k+1) y) (-1)\text{Erfc} \left ( \frac{\vert ((2(-k)+1) y \vert }{\sqrt{2}}  \right ) dy $
and this is where I'm stuck already. I know that the Errorfunction is an odd function, but I cant seem to bring it into a form where I can combine both sums into one.
Also, I don't understand how to use integration by parts to evaluate both of the integrals after combining the series.
Can anyone help me out with this? Thanks!
Answer: First of all, note that Erfc does not denote the Error function but its "complement", i.e.
$$\DeclareMathOperator{\erfc}{Erfc}\DeclareMathOperator{\erf}{Erf}   \erfc(x) := \frac{2}{\sqrt{\pi}} \int_x^{\infty} \exp (-y^2) \, dy = 1- \erf(x)$$
where
$$\erf(x) = \frac{2}{\sqrt{\pi}} \int_0^x \exp (-y^2) \, dy$$
is the Error function.

Since
$$|2(-k)+1| = |2k-1|$$
we have
\begin{align*} \DeclareMathOperator{\sign}{sgn}  \DeclareMathOperator{\erf}{Erfc} & - \int_{(0,\infty)} \sum_{k \geq 1} (-1)^k \underbrace{\sign((2k+1)y)}_{=1} \erf \left( \frac{|(2(-k)+1)y|}{\sqrt{2}} \right) \, dy \\ &= \int_{(0,\infty)} \sum_{k \geq 1} (-1)^{k+1} \erf \left( \frac{|(2k-1)y|}{\sqrt{2}} \right) \, dy \\
&\stackrel{k \to j+1}{=} \int_{(0,\infty)} \sum_{j \geq 0} (-1)^{j} \underbrace{(-1)^2}_{=1} \erf \left( \frac{|(2j+1)y|}{\sqrt{2}} \right) \, dy.
\end{align*}
Hence, by the computations from your question,
\begin{align*} \mathbb{E} \left( \sup_{t \in [0,1]} |B_t| \right) = 2 \int_{(0,\infty)} \sum_{j \geq 0} (-1)^j  \erf \left( \frac{|(2j+1)y|}{\sqrt{2}} \right) \, dy. \end{align*}
Interchanging sum and integration and applying the integration by parts formula we get
\begin{align*} \mathbb{E} \left( \sup_{t \in [0,1]} |B_t| \right) &= 2 \sum_{j \geq 0} (-1)^j \int_{(0,\infty)} \erf \left( \frac{(2j+1)y}{\sqrt{2}} \right) \, dy \\ &=  \frac{4}{\sqrt{2\pi}} \sum_{j \geq 0} (2j+1) (-1)^j \int_{(0,\infty)} y \exp \left(- \frac{(2j+1)^2}{2} y^2 \right) \, dy \\ &= \frac{4}{\sqrt{2\pi}} \sum_{j \geq 0} (-1)^j  \frac{1}{2j+1} \end{align*}
As $$\arctan(x) = \sum_{j \geq 0} (-1)^j \frac{x^{2j+1}}{2j+1}$$ we conclude that
$$\mathbb{E} \left( \sup_{t \in [0,1]} |B_t| \right) = \frac{4}{\sqrt{2\pi}} \arctan(1) =  \frac{4}{\sqrt{2\pi}}  \frac{\pi}{4} = \sqrt{\frac{\pi}{2}} $$
Remark I: Feel free to check the constants appearing in my computations. In the thread, which you linked, it is claimed that
$$\mathbb{E} \left( \sup_{t \in [0,1]} |B_t| \right) = \sqrt{\frac{\pi}{8}};$$
this is, however, wrong. It follows from the reflection principle that $\sup_{t \in [0,1]} B_t \sim |B_1|$, and therefore
\begin{align*} \mathbb{E} \left( \sup_{t \in [0,1]} |B_t| \right) \geq \mathbb{E} \left( \sup_{t \in [0,1]} B_t \right) &= \mathbb{E}(|B_1|) \\ &= \sqrt{\frac{2}{\pi}} \approx 0.797 \\ &> \sqrt{\frac{\pi}{8}} \approx 0.626 \end{align*}
Remark II: Let me provide a reference for the formula for $\mathbb{P}(\sup_{s \leq 1} |B_s| \geq r)$ which you used in your computations (just in case that somebody wants to look it up). In the Handbook of Brownian Motion by Borodin & Salminen it is stated on p. 339 (Part II, Chapter 3, Formula 1.1.4) that $$\mathbb{P}^x \left( \sup_{s \leq t} |B_s| \geq r \right) = \tilde{\text{cc}}_t(x,r)$$ where $$\tilde{\text{cc}}_t(x,r) := \sum_{k \in \mathbb{Z}} (-1)^k \sign(x+(2k+1)r) \erfc \left( \frac{|x+(2k+1)r|}{\sqrt{2t}} \right),$$ see p. 651 (Appendix II, Section 13).
Comment: Thank you very much for this explaination, this helps me alot! However, there is one step I don't quite understand. After using integration by parts, there is a negative sign before the series, and in the next step afterwards this is gone. Why does it disappear? From my calculations the integral $\int_0^\infty y \exp(-ay^2) = \frac{1}{2a}$ for a constant $a > 0$, which does not remove the negative sign in the next step, and makes me get $- \sqrt{\frac{\pi}{2}}$. I must be doing something wrong in this step, cause this means a postive random variable would have negative expecation..
Comment: @Bazzan I finally managed to solve the mystery. The point is that Erfc does not denote the Error function but its "complement", i.e. Erfc = 1- Erf, see the very beginning of my answer. This gives the missing minus sign and everything works fine.
Comment: Thanks alot! Now its all clear.


How to make fabric.js canvas center be 0,0?

Question: I'm just starting with fabric.js and I wonder if there is a way to create a canvas in such a way that I can work with cartesian coordinates? For example, I want a circle that I create at (0,0) to show up in the center of my canvas that reaches from -400 to 400 on the x-axis and -400 to 400 on the y.axis, with higher values of y going up and higher values of x going right.
Is there a way to do that without translating every position by hand?
Answer: You can use originX and originY attributes.
var obj = canvas.getObjects();
for (var i in obj) {
    obj[i].set({
        originX: 'left',
        originY: 'top',
        left: 0,
        top: 0
    });
}
canvas.renderAll();

Check this fiddle with examples: http://jsfiddle.net/1ow02gea/51/
Comment: Thanks, but this is not what I was asking for... I would like to change the coordinate system of the canvas itself in such a way that the point (0,0) is located at the center of the canvas (width/2, height/2). According to your FIddle, the circle's and text's coordinates should be (0,0) instead of (100,100) and still be in the center of the canvas.
Answer: You cannot change the origin of the canvas element without introducing visual artifacts. What you can do is pan the canvas to a virtual "0,0" position. Bear in mind that you will have to adjust both X_PAN_VALUE and Y_PAN_VALUE to your specific use case.
canvas.viewportTransform[4] = X_PAN_VALUE;
canvas.viewportTransform[5] = Y_PAN_VALUE;

Better late than never ;)


$x_n\to x$ implies that $m_{x_n}\to m_x$ ? where $m_t$ is Dirac measure supported on $t\in X$

Question: Let $(X, d)$ be a compact metric space.
We denote by $\mathcal{M}(X)$ the set of all Borel probability measures of $X$. Also,  $\mu_n\to \mu$ if and only if $\int f d\mu_n\to \int f d\mu$ for every continuous map $f:X\to \mathbb{R}$.
Denote by $m_x$ the Dirac measure supported on $x\in X$, indeed,
$m_x(A)=0$ or $1$ depending on whether $x\notin A$ or $x\in A$.
We have a sequence $\{x_n\}_{n\in\mathbb{N}}\subseteq X$ with $x_n\to x$.  What can say about $\{m_{x_n}\}_{n\in\mathbb{N}}$. Is it true that $m_{x_n}\to m_x$ as $n\to \infty$?
Comment: I think then $m_{x_n} \overset{?}{\to} m_x$ becomes equivalent to $f(x_n) \overset{?}{\to} f(x)$.
Comment: @angryavian, Thanks. If it is true, then by continuity of $f$ and $x_n\to x$, $m_{x_n}\to m_x$.
Answer: The answer to the last question is yes. The Lemma and the Theorem below summarizes the properties of embedding the space into its space of measures.
We also point out that the statement below hold not only in the setting of the OP but in the slightly more general setting of separable and complete metric spaces (Polish spaces) that is used extensively in the Theory of Probability.
Let $(S,d)$ be a Polish space and denote by $\mathscr{B}(S)$ the Borel $\sigma$-algebra, and let $\mathcal{M}(S)$ be the space of all finite Borel measures on $\mathscr{B}(S)$. Denote by $\mathcal{C}_b(S)$ the space of all bounded continuous functions on $S$. The weak topology $\sigma(\mathcal{M}(S),\mathcal{B}_b(S))$ is the smallest topology on $\mathcal{M}(S)$ that makes the the functions
$$\Lambda_f:\mu\mapsto \int_S f\,d\mu$$
for each $f\in\mathcal{C}_b(S)$ continuous. A local basis for this topology is generated by sets of the form
$$V(f_1,\ldots,f_n;\varepsilon)=\{|\Lambda_{f_j}\mu|<\varepsilon,\,1\leq j\leq n\}$$
where $n\in\mathbb{Z}_+$, $f_1,\ldots,f_n\in\mathcal{C}_b(S)$, and $\varepsilon>0$.

Observation If $(S,d)$ is a compact metric space then $\mathcal{B}_b(S)=\mathcal{C}_{00}(S)=\mathcal{C}(S)$, where $\mathcal{C}_{00}(S)$ denotes the space of continuous functions on $S$ with compact support, and $\mathcal{C}(S)$ denotes the space of continuous functions on $S$. By the Riesz representation theorem $(\mathcal{C}(S),\|\;\|_u)^*=(\mathcal{M}(S),\|\;\|_{TV})$ where $\|\;\|_{TV}$ is the total variotion norm. In this case, the weak-* topology on $\mathcal{M}(S)$ coincides with the weak-topology defines above.

The space $S$ itself embeds into $\big(\mathcal{M}(S),\sigma(\mathcal{M}(S),\mathcal{C}_b(S))\big)$ through the map $x\mapsto\delta_x$. The next results show that this mapping is continuous and that $S$ (the embeding) is a weakly closed.
For each $x\in S$, denote by $\delta_x$ the measure in $\mathcal{M}_+(S)$ such that $\delta_x(A)=\mathbb{1}_A(x)$ for all $A\in\mathscr{B}(S)$.

Lemma: Let $\{x_\alpha\}$ be a net in a metric space $S$ and $x\in S$.
$\delta_{x_\alpha}\Rightarrow\delta_x$ iff $x_\alpha\rightarrow x$.

Proof: $\delta_{x_\alpha}\Rightarrow\delta_x$ iff $\lim_\alpha f(x_\alpha)= f(x)$ for all $f\in\mathcal{C}_b(S)$. The particular choice $f(y)=1\wedge d(y,x)$ implies that
$x_\alpha\rightarrow x$. $\Box$

Let $\mathcal{M}_+(S)\subset\mathcal{M}(S)$ be the subspace  nonnegative finite Borel measures on $\mathscr{B}(S)$. The following result summarizes the properties of the embedding of $S$ into $\mathcal{M}_+(S)$

Theorem: The set $\{\delta_x: x\in S\}$ is weakly closed in $\mathcal{M}_+(S)$, where $\mathcal{M}_+(S)$ is considered as a subspace the space of all finite Borel  measure $\mathcal{M}(S)$ on on $\mathscr{B}(S)$ with the weak topology $\sigma(\mathcal{M},\mathcal{C}_b(S))$.

Proof: Suppose that   $\delta_{x_\alpha}\Rightarrow \mu$. As $\mathcal{M}_+(S)$ is a closed in $\big(\mathcal{M}(S),\sigma(\mathcal{M}(S),\mathcal{C}_b(S))\big)$ and $\{\delta_x:x\in s\}\subset\mathcal{M}_+(S)$, $\mu\in\mathcal{M}_+(S)$.
Let  $x\in\operatorname{supp}(\mu)$. For any open neighborhood $V$ of $x$, let   $f\in\mathcal{C}_b(S)$ be  such that $0\leq f\leq 1$, $f(x)=1$ and $f=0$ on $ S\setminus V$.  Then $\int f\,d\mu>0$ and,  as
$$\lim_\alpha\delta_{x_\alpha}f=\lim_\alpha f(x_\alpha)= \mu f,$$ there exists $\alpha_0\in D$ such that $\alpha\geq\alpha_0$ implies that $x_\alpha\in V$. Hence,   $x_\alpha\rightarrow x$, and by the Lemma presented above,  $\mu=\delta_x$. $\Box$


pandas how to get sorted value in groupby object

Question: I have a dataframe
df =
Col Val
 a.  8
 a.  9
 c.  4
 c.  0
 d.  3
 d.  9

I want to sort by Val of the smallest value within group and then foreach row get the index of the groupby Col
So the new df will df
df_new =
Col Val Idx
 c.  4.  0
 c.  0.  0
 d.  3.  1
 d.  9.  1
 a.  8.  2
 a.  9.  2

What is the best way to do so?
Answer: Use GroupBy.transform with min to new column, then for starting by 1 with range use Series.rank and then sorting by 2 columns - if same minimal value per multiple groups get same groups by Col together:
df['Idx'] = (df.groupby('Col')['Val'].transform('min')
               .rank(method='dense').astype(int).sub(1))
df = df.sort_values(['Idx','Col'], ignore_index=True)
print (df)
  Col  Val  Idx
0  c.    4    0
1  c.    0    0
2  d.    3    1
3  d.    9    1
4  a.    8    2
5  a.    9    2


auto.arima results in R has no intercept

Question: After fitting an ARIMA model with a covariate using the auto.arima function in R, I get the following results

What could be the reason as to why my results do not include the intercept. Also, I would highly appreciate interpreting the important metrics from the summary above.
Comment: The automatic model search routine believes that no mean is needed. Unfortunately, just how this happens is not described on the help page, so you would need to hunt through the [source code](https://cran.r-project.org/web/packages/forecast/index.html) if you are really interested. Re your second question: I would recommend posting a new question on that (because it is really different from "why no intercept?"), ideally [posting the output as text (formatted as code) rather than as a picture](https://stats.meta.stackexchange.com/a/3176/).
Comment: See https://otexts.com/fpp2/arima-r.html#how-does-auto.arima-work
Answer: The function auto.arima() has many arguments that you can add. Maybe what you are looking for auto.arima(x, allowmean = TRUE), because I am not sure that the default settings allows mean to be modeled. Also, as @Stephan-Kolassa said, apparently no mean is needed.


get sum of php multidiamentional array

Question: I am looking to store sum of all keys inside an array here is my example code
<?php

// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {

                list($sale_key, $sale_value) = explode('*', $value);
                $category->sale_data[$sale_key][] = $sale_value;
                //$category->sale_data_sum[$sale_key][] += $sale_value;
}
// display
print_r($category);

getting this output working example -> https://3v4l.org/NAKfb#v7.0.0

Here is expected to get  //$category->sale_data_sum[$sale_key][] +=
$sale_value;

I am expected output like this
stdClass Object
(
    [category_name] => 32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1
    [sale_data] => Array
        (
            [32459] => Array
                (
                    [0] => 1500
                )

            [32460] => Array
                (
                    [0] => 400
                )

            [32461] => Array
                (
                    [0] => 600
                )

        )
    [sale_data_sum] => 2500

)

Answer: Simply do this:
$category->sale_data_sum = 0; // initiate key
foreach ($category_sale_data as $key => $value) {
    list($sale_key, $sale_value) = explode('*', $value);
    $category->sale_data[$sale_key][] = $sale_value;
    $category->sale_data_sum += $sale_value; // add each sale value
}

Comment: work 100% very quick and short solution awesome thumbs up !
Answer: $category = [ 'category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1' ];

// category_name
$result['category_name'] = $category['category_name'];

// sale_data
$splitted = preg_split('/[*,]/', $category['category_name']);
for($i = 0; $i < count($splitted); $i += 4) {
  $result['sale_data'][$splitted[$i]] = $splitted[$i + 1];
}

// sale_data_sum
$result['sale_data_sum'] = array_sum($result['sale_data']);

print_r($result);

Answer: Try this
<?php

    // Sample data
    $category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
    // process
    $category_sale_data = explode(',', $category->category_name);
    foreach ($category_sale_data as $key => $value) {

                    list($sale_key, $sale_value) = explode('*', $value);
                    $category->sale_data[$sale_key][] = $sale_value;
                    //$category->sale_data_sum[$sale_key][] += $sale_value;
    }

    function sum($carry, $item)
    {
        $carry += array_values($item)[0];
        return $carry;
    }

    $a = array_reduce(array_values($category->sale_data), "sum");

    var_dump($a);

Or
<?php

// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
$category->sale_data_sum = null;
foreach ($category_sale_data as $key => $value) {

                list($sale_key, $sale_value) = explode('*', $value);
                $category->sale_data[$sale_key][] = $sale_value;
                $category->sale_data_sum += $sale_value;
}
// display
print_r($category);

get sum of php multidiamentional array


Redirect without changing URL

Question: Here's the setup. We have a hardware load balancer with an http virtual cluster. Let's call this virtual cluster example1.com. This virtual cluster load balances between two squid reverse proxies which are also on the same physical servers as the web servers. Squid listens on 80 and points to itself as the cache_peer web server which listens on 81. We also have a standalone web server which we will call example2.com.
What we are trying to do is create a subdirectory on example1.com called example1.com/example2. This will point to example2.com, but we want our users to stay at example1.com/example2 in their browser. So, it's like a redirect without actually being a redirect. How the hell do I go about doing this? Is this even possible? I'm looking at squid docs in the meantime.

example1.com is running a proprietary web server - not Apache :(
We can't host example2.com's content in example1.com's file system. These are two very different platforms.
Comment: Almost need a picture here or something.  Your setup is pretty complex.  Since I am not sure I have fully grasped your setup, I am not sure if I can provide a valid answer.  But have you looked at using the redirection features within Squid?  When squid redirects it is transparent to the end user. See: http://wiki.squid-cache.org/Features/Redirectors
Answer: I might be missing something here, but this actually sounds pretty straight forward. Load balance all requests where the URL path matches ^/example2/ to the example2.com web server.
Move all website content from the directory root to a subdirectory called /example2/ on the example2.com web server.
Comment: Mathias, you are absolutely correct. I incorporated some of your answer into my config file. Thanks.
Answer: I got it working. I reconfigured squid to use a urlpath_regex acl and set up example2.com as a secondary cache peer. Then I set example2.com to allow /example2, but deny all others. Then for example1.com, I set it to deny /example2. It's working as intended. Here's what the config file looks like.
acl redirect urlpath_regex ^/example2*
cache_peer example1.com parent 81 0 no-query originserver name=server1
cache_peer example2.com parent 80 0 no-query originserver name=server2
cache_peer_access server1 deny redirect
cache_peer_access server2 allow redirect
cache_peer_access server2 deny all
If I go to example1.com/example2, it's pulling the content from example2.com, but the example1.com URL remains in the browser.

Redirect without changing URL


Adding external databases to settings.php using prefix

Question: As per the comments in settings.php:
/*
 * You can also use a reference to a schema/database as a prefix. This maybe
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 * @code
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );
 * @endcode
 */

So if my current simple default looks like:
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dev',
      'username' => 'dev',
      'password' => 'dev',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => false,
    ),
  ),
);

How would I add two tables (table1 and table2) on another database (dev1) on localhost so that they are available to drupal?
Answer: If they're on the same mysql host (and you've got the appropriate permissions) you can access the tables by simply prefixing them with the schema name: otherdatabasename.tablename. You can even run queries joining across the two databases.
If they're on a different server you'll need to add a separate connection and specify it as part of the query by using the $options['target'] setting.
Comment: "If they're on the same mysql host (and you've got the appropriate permissions) you can access the tables by simply prefixing them with the schema name: otherdb.tablename. You can even run queries joining across the two databases" - this is exactly what I want the outcome to be. But whats the correct format in settings.php that would do this? Do you have an example?
Comment: if they're on the same host you don't need to do anything other than just refer to the table by it's full name, no new connection necessary.
Comment: Im pretty sure I had tried that but perhaps I had done it in the wrong context. Will take another look and get back.
Comment: cool, yeah post any error messages you get.


When and why did rugby union change the number of reserves?

Question: In the 2011 world cup teams fielded 22 players each and in the 2015 world cup fielded 23 players.
When was this changed? Is there a reason given by world rugby as to why this decision was made?
Answer: This was a change designed to reduce the number of matches which were forced to have uncontested scrums due to not having appropriate players available - rugby union scrummaging is a highly technical activity, and having players not skilled in it attempt it is not allowed due to the risk of injuries involved if the scrum collapses.
The original change to the Laws happened in 2009. However, at that point the option to allow 23 players, which  had to include 6 front-row players, was an option only for national and cross-border matches. It explicitly did not apply to international matches at that stage, which is why the 2011 World Cup was played with 22 man squads.
I can't find the exact date when 23 player squads were allowed in international rugby, but the change had obviously happened by 2015.


Symfony3.4 persist of oneTomany entity

Question: i need to make a chat for one application in symfony3.4, so i created a channel entity and a message entity, i made a One to Many relations and a i add message in the channel but there is no persistent of the entity include in the intentity.
In Message Entity
/* $channel.
*
* (Many-To-One, Unidirectional)
* @ORM\ManyToOne(targetEntity="Soraya\ChatBundle\Entity\chanEntity",inversedBy="messages")
* @ORM\JoinColumn(name="channel_id", referencedColumnName="id")
*
*/
protected $channel;

public function setChannel(\Soraya\ChatBundle\Entity\chanEntity $channel ){
    $this->channel = $channel;
    return $this;
}

In ChanEntity Entity
 /*
     * $messages
     * (One-To-Many, Bidirectional)
     * @ORM\OneToMany(targetEntity="Soraya\ChatBundle\Messages", mappedBy="channel"),cascade={"persist", "remove"})
     *
     *

     */
    protected $messages;

    public function __construct() {
        parent::__construct();
        $this->messages = new ArrayCollection();

    }

    public function addmessages(\Soraya\ChatBundle\Entity\Messages $message){

        $this->messages[]=$message;
        $message->setChannel($this);
        return $this;
    }

In my controller
`public function addMessageAction(Request $request, $idChan, $utilisateur, $message){

$em = $this->getDoctrine()->getManager();

//message
$advertmess = new Messages();

$advertmess->setMessage($message);
$advertmess->setpseudoUtilisateur($utilisateur);

// chan

$advert2 =  $em->getRepository('ChatBundle:chanEntity')->find($idChan);
$advert2->addmessages($advertmess);

// entity

$em->persist($advert2);
$em->persist($advertmess);
$em->flush();

//$em->persist($advert);
//$em->flush();

var_dump($advert2);
//var_dump($advertmess);

return new Response("OK");

}`

When i saw the var_dump in the request i can see the entity inside the entity but when i try to access to it after there nothing :

Exemple of what i can see in var_dump of chan
object(Soraya\ChatBundle\Entity\chanEntity)[790]
  protected 'messages' => null
  protected 'typesChan' => string 'contact' (length=7)
  .......

Exemple in request
object(Soraya\ChatBundle\Entity\chanEntity)[849]
  protected 'messages' =>
    array (size=1)
      0 =>
        object(Soraya\ChatBundle\Entity\Messages)[838]
          protected 'pseudoUtilisateur' => string 'user' (length=16)
          protected 'message' => string 'testword' (length=5)
          protected 'channel' =>
            &object(Soraya\ChatBundle\Entity\chanEntity)[849]
          protected 'id' => int 135
          protected 'sync_uuid' => string '64373958-f69e-4b84-8543-aa3ed6b3be19' (length=36)
          protected 'isDeleted' => boolean false
          protected 'cree_le' =
          ......

The entity inside my entity don't persist i can access to the message created in mydatabase but not in the connexion between chan and message. Someone get an idea of what could be wrong ? Thank you.
Answer: i find my mistake, there is need one more * in the ORM JOIN, it must be like that.
    /** $channel.
*
* (Many-To-One, Unidirectional)
* @ORM\ManyToOne(targetEntity="Soraya\ChatBundle\Entity\chanEntity",inversedBy="messages")
* @ORM\JoinColumn(name="channel_id", referencedColumnName="id")
*
*/
protected $channel;

Symfony3.4 persist of oneTomany entity


Build short cypher starting from a number and a password

Question: I have to build 50,000 codes starting from an incremental number (1 to 50000) and a secret password. I have to do it in php and the final code must be 8 or 12 characters long and contain only uppercase letters (A-Z) and numbers (0-9).
The final codes must be decryptable with the password...
I'm trying with openssl_encrypt but I can not find a way to make "short" the final code.
<code>$longCode = openssl_encrypt($number, $method, ENC_KEY, true, $iv);
$shortCode = .....
</code>
Some ideas?
Comment: As you speak about a 'password', I assume you want to be able to decrypt again, right? You're not looking for a cryptographic hashing function? This might be better in place at security.stackexchange.
Comment: First I thought about suggesting the [Vigenènere cypher](http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher), but seeing as your plaintext (numbers from 1 to 50k) is so limited (and ordered, at that) it turns into a weak caeser cypher.. Can you post some more requirements?
Comment: Joost is right I want to be able to decrypt the code back.
Answer: The first step is to use a cipher method that has a block size of 8 bytes, e.g. "rc2-cbc".
<code>$nr = 1234;
$key = 'secretkey';
$method = 'rc2-cbc';

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));

$code = openssl_encrypt($nr, $method, $key, true, $iv);
</code>
The second step is casting the resulting string into your alphabet; because your alphabet size is only 36, the closest and "easy" conversion is base32; this gives (after stripping away the optional padding) a string of exactly 13 characters.
Theoretically you can convert 4 bytes into 6 characters of base36:
<code>log(36) / log(2) ~ 5.17 bits, saves 1 bit after 6 blocks

6 x 5.17 ~ 31.02, 6 blocks fits inside 32 bits (unsigned long)

32 bits = 4 bytes -> 6 characters
</code>
Faulty implementation
The following code should do it - but doesn't (always) work!
<code>$final = '';
foreach (str_split($code, 4) as $part) {
    $x = current(unpack('L', $part));
    $final .= strtoupper(base_convert($x, 10, 36));
}
</code>
Decoding would go like this:
<code>$code2 = '';
foreach (str_split($final, 6) as $part) {
        $code2 .= pack('L', base_convert(strtolower($part), 36, 10));
}
</code>
Somehow the integer precision can't handle it or I'm doing something stupid; either way, it doesn't always work.
Comment: 13 characters... near to the solution... I have a must to stay into 12 characters.
Comment: @wildnove Managed to fit it into 12 characters :)
Comment: are you able to show me how to decrypt the code back into a number?
Comment: @wildnove I'm still proving the correctness on a piece of paper :)
Comment: @wildnove Unfortunately, it sometimes works and sometimes doesn't
Comment: @wildnove I ran my code a few times with random IV; it's like 50/50 ... the problem is that it goes wrong when all 32 bits are used; annoying.
Comment: exactly, however I liked your answer
Comment: @wildnove Thanks, hope you can stretch to 13 characters :)
Answer: Try this one:
<code>// generate random ID
    function generateRandomID ($len) {
        //To Pull Unique Random Values Out Of AlphaNumeric
        //removed number 0, capital o, number 1 and small L
        //Total: keys = 32, elements = 33
        $characters = array(
        "A","B","C","D","E","F","G","H","J","K","L","M",
        "N","P","Q","R","S","T","U","V","W","X","Y","Z",
        "1","2","3","4","5","6","7","8","9");

        //make an "empty container" or array for our keys
        $keys = array();

        //first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
        while(count($keys) < $len) {
                //"0" because we use this to FIND ARRAY KEYS which has a 0 value
                //"-1" because were only concerned of number of keys which is 32 not 33
                //count($characters) = 33
                $x = mt_rand(0, count($characters)-1);
                if(!in_array($x, $keys)) {
                     $keys[] = $x;
                }
        }

        foreach($keys as $key){
             $random_chars .= $characters[$key];
        }
        return $random_chars;
    }
</code>
EDIT: Removed some letters and numbers for better user-friendly reading, see comments in code.
Comment: He's generating codes based on an integer and a secret password. Don't you think he'd want to be able to decrypt the code with the secret password? Like in a shared key crypto protocol? Nowhere did he mention the word 'random'.
Comment: How is that even remotely close to being decryptable, when you have the password?
Comment: As far I read the question, user needs a function for generating a 50000 random codes, what decryption you mean?
Comment: True, but isn't that an inherit function of a 'secret password'?


Pegar apenas um valor repetido no mysql

Question: Galera, eu tenho uma tabela e nela um campo chamado cargo sendo que valor dele pode se repetir, como por exemplo, o cargo professor. No meu HTML eu estou montando um <select> quando recupero o valor desse campo, só que devido o valor dele se repetir ele mostra várias vezes a palavra professor ou qualquer outro que venha a se repetir no na tabela, lógico. Gostaria de saber se há alguma forma de "filtrar" e extrair apenas um valor desses repetidos?
Comment: A solução seria normalizar essa tabela, uma tabela para cargos e outra para funcionarios, o campo `cargo`(descrição) não fica na tabela funcionarios, somente seu id(`id_cargo`). POR FAVOR NÃO USE `DISTINCT`.
Comment: Não resolve o problema, apenas mascara ele. Já imaginou o que acontece quando o último estagiario for promovido ou demitido? esse cargo ainda estará disponível no combo? Edite a pergunta e coloque a estrutura dessa tabela.
Comment: @rray por que não posso usar o DISTINCT?
Comment: O ideal seria segmentar em 2 tabelas, conforme o rray comentou. Uma tabela onde estarão os dados do cargo e outra com os dados do funcionário, sendo que, um funcionário deverá conter um cargo...
Answer: Existem dois métodos:
1. Seria utilizando DISTINCT
SELECT DISTINCT(cargo) FROM tabela

2. Seria utilizando o GROUP BY:
SELECT cargo FROM tabela GROUP BY cargo

Teste isto clicando aqui!
Ambos os métodos possuem o mesmo resultado, como pode ser visualizado, não há muito o que explicar. A função do Group By é agrupar por igualdade, resumindo irá exibir uma das duplicações, sendo assim não será mais uma duplicação. =D
Comment: Foi explicado que, nesse caso, o distinct não é a melhor opção. A melhor opção é normalizar a tabela! Trabalhe com foreign keys, distinct nesse caso, é gambiarra! O primeiro comentário feito na pergunta, mostra como deve ser feito.
Comment: não entendi porque os down votes...
Comment: Também não. Na verdade até achei que era uma coisa que tinha colocado (ver edições) mas enfim. Pelo menos o  autor da publicação aprovou e aparentemente serviu.
Answer: SELECT cargo FROM `tabela` GROUP BY `tabela`.`cargo` =`cargo`;

Dessa forma, forço os resultados onde o meu campo for igual ao campo que pretendo trazendo apenas um resultado, mais o ideal é utilizar a normalização como dito anteriormente.

Pegar apenas um valor repetido no mysql


Appending file name to data frame in R

Question: I want to append the file name to my table, but it seems it is not really working.
What I am doing is iterating over a list of filenames, opening them, appending all the data to one data frame and for each appended file I want to add its file name. I expect it to be appended on each row, so that later when I look at the data, I would know from which file is the given row originating.
But it seems that it is not working as expected.
data <- data.frame()
for (file in files){

  name = strsplit(file, split = "\\.")[[1]][1]

  data <- data %>% bind_rows(read_delim(file = file, delim = ";", col_types = cols(
    a = col_double(),
    b = col_double(),
    )) %>% mutate(name = name))
}

I believed that the mutate function should have done the trick, apparently, in the end they all have the same value.
Comment: @akrun I have left it out by mistake. I am splitting the file .. I have edited the code now. Example albert.csv -> name = albert
Answer: As we are using tidyverse, an option is
library(readr)
library(purrr)
files_no_ext <- tools::file_path_sans_ext(files)
out <- imap_dfr(set_names(files, files_no_ext), ~
      read_delim(.x, delim = ";",
         col_types = cols(a = col_double(),b = col_double()),
              .id = 'name')

Or using data.table
library(data.table)
out <- rbindlist(lapply(setNames(files, files_no_ext), fread), idcol = 'name')

In the OP's for loop
dat <- data.frame()
for (file in files){
     name <- tools::file_path_sans_ext(file)
     tmpdat <- read_delim(file = file, delim = ";",
             col_types = cols(
                    a = col_double(),
                    b = col_double()
                      )) %>%
              mutate(name = name)
      dat <- rbind(dat, tmpdat)

 }

Comment: I adjusted my code and it works. Do you think the first solution is faster/ more effective than the second one?
Comment: @CroatiaHR I  thhink the first solution would be more readable (subjective), and it automatically creates the column based on the `.id`, regarding the faster option, you may have to try `fread` from `data.tabl` and `rbindlist`

Appending file name to data frame in R


How do I disable the close button in my goog.ui.Dialog?

Question: I would like to get rid of the close/X button on the top right corner of my Google Closure dialog.
I am browsing the documentation (http://closure-library.googlecode.com/svn-history/r8/trunk/closure/goog/docs/class_goog_ui_Dialog.html) and cannot find the method to do so.
Answer: The method is there! See http://closure-library.googlecode.com/svn/docs/class_goog_ui_Dialog.html
dialog.setHasTitleCloseButton(false);

Regards,
Rene
Answer: The goog.ui.Dialog title-bar close button can be disabled by first calling goog.ui.Dialog.prototype.getTitleCloseElement() followed by goog.style.showElement(el, display).
Example
var dialog = new goog.ui.Dialog();
dialog.setContent('Lorem ipsum dolor sit amet, consectetuer' +
    'adipiscing elit. Aenean sollicitudin ultrices urna. Proin vehicula ' +
    'mauris ac est. Ut scelerisque, risus ut facilisis dictum, est massa ' +
    'lacinia lorem, in fermentum purus ligula quis nunc. Duis porttitor ' +
    'euismod risus. Nam hendrerit lacus vehicula augue. Duis ante.');
dialog.setTitle('Lorem ipsum');
dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createYesNo());

var titleCloseEl = dialog.getTitleCloseElement();
goog.style.showElement(titleCloseEl, false);


how to hide the facet api block if it has only one item?

Question: I have to hide the Drupal facet API block if it has only one item. Is there any settings available or should I go with any hooks?
Answer: Use the module facetapi_bonus and you will get an option to hide a facet if the view has only X item(s)
This setting can be accessed through 'facets > configure filters'
Answer: I tried this and it works for me.
function MYCUSTOMMODULE_block_view_alter(&$data, $block) {
<code>if($block -> module == 'facetapi' && !empty($data)){
    $key = $data['content']['#contextual_links']['facetapi'][1][2];
    $count = count($data['content'][$key]['#items']);
    if($count <= 1){
        unset($data['content']);
    }
 }
</code>
}
This is a generic one where it affects for all facets blocks site wide which I need.


Why is T a type projection of this.type in expanded type designator C.this.type#T

Question: SLS 3.2.5 Type Designators indicates
trait C {
  type T
  val x: T
}

expands to
trait C {
  type T
  val x: C.this.type#T
}

I am familiar with .type notation in singleton types, but I am not sure how it translates to C.this.type#T. For example. what is this.type part trying to convey over just saying C#T?
Answer: In Scala specification primary concept is type projection rather than path-dependent type.
And path-dependent types are defined in terms of type projections (and singleton types).
For example for val c: C type c.T is c.type#T by definition.
And c.x has type c.T aka c.type#T.
Inside trait C such type (when instance c is not fixed) can be referred as T aka this.T aka this.type#T aka C.this.T aka C.this.type#T.


Estimate the error of two algebraic equations

Question:
Let $f, \tilde f$ be two continuous scaler functions from $\mathbb{R}\to \mathbb{R}$ such that $|f-\tilde f| \leq \epsilon$. Suppose that $f(x) = 0$ and $\tilde f(x) = 0$ has exactly two solutions. Let $x^*, \tilde x^*$ be the largest solution of $f$ and $\tilde f$, respectively. Can we give find the upper bound of $|x^*-\tilde x^*|$ in term of $\epsilon, f, \tilde f$? Does it imply that $|x^*-\tilde x^*| \to 0$ as $\epsilon \to 0$.

Update: As answer from Lutzl, we can not get the bound of $|x^*-\tilde x^*|$. My next question is what kind of assumptions do we need if I want to get the upper bound of $|x^*-\tilde x^*|$ in term of $\epsilon, f, \tilde f$? and what is the bound?
Comment: Do you have any additional information, fixed point schemes, derivatives information, metric regularity?
Comment: I don't have any further assumption. But I welcome the solution with some additional assumptions.
Comment: @LutzL (to LutzL only) I realize that you live in BL.  I am studying at FU Berlin now :))
Comment: If $\inf_x |f'(x)|>c$, $\inf_x |\tilde f'(x)|>c$ then both functions are continuously invertible and the function values relate to the distance to the root set. However, it is non-trivial to get two roots per function.
Answer: Let $\phi(x)=\frac{x^2-1}{x^2+1}$ and $f(x)=\frac{ϵ}3\phi(x-a)$ and $\tilde f(x)=\frac{ϵ}3\phi(x-b)$. Then all assumptions are satisfied, however no control over the values $a,b$ and thus the roots at $a+1, b+1$ can be obtained.

One strategy to lead to a positive result is to have some growth condition on $f$ so that you can localize points $x_\pm$ with $\pm f(x_\pm)\ge 2ϵ$ ( or some other value $>ϵ$). Then $\pm\tilde f(x_\pm)>0$ so that $\tilde f$ has a root via the intermediate value theorem between $x_-$ and $x_+$, leading to $|x^*-\tilde x^*|\le|x_+-x_-|$.
Comment: Thanks for your answer. What kind of assumptions do I need if I want to give the bound of $x^* - \tilde x^*$ in term of $f, \tilde f, \epsilon$?


If $G/K$ is isomorphic to $H$ then is $G$ isomorphic to $KH$?

Question: I don't know if the question is trivial but I would really appreciate if someone could prove/disprove this question.
Thank you in advance
Edit:
I meant this: Suppose that there is homomorphism $f$ from $G$ to $H' K = \ker f$ and $H = \operatorname{im} f$. Then by the 1st isomorphism theorem, we can denote that $G/K \simeq H$ now my question was if I can say that $G \simeq K \times H$
Comment: What do you mean by $KH$?
Comment: $KH$ doesn't make sense unless $H$ is a subgroup of $G$.
Comment: I meant this :
Suppose that there is  homomorphism f from G to H'
K = ker f and H = image (f)
then by the 1st isomorph theorm we can denote that
G/K≅H
now my question was if I can say that G ≅ K X H
Answer: If you mean $K\times H$ then No.
$\mathbb{Z}_4/\mathbb{Z_2} \cong \mathbb{Z}_2$ but $\dots\dots$


Como mudar uma variável texto para valor número?

Question: Tenho esse segmento de código, gostaria que alguém me ajudasse em transformar  a variável P (na qual pega o atributo 'valor' ) e transformar ele em valor número para a soma.
$(document).ready(function(e) {
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total+= P;
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;
});

Comment: Se colocar a parte do HTML relevante fica mais facil
Comment: Possível duplicata de [jQuery não soma "+"](http://pt.stackoverflow.com/questions/87787/jquery-n%c3%a3o-soma)
Answer: Eu gosto da simplicidade do + unário:
Total += +P;
// Variáveis começam com minúsculas,
// o ideal seria: total += +p;

Comment: É um operador unário (só tem um operando), que converte para o tipo Number.
Comment: Porque o + na frente do 'p'? Primeira que vejo ele sendo usando assim @bfvaretto.
Answer: Use parseFloat, pois o parseInt irá converter para inteiros e assim irá perder os centavos do valor, deve ficar assim:
$(document).ready(function(e) {
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total += parseFloat(P);
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;
});

Se precisar de precisão use .toFixed(2);
$(document).ready(function(e) {
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total += parseFloat(P).toFixed(2);
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;
});

Se precisar de um calculo fazer um parse de um valor formatado com virgulas e separadores decimais use esta resposta:

https://pt.stackoverflow.com/a/16308/3635
Answer: Basta utilizar o parseInt() na variável.
$(document).ready(function(e) {
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = parseInt($('label').attr('value'));//Mudança aqui
        Total+= P;
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;
});

Ou se for double/float, parseFloat()


How to remove duplicate VC in swift?

Question: I am making a game, where I go from the main screen to a ArcadeViewController, which loads up the SKScene, and save the previous VC as prevVC.
I use segues created in storyboard to move between VC.
The problem is that each time I move to a VC, instead of moving into the old one, a copy gets created, and both of them start to run at the same time.
I tried removing them by running the following codes, when I move into the VC:
<code>        override func viewDidAppear(_ animated: Bool) {
    UIApplication.shared.keyWindow?.rootViewController = self
    self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    prevVC.reloadViewFromnib()
    prevVC.dismiss(animated: false, completion: nil)
     UserDefaults.standard.set(0, forKey: "since_The_Last_Ad")

}
   extension UIViewController {
func  reloadViewFromnib() {
    let parent = view.superview
    view.removeFromSuperview()
    view = nil
    parent?.addSubview(view) // This line causes the view to be reloaded
}
}
</code>
It helped to reduce the number of copies created, but still the are some.
How can I remove duplicate views?
Comment: You need to use a special kind of segue called an unwind segue: https://stackoverflow.com/questions/12561735/what-are-unwind-segues-for-and-how-do-you-use-them
Answer: So the solution ended up being to use the normal segue to launch the ArcadeVC from GameVC(start VC) for the first time.
Then set the ArcadeVC as rootVC:
<code>   UIApplication.shared.keyWindow?.rootViewController = self
</code>
Then use a normal segue to go back to the GameVC.
After the ArcadeVC is set as the rootVC, just use normal segue to the ArcadeVC form GameVC, and unwind from GameVC to AracdeVC.

How to remove duplicate VC in swift?


Android Shell locksettings command from device terminal

Question: Since Oreo there is this fancy locksettings command, that allows you to change the screenlock from adb shell. Now, if I try to run it on my PC everything is working. On my handheld the command will just get an "Aborted." back. Why is that and how can I run the locksettings command from my device?
here is the code for the locksettings command, maybe you can already tell by that:
<code># Script to start "locksettings" on the device
#
base=/system
export CLASSPATH=$base/framework/locksettings.jar
exec app_process $base/bin com.android.commands.locksettings.LockSettingsCmd "$@"
</code>
Answer: Download QUTE, a command panel. Start from the first command click and run it. About 10 to 15 commands ran will give enough control over the system. Only because most of the commands are going to fail, unable to run. Then the terminal will suggest you to STACK, for the command code to lock setting. Copy the code and paste it in the terminal. For there your settings should be locked.


Mac to Windows Database issue

Question: I've been developing a Drupal site for over a year on my MacBook. The production server that the Drupal site will run on is Windows Server 2008 R2. As I try and load the SQL file from my MacBook, I'm getting this error from my MySQL client: "This file contains mixed linebreaks. They have been converted to Windows linebreaks." Then the import crashes. Can anyone share some tips with me on how to sucessfully migrate the Drupal database to Windows w/o carrying over assorted character/encoding problems?
Also-because the Drupal URL of the site on Windows is something other than "localhost", I end up having to edit the exported SQL file(s) either in TextMate (on Mac) or in Notepad++ (on Windows) to change the URLs. Could this also be contributing to the problem? I have also noticed in Sequel Pro that in the "field_data_body" table that there are hard returns everywhere. Is this normal?
Sorry if this is a dumb question, but I'm at my wits end and on a tight deadline. Thanks so much,
Jason
--Added on 2/9/14--
Here's some additional details related to my original question.

First, I realized that the Mac version of my database contains Windows line breaks (\r\n) and not OSX line breaks (\n). If my production MySQL server runs on Windows, should I even bother to try and convert the incorrect line breaks on my mac development site?
Importing using Backup & Migrate doesn't usually work from my Mac to my Windows server because the Windows server usually crashes. So I have to start the site off on Windows by importing the schema and data files separately. Schema imports fine, but the data file import encounters SQL errors from these issues: apostrophies in block of text (i.e., Drupal's, site's); brackets (i.e., 'Your membership request was approved for '[og_membership:group:label]' in an insert statement), anyplace where % or @ occurs.

I've tried putting a backslash before the offending characters in some tables, but don't want to do this for the whole data file. Is there something I'm doing wrong when exporting SQL files on my Mac that is causing these problems?
One thing I just remembered is that I had to uninstall and then reinstall MAMP on my Mac two weeks ago. Before this, I never encountered these type of import errors, on my Mac at least. I checked my MySQL config. file and the only difference is that I declared InnoDB as the default storage engine. I did not have this in my previous MAMP installation.
Thanks for any assistance.
Jason
Answer: First, I would suggest using the Backup and Migrate module to move Drupal databases between hosts. That may solve your line breaks issues, and YMMV, but loading Drupal dbs via other MySQL methods can cause other issues.
Second, have you tried setting the $base_url config variable on your production server? You shouldn't have to change URLs in the SQL files. It's a best practice to use relative paths in content. There are modules/filters that will convert them to absolute paths on the fly.
Cheers!

Mac to Windows Database issue


Inequality with quotient

Question: During my research I'm confronting the following inequality:
$N_1(\frac{t_1}{N_1})^{1/3} +N_2(\frac{t_2}{N_2})^{1/3}<(N_1+N_2)(\frac{t_1+t_2}{N_1+N_2})^{1/3}$
With $0<t_1,t_2,N_1,N_2$ and $0<\frac{t_1}{N_1}<\frac{t_2}{N_2}<2$
Could anybody give me a hint? That'd be great !
Thanks in advance
Answer: Observe that
$$\frac{t_1 + t_2}{N_1 + N_2} = \frac{t_1}{N_1} \cdot \frac{N_1}{N_1 + N_2} + \frac{t_2}{N_2} \cdot \frac{N_2}{N_1 + N_2}.$$
Divide your inequality by $N_1 + N_2$ and then apply Jensen inequality.
Comment: God what could I say to thank you ?! It takes me 1 week and you 3 mins!! Big thanks Mr!

Inequality with quotient


"Cannot declare self-referencing constant database.inc line 2101"

Question: Suddenly, I got this error when I was configuring rules; the entire Drupal site is not accessible, not even update.php.

Fatal error: Cannot declare self-referencing constant '' in I:\My Documents\web\xampp\htdocs\mysite\includes\database\database.inc on line 2101

The last thing I remember was configuring rules with custom PHP.
Comment: If cron ran, then system_cron() clears the cache tables.  Clearing cache fixes a lot fo problems/weirdness in Drupal.
Comment: What exact version of D7 are you using?  That file has changed a few times, so the number reference need to be looked at in context of the proper version.
Comment: 7.9 newest release I recently updated. However, on my other machine 7.8 with the same rules module and a copy of the same site I did not get this error...
Comment: this is weird, I opened the site just now and everything is fine again! Could it be that a cache with the problem code got refreshed and deleted after 24 hours?
Answer: I suddenly got this same error on a Windows workstation.
It does not have anything to do with the content of the database (including cache); it occurs before it even connects to the database.
The only fix that worked for me was restarting apache.
Notes

The character within quotes is "EOT" ("end of transmission"), which looks empty in the error message.
The line 2101 in database.inc is the start of the DatabaseStatementBase class.


Web e API no Laravel 5.6

Question: Alguém poderia explicar sobre as mudanças de rotas na versão 5.6 do Laravel, agora tem os arquivos web.php e api.php, e quais middleware o api está usando.
Obrigado.
Answer: Na verdade, o arquivo api.php está presente desde a versão 5.3 do Laravel.
A diferença basica é que o arquivo api.php é onde você vai colocar as rotas de sua api, caso sua aplicação seja baseada em uma api rest.
Todas as rotas nesse arquivo vão ter por padrão o prefixo /api, então se vc definir uma rota /login dentro do arquivo, o prefixo será adicionado e a rota final será /api/login.
Se você for fazer uma aplicação web normal, seguindo o padrão MVC, por convenção você vai definir suas rotas no web.php.
Claro que você pode também usar os dois ao mesmo tempo, caso necessário :)
Aqui estão os release notes do Laravel 5.3.

Web e API no Laravel 5.6


Modeling outliers of normal distribution

Question: I am using a linear model to predict under-nutrition in children under 5.  The common metric discussed is stunting (a binary outcome) which is defined as being more than two standard deviations away from a standard age-for height (I'm predicting the z-score which underlies the stunting status).  Below are overlapping histograms of actual (blue) versus predicted (red) height for age scores.  What I am really interested in predicting is whether or not an individual falls below a z-score of -2, and my distribution is very restricted.  Any tips?  Right now, my model looks like this:
<code>Height.Age.Z ~ age + mothers.education + wealth + sanitation + (fixed effect on region)
</code>
Any tips, general and specific, are appreciated.  Thanks,
Comment: These histograms are inconsistent, because one (blue) represents approximately five times as much data as the other.  They also don't show much, because they cannot portray the *paired* comparisons of actual and predicted values: you need a scatterplot (or something similar) for this.
Answer: Stunting is defined by general norms, not by your data. You need to find the standard height for age with its standard deviation for each age. Then you can find which people are more than 2 sd below the mean for their age. Then you can run logistic regression using stunting (yes/no) as the DV.
Comment: Mike, *all* predictions, if they are any good, will exhibit less variation than actual data, because a prediction cannot hope to project random variation.  "Generating more dispersion" perhaps can be accomplished with a better model, but beyond a certain point requires making poorer predictions.
Comment: Right -- Stunting is supposed to be measured against a standard (I'm not actually interested in finding -2SD in my data), but the challenge is still generating more dispersion in my predictions.  Also, I am choosing not to use logistic regression on stunting because it is a less precise measurement of height for age Z-score (which therefore uses more information).
Comment: OK, another alternative is quantile regression. You can model any percentile that you like. If you wanted 2 SD below the mean, you would choose the 2.2 percentile, approximately.


Available Annyang voice recognition commands/ addCommands

Question: I'm working on a project in which i'd love to add talaters voice recognition Annyang. There are plenty of tutorials on how to use annyang and I've got it working on my website by following a tutorial (a pop up appears when I say hello to it).
My question however is, are there any sites that describe the functions that you can pass to Annyang?
I understand that you can initiate Annyang using basically any voice command, but I'm looking for a comprehensive list of things you can actually execute with it.
I've looked everywhere and found nothing in terms of a list, or does one define and write these actions himself? If so, how do you go about this?
I looked at this guys implementation of it, he calls google maps when you ask for a map of a certain location, but I can't seem to figure out how it is implemented.
Am I that oblivious to the obvious or am I missing something?
Answer: please go through the following link https://github.com/TalAter/annyang. and https://github.com/TalAter/annyang/tree/master/docs. you will get everything that you want to know about annyang and regarding the calling map may be he is doing something like below.
<code><script src="annyang.min.js"></script>

    if (annyang) {
      // Let's define a command.
      var commands = {
        'show me map of *location': function(location) {
             //code for display map of argument location;
         }
      };

      // Add our commands to annyang
      annyang.addCommands(commands);

      // Start listening.
      annyang.start();
    }
</code>