Dúvidas git & github

Question: Comecei a usar o git recentemente para versionamento e, como qualquer novato que se preze, ainda estou apanhado para algumas funcionalidades. Toda vez que commito um projeto e o levo para o repositório do GitHub, sempre o projeto anterior vai junto. E eu não sei por que, pois quando uso "git status", apenas os meus arquivos que quero levar para o repositório estão commitados.

O projeto "Clinicall" que é o intruso, é esquisito porque o timer diz que ele está há 1 mês ali. É um erro meu no GitHub ou eu estou commitando o projeto "Clinicall" sem saber?
Answer: Imagine o seguinte cenário:
Eu tenho um directório que chamo que Workspace e dentro deste directório tenho todos os meus projectos. Exemplos:

Workspace/projecto1
Workspace/projecto2
Workspace/projecto3

Caso eu queira mandar o projecto1 para Github, eu devo inicializar o git dentro deste projecto1 e não dentro do workspace.
Ou seja, se eu rodar o comando git init . dentro de Workspace todo projecto que estiver dentro de Workspace passará a fazer parte de um único repositório.
Para que eu envie os três projectos de forma separada, ou seja, como repositórios separados, preciso iniciar o git dentro de cada projecto. Ou seja, entro no projecto1 e inicializo o git:
$ cd Workspace/projecto1
$ git init .

E assim sucessivamente.

Dúvidas git & github


html 5 DATE doesn't work in Windows Exploror and Firefox

Question: i been working on ticker reservation system and i used date function in forms but , which works fine on chrome but does not work on windows explorer and Firefox. what should i do?
departure date: <input type="date" name="departuredate"> departure time : <input type="time" name="departuretime"> arrival date : <input type="date" name="arrivaldate"> arrival time : <input type="time" name="arrivaltime">

Comment: Show us your markup and explain _"doesn't work"_ in more detail, please.
Comment: What date function? `type="date"` is not supported in FF for sure.
Comment: departure date:
departure time :
arrival date :
arrival time :
Comment: if its HTML5, IE wont work. You need a 3rd party library for this
Comment: Which one is the best can you tell me the code ? actually i'm new to it so i dont really know much about it.
Answer: You should use a third party date picker plugin which works on almost all browsers like JQuery UI Datepicker:
See the demo below:
https://jqueryui.com/datepicker/

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Date: <input type="text" id="datepicker">

How to use
In the   tags of your page insert the following lines:
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Now create an input element which will be used as the datepicker like below:
<input type="text" id="datepicker">

Now before closing the body tag () copy the following lines:

Or if you want you can copy these lines in the head tags as well, but I would recommend you put them here.
Comment: do i need to have jquery installed on my computer?
Comment: ...or the OP could show us the markup and explain the issue before including a bunch of bloated (and perhaps unnecessary) frameworks?
Comment: @Rizwan No you do not need to install JQuery on you computer to run it on your web page. simply use the code provided on their site or even in the code example I gave you and you are good to go.
Comment: how to embed the code in my sign up page, because i need to have the value so i can pass to DB.
Answer: Neither Firefox (desktop) not Internet Explorer implement any date/time input control. You can see this in the Browser compatibility table found at <input> documentation on MDN.
It probably wasn't a priority for either teams given how powerful an ubiquitous JavaScript selectors have become.


Extracting the values of Field Collection

Question: I have created a foreach loop in my node template in Drupal 8 where values of the field collection are being printed as 1 and 2. Instead I want the content of the field collection which includes an image and two text fields to be printed here. How do I achieve that? Complete code would be helpful.
My code:
 {% for member in content.field_robot['#items'].getValue()  %}

      {{member.value}}

 {% endfor %}

I have no experience of playing in the .theme file but can follow basic instructions.
Answer: Do you want to access the values or the rendered output of those field collections?
For the second, you're supposed to configure the view display to display the fields of the collection. I don't know how it works exactly. Looking at the code, the field collection itself should have a view display UI, just like the node itself, where you can configure each field.
If you want to access the values, then you should do the following:

Do not use getValue(). It returns non-computed properties only and it returns them as a simple array. You want the field item object.
content is the rendered output, node is the node object with the values. So, you'd use for item node.field_robot. Looking at the code, it seems you'd need to use item.getFieldCollectionItem() and from there, access a certain field again, e.g. item.getFieldCollectionItem().yourfield.value.
But... from looking at the code a bit and that it has two major 8.x branches and not even an alpha release yet... it might be too early to use that project. Maybe you want to look at Inline Entity Form (8.x-2.x actually seems to depend on that) together with e.g. a node type or custom entity type or Paragraphs. We use the second quite actively and it's pretty well progressed for Drupal 8.
Comment: Thanks for your response. Much Appreciated. I am now just printing the {{content.field_robot}} on the node.twig and theming using a specific field collection template file. I will definitely look into the other two modules if am not able to theme the individual fields in the field collection here.
Comment: This worked for my co-worker.
Answer: I got this to work using Berdir's advice. For example, I have a field collection called field_sponsors and I want the value of the field field_sponsor_role output in a node.html.twig file. So I write {{ node.field_sponsors.0.getFieldCollectionItem().field_sponsor_role.value }}. Note the 0 for just extracting the first item in the field collection. You could choose to loop through all of the items instead.
If the field is actually an entity reference, then you have to go deeper. In my field collection mentioned above, the field field_company is an entity reference. The value would just be the entity ID. But I want the name. So instead, I write {{ node.field_sponsors.0.getFieldCollectionItem().field_company.entity.label }}
Hope this helps.
Answer: You probably can find a way to solve the problem in the UI; look at Berdir's suggestions. If you want to add you own markup in the templates, you can try another strategy. You can use the Twig templates that come later, when the build array in content is processed.
First, put the field or field collection at any position where you want in the node template.
{{ content.field_robot }}

You can exclude this field from the content adding without() to avoid double content.
{{ content|without('field_robot') }}

Then enable twig debugging, and look at the source in the browser, which Twig templates the field collection and the fields that are in this collection are calling and change these templates.
You would probably find that the Twig code you are trying to put into the node is already in other templates, that you can see in the Twig debugging text. So there is no need to hack the render array in content, which can change at any time, when you update Drupal or install modules, or change the configuration of the node display.
Comment: Yeah, I was trying to use foreach to loop the field collection values. I was trying to find a way to print the values in that way to easily theme the field collection. Doesn't work that way I guess. Yours was the way to go. I am now just printing it on the node.twig and theming using a specific field collection template file. Thanks for your response. Much Appreciated


Ideal copula family to evaluate a joint CDF of a process with non-linear dependency?

Question: Say a process exhibits ARCH/GARCH type non-linear dependence and we wish to evaluate its joint CDF. Without relying on a criterion, such as AIC what is the best copula family that fits this framework? I was thinking perhaps normal marginals and the Gumbel copula?
Answer: Selecting the best-fit copula family is an important step in the copula model. One way to select the best-fit copula is by using a scatter plot to identify the shape of the dependency structures. In addition, the misspecification of the margins may lead to inaccurate results.


How do I enable developer/debugging mode?

Question: I'm installing Drupal 8 core (using the standard profile). Whenever I get an exception/error, I get a blank page with "The website has encountered an error. Please try again later." (As shown in the image below.) This is shown as text and has no details or tracing about the error.

How do I enable developer/debugging mode?
Comment: To enable debugging follow the article: https://www.codeproject.com/Tips/5246457/Enable-Debugging-in-Twig-templates-Drupal-8
Answer: On a development site I would suggest uncommenting the following lines in the settings.php file.     emacs sites/default/settings.php
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

and then copying the file example.settings.local.php from /sites folder to /sites/default folder and rename it to settings.local.php
cp sites/example.settings.local.php sites/default/settings.local.php

In addition to adding the following setting
$config['system.logging']['error_level'] = 'verbose';

it also adds a few other settings which will help you in debugging and making development easier. If you don't want any of them in particular, you can always comment them out.
Note : If you think adding a file_exists call to each page will slow down the site, you can always remove it in the production code.
Comment: As mentioned below the Devel module can make things easier for Drupal 8. Verified that the $config['system.logging']['error_level'] = 'verbose'; settings appears to work.
Comment: If you don't have an example file, you can also just create a file containing `<?php $config[...;`
Comment: I have created a docker container that comes with the necessary settings for debugging and non-caching - hope it's useful: https://hub.docker.com/r/feikede/drupal-dev/
Answer: Add the following line in the settings.php file.
$config['system.logging']['error_level'] = 'verbose';

See Make developer tricks / tools for D8 more discoverable/obvious for more details.
Answer: An easy option, if you have access to Drupal Console, is to enable the development/debugging environment using drupal site:mode dev; when you are ready to change it back to production, use drupal site:mode prod.
Comment: Is there something similar for drush?
Comment: Nice trick with the Drupal Console
Comment: Didn't know you could do this! w00t!
Answer: Here is the variable with the different values :
$config['system.logging']['error_level'] = 'all'; // hide|some|all|verbose

These error levels are defined in the Drupal Core Bootstrap, here is the details for each one :
/**
 * Error reporting level: display no errors.
 */
const ERROR_REPORTING_HIDE = 'hide';

/**
 * Error reporting level: display errors and warnings.
 */
const ERROR_REPORTING_DISPLAY_SOME = 'some';

/**
 * Error reporting level: display all messages.
 */
const ERROR_REPORTING_DISPLAY_ALL = 'all';

/**
 * Error reporting level: display all messages, plus backtrace information.
 */
const ERROR_REPORTING_DISPLAY_VERBOSE = 'verbose';

Comment: Thanks for adding the possible values.
Comment: Yes, thanks for adding the possible values, which were surprisingly difficult to find.
Comment: Hello @zkent, i update my answer with details for each error level.
Comment: @arnoldbird The fact that you were surprised tells me that you hadn't been a Drupal developer for very long when you wrote that comment LOL :P But yes, incredibly difficult to find and thank you @FloDevelop!
Comment: @flo-develop any chance anyone can define the "some" option?  Or a link to documentation?
Answer: To get basic error messages in Drupal 8 you don't need to touch any code at all.  Just go to:

/admin/config/development/logging

and set "Error Messages to Display" to an appropriate level.
You can also view your recent errors through the admin interface:

/admin/reports/dblog

That said, other answers about settings files are relevant – you should only ever make errors visible on your development site, not production.
Overwritten $config objects/keys in settings.php won't be written to the sync directory when exporting, so providing your settings.php is in .gitignore, you can continue to safely use the configuration system to sync between clones of the same site.
Answer: If you only have access to Drush (no Drupal console) and you are working on a remote server, you can set the config to show all errors:

drush MYSITE.MYENV config-set system.logging error_level all -y

This is useful if you are getting a WSOD on a remote server and can't troubleshoot without more info.
Comment: For the situation described I also highly recommend `drush sqlc` followed by `SELECT * FROM watchdog ORDER BY wid DESC LIMIT 1` to show the last entry in the dblog.
Answer: Adding $config['system.logging']['error_level'] = 'verbose'; to the   sites/default/settings.php should log the error.
I will rather suggest the following steps.

Enable Twig debug and disable the cache for development purpose

Copy the sites/example.settings.local.php file to sites/default/settings.local.php

Un-comment the $settings['cache']['bins']['render'] = 'cache.backend.null'; line in the settings.local.php file

On the site/default/settings.php file, un-comment the following lines
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

Add the following lines to the sites/development.services.yml file
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto-reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

when all steps completed change directory to root dir and rebuild cache
```

Run drush cr

You should now see the debug output. Don't forget to undo the changes before deploying to production.
Answer: You can also install the the Devel and Devel kint modules. This will let you debug using kint(xyz).
Answer: Blank page with "The website has encountered an error. Please try again later." won't take you anywhere. To get more information out of your Drupal 8 site you can enable following configs.
$config['system.logging']['error_level'] = 'verbose';

For local Drupal 8 development, you should also enable error reporting, display errors and display startup error to help you further debugging and fixing major runtime error.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

You can find more information about TWIG debugging and enabling debugging with Drupal Console in the blog post below.
https://www.drupixels.com/blog/enable-debug-mode-and-error-reporting-local-development-drupal-8


Feature extraction from matrices with unequal size

Question: The goal is to do supervised learning, we have a set of inputs and target variables. But for each entry, the input is not a 1-dimensional vector. But rather there is a symmetrical 2-D matrix for each entry. Also size of the matrix for one entry is different from other ones. What are the ways to unify all info from matrices into a standard form for all entries and preserve all the information at the same time?
I know one way is to extract eigenvalues for each matrix. Is that going to preserve all information? Even then, number of eigenvalues are different for each matrix depending on the size.
Comment: No, eigenvalues are not enough (unless your matrices are diagonal). You'll have to carry around the corresponding eigenvectors as well. I'm not sure why you want the inputs to be of the same length, but perhaps you can unroll all your inputs and just pad the smaller ones with zeros?
Comment: If your matrices are all diagonal, they are effectively equivalent to vectors; you can just write each matrix as a vector of its diagonal elements.  That already gives you a huge reduction in size, and it does not require any difficult computations.  You then have a problem where your inputs are vectors of different lengths, and you want to present them as a consistent size.
Comment: I forgot to mention that matrices are diagonal. How else will it work if inputs are not the same length? I am using them as input variables for ML algorithms to predict target variable. Those ML algorithms need same size and consistent variables for each entry. If I fill the smaller ones with zero, where should the zeros go? I am assuming to the end. That implies that first EV of a large matrix and the first EV of small matrix are of the same nature (same variable). Is that truly preserving information? Something gets lost, how can we make up for it?
Comment: Sorry for the confusion, the matrices are actually symmetrical but not necessarily diagonal all the time. I agree with you if they were all diagonal.
Answer: In my experience, problems where the input data has different sizes are usually multiple instance learning (MIL) problems in disguise. (wikipedia has 2 different entries for MIL: https://en.wikipedia.org/wiki/Multiple-instance_learning and https://en.wikipedia.org/wiki/Multiple_instance_learning)
In my opinion, the best paper to learn about MIL is Amores, Jaume (2013), "Multiple instance classification: Review, taxonomy and comparative study", Artificial Intelligence, 201: 81–105,
In a nutshell, in MIL you have to generate a different representation of the data. Historically the first solution was to generate features by aggregating the data in the original representation - taking mean, standard deviation, maximum and minimum values, and so on. Thus the data may have different sizes but you end up representing the data using this fixed set of aggregation measures.
The second family of approaches are vocabulary based. In some way  you learn "frequent sub-patterns of the data" ( if your data is an image, the sub-patterns can be patches of the image, if the data is a time series, they can be segments) and you represent (in very general terms) the data as the histogram of such sub-patterns for each of the original data. Again, the data has different sizes but the set of sub-patterns is fixed, so the histograms (number or frequency of each sub pattern appears in the data) are of fixed size (sometimes this vocabulary approach is called "bag of visual word" when the data are images).
Please read Amores papers. I learned a lot from it.
My experience in MIL was mainly in images and for a long time I used bag of visual words. In a time series problem, to my surprise, the aggregation approach was the best solution. Now, everybody and me also, are using deep nets to solve MIL problems!!
Comment: Your last sentence left me in suspense. Any reference on using deep nets for MIL problems?
Answer: For machine learning and statistical prediction problems, it is unlikely that there will be any value in trying to coerce symmetric matrices of different sizes to a uniform size.  This will generally either involve extending small matrices to large ones (thus having many useless entries), or coercing larger matrices to smaller ones (which is messy and unlikely to illuminate your problem).
Technically it is possible to map real matrices of any (finite) size down to real numbers, and vice versa.  Any $n \times n$ real matrix (for finite $n$) is cardinally equivalent to a single real number, so you can map either way.  There are innumerable ways that you could coerce these to equivalent size, either by extending the smaller ones (e.g., zero-padding each matrix to the size of the largest matrix), or by doing a nasty conversion down to smaller size (e.g., collapsing multiple real numbers to a single real number using annoying strings of alternating digits from different numbers).
Without knowing the context of your problem, it is difficult to say what is best here, but it is very unlikely that any of these methods is going to be helpful.  Extending smaller matrices to bigger ones without any additional information is essentially just a waste of extra matrix entries, and coercing larger matrices down to smaller ones is messy and does not save information.
Perhaps a better idea is to take a step back from your problem and think about the formulation of the underlying probabilistic mechanism generating these observable matrices.  If your statistical problem involves observing symmetric matrices then your model ought to be written in a way that takes a vector of these matrices, allowing for different sizes.


Ant Javac Compilation Output

Question: I am trying to compile java files from a java program using org.apache.tools.ant.taskdefs.Javac and to print its output on screen.
See the below code snippet for your reference,
Javac javaCompile = (Javac) webServiceProject.createTask("javac");
javaCompile.setSrcdir("D:\\Java\\src");
javaCompile.setDestdir("D:\\Java\\classes");
try{
    javaCompile.execute();
}catch (BuildException buildException){
    FacesMessage message = new FacesMessage(buildException.getMessage());
    message.setSeverity(FacesMessage.SEVERITY_FATAL);
    FacesContext.getCurrentInstance().addMessage(null, message);
}

When i compile the files with the above code and if any compilation error exists, i get a message "Compile failed; see the compiler error output for details.".
I don't know how to retrieve the compilation error and show it as an output on screen.
Can anyone suggest how to retrieve it?
Comment: You are compiling Java classes from your JSF application? Don't do that :-) Seriously, if you do such a monstrous thing, you should decouple your layers. Using a compiler does not belong to the concerns a JSF app should know about.
Answer: Ignoring the issue of whether you should be compiling code in a JSF application ...
I believe that Ant sends compilation output to the logger.  So to get hold of it, you will need to configure the logger to send the relevant log events to a file ... or something.
Answer: Try changing the build.compiler setting. Ant was having trouble finding the compiler I had specified, "org.eclipse.jdt.core.JDTCompilerAdapter" - changing it to "modern" allowed me to compile.
This was tricky to track down. I'm not sure why there was no output.
Answer: The below code did the trick and this retrieved me the compiler error.
Javac javaCompile = (Javac) webServiceProject.createTask("javac");
javaCompile.createCompilerArg().setValue("-Xstdout");
String filePath = basePath + "resources" + File.separator
        + "errorlog.log";
javaCompile.createCompilerArg().setFile(new File(filePath));
javaCompile.setNowarn(true);

Ant Javac Compilation Output


Cocoa Touch: iPad table grid layout

Question: I'm trying to build a iPad version of a iPhone application. The application has a section with  photos all organized in a album/event. On the iPhone version the albums are listed in a standard UITableView, but for the iPad version I think it should be done differently.
Here is a sample from Apple's Photos App where the albums/events are shown in a grid:

How can I create a similar view in my storyboard? Is it done using a custom TableView?
Answer: There is a very good open-source project named "AQGridView" to do custom grids. It can help you. The project is here on github.
I hope it's what you are looking for.
Comment: Do you know other open-source projects than AQGridView?
Comment: I don't know other projects like that. :/ May be the Three20 launcher project can fit to your needs ? http://three20.info/showcase/launcher

Cocoa Touch: iPad table grid layout


Webform get email addresses from entity select unlimited

Question: I have an Entity select element that references a role. The element is unlimited so multiple users can be selected at one time. I need to get each selected user's email address.
Using a computed twig element, I can get the email address of the first selected user with webform_token():
{% set reviewer_email_address = webform_token('[webform_submission:values:reviewer:entity:mail]', webform_submission, [], options) %}
{{ reviewer_email_address }}

Something simple like:
{{ data.reviewer.0 }}
{{ data.reviewer.1 }}

prints the user id of the users. So the user entities are present.
How do I get the email address from {{ data.reviewer.0 }}?
Comment: You can use debugger and view data.reviewer variable. If you use twig tweak module you can use {{ drupal_breakpoint() }} for debug twig templates
Answer: This is a non DRY solution:
{% set reviewer_0 = webform_token('[webform_submission:values:reviewer:0:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_1 = webform_token('[webform_submission:values:reviewer:1:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_2 = webform_token('[webform_submission:values:reviewer:2:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_3 = webform_token('[webform_submission:values:reviewer:3:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_4 = webform_token('[webform_submission:values:reviewer:4:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_5 = webform_token('[webform_submission:values:reviewer:5:entity:mail:clear]', webform_submission, [], options) %}
{% if reviewer_0|length %}{{ reviewer_0 }}{% else %}{% endif %}
{% if reviewer_1|length %},{{ reviewer_1 }}{% else %}{% endif %}
{% if reviewer_2|length %},{{ reviewer_2 }}{% else %}{% endif %}
{% if reviewer_3|length %},{{ reviewer_3 }}{% else %}{% endif %}
{% if reviewer_4|length %},{{ reviewer_4 }}{% else %}{% endif %}
{% if reviewer_5|length %},{{ reviewer_5 }}{% else %}{% endif %}

with
"Remove whitespace around the"
computed value and between HTML tags
and
"Automatically update the computed value using Ajax".
Checked
in the computed twig element.
The twig needs to be improved in case there are more than 6 reviewers and for DRY principle.


Retornar objeto selecionado em datagridview

Question: Eu tenho a seguinte parametrização do meu datagridview:
    List<ModelAluno> alunos;
    ModelAluno aluno = new ModelAluno();

    public PesquisaAluno(List<ModelAluno> alunos)
    {
        InitializeComponent();
        this.alunos = alunos;

    }

    private void PesquisaAluno_Load(object sender, EventArgs e)
    {
        ConfiguraDataGrid();

        foreach (var aluno in alunos)
        {
            dg.Rows.Add(aluno.Nome, aluno.Cpf, aluno.Matricula.IdCurso);
        }
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void ConfiguraDataGrid()
    {
        dg.Columns.Add("dg_Nome", "Nome");
        dg.Columns.Add("dg_Cpf", "CPF");
        dg.Columns.Add("dg_Curso", "Curso");
        dg.ReadOnly = true;
        dg.AllowUserToAddRows = false;

        foreach (DataGridViewColumn column in dg.Columns)
        {
            if (column.DataPropertyName == "Nome")
                column.Width = 300; //tamanho fixo da primeira coluna

            column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

    }

No caso, eu estou recebendo uma lista de alunos de um outro formulário e apresento no meu datagridview apenas os campos que eu quero (nome, cpf e idcurso).
No método CellContentClick eu preciso retornar o aluno selecionado para o meu formulário anterior, mas não posso retornar apenas esses tres campos, eu preciso retornar o objeto montado (que é recuperado, inicialmente, em uma pesquisa no SQL Server e que já está armazenado na lista recebida no datagridview)
Como faço para retornar o objeto inteiro?
Além disso, como faço para que, ao pressionar enter, eu selecione o objeto que eu quero e apresente nas textbox do formulário anterior?
Comment: pq só não fazer: `dg.DataSource = alunos;` ?
Comment: O datasource vai preencher campos que eu não quero apresentar no datagridview, então eu optei pela seleção manual das colunas
Comment: defina `dg.AutoGenerateColuns = false;` adicione as colunas que quer manualmente (como já fez) e é só definir o `DataPropertyName` (como também já fez)
Comment: Certo, e como eu posso recupero o objeto montado pelo datasource? É meu primeiro projeto com datagridview e estou com certa dificuldade
Comment: poderia ser algo como `ModelAluno obj = alunos[dg.SelectedRows[0].Index];` mas também tem outras formas
Comment: Acho que não entendi muito bem... Usando o datasouce e o `dg.AutoGenerateColuns = false;`, o datagridview apresenta as colunas que parametrizei, mas sem dados dentro. Não consegui setar o valor dessas linhas com base no `DataPropertyName`. Como seria isso?
Comment: `DataPropertyName` tem que ser igual ao nome da propriedade (Nome, Cpf, Matricula.IdCurso) etc... depois é só colocar a List como source
Comment: column.DataPropertyName = "Nome";

column.DataPropertyName = "CPF";

column.DataPropertyName = "Curso";

Seria mais ou menos assim? Dentro do foreach?
Answer: Mudando um pouco se DataGridView:
List<ModelAluno> alunos;
ModelAluno aluno = new ModelAluno();

public PesquisaAluno(List<ModelAluno> _alunos)
{
    InitializeComponent();
    this.alunos = _alunos;
}

private void PesquisaAluno_Load(object sender, EventArgs e)
{
    ConfiguraDataGrid();
    dg.DataSource = this.alunos;
}

private void ConfiguraDataGrid()
{
    //Essa parte você pode fazer pelo design do visual studio

    dg.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "Nome", Name = "columnName", DataPropertyName = "Nome" });

    dg.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "CPF", Name = "columnCpf", DataPropertyName = "Cpf" });

    dg.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "Curso", Name = "columnCurso", DataPropertyName = "Matricula.IdCurso" });

    dg.ReadOnly = true;
    dg.AllowUserToAddRows = false;
    dg.AutoGenerateColumns = false;
}

Evento double click:
private void dg_CellMouseDoubleClick(object sender, CellMouseEventArgs e)
{
    aluno = alunos[e.RowIndex]; //o aluno que vocÊ clicou foi esse
}

Comment: no caso do enter, pegue a primeira linha que estiver selecionada: `dg.SelectedRows[0].Index` mas verifique se há linhas selecionadas antes: `if (dg.SelectedRows.Count > 0)`
Comment: Obrigado pela ajuda, amigo! Mais uma duvida: No caso, o objeto está sendo montado corretamente ao clicar na celula. Porém, eu conseguiria montar esse objeto pressionando ENTER também? Pelo que vi, o evento KeyDown não possui a propriedade RowIndex para eu setar.


Laravel CRON job not working in aws

Question: I have deployed laravel 5.4 app in AWS Ubuntu 16.04 apache2, i have created task scheduler for sending emails dailyAt('10:00').
When i run the artisan command php artisan email:reminder manually every thing works fine.
But when i run php artisan schedule:run i am getting No scheduled commands are ready to run.
I have also ran * * * * * php /var/www/html/app/artisan schedule:run >> /dev/null 2>&1 referring to documentation.
This is Kernal.php
class Kernel extends ConsoleKernel
{
    protected $commands = [
        \App\Console\Commands\EmailReminder::class,
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('email:reminder --force')->dailyAt('10:00');
    }

    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Comment: Your crontab has a spelling error: it's `schedule:run`, not `Schedule:run`
Comment: @Darshan Jain the typo is here while writing :)
Answer: Your schedule will only work if you call it at 10:00,
add this cronjob
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

Laravel will call this function everyminute, and once it is 10:00 it will call the function accordingly.
Check https://laravel.com/docs/5.5/scheduling#introduction , search for 'Starting The Scheduler'
Comment: Try with `->everyMinute();`
Comment: thank you for you response and time, for testing i have changed ti to `->everyFiveMinutes();` and ran the above command still not excecuting
Comment: Awesome, we are making progress. i'm getting `Running scheduled command: '/usr/bin/php7.1' 'artisan' email:reminder --force > '/dev/null' 2>&1
` after running `php artisan schedule:run` but not getting any email or SMS
Comment: if i run `php artisan email:reminder` i'm getting email and SMS. what could be the problem here
Comment: hmm, try to `Log` some of your config parameters in the function and check laravel.log, as for the asked question, what do you have in your crontab?
Comment: i ran `corntab -l` it says `no crontab for ubuntu`
Comment: run `crontab -e` and add the line i have in my answer, replace `/path-to-your-project` accordingly ofcourse
Comment: indeed i have replaced the path `* * * * * php /var/www/html/app/artisan schedule:run >> /dev/null 2>&1`, thanks for the command. i'm getting `no crontab for ubuntu - using an empty one`
Comment: if you run `whoami` in terminal what does it return?
Comment: it's returning `ubuntu`
Comment: wow! it worked. the problem was with `--force`. if run `php artisan schedule:run` everything works fine. Ideally it should trigger the `Task` `->everyMinute()` but i'm not getting any emails. you have any idea?
Comment: check your larave.log file under /storage/logs/laravel.log , it might contain usefull information on why it's not working
Answer: In AWS ECS we can use this without adding cron in to the container
https://github.com/spatie/laravel-cronless-schedule
php artisan schedule:run-cronless

Laravel CRON job not working in aws


game of fifteen in C. Segmentation fault

Question: My code returns a segmentation fault. I just started to code functions init and draw.
It's written in C and is from the cs50 thing.
This is my code:
/**
* fifteen.c
*
* Implements Game of Fifteen (generalized to d x d).
*
* Usage: fifteen d
*
* whereby the board's dimensions are to be d x d,
* where d must be in [DIM_MIN,DIM_MAX]
*
* Note that usleep is obsolete, but it offers more granularity than
*  sleep and is simpler to use than nanosleep; `man usleep` for more.
*/

#define _XOPEN_SOURCE 500

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// constants
#define DIM_MIN 3
#define DIM_MAX 9

// board
int board[DIM_MAX][DIM_MAX];

// dimensions
int d;

// prototypes
void clear(void);
void greet(void);
void init(void);
void draw(void);
bool move(int tile);
bool won(void);

int main(int argc, string argv[]) {
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: fifteen d\n");
        return 1;
    }

    // ensure valid dimensions
    d = atoi(argv[1]);
    if (d < DIM_MIN || d > DIM_MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);
        return 2;
    }

    // open log
    FILE *file = fopen("log.txt", "w");
    if (file == NULL)
    {
        return 3;
    }

    // greet user with instructions
    greet();

    // initialize the board
    init();

    // accept moves until game is won
    while (true)
    {
        // clear the screen
        clear();

        // draw the current state of the board
        draw();

        // log the current state of the board (for testing)
        for (int i = 0; i < d; i++)
        {
            for (int j = 0; j < d; j++)
            {
                fprintf(file, "%i", board[i][j]);
                if (j < d - 1)
                {
                    fprintf(file, "|");
                }
            }
            fprintf(file, "\n");
        }
        fflush(file);

        // check for win
        if (won())
        {
            printf("ftw!\n");
            break;
        }

        // prompt for move
        printf("Tile to move: ");
        int tile = get_int();

        // quit if user inputs 0 (for testing)
        if (tile == 0)
        {
            break;
        }

        // log move (for testing)
        fprintf(file, "%i\n", tile);
        fflush(file);

        // move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // sleep thread for animation's sake
        usleep(500000);
    }

    // close log
    fclose(file);

    // success
    return 0;
}

/**
* Clears screen using ANSI escape sequences.
*/
void clear(void) {
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);
}

/**
* Greets player.
*/
void greet(void) {
    clear();
    printf("WELCOME TO GAME OF FIFTEEN\n");
    usleep(2000000);
}

/**
* Initializes the game's board with tiles numbered 1 through d*d - 1
* (i.e., fills 2D array with values but does not actually print them).
*/
void init(void)
{
    int x = 0;
    int z = 0;
    int y = d * d;
    int w = 1;
    for (x = 0; x < d; x++)
    {
        for (z = 0; z < d;x++)
        {
            board[x][z] = y - w;
            w++;
        }
    }
    board[d-1][d-1] = y;

    if (y % 2 == 0)
    {
        board[d - 1][d - 2] = 2;
        board[d - 1][d - 3] = 1;
    }
}

/**
* Prints the board in its current state.
*/
void draw(void)
{
    int q = 0;
    int r = 0;

    for (q = 0; q < d; q++)
    {
        for (r = 0; r < d; r++)
        {
            printf("|%2i|", board[q][r]);
        }
    }

    if (board[q][r] == 0)
    {
        printf(" |__|");
    }
}

/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*/
bool move(int tile) {
    // TODO
    return false;
}

/**
* Returns true if game is won (i.e., board is in winning configuration),
* else false.
*/
bool won(void) {
    // TODO
    return false;
}

As you can see it is still not finished.
I am a little stuck here.
Maybe somebody knows how I could get around this.
Thanks in advance for the help.
Comment: SO is prompting for more info for a reason, and cheating it won't yield you any good. You haven't provided any problem description, just some incomplete long code you want us to debug.
Comment: `if (board[q][r] == 0)` in `draw` is out of bounds: `q==d` and `r==d` (for `d==DIM_MAX`).
Comment: Well I'm sorry. I mentioned that everything was good in the code until the init function so the mistake should be there. It's my first submission. I'll be better next time
Comment: Thank you so much I will have a look at that
Answer: Change for (z = 0; z < d; x++) to for (z = 0; z < d; z++) and you won't get the segfault in init(...) anymore.  You just need to use a debugger to find out these types of things.  If you're using gcc try gcc -g file.c then run gdb a.out and type run
Comment: Good catch! The silly errors...
Comment: that is a great and sharp eye you've got there. Thank you !
you've guys are great helping me in such a short time!


.removeClass() not removing class. Possible specificity error

Question: I'm trying to simultaneously add a class to a clicked link, while simultaneously removing that same class from the DOM. The part of the code that adds the class works, but it just makes the class appear again and again. I'm also curious about the efficacy of a javascript solution vs. a server-side solution.
$(document).ready(function() {
    $(function() {
    $('#header a span').click(function(e) {
    var title = this.innerText;
    //possible browser compatability from .text?
        $('selected').removeClass('selected');
        $(this).addClass('selected');
        // Also prevent the link from being followed:
    });
    });

         home
         code
         design
         illustration
         writing
         links
         about

Comment: `$('selected')` are you missing dot here?
Comment: `this.innerText` -> `$(this).text()`
Comment: Also no need to nest `$(document).ready()` and `$(function() {})`.
Answer: $('selected').removeClass('selected');

should be
$('.selected').removeClass('selected');

Answer: Change your JS to:
$(document).ready(function() {
    $('#header a span').click(function(e) {
       var title = $(this).text();
       //possible browser compatability from .text?
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
        // Also prevent the link from being followed:
        return false;
    });
});

By the way, do you want your class selected on the span elements, or a elements, your JS indicates span but your html indicates a.
Comment: While you're at it, change a few other things that are mentioned in the question comments...
Answer: Your class needs (.) Before it I think.
Comment: It's not worth answering questions if you just "think" that you know the answer.


avoid meteor load scripts on

Question: Its there a way to run scripts after some template load?
Im totally noob on meteor, so i want to load my scripts.js after my template.html get loads, without meteor i put thats scripts on the body and works, but now im using meteor its seems like meteor load all scripts at same time on the  and the problem its like i need to load first the template and later the script
so my question its there a way to put a script on somewhere and call him when the template finish load?
Answer: I might be off here, but I think you'll want to think of this a bit differently. The whole idea behind Meteor is to not care about forcing the load order of scripts. If you need to fire some event after your page is loaded, put it in a Template.rendered callback. Try reading this https://docs.meteor.com/#/full/template_rendered to get a better idea. This way the template is ready and you can do whatever you want.
Comment: Yep i did that yesterday and worked, sorry for not uopdate the answer
Answer: First, put classie.js and sidbarEffects.js into the public directory so Meteor doesn't bundle them.
Then add the following inside any body tag:

You can leave modernizer.custom.js on the root of the client directory.
I put normalize.css inside client lib and the remaining css in client/css.
This solution works for me, good luck. Solution inspired by the YouTube API implementation I did a few days ago.
Answer: EDIT: I just re-read your question, and noticed you want to load your .js after your html loads. Is there any particular reason this is the case? Normally this is the exact opposite of what you want.
Granted I am understanding you correctly, in your folder structure, you should have a client folder. In that client folder, create a lib folder. Anything in that folder will load before anything else.
Here is something from a solid unofficial FAQ about Meteor that will be a really good help while learning some of the basics of Meteor. It is supported by a very active member of the Meteor community.
Comment: hello sean, yea sorry about the question its just very bad formulated, but look the point its this, im trying to use this http://tympanus.net/Development/FullscreenLayoutPageTransitions/ layout on my meteor app, but its just don't working on meteor, on a simple page without it work just like calling the 2 js on the  and works, but here on meteor its just don't working so after looking something it seem like i need to first load the html layout and after the .js so i guess it will work
Comment: o and yea i have that structure on my app
Comment: Well, if you have the proper structure where you are putting the `.js` files in the proper lib folder it should work just fine. I can think of any time where you would want to load `.js` after the page has loaded. There just must be a minor error in how your setting up your folders.

avoid meteor load scripts on


What are the difference between: sequence id using JPA @TableGenerator, @GeneratedValue vs database Auto_Increment

Question: Q1.: What is the difference between applying sequence Id in a database using
A.
CREATE TABLE Person
(
   id long NOT NULL AUTO_INCREMENT
   ...
   PRIMARY KEY (id)
)

versus
B.
@Entity
public class Person {
    @Id
    @TableGenerator(name="TABLE_GEN", table="SEQUENCE_TABLE", pkColumnName="SEQ_NAME",
        valueColumnName="SEQ_COUNT", pkColumnValue="PERSON_SEQ")
    @GeneratedValue(strategy=GenerationType.TABLE, generator="TABLE_GEN")
    private long id;
    ...
}

My system is highly concurrent. Since my DB is a Microsoft SQL server, I do not think it supports @SequenceGenerator, so I have to stay with @TableGenerator which is prone to concurrency issues.
Q2. This link here (http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Advanced_Sequencing) suggests that B might suffer from concurrency issues, but I do not understand the proposed solution. I would greatly appreciate it if someone could explain to me how to avoid concurrency issues with B. Here is a snippet of their solution:
If a large sequence pre-allocation size is used this becomes less of an issue, because the sequence table is rarely accessed.
Q2.1: How much allocation size are we talking about here? Should I do allocationSize=10 or allocationSize=100?
Some JPA providers use a separate (non-JTA) connection to allocate the sequence ids in, avoiding or limiting this issue. In this case, if you use a JTA data-source connection, it is important to also include a non-JTA data-source connection in your persistence.xml.
Q2.2: I use EclipseLink as my provider; do I have to do what it suggests above?
Q3. If B suffers from concurrency issues, does A suffer the same?
Answer: Using a TableGenerator the next id value will be looked up and maintained in a table and basically maintained by JPA and not your database. This may lead to concurrency issue when you have multiple threads accessing your database and trying to figure out what the next value for the id field may be.
The auto_increment type will make your database take care about the next id of your table, ie. it will be determined automatically by the database server when running the insert - which surely is concurrency safe.
Update:
Is there something that keeps you away from using GenerationType.AUTO?
GenerationType.AUTO does select an appropriate way to retrieve the id for your entity. So in best case in uses the built-in functionality. However, you need to check the generated SQLs and see what exactly happens there - as MSSQL does not offer sequences I assume it would use GenerationType.IDENTITY.
As said the auto_increment column takes care about assigning the next id value, ie. there is no concurrency issue there - even with multiple threads tackling the database in parallel. The challenge is to transfer this feature to be used by JPA.
Comment: When you said: `The challenge is to transfer this feature to be used by JPA.`, do you refer to the use of `@GeneratedValue`? So I try to set the column in the table `AUTO_INCREMENT`, I then try to create multiples `Person`. The first person create correctly with the `id` start out to be 5, but it generate an exception for person 2. `Null or zero primary key encountered in unit of work clone`. Can we not just annotated the id with `@Id`, without `@GeneratedValue`, then persist the entity object, and let the database with `AUTO_INCREMENT` PK take care of it?
Comment: Can you show your mapping? You should use `@GeneratedValue` to tell the JPA implementation that the ID is taken care of. Here's one link to help you get going: http://www.developerscrappad.com/408/java/java-ee/ejb3-jpa-3-ways-of-generating-primary-key-through-generatedvalue/
Answer: A: uses IDENTITY id generation, @GeneratedValue(IDENTITY)
B: uses TABLE id generation
JPA supports three types, IDENTITY, SEQUENCE and TABLE.
There are trade-offs with both.
IDENTITY does not allow preallocation, so requires an extra SELECT after every INSERT, prevents batch writing, and requires a flush to access the id which may lead to poor concurrency.
TABLE allows preallocation, but can have concurrency issues with locks on the sequence table.
Technically SEQUENCE id generation is the best, but not all databases support it.
With TABLE sequencing if you use a preallocaiton size of 100, then only every 100 inserts will lock the row in the sequence table, so as long as you don't commonly have 100 inserts at the same time, you will not suffer any loss in concurrency.  If you application does a lot of inserts, maybe use 1000 or larger value.
EclipseLink will use a separate transaction for TABLE sequencing, so any concurrency issue with locks to the sequence table will be reduced.  If you are using JTA, then you need to specify a non-jta-datasource to do this and configure a sequence-connection-pool in your persistence.xml properties.
Comment: Your information about `TABLE sequencing a preallocaiton size` help me lot as I decide to use `TABLE` sequence for my implementation. You should have this bounty, I will wait out a bit more to see if anyone have any other idea to contribute, if not, I will grant you the bounty. thank you very much


How to resolve the error when adding an entity reference relationship?

Question: Multifield Contributed Module - https://www.drupal.org/project/multifield
Company Content Type has multifield
1) Company Division - Entity reference
2) Company Categroy - list
While adding relationship as entity reference node company division in views an error is thrown.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_fieldname_node.id' in 'on clause'
Answer: It looks like your issue is because of the Multifield issue Add Views API integration for the multifield field type. And that the patch attached to comment nr 96 of this issue solves it.


what is use of referring object to an interface?

Question: i have searched a lot but did not get exact answer for this Question hope i will get it from here.
what is exactly the use of referring object of a class to an interface instead of referring to the same class ??
void foo(list l){}

public static void main(String a[]){
List l = new ArrayList(); // why use this?
ArrayList a = new ArrayList(); //instead of this?
foo(l);
foo(a);

}

Comment: This is answered all over the internet *and* Stack Overflow. Google for "code to interface not implementation" or any of several other similar queries.
Comment: Your question is pretty unclear, but I suspect you want http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface
Comment: Look here: http://stackoverflow.com/q/383947/2030471
Answer: Maybe because an interface is something like a contract, which can be fullfilled by an implementation. You shouldn't depend on an implementation, because its about to change constantly, instead an interface/contract should not. Referring to an interface makes your implementation more robust.
Comment: And just this moment I am exporting an OSGI service, the interface rather than the implementation...
Answer: Sometimes, the actual class of an instance does not matter, but only the interface it implements.
Also sometimes, it is impossible to know the actual class of an instance in compile time, but we only know the interface this class will implement.
For example, you have an interface called GeometricFigure
public static interface GeometricFigure {
    public Double getGirth();
    public String getName();
}

And you use this interface in a real class, for example, Canvas. Canvas has a list of GeometricFigures.
public class Canvas {
    private List<GeometricFigure> figures;

    public void printAllFigures() {
         for (GeometricFigure figure : figures) {
              System.out.println(figure.getName() + " " + figure.getGirth());
         }
    }
}

Now, your Canvas is independent of actual implementations of GeometricFigure. Canvas does not care how you is GeometricFigure is implemented, is it a square, circle or whatever. It only that this class can return a name and a girth so it can print them. So, the actual implementations can be Square, Circle, Triangle, etc. Only important thing is that these future classes implement the GemometricFigure interface.
For example:
public class Square implements GeometricFigure {

    private String name;
    private Double sideLength;

    public Square(String name, Double sideLength) {
        this.name = name;
        this.sideLength = sideLength;
    }

    @Override
    public Double getGirth() {
        return 4 * sideLength;
    }

    @Override
    public String getName() {
        return name;
    }
}


HTTParty adds params from :options hash multiple times to URL

Question: HTTParty.get is adding parameters multiple times to the URI it sends.  Has anyone else come across this before?
def initialize(address)
   self.address = address
   self.base_uri = 'https://api.randomapi.com/street-address'
end

def get
  response = HTTParty.get(base_uri, :query => {
    :street => address.street.strip,
  })
end

If this I format a request this way:
HTTParty.get(base_uri, :query => {:street=>"random street"})

This is the URI is sends.  Note how many times the street param is added.
#<URI::HTTPS:0x007fbc78582d70 URL:https://api.randomapi.com/street-address?street=random%20street&street=random%20street&street=random%20street&street=random%20street>

Answer: Turns out it was a bug in the gem(https://github.com/jnunemaker/httparty/issues/185 ,  https://github.com/jnunemaker/httparty/pull/189).  I upgraded to 0.11 and it fixed the duplicate parameters problem.


Script to refresh SDProp immediately?

Question: I'm reading this document, how can I refresh sdprop immediately on a Windows 2016 domain controller?
I'm trying to do this in command line, but referenced link in the document above is quite vague, I couldn't get it.
Does anyone know?
Comment: https://github.com/edemilliere/ADSI/blob/master/Invoke-ADSDPropagation.ps1
Comment: @GregAskew Thanks! I confirm Invoke-ADSDPropagation works for me, you may add an answer and I'll accept it.
Answer: This could be made somewhat generic due to there are other commands that may be run. For example, removeLingeringObject is commonly used.
Source: https://github.com/edemilliere/ADSI/blob/master/Invoke-ADSDPropagation.ps1
<code>Function Invoke-ADSDPropagation{
<#
.SYNOPSIS
    Invoke a SDProp task on the PDCe.
.DESCRIPTION
    Make an LDAP call to trigger SDProp.
.EXAMPLE
    Invoke-ADSDPropagation
    By default, RunProtectAdminGroupsTask is used.
.EXAMPLE
    Invoke-ADSDPropagation -TaskName FixUpInheritance
    Use the legacy FixUpInheritance task name for Windows Server 2003 and earlier.
.PARAMETER TaskName
    Name of the task to use.
        - FixUpInheritance for legacy OS
        - RunProtectAdminGroupsTask for recent OS
.INPUTS
.OUTPUTS
.NOTES
    You can track progress with:
    Get-Counter -Counter '\directoryservices(ntds)\ds security descriptor propagator runtime queue' | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue
.LINK
    http://ItForDummies.net
#>
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$false,
        HelpMessage='Name of the domain where to force SDProp to run',
        Position=0)]
    [ValidateScript({Test-Connection -ComputerName $_ -Count 2 -Quiet})]
    [String]$DomainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name,

    [ValidateSet('RunProtectAdminGroupsTask','FixUpInheritance')]
    [String]$TaskName = 'RunProtectAdminGroupsTask'
)

try{
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('domain',$DomainName)
    $DomainObject = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)

    Write-Verbose -Message "Detected PDCe is $($DomainObject.PdcRoleOwner.Name)."
    $RootDSE = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($DomainObject.PdcRoleOwner.Name)/RootDSE")
    $RootDSE.UsePropertyCache = $false
    $RootDSE.Put($TaskName, "1") # RunProtectAdminGroupsTask & fixupinheritance
    $RootDSE.SetInfo()
}
catch{
    throw "Can't invoke SDProp on $($DomainObject.PdcRoleOwner.Name) !"
}
</code>
}

Script to refresh SDProp immediately?


Understanding the Objective-C++ __block modifier

Question: I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.
I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).
Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.
To try and understand this, I made a quick scratch application, and found the same thing happens there:
class Foo
{
public:
    Foo() : value(1) { printf("constructor"); }
    void addOne() { ++value; printf("value is %d", value); }
private:
    int value;
};

void Bar()
{
    Foo foo1; // prints "constructor"
    __block Foo foo2; // doesn't print anything

    foo1.addOne(); //prints "2"
    foo2.addOne(); //prints "1"
}

Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?
Answer: As I understand it, your example there isn't using a block as such, but is declaring foo2 as to be used by a block.
This does funny things to the handling of foo2, which you can read more about here.
Hope that helps.
Comment: I tried to cut the example down to the bare minimum to try and work out what was happening - the real thing is being used within a block. I've already seen that article, but that doesn't really explain it. I can see that the variable then lives in a special place and is handled in strange ways, but surely it still needs to be constructed?
Answer: Stumbled upon this old question. This was a bug that's long been fixed. Now __block C++ objects are properly constructed. If referenced in a block and the block is copied, the heap copy is move-constructed from the original, or copy-constructed if it cannot be move-constructed.


Windows Task Scheduler job not starting but runs on manual start

Question: Windows Server Version : 2016
Problem Description :
This is indeed a weird problem I am facing. I have a .bat file that I have scheduled to run every 15 min but it does not start on its own at the scheduled time if I disable and re-enable it. But the moment I update the job (any parameter) it just works fine. But if I disable it and re-enable it again it won't kick start.
There is no problem with the .bat file as it just runs fine when I manually start the job from task scheduler or from the command line.
I have tried following things:

Give full permissions to .bat file connected folders
'Run with highest priority' selected
Change user to system & administrator
'Run whether user is logged on' selected. I cannot have the other option
'Configure for' = 'Windows Vista, Windows Server 2008' & 'Windows Server 2016'
Tried 'Start in' option
Power settings in Conditions tab (all combination) Selected 'Run task' as soon as possible after a scheduled start is missed'
Also restarting windows after creating the job (as suggested in some forums)

I am pretty confident that the job setup is fine as I have been using this job for past many years and recently migrated to a new server. This disabling of job is doing something which I am unable to figure out. I am sure some of you have encountered this problem and I am not alone. Any help or clues appreciated. Thanks in advance.
Comment: How did you migrate the scheduled task?
Comment: You need to set the start date to future. If you do that your job will run as per the set schedule. Also, note that some times when you change the job settings it will stop running automatically. If that happens you again need to set the start date to future. It is bug in windows servers. Hope this is helpful
Comment: I created a fresh task.
Comment: same for windows server 2019
Comment: @Drake - This was the issue! Not sure why this is still not fixed. Faced this with even Windows Datacenter 2019!
Answer: This highlights the difference in behavior between a "Daily" task and a "One time" task. This is a bit counterintuitive, but if you want to be able to disable a task, then have it start firing automatically again right after you re-enable it, you need to make it a "One time" task rather than "Daily."
Here is how they look in the task list (deliberately named to highlight the schedule differences):

When a Daily task is disabled and re-enabled, it will resume at its Start time (so, later that day or the next day):

If a One time task is disabled and re-enabled, it will resume as soon as one more repeat interval elapses, relative to its Start time.


Private files aren't blocking direct access to image files

Question: I'm currently very confused by how private files work:

I have a content type that has an image field and a file field.  Both
are set up to use private file access for their contents.
Node access on the content type is working correctly.
A user who does not have access to the node cannot get to the contents of the file field -- they get an access_denied page when they try to load the URL of the file.
However, they DO have access to the image file, via the image's url (/system/files/...): hitting the image URL in a browser brings it right up.

Are there any insights out there about why the image file is leaking through, and what I can do to stop it?   I've explored hook_file_download and hook_file_download_access, and have been putting watchdog statements throughout the image and files modules trying to track this down, but to no avail.  Thanks!
Answer: There are three implementations of hook_file_download(), in Drupal:

file_file_download()
image_file_download()
user_file_download()

The first two implementations always check the user has access to the entity to which the file is associated; the third one doesn't check that, but it only checks the directory containing the file is the one used for the user profile's pictures.
function user_file_download($uri) {
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($uri);
    return array('Content-Type' => $info['mime_type']);
  }
}

If there isn't any other module implementing hook_file_download(), I would expect the users to be able to access the files through http://example.com/system/files when the URI points to the same directory containing the images used for the user accounts.
Comment: Yeah -- I had run into those functions while trying to figure out what was going on. What I found was that image_file_download was allowing access, down in the "Private file access for the original files" area. Also, btw, the files in question are not being saved in the user_picture_path directory.  Anyway, I put together a hook_file_download() handler that, by borrowing some code from image_file_download, checks the assigned node and does the right thing re access.  I'm still not sure why it's not just happening has part of the basic system; maybe I'm messing something up elsewhere.  Thx!


Find minimal number of elements in matrix.

Question: Consider a $A \in Mat_{n}(\{+1,-1\})$ (square matrix consisted of +1,-1).
Now we can make and operation majority , i.e. $a_{i,j} = $ median of his neighborhoods(closest elements around him, i.e. closest 3,5, or 8 elements).
If number of elements are equal , then majority return -1 , i.e.:
$\begin{pmatrix}
  -1& -1 &1\\
  -1& 1 &1\\
  -1& 1& 1\\
\end{pmatrix} \to \begin{pmatrix}
  -1& 1 &1\\
  -1& -1 &1\\
  1& 1& 1\\
\end{pmatrix}$ medium element go to $-1$, because of there are equal number of +1/-1.
After this we will have another matrix. Obviously there could be three situations (depends of initial positions of +1/-1): after some number of majority operations there will be 1 matrix,-1 matrix or matrix will cycled.
So my question: does there some estimates on number of $1$($-1$) to get 1 matrix (-1 matrix).
I've thought that it should be $O(n^{2})$ (actually I thought that $n(n-1)$ is enough for $n>3$).
For easier understanding I've left an example:
$\begin{pmatrix}
  -1& -1\\
  1& -1
\end{pmatrix} \to \begin{pmatrix}
  -1& -1\\
  -1& -1
\end{pmatrix} $
Added example for $n=3$
$\begin{pmatrix}
  1& 1& 1\\
  -1& -1& 1\\
  1 & 1 &-1
\end{pmatrix} \to \begin{pmatrix}
  -1& 1& 1\\
  1& 1& 1\\
  -1 & -1 &1
\end{pmatrix} \to \begin{pmatrix}
  1& 1& 1\\
  1& 1& 1\\
  1 & 1 &1
\end{pmatrix}$
EDIT 1 :
I've tried to consider such sequence in OEIS.
First of all I've found that for $n =2$ we have $f(2) = 3$, $n = 3$ we have $f(3) = $7 , if $n = 4$ we have $f(4) = 11$ and probably for $n = 5$ $f(5) = 17$.
I've considered some sequences but for some large $n$ this sequences became near the $n/2$. Which contradict with my logic.
Comment: @RossMillikan Thank you sir. One more doubt. The (2,3) position of second 3×3 marix is right?
Comment: No, I don't think so.  Nor is the (3,1) in the third $3 \times 3$. Fixing the $(2,3)$ in the second will flip $(1,3), (2,2)$ and $(3,3)$ in the third.  OP, please check these.  I suspect this goes to $-1$
Comment: What is the meaning of your 3rd paragraph? How do you transform the matrices?It is confusing me..
Comment: @AvinashN:  each cell simultaneously looks at its (up to) four neighbors and is set equal to the majority, so one that has three $1$ neighbors and one $-1$ is set to $1$.  Ties are resolved by going to $-1$.  It is similar to Conway's game of Life, with a four cell neighborhood and perturbations for the edges/corners.
Comment: @AvinashN added example.
Comment: @openspace I got it. Thanks much.
Comment: @RossMillikan am I right that $(2,3)$  is second row and third column? If yes , then there are 3 - "+1" and 2 "-1", so the element will be "+1"
Comment: @openspace:  Yes, $(2,3)$ is second row, third column.  You set the rules, but I read closest to just mean the four nearest neighbors for a cell in the center and for this cell I would just see three:  the one above, to the left, and below.  Two of them are $-1$.  It sounds like you mean the eight cell neighborhood for the center cells, including the diagonals.  Please clarify.
Comment: @RossMillikan my bad. Thanks for note!
Comment: This would usually be stated in the language of cellular automata.  Your $+1$s are filled squares and $-1$s are empty.  Each operation is a generation.  There is a large literature.
Answer: With the clarified neighborhood definition:
Here is a probabilistic approach.  Assume we start with a matrix that has each entry $1$ with probability $p$ and $-1$ with probability $1-p$.  We assume the matrix is large so we don't care about the boundary.  After one operation a cell becomes $1$ with probability $p^8+8p^7(1-p)+28p^6(1-p)^2+56p^5(1-p)^3$.  If we want to go towards a $1$ matrix we need this to be greater than $p$.  According to Alpha, this is true when $p \gt 0.604487$ so we need a bit more than $\frac 35$ of the cells to start out as $1$.
On the other hand, a matrix that has two neighboring rows and two neighboring columns filled with $-1$s at the start will go to $-1$, so you can have as many as $(n-2)^2\ 1$'s and still go to $-1$.  I think a checkerboard matrix with a $3 \times 3$ block set to $1$ will eventually go to $1$, so you can have only half $1$s and get to a $1$ matrix.
Comment: Why probability should be so ?
Comment: I was assuming each cell in the middle had four neighbors.  The chance they are all $1$ is $p^4$ and the chance three of them are $1$ is $4p^3(1-p)$
Comment: I guess the idea about $(n-2)^2 matrix is false
Comment: It is correct.  Each cell that starts -1 has enough neighbors that it will never switch.  The $(3,3)$ cell starts $1$ but has five $-1$ neighbors so it will switch.  The $-1$s will propagate through the whole matrix
Comment: May I ask you : we compare probability with some value $p$ it's looks like true , but how can we explain it
Comment: I mean : why it should be more than $p$
Comment: For the random matrix, we want the number of $1$s to increase.  The chance at the first generation is $p$, while the chance at the second is the eighth degree polynomial I gave.  This assumes the $1$s are distributed randomly.  At the first generation we may be given this is true, but it is not really fair to assume the second generation is random as well.  There will be correlations in the locations of the $1$s.  I suspect there will be more clumping in the second generation, which is probably good for the $1$s, but a random second generation is the easy thing to check.
Comment: What will be if we consider $P(P \dots P(p)))$ , where $P(x)$ is given polynomial , maybe it will give the better approximation?
Comment: The root I cite is an unstable equilibrium.  If you start above it, iterating will converge to $1$ and if you start below it will converge to $0$.  The problem is that you can't say that $P(P(p))$ is the expected fraction of $1$s in the second generation because of the correlations of the $1$s in the first generation.


How to transcribe an arpeggiated 4-note chord to be playable on a violin?

Question: I finished arranging the first movement of Beethoven's Piano Sonata in F minor for a string quartet, only to find out that the chord at bar 7 is impossible for a violinist. My instinctual reaction was:

No, it isn't impossible, listen, it is arpeggiated. Arpeggios are easy. And your typical triple or quadruple stop is an example of arpeggiation out of necessity, not out of beauty.

The person who told me that the chord was impossible, also happened to be a violinist herself. And here was her response to my reaction:

When it is written down as an ordinary chord, we try as much as possible to make it sound simultaneous. I would suggest that you stick to the C grace note as you have in the previous 2 bars. It will still be difficult since it is a leap of an octave then, but it won't be an impossible task.

Here is Beethoven's original:

And I will only be showing the arrangement of a few bars for the sake of space here, but that should be enough for context. Here is my arrangement as it is now, just taking Beethoven's notes and spreading them across the quartet:

You can see the arpeggio symbol that I made invisible in Musescore in the image at that chord.
The violinist that commented on the chord saying that it is impossible is suggesting that I do this instead:

Now, there is another option, but one probably not familiar for most violinists, leaving the arpeggio symbol visible. Most arpeggios on the violin are written out explicitly, with a note value for every note of the arpeggio, not like an arpeggiated chord(which is what Beethoven wrote).
If I go with the grace note option, that leaves me wondering what to do with the other notes of the chord.
Should I go with the grace note option that the violinist is suggesting to me? And is the quadruple stop as I have it right now really an impossibility for the violinist or is it just difficult? I mean surely a close position triad including a note an octave above the bass note is possible as a quadruple stop for more than just the lowest G major chord in the violin's range, even if it has to be arpeggiated.
Comment: The bolded bit at the end is simply not true.  There is an octave and a 6th between the lowest open string and the highest open strength.  Because the pinky is the shortest finger, it's the most comfortable to put on the E string in a quadruple stop.  Therefore, the most comfortable quadruple stops to play on the violin have *two* octaves between their lowest and highest notes.  Closed quad stops are very hard or impossible - open ones are much easier.
Comment: For an arpeggiated chord, us bowed string players really like it if it can be played as a "separated  triple or quadruple stop" .  Perhaps ask your violinist if the chord can be adjusted so the notes can be played on at least two and preferably 3 strings. e.g. first two notes on the D string, then easy(!!) cross to A string without a left-hand position change for the latter two notes.
Answer: The octave your violinist suggested is fine. Another possibility is the following:

Why did Beethoven not write the above chord in his piano sonata? Because that major tenth is rather awkwardly wide for a pianist's hand. The chord he did write spans only an octave and so fits the pianist's hand. People writing for the piano prefer what is easier  (and prefer not to write what is needlessly hard) for a pianist to play.
Likewise, seeing as you are writing for a violinist, it's as well for you not to write what is needlessly hard for a violinist. Chords that span an octave, and are played with piano keys that fit under the fingers well, are idiomatic for the piano. What's idiomatic for a violin is chords made up of fifths and sixths. Fifths because the instrument is tuned in fifths. In chords of more than two notes, sixths are easier than small intervals because a small interval entails placing a finger on a lower string but avoiding it touching higher strings, and this might be tricky.
Comment: This is both an excellent suggested solution, and a good general point: You don't need to always follow the original spacing/voicing of chords and parts so closely.  Beethoven's choices in the piece were partly shaped by writing for the piano, and he would have made different choices in many places if he'd been writing/arranging it for a string quartet.
Comment: @PLL I would make that point slightly more strongly: you usually *shouldn't* follow the original voicing so closely when transcribing a keyboard piece for an instrumental and/or vocal ensemble.
Comment: This would be played in 3rd position, fingering 2-3-3. (Ring finger on the 5th.)
Comment: Great answer. How exactly do you play that chord on violin – ring finger for the a♭ and pinky-barrée f and c, I'd guess?
Comment: @leftaroundabout Violinists often move their left hand up and down the finger-board as needed. So it doesn't have to be those fingers. It might be index and middle fingers, with the hand in a higher position.
Answer: Don't be so literal minded. This is easy to play, and effective:

If the quartet know the original piano version, they can easily simulate the arpeggio simply by violin 2 playing a bit ahead of the beat.
Trying to get Violin 1 to play all four notes as written will probably be sound clumsy at this tempo, and it won't be as "ff" as something easier to play because of the technical problem of coordinating the fingering and bowing across the two or more strings.
Comment: This is the right idea. Beethoven's **intent** was power and drama, not that it  **must** be a rolled chord per se. I would go even further and use the C grace note as suggested elsewhere **plus** appropriate double stops on the downbeat in **all** lower parts. "Ka-POW".
Answer: Disclaimer: I'm not a violinist. What follows is all head-knowledge, not practical experience.
As you know, since a violin bridge is curved, no more than two strings can sound at a time, so any chord will of course need to be arpeggiated. This isn't that big a deal, and is part of the characteristic sound of violin stops.
However, you also need to consider where the fingers will be stopping the strings. As I'm sure you know, violin strings are tuned in fifths. In order to play a chord, each note must be located on one of those four strings. Your chord has a high C, E♭, G, and a top C, which would need to be played o the G, D, A, and E strings respectively. The C on the G string is up an octave and a fourth (up 17 semitones), which is well past the half way point along the string. Now I'm not sure how high a violinist can go up the neck, especially on the G string, so I don't know if that's actually possible. But let's assume it is, and look at the rest of the chord. The F is going to be played on the D string, a minor third more than an octave (so 15 semitones up), the A♭ is going to be played on the A string (13 semitones up), and the top C will be on the E string (8 semitones up). You can think of these counts of "semitones up" as if they were imaginary frets on a guitar, so your essentially asking for a chord that requires fingering on the 8th, 13th, 15th, and 17th imaginary "frets" -- covering a span of 9 "frets". I believe in normal violin playing, the fingers are all within about 5 or 6 "frets" of each other. Nine is probably more than what can be stretched.
This is why violins are not good with close-voiced chords. If you want to retain a chord, one possibility might be to use a more open voicing. Obviously, you need to retain the top C, as that's the melody note. Skip the A♭ below that, and go down the F. That's a fifth below the C so it will use the same 8th "fret" as the the C on the E string. Then add the A♭ a sixth below that (and octave below the one you have written). That fits on the D string at the 6th "fret". At this point, you've got all thee notes of the chord covered, and you may not even need to add a fourth note. You'd have to check with a violinist to be sure, but I would think this open-voiced chord should be more doable on a violin.
A completely different possibility, though perhaps not elegant, would be to split the chord up between the first and second violins. For example, the first could play the octave C that your friend suggests, while the second plays an A♭ and F (either separated by a third, or by a sixth as above). In this case, the 2nd violin's F on beat two could either be missed, or added as a double stop to the viola.
Finally, if you want to notate an arpeggio that isn't a quadruple stop, instead of using a chord with (or without) an arpeggio symbol, I think it might be clearer to notate it as a series of arpeggiated grace notes (as WillRoss1 already suggested). I say this purely from a notational standpoint, without knowing if it's any more playable, though Jomiddnz seems to indicate it is.
Comment: @JeffY That second paragraph isn't how Caleb Hines advises a violinist to play; it proves, in his words, "why violins are not good with close-voiced chords".
Comment: AFAIK violinists span 6 "frets" on the very first position (that starts on the second "fret"). The distance from 6th to 7th is about 1cm so spanning 10 "frets" in the middle of string should be quite easy, the distance will surely be like 8cm or even less. And there should be about two octaves available on the neck.
Comment: There's a difference between playing a quadruple-stop and playing a four-string arpeggiated chord. Since the original score is an arpeggio, it does provide a bit more leeway in the transcription.
Comment: -1 for that second paragraph. Good lord no violinist is going to play like that.
Comment: @RosieF is correct. I was attempting to explain why OP's friend might consider the chord unplayable, in the context of her statement: "When it is written down as an ordinary chord, we try as much as possible to make it sound simultaneous."
Answer: Your arpeggiated chord is perfectly fine.  All four notes can be played in 2nd position on the A and E strings only (not as a quadruple stop).  It could also be played in 3rd position on the D, A and E strings.
Of course only the top C note will be sustained, but the effect will still be there.
Comment: I am a violinist, and although you are correct that it is playable, it is rather awkward. For "chords" like these, even broken ones, it is normal to write notes that are playable on different strings. Unless every note is absolutely necessary, I would prefer playing one of the other alternatives already suggested here. In any case, it would need to be notated differently (with grace notes); that would be more familiar to the vast majority of violinists.
Comment: @Jomiddnz I think the point is that, as written, a typical string player will read it as an instruction to quadruple stop (because it's a chord) - in which case it isn't possible. If it's written as grace notes, then it is possible as you say, and will be read as an instruction to play the arpeggio ahead of the top C.
Comment: @ orthocresol.  I am also a violinist.  I am surprised you think 'it is rather awkward'.  In both 2nd position and 3rd positions, it is perfectly comfortable to play the exact notes that Beethoven wrote for that chord (using three grace notes leading to the sustained top C).  I imagine that retaining Beethoven's original notes would be the arranger's preference.  It is not only comfortable to play, but quite typically violinistic.
Answer: To play a chord on a bowed string instrument, even if by necessity of string crossings it is a spread chord (i.e. arpeggiated), the key point is that you want to be able to put all of your fingers in the necessary positions at the same time. That is impossible for the four note chord written.
It would be possible to rewrite the chord to be playable, by choosing notes such that they can comfortably be played one on each string in some position - this means going for a less closely voiced version of the chord.
The reason you see more arpeggios written out with note values in string music is that they are being played as arpeggios rather than "as close to simultanous as possible" - meaning that the player is moving their fingers around - strings are much more limited in the chords they can play comfortably than the piano, although scales and arpeggios generally work fine.
For this, if you don't want to rewrite the chord, you've got the option of putting some notes in the other parts. Alternatively, write the arpeggiated part as grace notes - so the player actually plays say C F A as an arpeggio as fast as possible, leading in to the top C (which would then be the only note held), similar to the start of the following bar. This, unlike playing it as a chord, should be possible
Answer: You might be able to meet in the middle and use a triple grace note, like in the next measure, only on C-F-A. Only having to sustain the high C might take it from impossible to challenging, while still maintaining all the notes from the original in some form. That said, I'm not a violinist and have no clue if this would actually work, so definitely run this idea by someone that knows what they are talking about first!
(If anyone on here can confirm or deny the practicality of this idea I will gladly update my answer to reflect that)
Answer: I'm a bit attached to the dramatic effect of having the first real chord of the piece - FORTISSIMMO - there...
I would suggest a more radical change:
0) Transpose the whole piece up a whole step, so that for the string quartet, you're writing in g minor.  (Beethoven arranged exactly one of his piano sonatas for string quartet, Op. 14 No. 1 - the piano version is in E major, but the string version is transposed up to F major.)
1) Write that chord as a quadruple stop - low G and D on the open strings, B-flat on the A-string (a ninth above the open string), D on the E string (a seventh above the open string).  (It will naturally be arpeggiated since a violinist can't play it otherwise; you don't need to indicate it.)  This is easily playable in 5th or 6th position - because of the grace note f# at the beginning of the next measure, 5th is probably best, but a violinist can figure this out.
Comment: I usually stick to the key that the composer originally wrote it in unless there is an absolute necessity to transpose. This is because transposition changes the character of the piece. Going from F minor to A minor for instance is like going from deathly sadness to the neutrality of the void. If something like a bass note out of range occurs, I do changes like different articulations or adding another instrument that can reach that range before I decide to transpose unless the key is difficult for the instrument(like F# major on strings). F minor typically isn't a difficult key at all.
Comment: I should add that Beethoven had a good reason to write the piano sonata in f minor - the high F's in the piece were the highest note on the piano when that piece was written.  Most pianos of the time had the F below the low G that is the lowest note in the piece - but not all - and some had the F but were missing the F-sharp in between.
Comment: Changing instruments also changes the character of the piece, and sometimes transposition (partially) undoes the character change from changing instruments
Answer: Don't draw attention to it.
Don't make it stick out and ungainly. It's a detail leading to a cadence .
You are pedantically stuck trying to translate piano into violin.
It's the leading (note of a short phrase)soon forgotten
Comment: @Caters is clearly aware that some things need to be adjusted, simplified or dropped entirely when translating from one instrument to another. There is certainly an argument to be made about leaving off the other notes entirely, but this can be done objectively, without critiquing general arranging ability (ie, "you're doing it wrong"). Something like "The lower notes of the chord serve a more ornamental purpose in the original. Leaving them off entirely is a perfectly viable alternative."
Answer: I am not a violinist. If anyone can correct me, please do so and I will update this answer as necessary:
Play the chord as is. It isn't impossible to quadruple stop, just hard.
Because the bridge is curved, in order to strike all four strings simultaneously, you need to physically bend the two strings in the middle. This detunes the notes on those strings up, and must be compensated for by detuning on the neck in the opposite direction (playing less than a half-step lower than written). This is extremely hard and is rarely done. You have two options: either tell your violinist to play the chord as written, or move parts of it between the voices as necessary.
If your violinist is using an electric violin, or other violin with a significant sustain time (effect pedal?), you also have the third option of having her perform a pizzicato strum (like on a guitar) and switching back to a bow in the half bar of space she has.


What is the Cartesian product of this?

Question:
I am trying to find I am trying to find the Cartesian product of $\{\emptyset,1,2\} \times \{\emptyset,\{1,\emptyset\},2\}$

what i came up with so far is
edited:
{∅, (∅,{1,∅}),(∅,2),(1,∅), (1,{1,∅}) , (1,2), (2,∅),(2,{1,∅}) , (2,2)}
but I am not sure about it since, any non empty set x set = empty
Comment: $\emptyset\times A=\emptyset$, but $(\emptyset,a)\ne \emptyset$ (in fact, the usual definition of pair has $(a,b)\ne \emptyset$ for all $a,b$).
Comment: @Gae.S. is (∅,∅) correct ?
Comment: @MustafaShama "*is $(\emptyset,\emptyset)$ correct?*"  The result of the cartesian product will *contain* $(\emptyset,\emptyset)$ as one of the elements, yes, but will contain many other elements as well.  More explicitly,  your currently shown attempt above (*after the second edit*) is correct with the exception of that what you wrote as your first element as $\emptyset$ should instead have been $(\emptyset,\emptyset)$.
Comment: It should be a set of exactly $9=3 \times 3$ pairs, as both sets have three elements. $\emptyset$ is not a pair so does not belong in it.
Answer: Definition
Let $A,B$ be sets. Then $A \times B = \{(a,b)|a \in A, b \in B\}$.
Example
Let $A = \{11,22\}$ and $B = \{A, \emptyset\}$. Then,
$$
A \times B = \{(11,A),(11,\emptyset),(22,A),(22,\emptyset) \}.
$$
Can you now apply this to your problem?

What is the Cartesian product of this?


Bayesian ROPE (region of practical equivalence) for simultaneous comparison of multiple parameters?

Question: I very much like the idea of the ROPE (region of practical equivalence) (e.g. see here), where you compute the posterior probability that a given parameter is in a previous range that counts as "small" in subject-area terms. (This is not a substitute-for-a-hypothesis-rejection-procedure question; in the particular context I'm working on, the authors want specifically to test for equivalence.)
As I have seen it, the ROPE is a univariate procedure, i.e. testing the marginal posterior distribution of some particular parameter. Does any discussion of a multivariate version exist? I can think of some crude approaches (e.g. test for the simultaneous satisfaction of a bunch of univariate ROPEs — probability of being inside a specified 'rectangular' region — or some kind of sum-of-squares/Mahalanobis variant) but am hoping not to reinvent any wheels.
(I do see that there are some papers on frequentist multivariate equivalence testing, e.g. Hoffelder et al 2015, perhaps these could be adapted ...)
Hoffelder, Thomas, Rüdiger Gössl, and Stefan Wellek. 2015. "Multivariate Equivalence Tests for Use in Pharmaceutical Development." Journal of Biopharmaceutical Statistics 25 (3): 417–37. https://doi.org/10.1080/10543406.2014.920344.
Answer: If you use a rectangular multivariate ROPE, i.e., have a series of assertions in the form of inequalities about an array of effects on different outcomes, and you have the dependency between outcomes modeled (e.g. using a multivariate outcome distribution or a copula connecting the various univariate outcomes), the computation of the posterior probability of being int he ROPE rectangle is straightforward using multivariate posterior samples.
If you don't have a multivariate outcome model but model the outcomes as independent, the multivariate posterior draws will lead to bounds on the true dependent posterior samples.  Sometimes the bounds may be tight enough that you don't need to have a full multivariate model.  For example, if Pr(A & B) is very high assuming A and B are independent, this probability will only be higher if there is a positive dependence between A and B.


Javascript add class if localStorage value exists without reloading page

Question: I work on ionic 5 and angular and I need to change the DOM of my view after a modal popup.
The problem is that I have to reload the view to see the DOM modifications, and I need it to change without any reload.
First step = add key and value in LocalStorage and modal appears on element click.
Second step = I need a addCLass('hide') on divs when modal is dismiss.
Any tips to make these changes without reloading the page ?
HTML code :

Ts :
  ngOnInit() {
let content = document.querySelector(".circleImgContainer");

if (localStorage.getItem('serie_1') == 'true') {
  content.classList.add('hide');
}

}
Comment: I don't know if I understood this correctly: Why don't you bind it to another click event of the modal. For example when it's dismissed.
Answer: I believe in this case you can use setInterval to always check if a localStorage has the desired value and change page content without having to reload.
Here's an example below, normally you can provide setInterval with a time (in milliseconds) interval, but without, it will always constantly update if the if statement matches your set condition.
setInterval(() => {

  ngOnInit() {
    let content = document.querySelector(".circleImgContainer");

    if (localStorage.getItem('serie_1') == 'true') {
      content.classList.add('hide');
    }
  }

})

Comment: I binded the changes on another click, waiting to find a cleaner solution. The use of setInterval could work I guess, I didn't think about it, very good idea ! Thanks a lot.


Is the Generalized Dirichlet Distribution an Exponential Family?

Question: Is the Generalized Dirichlet distribution an exponential family?  If so, what is its log-normalizer, sufficient statistics, and carrier measure?
Answer: Yes, it is an exponential family.
It has sufficient statistics: $\{\log(x_i)\}_i$ and $\{\log(1 - \sum_{j \le i}x_j)\}_i$.
It has zero carrier measure.
Its log-normalizer is $\sum_i B(\alpha_i, \beta_i)$ where the natural parameters that correspond to the above sufficient statistics are $\{\alpha_i-1\}_i$ and $\{\gamma_i\}_i$ with $\gamma_j=\beta_j-\alpha_{j+1}-\beta_{j+1}$.
After some work, I was able to implement the distribution here.