Active a menu  when the menu entry is a view page

Question: I have a section (call news) that have an "home page". This home page is created via "views" and via "views" I have insert a link item into "main menu" menu based on path (/news). When I go to /news the relative entry in "main menu" is active (the
 item has "active-trail" class). All works.
How can I active the same menu when I'm into a node of type news ? I have read that I need to use menu_tree_set_path() into a hook_preprocess_page(). So I have tried to add this line into THEME_preprocess_page(&$vars) :
menu_tree_set_path('main-menu','/news');

but it does not work. I have tried with:
menu_tree_set_path('main-menu','news');

Same result. Not working.
In all my search, all tutorials tells to set for the second parameter of menu_tree_set_path a node/NID or a taxonomy/term/NID, but I have not this node/nid. I have a view page path.
So, How can I do it ?  Thanks.
Answer: I guess you could achieve this with Menu Position module, where you can set an active parent for specific node/content types.
https://www.drupal.org/project/menu_position
Answer: I had to do a trick like that once. I just used menu_set_active_item() but I had to manage the breadcrumb display too and here is my piece of code for that:
// Activate the View menu item but memorize the actual nature of the node for the breadcrumb
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->type == "news" && $view_mode == "full") {
    $_SESSION['mymodule_active_trail'] = serialize(menu_get_active_trail());
    $_GET['mymodule_node_id'] = $node->nid;
    menu_set_active_item("news");
  }
  else {
    if (isset($_SESSION['mymodule_active_trail'])) {
      unset($_SESSION['mymodule_active_trail']);
    }
  }
}
// Alter the breadcrumb to show the real path to your news node
function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  if ($item && $item['path'] == "news") {
    if (isset($_GET['mymodule_node_id'])) {
      if (isset($_SESSION['mymodule_active_trail'])) {
        unset($_SESSION['mymodule_active_trail']);
      }
    }
    if (isset($_SESSION['mymodule_active_trail'])) {
      $original_active_trail = unserialize($_SESSION['mymodule_active_trail']);
      if (is_array($original_active_trail)) {
        $total = count($active_trail);
        $active_trail[$total] = $item;
      }
    }
  }
}


OLD ESXi Host needs to be upgraded however SSH is not working after being turned on

Question: So I've been asked to look at an ESXi 5.5 host which needs upgrades/updates big time.
It is a Dell server...I've enabled SSH however the same root/password combination I can log into the GUI with doesn't seem to work with the SSH client (Putty)..I've also tried OSX terminal to SSH in with no luck..
"Permission denied, please try again."
is the message I get when trying to log in..
I need to get in so I can upload patches and run them to upgrade the host...at least to the newest 5.5 for now..
Thanks
EDIT I have also added another account and enabled shell access and get the same result...
Comment: Have you checked the server hardware against the VMware HCL for the version you want to move to?
Comment: You can't upgrade to a newer major version via SSH anyway. Create an installation media from the next version in the upgrade path, boot from it, install it and choose to keep your VMs.
Comment: Is the SSH port open on the firewall?
Comment: ESXi 5.5 has been end of life since 2018. Upgrade to a supported release.
Comment: @GeraldSchneider did you not read the comment above that is the goal..
Comment: @Davidw yes because I would not have been able to get to the prompt to do the SSH login or password....
Comment: Then why bother with updates? Just install the newer version.
Comment: According to the [upgrade path](https://interopmatrix.vmware.com/Upgrade) you can Upgrade 5.5 directly to 6.5 and then 6.5 to 7.0
Comment: @Chopper3 all set there...but again without being able to SSH into the machine it is difficult to do much of anything..
Answer: Sometimes root user got blocked for try many times without luck.Check that ssh service is running on esxi and that esxi firewall is not blocking incomming connections. If you need to upgrade asap, choose another aproach.
Create or downlod dell custom iso and use Server IPMI. If you can't use virtual cd-rom, you should create a booteable pendrive to upgrade your server. Remember to check Vmware HCL, vmware interoperability matrix and upgrade path.


Can a android phone act as a usb hid mouse?

Question: In Android Open Access Protocol 2.0, the section titled HID Support:
The AOA 2.0 protocol adds four new USB control requests to allow the accessory to act as one or more HID input devices to the Android device. Since HID support is done entirely through control requests on endpoint zero, no new USB interface is needed to provide this support.
Is that mean that, the Android device can act as a usb hid mouse?
I get a example for Arduino in
https://github.com/YuuichiAkagawa/Arduino-AOA2/blob/master/AOA2/examples/AOA2HID/AOA2HID.ino.
And write a demo show as below. but it doesn't work. Whether a android device can become a usb hid mouse as the Arduino example do? Thanks!
<code>private void initIdentity(UsbDeviceConnection connection) {
    Log.i("initAccessory", "initStringControlTransfer");

    initStringControlTransfer(connection, 2,
            "showcasing android2android USB communication"); // DESCRIPTION
    initStringControlTransfer(connection, 3, "0.1"); // VERSION
    initStringControlTransfer(connection, 4, "http://minji.cn"); // URI
    initStringControlTransfer(connection, 5, "42"); // SERIAL
}

private void initStringControlTransfer(
        final UsbDeviceConnection deviceConnection, final int index,
        final String string) {
    deviceConnection.controlTransfer(0x40, 52, 0, index, string.getBytes(),
            string.length(), USB_TIMEOUT_IN_MS);
}

private int HID_ID = 0;

private int GET_PROTOCOL = 51;
private int ACCESSORY_REGISTER_HID = 54;
private int ACCESSORY_UNREGISTER_HID = 55;
private int ACCESSORY_SET_HID_REPORT_DESC = 56;
private int ACCESSORY_SEND_HID_EVENT = 57;

char[] _hidReportDescriptor = {
        // Mouse
        0x05, 0x01, 0x09, 0x02, 0xA1, 0x01, 0x09, 0x01, 0xA1,
        0x00, 0x05, 0x09, 0x19, 0x01, 0x29, 0x08, 0x15, 0x00, 0x25, 0x01,
        0x95, 0x08, 0x75, 0x01, 0x81, 0x02, 0x95,
        0x00, 0x81, 0x03, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09,
        0x38, 0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x03,
        0x81, 0x06, 0x05, 0x0C, 0x0A, 0x38, 0x02, 0x95, 0x01,
        0x81, 0x06, 0xC0, 0xC0, };

private void initUsbHid(UsbDeviceConnection connection) {
    connection.controlTransfer(REQUEST_OUT_TYEP, ACCESSORY_REGISTER_HID,
            HID_ID, _hidReportDescriptor.length, new byte[] {}, 0,
            USB_TIMEOUT_IN_MS);

    connection.controlTransfer(REQUEST_OUT_TYEP,
            ACCESSORY_SET_HID_REPORT_DESC, HID_ID, 0, _hidReportDescriptor.toString().getBytes(),
            0, USB_TIMEOUT_IN_MS);
}

private void unRegisteHid() {
    UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);
    connection.controlTransfer(REQUEST_OUT_TYEP, ACCESSORY_UNREGISTER_HID,
            HID_ID, 0, new byte[] {}, 0, USB_TIMEOUT_IN_MS);
}

public void send(String msg) {
    Log.i(this.getClass().getName(), msg);
    UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);

    byte[] m = new byte[5];
    m[2] = 0;
    m[1] = 0;
    m[0] = 1;

    connection.controlTransfer(REQUEST_OUT_TYEP, ACCESSORY_SEND_HID_EVENT,
            HID_ID, 0, m, m.length, USB_TIMEOUT_IN_MS);
}

private void startAccessory(UsbDeviceConnection connection) {
    connection.controlTransfer(REQUEST_OUT_TYEP, // request type for this
                                                    // transaction
            53, // request ID for this transaction
            0, // value field for this transaction
            0, // index field for this transaction
            new byte[] {}, // buffer for data portion of transaction, or
                            // null if no data needs to be sent or received
            0, // the index of the first byte in the buffer to send or
                // receive
            USB_TIMEOUT_IN_MS);
}

private boolean initAccessory(final UsbDevice device) {
    Log.i("initAccessory", "initAccessory start");

    final UsbDeviceConnection connection = mUsbManager.openDevice(device);

    if (connection == null) {
        Log.i("initAccessory", "connection == null");
        return false;
    }

    int protocol = getProtocol(connection);
    if (protocol <= 1) {
        Log.i("initAccessory", "Protocol: " + protocol
                + " not support USB HID");
        return false;
    }

    //initIdentity(connection);

    initUsbHid(connection);

    //startAccessory(connection);

    connection.close();

    return true;
}
</code>
Answer: AOA 2.0 HID class implementation allows an Accessory attached to the Android phone to act as an HID device. But not the other way around.
Check out Android Keyboard Key Assignments here. I am not sure if they support HID Page for Mouse. I have tested Keyboard Page and Consumer Page, and found them working.
I found your Accessory ID is 0 (private int HID_ID = 0;), Maybe use something else. I am not sure if they enumerate a device with ID 0.
Also try to send a release key after few ms, where all the data is zero. I am not sure what is the release key for mouse.


Duvidas SQL - duas tabelas (planilhas excel) consolidadas

Question: Olá.
Estou com uma duvida, que creio ser simples para os veteranos do forum.
Não tenho muita noção de SQL, mas preciso integrar dois arquivos em excel
Um de estoque e um de vendas
São dois xls diferentes. Os dois possuem um BD (aba) chamada "Base Geral".
Tenho colunas de marca, produto, mês, ano e valores... onde:
Na planilha de estoque , o meu campo de valor se chama ESTOQUE e na de vendas, VENDA
Preciso criar uma terceira planilha que consolide as duas via Query, onde eu levarei as colunas de (MARCA / PRODUTO / ANO / MES) das duas e levarei a ESTOQUE e VENDAS tambem, além de criar uma terceira coluna..
Nessa terceira coluna, chamada "SAIDA ESTOQUE", a formula é a seguinte:
<code>SAIDA ESTOQUE = Estoque do mês anterior* + venda - estoque do mês atual
</code>
Desta forma, no estoque do mes anterior, precisaria fazer um prov ou somase, puxando o valor do mes anterior... por exemplo. se eu trouxer uma linha que tenha mes de fevereiro, deve trazer    (ESTOQUE DE JANEIRO + vendas de fevereiro - Estoque de fevereiro)
Se alguém me ajudar a resolver, agradeço imensamente.
PS: já usei union no sql, mas empaquei nas colunas com nomes diferentes
[![imagem 1 - base de estoque][1]][1]
[![imagem 2 - base de vendas][2]][2]

infelizmente não consigo inserir todas as imagens
Comment: seria util colocar  algum codigo para podermos verificar apenas palavras é dificil ver o seu real problema, caso tenha leia https://pt.stackoverflow.com/help/mcve
Comment: Você está importando os `xls` para alguma tabela e quer unir os dados com `SQL`? É isso?
Comment: na verdade não Marcelo... eu estou jogando os dois arquivos de excel diretamente para um outro arquivo em excel... em (Dados > de outras fontes >Microsoft Query > arquivos excel).... o que eu queria era unir essa consulta de forma automática.. desta forma, toda vez que as duas "bases" fossem atualizadas.. quando eu atualizasse esta consulta, eu conseguisse replicar o que pretendo para a tabela
Answer: Pode fazer da seguinte forma:
Passo 1: Criar consulta para o arquivo 1 (Imagem 1)
Passo 2: Criar consulta para o arquivo 2 (Imagem 1)
Passo 3: Criar uma nova consulta Pelo menu "Combinar Consultas" > "Iniciar Editor de consultas" (Imagem 2)
Passo 4: Manter as colunas desejadas de cada consulta, se necessário, pode clicar com o botão direito para renomear as colunas.
Comment: boa tarde Alexandre.. na verdade, eu não queria subir os dados como tabela. eu tenho dois arquivos em excel, relativamente pesados... o que gostaria de fazer é ter um novo excel, onde eu possa atualizar a tabela de dados e conseguir disponibilizar as informações de forma automática... eu nunca subi dados de consulta, utilizando duas tabelas... geralmente, faço isso usando um único arquivo.. e só para fim de consulta mesmo.... desta vez, queria integrar os dois arquivos e incluir algumas operações no arquivo que vai consolidar as duas tabelas... não sei se isto realmente é possivel
Comment: Entendi, isso também poderia ser feito no SQL e depois transportar para o Excel. Mas editei a resposta para utilização das consultas diretamente no Excel.
Comment: Valeu pela ajuda.... o problema é que não sei se isso esta disponível no Excel 2010. Eu até consegui fazer a integração usando right outer join... e inner join.... o problema é que eu precisaria de uma consulta completa que tivesse todos os valores.. mas ta dando erro quando eu tento aplicar Full outer join.. eu cheguei a postar o exemplo num outro fórum onde eu consigo anexar arquivos... isso é temporário.. é que precisava consolidar uma base aqui.. vou tentar me matricular num curso de banco de dados o mais rápido possivel
Comment: O Stack Overflow não é um fórum.


acoustics under water

Question: I've got the following problem that is taken from the numerical analysis book
by Kahaner-Moler-Nash (P8-15):

The speed of sound in ocean water depends on pressure, temperature and
  salinity, all of which vary with depth in fairly complicated ways. Let
  z denote depth in feet under the ocean surface (so that the positive z
  axis points down) and let c(z) denote the speed of sound at depth z.
  We shall ignore the changes in sound speed observed in horizontal
  directions. It is possible to measure c(z) at discrete values of z;
  typical results can be found in the table. We need c(z) and also c0(z)
  between data points. Fit the data in a least-squares sense with the
  non-linear model function

c(z) = 4800 + p1 + p2*z/1000 + p3*e^(-p4*z/1000)

To obtain startguesses, solve the linear approximation problem with p4
  = 1: Make a plot over the data points and the received model curve c(z). Since the sound speed varies with depth, sound rays will travel
  in curved paths. A fixed underwater point emits rays in all directions.
  Given a particular point and initial direction we would like to follow
  the ray path. Thus letting x be the horizontal coordinate we know the
  initial values: x = 0, z = z0, dz=dx = tan 0, where 0 denotes the
  angle between the horizontal line z = z0 and the ray in the start
  point.

z c(z)
0 5050
500 4980
1000 4930
1500 4890
2000 4870
2500 4865
3000 4860
3500 4860
4000 4865
5000 4875
6000 4885
7000 4905
8000 4920
9000 4935
10000 4950
11000 4970
12000 4990

The ray path z(x) is described by the following second order
  differential equation

d^2z/dx= -q0*c'(z)/c(z)^3
where q0 = (c(z0) / cos b0)^2

Use the Runge-Kutta method (or ode45) to trace the ray beginning at z0
  = 2000 feet and b0 = 7.8 degrees. Follow the ray for 25 nautical miles (1 nautical mile is 6076 feet). Plot the curve z(x). You should
  find that the depth at xf = 25 nautical miles is close to 2500 feet.
Now suppose that a sound source at a depth of 2000 feet transmits to a
  receiver 25 miles away at a depth of 2500 feet. The above calculation
  shows that one of the rays from the source to the receiver leaves the
  source at an angle close to 7.8 degrees. Because of the nonlinearity
  of the equation there may be other rays leaving at different angles
  that reach the same receiver. Run your program for b0 in the range
  from 10 up to 14 degrees, plot the ray paths and print a table of the
  values z(xf).
We are interested in finding values of 0 for which z(xf) = 2500. Use
  an efficient algorithm to determine the rays which pass through the
  receiver. Discuss the accuracy of your results.

So how should I proceed with solving this? I should study the methods, I think I know RK¤ already but not the non-linear least squares. Can you help me?
Answer: A short (and fairly general) answer.
We have some experimental data points $(x_{i},y_{i})$ and a model
$$ y = f(x;\textbf{p})$$
which depends on some parameters. As we change the values of these parameters $\textbf{p}$ the sum of the squares of the differences change, i.e. $$\text{Objective}(\mathbf{p}) =  \sum_{i} \left[ y_{i} - f(x_{i};\mathbf{p})\right]^2.$$
We  want to find a vector $\mathbf{p}_{0}$ such that $\text{Objective}(\mathbf{p})$ is minimised at $\textbf{p}_{0}$.
MATLAB can deal with these sorts of problems fairly easily. It has a built in solver lsqnonlin which solves nonlinear least square problems (as you may have guessed from the name). If you are actually asking about how that solver works, this answer needs to be a lot longer, but I believe that lsqnonlin implements the Levenberg-Marquadt algorithm.
Comment: Default for MATLAB is a trust region Gauss-Newton method, though Levenberg-Marquardt can be used too if specifically called for. It's quite related though - one can view the LM method as a trust region method with a weird rule for updating the trust region size.

acoustics under water


Set select list default value

Question: I have select list with options:
$options = array(0 => '0', 500 => '500', 1000 => '1000');

I'm trying to set it's default value to 500:
$form['price']['min']['#options'] = $options;
$form['price']['min']['#default_value'] = 500;

But this don't work.
Comment: I ran into the same issue.  The problem was that I was not rendering the form using drupal_get_form(), but some other way because of the use case.
Comment: 500 should be a '500', string not an integer.
Comment: I met the same question!!!!who can help me?
Answer: I've never seen this problem. That default value should work. I would say try making the key a string and set #default_value as a string. The #options array may be being passed through array_merge  somewhere, thus rekeying integer keys. If keys are strings then that shouldn't happen.
Currently, your array looks like this:
$options = array(
  0 => '0',
  500 => '500',
  1000 => '1000',
);

But passing that array through array_merge can reorganize those integer keys to be in sequential order:
$options = array(
  0 => '0',
  1 => '500',
  2 => '1000',
);

If that happens then the 500 key simply doesn't exist. This is because array_merge does not like to preserve integer keys, but you can use strings to prevent it.
So, I think your array should look more like this:
$options = array(
  '0' => '0',
  '500' => '500',
  '1000' => '1000',
);

Then you can set your #default_value:
$form['price']['min']['#default_value'] = '500';

Otherwise, is there anywhere else where the default_value may be being overridden?
Answer: Your code should be work, generally use key value as default value, if it not working make the string as keys and use it as default value.
Answer: Did you try using a string instead of an integer?
$form['price']['min']['#default_value'] = "500"

Maybe also worth a try adding the 'und' key.
Answer: Did you try using the key out of the array $options to define the default value?

$form['price']['min']['#default_value'] = $options[500];

Comment: If that is done it will technically just pass the value of $options[500], which is (string) '500'.
Answer: $options = array(0 => '0', 500 => '500', 1000 => '1000');
$form['price'] = array(
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => 500,
        );

In order to set default value in select list we use #default_value parameter. The value of the default_value attribute of the select list would be the key of the select list array.
Answer: Following code will show the field with its default value as 500.
$options = array(0 => '0', 500 => '500', 1000 => '1000');
$form['price'] = array(
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => 500,
          '#title' => 'Price',
        );

Answer: I faced the same problem and I tried giving the index of the array which I want to be the default value and it worked.
My answer is similar to Ashok KS but his second line I could not understand.
Answer: fixed,we should set default value first of that $option array, if we added last,the array key changed [1]=>science,[2]=>drama,the right should be [192]=>science,[231]=>drama:-)
Answer: try:
$form['price']['#default_value'] = 500;
It's work good for me.
Answer: The #default_value should have it's arguments in the form as the #value.
$form['price']['min']['#default_value'] = $options['500'];

Answer: Just use
$form['price']['min']['#default_value'] = 2

which means the default value will take the 2eme option
Answer: SOLUTION: Figure out that form_select_options doesn't handle #default_value at all. So I used #value property:
$form['price']['min']['#value'] = isset($_REQUEST['price']['min']) ? $_REQUEST['price']['min'] : $my_default_value;

Comment: Select options do have a default value. Also setting the `#value` param will make it impossible for the user to change the value.
Comment: Look at the code, I set #value to default_value only if there is no any value in #value.
Comment: You always set a value to #value, either `$_REQUEST['price']['min']` or `$my_default_value`. Whatever you put in the #value will be the value of the field regardless of what ever the user inputs.
Comment: If user inputs some value, this value is send through GET ($_REQUEST['price']['min']). So if user inputs value I set #value to user input, otherwise #value = $my_default_value
Comment: That is the problem. Users can use the select, but it wont matter what they select, the result will be the same.
Comment: Indeed, this is not a good idea. There's a reason there are separate keys for value and default_value. I guess it *can* be done in a form builder, but it's certainly incorrect and bad practice.

Set select list default value


Frequent 504 Gateway timeout

Question: Lately, we often encounter this 504 Gateway timeout on multiple endpoints
Example of /preview endpoint:
Server error: `POST https://graph.microsoft.com/v1.0/sites/root/drive/items/014THVUXPVDHARRLTKGZHI2GLKYADOOZDI/preview` resulted in a `504 Gateway Timeout` response:
{
  "error": {
    "code": "UnknownError",
    "message": "",
    "innerError": {
      "request-id": "3f981b5d-883 (truncated...)

another example on small file upload endpoint:
PUT /email@example.com=rename` resulted in a `504 Gateway Timeout` response:
{
  "error": {
    "code": "UnknownError",
    "message": "",
    "innerError": {
      "request-id": "12d80986-9cb (truncated...)

Comment: Okay, as with any "gateway timeout" situation, you need to first look at your hardware.  Where are the "gateways" in question?  Then, look at your request patterns and volume.  A "gateway timeout" might be caused by load-shedding.  In any case it is a transient condition that your code must be prepared to handle.
Comment: This is an error happening with microsoft graph api, I've put the tag in the OP, not sure if I should include it in content aswell... Either way this error happens way too often..
Answer: Please test the above API calls with Microsoft Graph Explorer and see if you can still repro the issue.
Comment: Using the `POST /preview`, I have tried with graph explorer, and I'm unable to get a timeout. At the same time I have tested to get a preview using microsoft graph sdk with a timeout of 5sec, and it times out. I removed the 5sec timeout on the code, but I couldn't get the gateway timeout. It seems to happen randomly. I have many sentry logs regarding this problem though.

Frequent 504 Gateway timeout


Ansible create a virtualenv using the venv module

Question: How can one use Ansible to create a virtualenv using the venv module from Python3's standard library?
Manually, one would do this to create a venv (virtual environment):
python3 -m venv <venv-name>

How do I do this using Ansible?
Comment: @kyslik I have already read the documentation multiple times, searched SO, and tried to make things work on my computer. I am aware of the `virtualenv_command` option in the ansible pip module. However, ansible gives an error that `python3 -m venv` is not a valid command. So I am at loss.
Comment: @kyslik Unfortunately, ansible will throw an error if you don't give pip a name.
Comment: Note that ansible's python 3 support might still be flaky
Answer: I ran into the same issue tonight and found that specifying the full path to the interpreter, including the arguments, worked for me (at least it does in ansible==22.214.171.124):
- pip:
     requirements: /website/requirements.txt
     virtualenv: /opt/website-venv
     virtualenv_command: /usr/bin/python3.6 -m venv

or
- pip:
    requirements: /opt/project/requirements_prod.txt
    virtualenv: /opt/.virtualenv/project_env
    virtualenv_python: python3

Comment: It's important to use full path to the python executable. Otherwise ansible says it can't find it in PATH dirs.
Comment: Just FYI in ansible=2.7 to use python3 -m venv you have to use: virtualenv_command:  -m venv and do not include virtualenv_python. See: https://docs.ansible.com/ansible/latest/modules/pip_module.html
Answer: Here is an example using Ansible's command statement:
- name: Create Python virtual environment
  command:
    cmd: python3 -m venv {{ project_path }}/project_venv
    creates: "{{ project_path }}/project_venv"

Answer: # Install specified python requirements in indicated (virtualenv).
- pip:
  requirements: /my_app/requirements.txt
  virtualenv: /my_app/venv

If python3 is indeed being flaky, you can specify which version of python you'd like to use:
# Install specified python requirements in indicated (virtualenv).
- pip:
  requirements: /my_app/requirements.txt
  virtualenv: /my_app/venv
  virtualenv_command: virtualenv-2.7

I think that answers your question.
Comment: I am using the venv module from the python standard library to create virtual environments. Not the virtualenv module.
Comment: Syntax is broken. And you seemingly did not understand the meaning of the remark on Python 3 support. It was not about the version of Python inside the virtualenv, but which version of Python Ansible uses to run its modules. You don't set that in your example.


localizar palavra dentro de strings array

Question: estou usando o seguinte código:
foreach ($lista_grupos as $key => $value) {
    if(strpos($lista_grupos[$key],'Tecnologia_da_Informacao')===true){
        $admin = true;
    }else{
        $admin = false;
    }
}

Porém sempre retorna false, não encontra a string que desejo. O que estou fazendo de errado?
Segue array:
(array =>
    [21] => CN=Tecnologia_da_Informacao,OU=Tecnologia_da_Informacao,OU=03-Operadora,DC=asdt,DC=com,DC=br
    [22] => CN=asdasd,OU=02-Grupos,DC=uniiaca,DC=com,DC=br
    [23] => CN=asdasd,OU=02-Grupos,DC=jçasdia,DC=com,DC=br
)

Comment: Cara, dá um tapa nesse código php aí
Comment: Isso ai tem cara de ldap.
Comment: É sim, mas não descobri como conseguir exatamente o nome do grupoo, desta forma está trazendo os grupos que a pessoa participa em um array
Comment: Você precisa sair do loop quando encontrar o que procura, senão pode mudar sua variável para false na passada seguinte.
Comment: fiz o teste, mas não entra no if verdadeiro.
Comment: `if(strpos($value, 'Tecnologia_da_Informacao')  !== false)`
Comment: Não compreendi, por que diferente de false?
Answer: Faz muito tempo que não programo em php mas pelo que li na documentação, o strpos() retorna um inteiro e você compara com boolean ali. Pela documentação, utilize algo assim:
if ($pos !== false) {
    $admin = true;
    return ...;
}

O === compara o resultado mais o tipo. O strpos() pode retornar false mas nunca vai retornar true e sim um inteiro da primeira ocorrência da sua string (Operadores PHP).


How to check if ID in the URI is null and throw an error?

Question: I tried to check if a specific URL doesn't specified an ID
This are what I've got so far:
<code>http://localhost:8082/orders/1234 ---- Success!
http://localhost:8082/orders/ ---- URL not found!
</code>
I want to throw and error something like "Id not specified!" not a URL not found.
Answer: Define a custom error handling and that will return error description alongside other required data
set  status code 400 in a variable, map fields as per below example.
ex:
<code>{
    "error": {
        "errorCode": "NOT_FOUND",
        "errorDateTime": "2019-10-10T14:00:46",
        "errorMessage": "The requested API cannot be found,  ID is not specified",
        "errorDescription": "Description: /orders"
    }
}
</code>
Answer: Look at Validation Module
Look at the "Matches Regex" section down.

I have not tried it
Hope it may help
Answer: the believe the best approach for you is to start using RAML. you can design the endpoint in RAML and specify what error to be thrown if the request is not a match.
<code>/{order_id}:
    get:
      description: Get a Order by id
      responses:
        200:
          body:
            application/json:
              type: Foo
              example: !include examples/Order.json
        400:
          body:
            application/json:
              type: Error
              example: !include examples/Error.json
</code>
in the above RAML definition if there is no orders/{order_id} you will get a http 400 returned.


Integral of velocity if acceleration is a function of velocity

Question: I am having trouble taking the integral of this acceleration function:
$$a = (b - v^2)/c$$
where b and c are constants.
I cant seem to get the $dv$ and $dt$ on one side :(
If anyone can help me, please explain.
Thank you.
Answer: Write the equation as,
$$\frac{dv}{dt}= (b - v^2)/c$$
or,
$$\frac{dv}{b-v^2}= \frac 1c dt$$
Then, integrate
$$\int \frac{dv}{b-v^2}= \frac 1c \int dt$$


Validar e-mail com angularjs

Question: Eu tenho o seguinte campo para e-mail:
<input type="email" class="form-control" id="email" name="email" ng-model="fields.email" required="true" />

Na div onde está o campo, tenho a seguinte validação:
ng-class="{ 'has-error': userForm.email.$error.email }"

Acontece que se digitar "abc@abc" é dado como válido, porém como podemos ver está errado.
Já tentei usar expressão regular mas sem sucesso. Como validar e-mails correctamente no AngularJS?
Answer: Utilize ngPattern para alterar o comportamento padrão do Angular:
<input type="email"  ng-model="fields.email" ng-pattern="/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/" />

Confira a documentação do Angular para mais informações:
AngularJS: input[email]
Comment: apenas fiz uma modificação, como a regra de negócio está toda dentro do .js, criei uma variável dentro do escopo e adicionei a expressão regular lá, funcionou perfeitamente com essa.
Answer: Na verdade o email abc@abc pode ser válido, da mesma forma que email@localhost.
É incomum, mas é válido tecnológicamente falando, poderia responder a algum endereço.
Podes verificar em:
http://en.wikipedia.org/wiki/Email_address#Examples
Inclusive não sei como isto vai se comportar com os novos domínios personalizados como .google ou .globo, eles já existem e talvez possam usar emails desta forma, mas aí já não tenho certeza.
Comment: É verdade, mas ainda são incomuns e como você disse, ninguém sabe ainda como vai se comportar com os novos domínios.

Validar e-mail com angularjs


something about ansi_nulls

Question: I have a question that we always say that null =null is false ,I want to know that when the ansi_nulls is off this statement which is "null=null" is also false? thanks
Comment: NULL=NULL evaluates to unknown rather than false with 3 valued logic. *NOT (NULL=NULL)* is not true.
Answer: With ANSI_NULLS OFF, NULL = NULL evaluates to TRUE.
With ANSI_NULLS ON (the default), NULL = NULL evaluates to NULL.
NULL IS NULL always evaluates to TRUE.
However, in MySQL, you cannot turn off ANSI_NULLS. You are probably thinking of MS SQL Server.
Future versions of MS SQL Server won't support ANSI_NULLS OFF, so I wouldn't use it.
You should leave ANSI_NULLS ON and use IS NULL to evaluate if something IS NULL.
If you're having problems remembering how NULL works by default (ANSI_NULLS ON), you should think of NULL as "unknown". For example, if there are two strangers in the room, their names are NULL. If your query is, "Are their names the same?" Your answer IS NULL.
Now, let's say Bob is in the room with just one stranger, whose name IS NULL. Again the answer to your query "Are their names the same?" IS NULL. Note that if you compare anything to NULL, your answer IS NULL.
Answer: When ansi_nulls is off, null=null will return true.
Eg.
set ansi_nulls off
select 1 where null=null

Gives  you:
1

something about ansi_nulls


NODE/EXPRESS/BODY-PARSER não estou conseguindo ler o body, fica dando UNDEFINED

Question: Bom vou postar a index aqui para vocês darem uma olhada, eu refiz o código e funcionou com outro proposito, mas com esse proposito de pegar as informações e mandar pro banco de dados sempre da undefined, não sei oque poderia ser.
<code>insira o código aqui
const porta = 3003
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const bd = require('./callBd.js')
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());

app.get('/user', (req, res) =>{
    bd.execQuery('SELECT * FROM User', res);
})

app.get('/user/:id?',(req,res) => {
    bd.execQuery(`SELECT * FROM User where ID = ${req.params.id}`, res);
})

app.post('/user/:user?/:prof?/:pass?', (req, res) =>{
    const name = req.body.nome
    const prof = req.body.profissao
    const pass = req.body.password
    /**const name = req.params.user
    const prof = req.params.prof
    const pass = req.params.pass**/

    console.log(name,prof,pass)
    bd.execQuery(`INSERT INTO User(Name, Profission, Password) VALUES('${name}','${prof}','${pass}')`, res);
});

app.listen(porta,()=>{
   console.log(`Servidor está executando na porta ${porta}.`)
})
</code>
Answer: Olá, boa tarde.
Na opção de "Body", do Postman, marque a opção "row", e no lado esquerdo vai aparecer ao opção do tipo de "Body". Clique nele e selecione a opção "JSON (application/json)".
Veja a imagem abaixo:


CastContext.getSharedInstance(Context) is now deprecated

Question: As the title says, CastContext.getSharedInstance(Context) is now deprecated:

getSharedInstance(Context context): This method is deprecated. Use getSharedInstance(Context, Executor) instead to handle the exception when Cast SDK fails to load the internal Cast module.
https://developers.google.com/android/reference/com/google/android/gms/cast/framework/CastContext

What would be the correct way to specify an Executor and return the CastContext?
I got it working like this but I wonder if this is the best way to do it:
CastContext
    .getSharedInstance(context, Executors.newSingleThreadExecutor())
    .addOnSuccessListener(castContext -> {
        //do something with castContext
    })
    .addOnFailureListener(exception -> {
        //throw exception
    });

Answer: Your approach is good for retrieving CastContext asynchronously.
But, in the official cast sample app, they are retrieving CastContext synchronously by directly calling getResult() on the getSharedInstance() task.
val castExecutor = Executors.newSingleThreadExecutor()
val castContext = CastContext.getSharedInstance(this, castExecutor).result

Comment: Doing this might result in crash with "Task is not yet complete" as this is async job
Answer: This is exactly the correct way to use it. In Xamarin (C#) you would do it this way :
var instanceTask =  CastContext.GetSharedInstance(Application.Context, Executors.NewSingleThreadExecutor());
var sharedInstance = await instanceTask as CastContext;

// do something with it

Answer: We could simply use the executor service already used for other background processing instead of creating a brand new one:
CastContext.getSharedInstance(getApplicationContext(), Common.getBackgroundProcessor());


Notating Sound Effects on a Score?

Question: I'vw composed a piece of music that contains various sound effects, most notably movie trailer-style "braaaam" horn sounds, and large, synthetic drum hits that don't fall within the drum part.
For the purpose of my qualification I have to write a full traditional score for this, and I couldn't find anything about a convention for how to notate sound effects like this on a score.
Is there an existing convention for how to notate sounds like these on a score, or any ideas on good ways to do it? These can't really be notated in with the horn or drum parts as they're completely distinct from those musical parts.
Comment: I'd suspect giving them their own separate parts (a la "timpani", "cymbals", "bass drum", etc.) would do the trick.
Comment: Are they all triggered from a keyboard?
Comment: @OldBrixtonian the piece is actually 100% digital, although even though it will never be played by humans I'm required to produce a score for it.
Answer: The best way of notating sound effects is the same way you would notate a percussion part. There are three possibilities depending on the complexity you need:

Put each effect on a single-line percussion system.
Use a 5-line percussion system and assign each effect to a specific line or space.
Use a 5-line percussion system and write the name of the effect over each entry.
If a keyboard player is going to be playing the effects, use a 10-line grand staff and assign each effect to a note (naming the effects the first time they're played).

Or use some combination of these methods.
A couple of examples
Comment: Writing the name of the effect over each entry makes the most sense for music where human players are actually expected to play the effects parts (a la concert band pieces where a percussionist needs to play brake drums and glockenspiel at different points).
Comment: @Dekkadeci It depends on how complex the music is. Above a certain level of complexity writing the names of the effects every time can get very cluttered. If the effects are going to be played on a keyboard, modern keyboard players are used to just playing the notes and have all sorts of different sounds come out, although it's a good idea to name the effects the first time they occur.
Answer: I don't think that there is any standard for this. If there is, I didn't hear of it.
The best thing would be to use some notehead type that is not used elsewhere and then simply notate your intentions with written instructions.
In the end what matters most is that your intentions are clear to the musicians.

Notating Sound Effects on a Score?


Python Pandas how to get f-string to work in an url

Question: I am getting an error of urllib.error.HTTPError: HTTP Error 404: Not Found. I feel like f-string should work for the url but it is not how would I fix this?
import pandas as pd

stockslist = ['f','goog', 'aapl']
for s in stockslist:
    url = f'https://finance.yahoo.com/quote/{s}/'
    print(url)
    tablelist = pd.read_html(url, flavor='html5lib')
    df = pd.concat(tablelist[:2])
    print(df)

Comment: @ShaneS would you like to try out with `yfinance`? I've been working the same way as yours except I'm using yfinance. And what output are you seeking?
Comment: Does this answer your question? [URLLIB request code reading issue. Cannot read error code 404](https://stackoverflow.com/questions/61975308/urllib-request-code-reading-issue-cannot-read-error-code-404)
Answer: you have to parse html first then read it
try it:
    import pandas as pd
    import requests
    stockslist = ['f','goog', 'aapl']
    for s in stockslist:
        print(s)
        url = f'https://finance.yahoo.com/quote/{s}/'
        html = requests.get(url).content
        tablelist = pd.read_html(html, flavor='html5lib')
        df = pd.concat(tablelist[:2])
        print(df)

Comment: You solution it is close to fully working. The df is returning "0  Will be right back...  Thank you for your pati..." so I thought to add `import time` and just after `html = requests...` I added  `time.sleep(5)`.  but this still is not returning the expected tables. Do you have any recommendations?
Comment: debug html variable and trace html content ,already disabled current url by owner ,


Data não recebe valor mais 30 dias

Question: Estou com um código que quero verificar se a data é superior a 30 dias com o JodaTime, mas colocando na saída do console o valor não é atribuído. Vi o seguinte: https://stackoverflow.com/questions/16461361/add-one-day-into-joda-time-datetime
e fiz a mesma ideia, mas continuou não funcionando.
Segue o código :
DateTime dataEnvioPrevistoMaisTrintaDias = new DateTime();
dataEnvioPrevistoMaisTrintaDias = peg.getDataEnvioPrevisto().plus(30);
System.out.println("Data Envio : "+ peg.getDataEnvioPrevisto());
System.out.println("Data Envio + 30 : "+dataEnvioPrevistoMaisTrintaDias);

Saída no console:

Data Envio : 2017-09-29T00:00:00.000-03:00
Data Envio + 30 : 2017-09-29T00:00:00.030-03:00
Answer: Você está usando o método errado. Veja a documentação do método plus(long):

Parameters:
duration - the duration, in millis, to add to this one

Traduzindo:

Parâmetros:
duration - a duração, em millis, para adicionar a este objeto

Ou seja, ao invés de somar 30 dias, você somou 30 milissegundos!
O método que você deveria usar é o plusDays(int).
Answer: Creio que o correto seria plusDays() e não plus() como você está utilizando. Altere esta linha:
dataEnvioPrevistoMaisTrintaDias = peg.getDataEnvioPrevisto().plus(30);

para:
dataEnvioPrevistoMaisTrintaDias = peg.getDataEnvioPrevisto().plusDays(30);

Aconselho dar uma lida neste post que ensina a manipular classes do novo pacote java.time. pois a partir do java-8, todas as funcionalidades do jodaTime foram adicionadas nativamente a linguagem.
Answer: O método que está a utilizar para adicionar dias, o plus(), não é o correto. Esse serve para adicionar milisegundos, como a própria documentação indica:

public DateTime plus(long duration)
...
Parameters:
duration - the duration, in millis, to add to this one

Em vez disso tem de usar o plusDays() que adiciona a quantidade indicada em dias:
dataEnvioPrevistoMaisTrintaDias = peg.getDataEnvioPrevisto().plusDays(30);

Documentação para plusDays()

Data não recebe valor mais 30 dias


Show existence of vector of a function

Question: $ U ⊂ R^m$ is open and we have $f : U → R^n$. Prove if $df_a(u)$ exists, then $df_a(bu)$ exists and is equal to $b*df_a(u)$ for any $b \in R$ that is not 0.
I assumed $df_a(u)$  is a directional vector in the direction of a, and I used chain-rule to derive the result but I am not sure if it applies to directional vectors.
This was actually a quiz question that I couldn't get and hope to understand before my midterm. Thanks for the help.
Comment: If $df_a(u)$ is what you say it is, the result as stated is not true.
Comment: I assumed $df_a(u)$ was the total differential at the point $a$.
Comment: i am probably wrong then, because I did not fully understand what the notation is
Comment: @jamesblack are you familiar with the Jacobian matrix?
Comment: do you mean differential at point a with value u?
Comment: yes but in terms of linear algebra not real analysis
Comment: $u \in U$ so it's in the open set around the point $a$. Think of it as an open patch where the derivative is well-defined.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103726/discussion-between-cyclotomicfield-and-james-black).
Comment: Ok, the total differential is an $n\times m$ matrix. By definition, it is interpreted as a linear operator, so $df_a(bu)=b\,df_a(u)$ by definition. And it is not true that the total differential exists for an arbitrary function; lots of functions exist that are not differentiable.
Answer: It appears that $df_a(u)$ denotes the directional derivative of $f$ at a point $a$ in the direction of $u$ (not the direction of $a$!).  The result in question then indeed follows from the chain rule (for ordinary functions of a single variable; no need to worry about a chain rule for directional derivatives): $df_a(u)$ is by definition $g'(0)$ where $g$ is defined by $g(t)=f(a+tu)$, and $df_a(bu)$ is by definition $h'(0)$ where $h(t)=f(a+tbu)$.  But $h(t)=g(bt)$ so by the chain rule $h'(0)=bg'(0)$.
If you are not comfortable using the chain rule in this way, this fact is also easy to verify directly from the definition of the directional derivative as a limit: you wish to show $$\lim_{t\to 0}\frac{f(a+tbu)-f(a)}{t}=b\cdot\lim_{t\to 0}\frac{f(a+tu)-f(a)}{t}$$ assuming the limit on the right exists.  To do so, just substitute $t'=tb$ on the left side and observe that a limit as $t\to 0$ is equivalent to a limit as $t'\to 0$.
Comment: thank you for the detailed explanation! why does this have to do with U being open btw? why cant U be closed U is the domain btw
Comment: and what is the intuitive meaning of this result?

Show existence of vector of a function


How to enter non-rich-text?

Question: Is it possible to enter non-rich-text into the text editor? The apostrophe-rich-text editor seems to add
 tags around everything inside it. I'd like to format the widget.html like so:

{{ apos.singleton(data.widget, 'section-heading', 'apostrophe-rich-text') }}

but the output wraps the text in
 tags so they override the
. Is there any way to override this behavior?
Answer: I figured it out.
You have to use the "string" type in the index.js. For example in the /widget-name/index.js, you would put:
module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Section Heading',
  addFields: [
    {
      name: 'sectionHeading',
      label: 'Section Heading',
      type: 'string'
    }
  ]
};

Then, in the /widget-name/views/widget.html, put:

{{ data.widget.sectionHeading }}

This will bring up a dialogue box with a text field labelled "Section Heading". When you save the dialogue box, the string will render on your site.
Comment: That's correct! Currently there is not a way to edit a simple string in context, like you can with a rich text widget. There are some clunky ways to implement this by using the rich text editor, but a simple in-context string editor would be a nice thing to add.
Comment: can this widget be made generic? I want to avoid creating separate widgets for each and every editable text because the label and name are hardcoded

How to enter non-rich-text?


KL divergence theorem

Question: Given two distributions $p(x)$ and $q(x)$, I can find the similarity measure between them using $KL(p||q) = -\sum_xp(x) log \frac{q(x)}{p(x)}$. Now I'm defining mutual info as $I(X,Y) \equiv KL(p(x,y) || p(x)p(y))$. I am defining $H$ as the information entropy.
I want to show that $I(X,Y) = H(X) - H(X|Y)$ and $I(X,Y) = H(Y) - H(Y|X)$.
However, I'm having a hard time wrapping my mind around how the information entropy plays a role in the mutual information from a conceptual standpoint.
Not sure how I can start to prove this mathematically either using the equation I have. How do I start?
Comment: $$\log(p(x) p(y)) =\log(p(x)) + \log(p(y))$$ and $$\sum p(y) f(x) = f(x)$$. Also, you can find the proof in any information theory textbook. (Cover and Thomas being a canonical one.)
Comment: Yep, just pulled the proof from that textbook.... Thank you!
Answer: Here is a qualitative way to interpret that identity: $KL(p||q)$ is a measure of how different the distributions $p$ and $q$ are.  So the KL divergence between the true joint distribution of $(X,Y)$ and the product of their marginals is a measure of how far away $X$ and $Y$ are from being independent (if $X$ and $Y$ are independent then their joint distribution is the product measure).  We also know that in terms of entropy, $H(X|Y) \leq H(X)$ and equality holds iff $X$ and $Y$ are independent.  Therefore $H(X) - H(X|Y)$ is also a measure of how far away $X$ and $Y$ are from being independent.  So it makes sense that these two quantities should be related to each other, but it's not clear just from this qualitative analysis why they should be exactly equal.
Comment: So what would it mean if $I(X,Y) = 0$?
Comment: That means $X$ and $Y$ are independent

KL divergence theorem


Which storage method would be better to store images along with some text in android?

Question: I am creating an android app in which user can take a pic directly from camera or can choose it from gallery and can also put some text in Edittext box, like a form. Later the app will show all the feeded data in a Listview. Clicking on Listview item will open the detail page. Listview should display a thumbnail of the pic along with the text entered and detail page should display the whole pic with text.
I am very confused how to first save this data and which storage method would be efficient. Should I go for Sqlite or internal file storage? And then this whole thumbnail thing. If you can share any info, tutorial on how to do it would be appreciated :)
And forgive me, if this question is out of the box.
Answer: Regardless of the storage engine you use, you should store the following:

Image file URI
String of entered text

These two elements can be stored using any of these options:

"Pure" SQLite
An ORM that wraps SQLite, providing more flexible functionality (ActiveAndroid, for example).
A non-SQLite DB, such as Realm (realm.io)
Store a list in shared preferences

Depends on how much data you have, and on how confident you feel with DBs in general.


Detecting similar elements in jagged arrays

Question: Is there a way to detect similar elements within multidimensional arrays? For example:
int[][] arrayA = {{1 , 2}, {4 , 6}, {3, 7}};
int[][] arrayB = {{3 , 2}, {1 , 2}, {8, 5}};

Both arrayA and arrayB have the element {1 , 2}. (Or simply, any element in common) Is there a way to detect that it's true?
Comment: these are **jagged** arrays, not **multidimensional**
Comment: Ahh I see. But is there still a way to find the elements regardless if it's jagged?
Comment: @RogueCSDev ANY element in common, yes.
Comment: for int i in array1, for int j in array2, blah-blah - you know, write a code.
Answer: Yes, you just need to code the logic and you can detect.
    bool result = false;
    foreach (var arrayAItem in arrayA)
    {
        foreach (var arrayBItem in arrayB)
        {
            if (arrayAItem.SequenceEqual(arrayBItem))
            {
                result = true;
                break;
            }
        }
        if (result == true)
        {
            break;
        }
    }

and a one liner
bool result = arrayA.Any(arrayAItem => arrayB.Any(arrayBItem => arrayAItem.SequenceEqual(arrayBItem)));

Answer: Something along this?
arrayA.Where(arr => arrayB.Any(arr2 => arr1.OrderBy(x => x)
                                           .SequenceEquals(arr.OrderBy(x => x)))).ToArray()

You can remove the two OrderBy calls if you want, depending on how you wish to consider two arrays "the same".
Answer: It's hard to give you the answer without just feeding you code, but:
For each element in Array A, check if it's equal to each element in Array B. So basically, you'd need a nested foreach. If you want to record which elements they have in common, add them to a List<ElementType> (not an array since you want to dynamically populate it).
It's not quite that simple since your arrays are nested. You can't just check arrayA[x] == arrayB[x] because you'd be comparing arrays, which are reference types (it would return false unless they both pointed to the same piece of memory). Instead, you'll have to add one more loop inside of the two foreaches you already have to check each int in arrayA against the correlating one in arrayB. int is a value type, so an == comparison would behave how you'd expect it to.
Answer: Here is how you can do this (and not only):
var commonItems = from innerA in arrayA
                  from innerB in arrayB
                  where innerA.SequenceEqual(innerB)
                  select innerA;
bool anyCommon = commonItems.Any();
var firstCommon = commonItems.FirstOrDefault();
var commonCount = commonItems.Count();

I guess the variable names are self explanatory :-)
Answer: The following code becomes lengthened, but will give you the output you want:
    private void TestArrays()
    {
        int[,] arrayA = new[,] { { 1, 2 }, { 4, 6 }, { 3, 7 } };
        int[,] arrayB = new[,] { { 3, 2 }, { 1, 2 }, { 8, 5 } };

        int parentLengthA = arrayA.GetLength(0);
        int childLengthA = arrayA.GetLength(1);
        int parentLengthB = arrayB.GetLength(0);
        int childLengthB = arrayB.GetLength(1);

        int[] itemsOfA;
        int[] itemsOfB;

        List<int[]> matchedArrays = new List<int[]>();

        for (int i = 0; i < parentLengthA; i++)
        {
            itemsOfA = new int[childLengthA];

            for (int j = 0; j < parentLengthB; j++)
            {
                itemsOfB = new int[childLengthB];

                bool isMatched = true;

                if (itemsOfA.Length != itemsOfB.Length)
                {
                    isMatched = false;
                    break;
                }

                for (int k = 0; k < itemsOfA.Length; k++)
                {
                    if (arrayA[i, k] != arrayB[j, k])
                    {
                        isMatched = false;
                        break;
                    }
                    else
                    {
                        itemsOfA[k] = arrayA[i, k];
                    }
                }

                if (isMatched)
                {
                    matchedArrays.Add(itemsOfA);
                }
            }
        }

        //Just to output the matched array(s)
        if (matchedArrays.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            foreach (int[] matchedArray in matchedArrays)
            {
                foreach (int i in matchedArray)
                {
                    sb.Append(i + ",");
                }

                sb.AppendLine();
            }

            MessageBox.Show(sb.ToString());
        }
    }


Python Matplotlib string-formatting in plots with bold and Italic font

Question: I have a little problem with bold and italic fonts in a plot at the same time.
I tried:
plt.text(0.5,0.5,r'\it{italic} + \bf{bold}' = \it{\bf{both}}')

this gives: italic and bold = both
and with:
plt.text(0.5,0.5,r'\it{italic} + \bf{bold}' = \bf{\it{both}}')

I get: italic and bold = both
But what I want to get is both
I also tried to use the latex version with \textbf{...} and \textit{...} and the commands \mathit{...} and \mathbf{...}.
They work as they should but not if they are used combined. The combination of different "technologies" like \mathbf{\textbf{...}} does not help. It is alway only the last style that stays.
I saw a few different questions on that topic but no correct answer, so I hope that asking espacially for this contextless case helps to find an answer. I am looking for a generall solution, not for a workaround for a special case, e.g. using a special font that already looks bold.
Answer: I have found the answer. Yoi have to use a different font. The work around I mentioned is the answer. If you use:
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

you will get the desired result. The default font in matplotlib seems to not support the bold and italic edits at the same time. Maybe this helps in many other situations you will have with other edits in case you are looking for different combinations.


After clicking OK button, Data should send to another window

Question: After clicking the OK button in the Window, It open the another window after clicking that Ok button. and I want to send the information into that window.
<code>public void saveSelection(IMiniTable miniTable) {

    final int AD_Window_ID = 1000108;

    String whereString = " ROUTE_ID" + getM_Route_ID();

    final AWindow poFrame = new AWindow();

    final MQuery query = new MQuery("ROUTE_ID");

    query.addRestriction(whereString);

    final boolean ok = poFrame.initWindow(AD_Window_ID, query);

    if (!ok) {
        return;
    }``

    poFrame.pack();

    AEnv.showCenterScreen(poFrame);

    return;

}
</code>
help me out
Comment: Stack overflow is not a code writing service. Please read the [help] pages to see what sort of question are allowed here.
Answer: when you are manipulating window inside adempiere , you can get the ad_window_id from context like #AD_Window_ID.
When you inicialize another windows, you can get this object to add logs or info to show inside frame.


Simulation from linear model with additional variables

Question: I want to test the performance of a variable selection method in linear regression with normal errors using simulated data:
$${\bf y}= {\bf X}{\bf \beta} + \epsilon,$$
where, as usual, ${\bf y}$ is $n\times 1$, ${\bf\beta}$ is $p\times 1$, $n>p$, $\epsilon_j\stackrel{ind.}{\sim}N(0,\sigma^2)$, $j=1,\dots,n$.
How can I simulate additional superfluous variables? Is there a benchmark method for adding variables or is it an irrelevant part of the simulation? I was thinking of adding simulated columns, from some arbitrarily chosen distribution, in the design matrix and check whether or not the variable selection method detects the artificial additional variables.
Comment: **I have accepted an answer based on the merits of the effort shown. However, the general question about whether or not there is a benchmark method remains (in a formal sense) open.**
Answer: One way would be to simulate all $x_1, x_2, ..., x_p$ together, assign each explanatory variable a coefficient, then simulate the error term $\epsilon$, and finally your dependent variable would just be the sum of the $X'\beta$ and $\epsilon$. Many statistical packages have functions where you can specify the correlation between the $x$ variables, too. In Stata, for instance, that could be achieved with the corr2data command.
Perhaps you are not using Stata but as long as you know the simulation commands in other languages the steps should be the same.
// set a certain number of observations
set obs 1000

// generate the explanatory variables (here we simulate 2 variables from a normal distribution)
gen x1 = rnormal(5,3)
gen x2 = rnormal(9,1)

// generate the error term (here is the simple case where the error is distributed as N(0,1) - for other distributions use the according sampling technique)
gen e = rnormal(0,1)

// generate the dependent variable and assign coefficients to the explanatory variables (0.5 for x1 and 0.9 for x2, for instance)
gen y = 0.5*x1 + 0.9*x2 + e

// run the linear regression of y on x1 and x2
reg y x1 x2

The corr2data command gives you much more options to specify correlations between the variables. So you can see what happens to your model if you have high collinearity between x1 and x2, you can simulate measurment error, correlations with the error, etc. It can also be used to generate a heteroscedastic relationship between one or more of the explanatory variables with the error.
Given the edit of the original question, here is also how to add superfluous variables. For this you would need to specify a correlation matrix before generating the data, for example:
    |       x1       x2       x3        e
----+------------------------------------
 x1 |   1.0000
 x2 |   0.3000   1.0000
 x3 |   0.0100  -0.0000   1.0000
  e |   0.0000  -0.0000  -0.0000   1.0000

Which can be achieved via
mat C = (1, 0.3, 0.01, 0 \ 0.3, 1, 0, 0 \ 0.01, 0, 1 , 0 \ 0, 0, 0, 1)
corr2data x1 x2 x3 e, n(1000) means(5 7 13 0) sds(3, 1, 2, 1) corr(C)
corr

where you then make x3 "superfluous" by simply not including it in the construction of y. It's not completely useless because it is correlated with x1, so through the correlation matrix C you can decide how superfluous x3 actually is. Then generating y in the same way as before
// generate the dependent variable
gen y = 0.5*x1 + 0.9*x2 + e

// run the regression with the useless variable
reg y x1 x2 x3

gives the result you wanted.
But this would be the generic set-up to generate such data which should work in any other statistical package in the same way. Presumably other packages have additional/different functions that you can use but the steps done here are a basic way to achieve this.
Comment: Thank you for your answer. If I properly understand, you are explaining how to simulate from the linear model. Now, if I want to add "superfluous" variables (in addition to $x_1,\dots,x_p$, say, $x_{p+1},\dots$), what would you recommend?
Comment: You can simulate other variables and simply add them to the regression. By construction they are then uncorrelated with $y$. The `corr2data` command, for instance, would also allow generation of "superfluous" variables that are not correlated with $y$ but with the other explanatory variables.
Answer: You could also approach to simulating data ($\mathbf{X}$) containing $p$ variables and $n$ observations by using a Cholesky decomposition of an a priori specified $p$-by-$p$ correlation matrix ($\mathbf{R}$) and an $p$-by-$n$ 'noise matrix' ($\mathbf{V}$):
$$\mathbf{X} = \left(\mathbf{R^{*}V}\right)^{\text{T}}$$
where $\mathbf{R^{*}}$ is the Cholesky decomposition of $\mathbf{R}$, and $\mathbf{V} \sim \mathcal{N}\left(0,\sigma\right)$. Your linear relationships would thus be articulated through the correlations defined as elements of $\mathbf{R}$.
References:
Dray, S. (2008). On the number of principal components: A test of dimensionality based on measurements of similarity between matrices. Computational Statistics & Data Analysis, 52(4), 2228–2237.
Linn, R. L. (1968). A Monte Carlo approach to the number of factors problem. Psychometrika, 33(1), 37–71.
Answer:
Generate shocks ($ \epsilon_j \sim N(0, \sigma^2))$
Let $ Y_{truth} = X\beta + \epsilon$
Fit $Y_{polluted} = X\beta + P\gamma$
Run your selection procedure and hope that $Y_{polluted}$ will reduce to $Y_{truth}$
Comment: Thanks. Is there a standard procedure for choosing $P$? How relevant is this choice?
Comment: In theory the choice of P does not really matter, because you have already generated the ground truth! In this case you know the data generating process so your goal is just to recover the parameters you used for simulating the ground truth. In practice, the choice of P might be important due to numerical stability. For starter, you could choose a P that is as orthogonal as possible to X.
Comment: Thank you. I like your answer, I just wonder if there is a formal argument to justify the irrelevance of the choice of $P$. I think the answer is not straightforward.


Yii CGridView - Sort by DESC first on column header click

Question: Is it possible to change the order of a column-header click sort?
I have a "ranking" column, which upon first click will sort by ASC, and only on 2nd click would go to DESC sort - I need to reverse that so that 1st click is DESC, and 2nd click is ASC.
Is this possible?
return new CSqlDataProvider($sql . $search, array(
            'totalItemCount' => $itemCount,
            'params' => $params,
            'sort' => array(
                'attributes' => array (
                    'enabled',
                    'store_name',
                    'rating' => array (
                        'desc' => 'rating * percent / 100 DESC',
                        'asc' => 'rating * percent / 100 ASC',
                    ),
                ),
                'defaultOrder' => array( 'store_name'=>false )
            ),
            'pagination' => array('pageSize' => Yii::app()->user->getState('pageSize_cs', Yii::app()->params['defaultPageSize']),),
        ));

Answer: The only way I know of to do this is a hack that results in column arrows pointing the wrong way.
'desc' => 'rating * percent / 100 ASC',
'asc' => 'rating * percent / 100 DESC',

Answer: I think it will show the CGridView in descending order by default if you click the header it will display in ASC if u want the reverse process do it in the reverse
   public function search($status)
   {
        $criteria = new CDbCriteria;
        $criteria->order = 'store_name desc';
   }

Comment: This will not accomplish what OP wants. It will always sort by store_name desc.
Answer: As of Yii 1.1.3 there was added default key support for attributes settings. This does exactly what you want. Example:
'sort' => array(
    'attributes' => array (
        'enabled',
        'store_name',
        'rating' => array (
            'desc' => 'rating * percent / 100 DESC',
            'asc' => 'rating * percent / 100 ASC',
            'default' => 'desc',
        ),
    ),
    'defaultOrder' => array( 'store_name'=>false )
),


Get top three match records from each group

Question: I run this query which gives me proper data. The only problem is that I want the top 3 records from each group; this will give me total records.
SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points

FROM seasons
INNER JOIN division_teams ON division_teams.season_id = seasons.id
INNER JOIN team_points ON
     eam_points.team_id = division_teams.team_id
WHERE seasons.id = 19
GROUP BY
     division_teams.division_id,team_points.team_id
ORDER BY division_id ASC,points DESC

table output
Answer: Use self join with subquery
SELECT A.devision_id, A.team_id,A.name,a.points, COUNT(lesser.point) AS rank
FROM
(SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points FROM seasons INNER JOIN division_teams ON division_teams.season_id = seasons.id INNER JOIN team_points ON eam_points.team_id = division_teams.team_id
WHERE seasons.id = 19 GROUP BY division_teams.division_id,team_points.team_id
) A
LEFT JOIN
(SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points FROM seasons INNER JOIN division_teams ON division_teams.season_id = seasons.id INNER JOIN team_points ON eam_points.team_id = division_teams.team_id
WHERE seasons.id = 19 GROUP BY division_teams.division_id,team_points.team_id
) AS lesser
ON A.division_id = lesser.division_id  AND A.points < lesser.point
GROUP BY A.devision_id, A.team_id,A.name,a.points
HAVING COUNT(lesser.point) < 3
ORDER BY A.division_id ASC,A.points DESC

Comment: Any other solution without subquery ?


Interpretation of empirical frequency of null hypothesis rejections

Question: assume I know a theoretical distribution that is quite non-normal.
I simulate many (N) samples of given size (T).
Then for each sample I test if the sample average is equal to the theoretical one (t-test).
Then I look at the frequency of rejections as a function of T.
Let T* the smallest T such that the rejection frequency equals the significance level used in the test.
Does it make sense to say that T* is the minimum sample size such that a random sample is informative about the mean of the theoretical distribution?
In general, what is the most appropriate way to identify the minimum size of a random sample such that I can consider it informative, given a non-normal theoretical distribution?
Thanks a lot
Comment: For your non-normal distribution, $T^*$ is the smallest sample size for which the test has the correct [type I error rate](http://en.wikipedia.org/wiki/Type_I_and_type_II_errors#Type_I_error) (also called size). $T^*$ only tells you what sample size you need in order for the t-test to work as you'd expect. A random sample will (almost) always be informative, even if consists of $T<T^*$ observations. Even if the sample is too small to use the t-test, other statistical methods can be used to subtract information from your data
Comment: Could you mention which other statistical methods should I consider, please?
Answer: Sounds like you want to do a power analysis. There is a large literature on that, so you may want to read that first. However, if you worry about non-normality, then I would start with worrying whether a t-test is appropriate in the first place before looking at the power of that test.
Comment: Traditionally "informative" means H0 is false, so they are one and the same thing.
Comment: But power analysis concerns the possibility that H1 is true. Here I'm just drawing from the true (and assumed to be known) distribution. Given this, I would know how to infer on the minimum size needed to consider a random sample informative (at least about the mean).


What is the proper mime-type on a link rel pingback (WordPress)?

Question: This question applies to WordPress, but maybe someone knows if it applies universally?
Is there a proper mime-type (type attribute) for this... ?
<link rel="pingback" type="WHICH-TYPE/HERE?" href="http://www.example.com/xmlrpc.php" />

Something tells me it may be text/xml, but I'd rather not guess if someone knows the right answer.
EDIT:
I am reading here that including a link rel pingback in your  is discouraged...
Answer: According to the specs ( http://www.hixie.ch/specs/pingback/pingback ), you don't need to specify a type attribute.
Presumably because it doesn't send any content.
Comment: I understand you don't NEED to specify a type, just wondering what the proper type is, if any. Maybe there is no "right" answer?


In Probabilistic Graphical Models, what does it mean that r.v. X influences r.v Y?

Question: I wanted to pin down what the intuitive phrase:

r.v. X influences r.v. Y

as precisely and as rigorously as I could, and wanted to check if my interpretation was correct and complete with the community.
The way I interpret that phrase is as the following:
X influences Y if any observation (or realization) of the r.v X affects the probability distribution for the values of Y.
So for example, if we are wondering what the probability for a certain value of Y might be, we might go reference its distribution $p_Y(y)$ for an answer. However, if we believe that X could influence Y, then we believe that the distribution for Y is affect by a realization of X, yielding a different but valid distribution $p_{Y|X}(y|x)$.
Is this a correct way of interpreting what "r.v. X influences r.v. Y" means? Are there alternative interpretations of that sentences in probability, statistics, machine learning or inference?
Answer: Your definition bears some similarity to Judea Pearl's definition, but is missing something very important. We need the concept of manipulation, as opposed to observation. Causal claims are claims about the results of manipulations, even if we can learn about them via observation.
The results of observations and manipulations can be very different. For example: if I were to observe that a patient has nicotine-stained fingers, then the probability that that patient has lung cancer would increase. But if I perform a manipulation, and paint the patient's hands yellow, then the probability of lung cancer does not change.*
Manipulation and observation have other different properties. Observation is symmetric (if learning the value of $X$ informs me about the value of $Y$, then the converse is also true), whereas manipulation is asymmetric (if manipulating $X$ leads to a change in $Y$, we can't assume that manipulating $Y$ will lead to a change in $X$).
Philosophers have attempted to define causation and manipulation in terms of observation alone, and every such attempt has run into some irresolvable difficulty. So the current approach in the causal literature is to take the idea of manipulation as a primitive, and define causation in terms of it. Pearl uses the "do" operator to represent manipulations: $do(X=x)$ means manipulating $X$ so that it takes the value $x$. Using this operator, we can define influence concisely:

$X$ causally influences $Y$ iff there exist at least two values of $X$, $x$ and
  $x'$, such that $P(Y\;|\;do(X=x)) \neq P(Y\;|\;do(X=x'))$

*Note: The phrase "controlling for X, Y and Z" actually means conditioning on the values of X, Y and Z – that is, observing them. This can mislead non-statisticians, because "control" sounds like a kind of manipulation.
Comment: @Alexis Actually, learning that Joe was born *does* make it more likely that Joe won a marathon, compared to when I'm unsure about whether Joe was born at all! Probabilistic dependence/independence is symmetric: if A is dependent on B, then B is dependent on A. But I agree that the *degree* of dependence can be asymmetric (as in your example), for some measures of dependence.
Comment: Are you quite sure about this? "Observation is symmetric (if learning the value of X informs me about the value of Y, then the converse is also true)" I think association can be directional: if I observe that someone *won a marathon*, that tells me (with certainty) that that individual was *born*, however knowing that someone was born tells me nothing about whether they won a marathon. Another example would be the non-functional relationships comprising some of the examples in Reshef &Co.'s "Detecting novel associations in large data sets" (http://www.sciencemag.org/content/334/6062/1518 )


student attendance prediction

Question: Let's say I wanted to be able to predict, from game to game, what the total student attendance would be at an average college football game, where would I even begin?
I would have access to historical attendance figures, would be able to recreate which games were day games and which were night games, would be able to tell you if it was sunny or rainy, which game was homecoming, etc. (all variables that might impact attendance). I'd be able to track percentage increase/decline from one game to the next from any past season.
Where would you take this if you were me?
Answer: I would organise the data into the tidy data format and load it into a R. From here I would check the data is accurate (i.e. mis-entries, odd values, etc.)s. I would then plot the data and try and work out what kind of models would preform best.
If prediction is the goal I would try a suite of models that are fit for the task, but likely beginning with something relatively simple like a generalised linear model with poisson errors. I would check the assumptions and model fit, and perhaps try a few other models depending on what makes sense. These might include things like support vector regression or tree-based models. Alternatively, I might look at time-series models if I thought there was auto-correlation between games, which there likely would be.
I would probably work in a cross-validation framework to assess how accurately my models were at predicting turn-out as well.
Let me know if anything is unclear.

student attendance prediction


How many factors of $2010^{2010}$ have last digit $2$?

Question:
How many factors of  $2010^{2010}$ have last digit $2$?

It is not difficult to solve this using python/mathematica, but I want to know how to (smartly) solve this one with paper and pencil?
Comment: Preliminary question: are you familiar with [modular arithmetic](http://en.wikipedia.org/wiki/Modular_arithmetic)?
Comment: The problem would be easier if the exponent was $2007$, because the digits of $3^a$ and $67^b$ each cycle with period $4$. For any of $2$, $4$, $8$, $6$ there are four patterns $(a,b)$ within each cycle that multiplied by $2$ yield $2$, also four that multiplied by $4$ yield $2$, and so on. There is an additional bit of asymmetry because the digits of $2^c$ cycle with period $4$, with the exceptional $1$ at $c=0$.
Answer: Since $2010=2\cdot3\cdot5\cdot67$, the factors of $2010^{2010}$ are all of the form $F=2^a\cdot3^b\cdot5^c\cdot67^d$ with $0\le a,b,c,d\le2010$. Since we want the last digit of $F$ to be $2$, we must have $a\ge1$ and $c=0$.

The last digits of $2^a$ ($a\ge1$) are $2,4,8,6$, and they repeat
periodically.
The last digits of $3^b$ ($b\ge0$) are $1,3,9,7$, and they repeat periodically.
The last digits of $67^d$ ($d\ge0$) are $1,7,9,3$, and they repeat periodically.

Let $\alpha$ be the last digit of $2^a$, $\beta$ be the last digit of $3^b$ and $\delta$ be the last digit of $67^d$. For the last digit of $F=2^a\cdot3^b\cdot67^d$ to be $2$, the last digit of $\alpha\cdot\beta\cdot\delta$ must be also $2$. When does this happen? There are $16$ possibilities for the triple $\{\alpha,\beta,\delta\}$: $\{2,1,1\}$, $\{2,3,7\}$, $\{2,9,9\}$, $\{2,7,3\}$, $\{4,1,3\}$, $\{4,3,1\}$, $\{4,9,7\}$, $\{4,7,9\}$, $\{8,1,9\}$, $\{8,3,3\}$, $\{8,9,1\}$, $\{8,7,7\}$, $\{6,1,7\}$, $\{6,3,9\}$, $\{6,9,3\}$ and $\{6,7,1\}$. All we have to do is count how many factors there are with each of the $16$ possibilities. For instance, for $\{2,1,1\}$ we must have
$$
a\equiv 1 \mod4,\quad b\equiv0\mod4\quad\text{and}\quad  d\equiv0\mod 4.
$$
This gives $503$ possible values for each of $a$, $b$ and $c$, for a total of $503^3$ factors.
I'll leave it to you to do the computations for the other $15$ cases.


Tor amplitude of dual complex

Question: Let $E^\bullet$ be a perfect complex of $R$-modules (where $R$ comm. ring). So $E^\bullet$ is quasi-isomorphic to a bounded complex of finitely generated projective R-modules. Now $E^\bullet$ has Tor-amplitude in some interval $[a,b]$, which means that $H^i(E^\bullet \otimes_R M) = 0$ for all $i \not\in [a,b]$ and for all $R$-modules $M$.
Now my question is, let $(E^\bullet)^\vee$ be the dual of $E^\bullet$. What can we say about the Tor-amplitude of $(E^\bullet)^\vee$? Of course $H^i((E^\bullet)^\vee \otimes_R M) = H^i (RHom_R(E^\bullet, M)) =: Ext^i(E^\bullet, M)$. so the question is about which degrees the Ext is concentrated in. my guess is $[-b,-a]$.
Answer: Your guess is correct. I think that the easiest way to prove this is to note that for some $c,d$, $E^\bullet$ is quasi-isomorphic to a bounded complex of finitely generated projectives concentrated in degrees $[c,d]$ such that the first differential is not a split monomorphism and the last differential is not a (split) epimorphism, and that then $-d,-c$ are precisely the smallest and largest integers $i$ such that $Ext^i(E^\bullet, M)$ does not vanish for all $M$ (take $M$ to be the cokernel of the last non-zero differential or the first non-zero term of $E^\bullet$ respectively).
And dualizing turns $E^\bullet$ into a complex concentrated in degrees $[-d,-c]$ with exactly the same properties.

Tor amplitude of dual complex


how to specify a hierarchical mixed model with two factors nested within participant that are crossed with each other

Question: I've read a bunch of questions and answers here about how to specify models and some tutorial walk throughs and I still not sure how to deal with my data structure.  I want, obviously, to avoid any hint of pseudoreplication.
I'm trying to test for brain-behavior correlations in some fMRI data.  I have 34 clusters/ROIs that came from another analysis (independent, I hope, since it did not involve the behavioral measure to generate them).
I have 37 participants, 12 runs per participant (i.e., a run is a single session of neuroimaging data).  For a few participants there are only 6 runs.
I have three experimental variables.  Levels of variable A apply to an entire run, while levels of variables B and C apply to trials within a run.  There are three levels of A and two of B and C.
I am trying to specify a model in which the contrast over levels in variable B in the brain data for a run is regressed on the same contrast in the behavioral data. I also want to know how this is modulated by levels of A and C.
I started with:
model <- lmer(B_contrast_brain ~ B_contrast_behavior*A*C + (1|subject/cluster), data=data)

I was getting some p-values that feel implausibly low to me, so I was trying to figure out what I'm doing wrong. One thing I realized: because I have two levels of C per run, run is also a grouping variable nested within subject.  But I'm not sure of the correct way to specify that.
My best guess is:
  model <- lmer(B_contrast_brain ~ B_contrast_behavior*A*C + (1|subject/cluster) + (1|subject/run), data=data)

But I'm not sure.  When I do that my p-values inch into the realm of plausibility, although a few of the effects are still very strong.
So my questions are:

Is the above the right specification?

Is there anything else that pops out that I'm doing wrong that could lead to spuriously strong effects?

Edit: I should add that since I asked this question I realized that I was getting the singular fit warning.  Since paring down my fixed effects is not making that warning go away, this must be to do with how I specified my random effects.  This might explain p-values that still feel implausibly low, but I guess I don't understand why I don't have enough data to have both cluster and run be random effects, when I have 34 clusters and 12 runs per subject, with cluster and run fully crossed.
Edit 2, per request:
Here is the output of summary for the first model. rel is what I have been calling B, type is A, and taught is C.
Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
Formula: winsorized_rel_brain ~ rel_behavior * type * taught + (1 | subject/cluster)
   Data: all_data_dx

REML criterion at convergence: 71101.8

Scaled residuals:
    Min      1Q  Median      3Q     Max
-5.0352 -0.3851 -0.0614  0.3395  5.7847

Random effects:
 Groups          Name        Variance Std.Dev.
 cluster:subject (Intercept) 0.003915 0.06257
 subject         (Intercept) 0.010999 0.10488
 Residual                    0.771609 0.87841
Number of obs: 27466, groups:  cluster:subject, 1153; subject, 37

Fixed effects:
                             Estimate Std. Error         df t value Pr(>|t|)
(Intercept)                 6.153e-02  2.170e-02  7.076e+01   2.836 0.005957 **
rel_behavior                4.071e-02  1.489e-02  2.706e+04   2.734 0.006264 **
typeN                      -8.669e-02  1.847e-02  2.712e+04  -4.693 2.70e-06 ***
typeY                      -1.113e-03  1.849e-02  2.707e+04  -0.060 0.951981
taughtU                    -1.387e-01  1.835e-02  2.706e+04  -7.556 4.29e-14 ***
rel_behavior:typeN         -5.066e-02  2.023e-02  2.708e+04  -2.504 0.012283 *
rel_behavior:typeY         -1.931e-02  2.231e-02  2.711e+04  -0.866 0.386571
rel_behavior:taughtU       -9.047e-02  2.336e-02  2.693e+04  -3.872 0.000108 ***
typeN:taughtU               2.093e-01  2.617e-02  2.707e+04   7.998 1.31e-15 ***
typeY:taughtU               7.923e-02  2.622e-02  2.707e+04   3.021 0.002518 **
rel_behavior:typeN:taughtU  7.945e-02  3.394e-02  2.695e+04   2.341 0.019227 *
rel_behavior:typeY:taughtU  1.676e-01  3.440e-02  2.711e+04   4.874 1.10e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) rl_bhv typeN  typeY  taghtU rl_b:N rl_b:Y rl_b:U typN:U typY:U r_:N:U
rel_behavir  0.028
typeN       -0.421 -0.034
typeY       -0.420 -0.034  0.493
taughtU     -0.423 -0.034  0.497  0.497
rl_bhvr:tyN -0.021 -0.734  0.101  0.023  0.025
rl_bhvr:tyY -0.020 -0.660  0.022  0.103  0.023  0.482
rl_bhvr:tgU -0.017 -0.649  0.021  0.023  0.018  0.468  0.434
typeN:tghtU  0.297  0.023 -0.705 -0.348 -0.701 -0.069 -0.016 -0.011
typeY:tghtU  0.296  0.025 -0.348 -0.705 -0.700 -0.018 -0.074 -0.014  0.491
rl_bhvr:N:U  0.011  0.449 -0.061 -0.014 -0.012 -0.607 -0.292 -0.683 -0.025  0.009
rl_bhvr:Y:U  0.013  0.428 -0.014 -0.067 -0.012 -0.310 -0.651 -0.670  0.008 -0.015  0.454

Here is the output for the second:
 Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
Formula: winsorized_rel_brain ~ rel_behavior * type * taught + (1 | subject/cluster) +      (1 | subject/run)
   Data: all_data_dx

REML criterion at convergence: 68406.7

Scaled residuals:
    Min      1Q  Median      3Q     Max
-7.4126 -0.3985 -0.0264  0.3608  6.9236

Random effects:
 Groups          Name        Variance  Std.Dev.
 cluster.subject (Intercept) 0.000e+00 0.0000000
 run.subject     (Intercept) 1.091e-01 0.3303322
 subject         (Intercept) 0.000e+00 0.0000000
 subject.1       (Intercept) 1.638e-10 0.0000128
 Residual                    6.784e-01 0.8236462
Number of obs: 27466, groups:  cluster:subject, 1153; run:subject, 443; subject, 37

Fixed effects:
                             Estimate Std. Error         df t value Pr(>|t|)
(Intercept)                 5.231e-02  2.976e-02  5.206e+02   1.758 0.079394 .
rel_behavior                4.339e-02  1.890e-02  1.869e+04   2.296 0.021689 *
typeN                      -9.501e-02  4.216e-02  5.238e+02  -2.253 0.024652 *
typeY                      -7.202e-03  4.223e-02  5.235e+02  -0.171 0.864643
taughtU                    -1.394e-01  1.722e-02  2.702e+04  -8.096 5.93e-16 ***
rel_behavior:typeN         -1.067e-01  2.563e-02  1.894e+04  -4.165 3.13e-05 ***
rel_behavior:typeY         -7.256e-02  2.801e-02  2.008e+04  -2.590 0.009597 **
rel_behavior:taughtU        4.737e-03  3.241e-02  1.452e+04   0.146 0.883789
typeN:taughtU               2.160e-01  2.465e-02  2.709e+04   8.761  < 2e-16 ***
typeY:taughtU               8.743e-02  2.475e-02  2.714e+04   3.532 0.000413 ***
rel_behavior:typeN:taughtU  5.267e-02  4.664e-02  1.504e+04   1.129 0.258884
rel_behavior:typeY:taughtU  1.129e-01  4.516e-02  1.769e+04   2.500 0.012416 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) rl_bhv typeN  typeY  taghtU rl_b:N rl_b:Y rl_b:U typN:U typY:U r_:N:U
rel_behavir  0.027
typeN       -0.706 -0.019
typeY       -0.705 -0.019  0.498
taughtU     -0.290 -0.045  0.205  0.204
rl_bhvr:tyN -0.020 -0.737  0.056  0.014  0.033
rl_bhvr:tyY -0.018 -0.675  0.013  0.056  0.030  0.498
rl_bhvr:tgU -0.020 -0.734  0.014  0.014  0.028  0.541  0.495
typeN:tghtU  0.202  0.031 -0.290 -0.143 -0.698 -0.076 -0.021 -0.019
typeY:tghtU  0.202  0.031 -0.142 -0.290 -0.695 -0.023 -0.095 -0.019  0.486
rl_bhvr:N:U  0.014  0.510 -0.039 -0.010 -0.019 -0.698 -0.344 -0.695 -0.025  0.013
rl_bhvr:Y:U  0.014  0.527 -0.010 -0.036 -0.020 -0.388 -0.691 -0.718  0.014 -0.016  0.499
optimizer (nloptwrap) convergence code: 0 (OK)
boundary (singular) fit: see ?isSingular

Comment: Please include the output of `summary(model)` for both models. Also please can you let us know how you determine whether a p-value is plausible ?
Comment: @RobertLong thanks for the engagement!  I added both outputs.  As for the p-values, if asked to weigh the likelihood that an interaction in my experimental variables (e.g. typeN:taughtU ) is determining a contrast in brain activation estimable with such precision, versus the likelihood that I'm making a mistake in reasoning somewhere, I think "I'm making a mistake" is more plausible.
Comment: Specifically, I think my mistake may be about the degrees of freedom in my denominator, but I can't figure out how to correctly specify them.  A domain expert also pointed me to this blogpost, which may be affecting my inference as well: https://mumfordbrainstats.tumblr.com/post/126904300281/inconspicuous-double-dipping?fbclid=IwAR0nRVSqJQ1b0K6FIos7IfLJw5T6kXKkFM6tOu01TL2sU6Kk5XmxKrKMQqI
Comment: The 2nd model is singular. As for the denomnator degress of freedom, in a mixed model this is an approximation at best and woefully wrong at worst and underlines why I recommend not using p-values at all - they are little more than a test of sample size.
Answer: From the description given it does sound as though you have repeated measures within run, which is not accounted for in the first model. However, the 2nd model:
B_contrast_brain ~ B_contrast_behavior*A*C + (1|subject/cluster) + (1|subject/run)

has the following features:

fixed effects for B_contrast_behavior, A, C and all the interactions
random intercepts for subject and also for cluster varying within levels of subject
random intercepts for subject (again) and also for run varying within levels of subject.

So, you have specified random intercepts for subject twice, which may very well be the cause of the singular fit for the 2nd model. In order to just fit random intercepts for subject once you can use:
B_contrast_brain ~ B_contrast_behavior*A*C + (1|subject/cluster) + (1|subject:run)

where we specify random intercepts for run varying within levels of subject but without re-specifying random intercepts for subject again.
As for the p-values, in a mixed model these are approximations at best, so I would avoid them. Also, since you appear to have quite a large sample size, with rather small variance components for subject and cluster (based on the first model output) small p-values are to be expected.
Comment: Thank you!  Interestingly, when I run your suggested model with my winsorized DV (I didn't winsorize very aggressively; I brought the tails in to about 4 SD) I still got a singular fit that this time failed to converge, but when I ran it on my standardized DV with no winsorization it was fine.  I was only winsorizing as an attempt to eliminate the possibility that (really large) deviations from normality of the residuals in the model were the source of my strong effects.
Comment: On reflection, the strongest effects here are expected,  because they are not interactions with the behavior variable, but rather another way of representing contrasts that I also ran whole brain, and found effects in -- in different clusters, but still, if the three way interaction between A and B and C was powerful enough to generate a bunch of clusters that survived correction for multiple comparisons, it's not surprising that I see it reflected in a different way in my data here.
Comment: Do you have a link to where you describe your alternatives to p-values recommendations? Do you recommend confidence intervals?  Some kind of bootstrappy simulation test?
Comment: I didn't recommend an alternative to p-values. I don't need to know the probability of observing my data if the null hypothesis is in fact true, and that's all a p-value tells me.


Many warnings while deploy glassfish v3

Question: Hello when i am try deploy ear app in glassfish i have got many warning like that :
<code>[#|2013-01-14T14:12:52.404+0100|WARNING|glassfish3.1.2|org.apache.jasper.runtime.TldScanner|_ThreadID=34;_ThreadName=Thread-2;|PWC6351: In TLD scanning, the supplied resource file:/usr/local/glassfish3/glassfish/domains/pi/applications/person-ear-1.0-SNAPSHOT-rnull/APP-INF/lib/jaxb-api-2.1.jar does not exist
java.io.FileNotFoundException: /usr/local/glassfish3/glassfish/domains/pi/applications/person-ear-1.0-SNAPSHOT-rnull/APP-INF/lib/jaxb-api-2.1.jar (Nie ma takiego pliku ani katalogu)
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:214)
    at java.util.zip.ZipFile.<init>(ZipFile.java:144)
    at java.util.jar.JarFile.<init>(JarFile.java:152)
    at java.util.jar.JarFile.<init>(JarFile.java:89)

[#|2013-01-14T14:12:52.407+0100|WARNING|glassfish3.1.2|org.apache.jasper.runtime.TldScanner|_ThreadID=34;_ThreadName=Thread-2;|PWC6351: In TLD scanning, the supplied resource file:/usr/local/glassfish3/glassfish/domains/pi/applications/person-ear-1.0-SNAPSHOT-rnull/APP-INF/lib/resolver-20050927.jar does not exist
java.io.FileNotFoundException: /usr/local/glassfish3/glassfish/domains/pi/applications/person-ear-1.0-SNAPSHOT-rnull/APP-INF/lib/resolver-20050927.jar (Nie ma takiego pliku ani katalogu)
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:214)
    at java.util.zip.ZipFile.<init>(ZipFile.java:144)
    at java.util.jar.JarFile.<init>(JarFile.java:152
</code>
And other .... Its seems for me that glassfish dont use his own classloader but i am not sure....
Comment: What does _(Nie ma takiego pliku ani katalogu)_ mean?
Comment: Its means There is no file or directory
Answer: It is likely that misconfiguration in your pom.xml is causing this issue. The maven-war-plugin is likely to contain directives customising the class path for your MANIFEST.MF. In my case, I had:
<code> <manifest>
     <addClasspath>true</addClasspath>
 </manifest>
</code>
You should be able to solve it by simply commenting out/removing the directive.
Comment: This helped. Thanks

Many warnings while deploy glassfish v3


python slice set in list

Question: i would like to slice a set within a list, but every time i do so, i get an empty list in return.
what i try to accomplish (maybe there is an easier way):

i got a list of sets
each set has 5 items
i would like to compare a new set against the list (if the set already exists in the list)
the first and the last item in the set is irrelevant for the comparison, so only the positions 2-4 are valid for the search of already existing sets

here is my code:
result_set = ['1', '2', '3', '4', '5']

result_matrix = []

result_matrix.append(result_set)

slicing the set is no problem:
print result_set[1:4]

['2', '3', '4']

print result_matrix[:][1:4]

[]

i would expect:
[['2', '3', '4']]

Comment: Did you mean `result_matrix[0][1:4]` instead of `result_matrix[:][1:4]`?  OR `result_matrix.extend(result_set)` instead of `result_matrix.append(result_set)`?
Comment: the issue is that result_matrix[:] == result matrix. result_matrix has only one result set in it, the 0th one. You're asking it for the 1st result set through the 4th result set, which is an empty set.
Comment: I feel a sense of duty to point this out: `result_set` is a list, not a set.
Answer: >>> result_set = ['1', '2', '3', '4', '5']

>>> print result_set[1:4]
['2', '3', '4']

>>> result_matrix.append(result_set[1:4])
>>> result_matrix
[['2', '3', '4']]

Answer: I think this is what you want to do:
>>> target_set = ['2', '3', '4']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
True
>>> target_set = ['1', '2', '3']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
False

Generalising and making that a function:
def is_set_in_matrix(target_set, matrix):
    return any(True for l in matrix if list(target_set) == l[1:-1])

>>> result_matrix = [['1', '2', '3', '4', '5']]
>>> is_set_in_matrix(['1', '2', '3'], result_matrix)
False
>>> is_set_in_matrix(['2', '3', '4'], result_matrix)
True
# a quirk - it also works with strings...`
>>> s = '234'
>>> is_set_in_matrix(s, result_matrix)
True

Note that I have used l[1:-1] to ignore the first and last elements of the "set" in the comparison. This is more flexible should you ever need sets of different lengths.
Comment: Thank you very much, that is exactly what i needed. I altered just this: any([l for l in result_matrix if target_set **[1:-1]** == l[1:-1]])
Answer: Using result_matrix[:] returns the whole matrix as it is. You need to treat the result you want as a part of the array.
>>> result_matrix.append(result_set)
>>> result_matrix[:]
[['1', '2', '3', '4']]
>>> result_matrix[:][0]
['1', '2', '3', '4']
>>> result_matrix[0][1:4]
['2', '3', '4']

Also, as pointed out by falsetru:
>>> result_matrix.extend(result_set)
>>> result_matrix
['1', '2', '3', '4']
>>> result_matrix[1:4]
['2', '3', '4']

python slice set in list


Nullity and an Isomorphism

Question: I'm working on some introductory proofs in linear algebra, and I think that
I could use some help on this particular problem. I want to prove that a
linear surjective map $T: R \rightarrow W$ is an isomorphism if and only if
its nullity is zero.
Essentially, what I need to do is show that linear transformation will be
injective if and only if its kernel is 0. Consider the case where $T$ is
injective. I know that there is one vector in $R$ that maps to the zero
vector in $W$, but why must that necessarily mean that that such a vector is
the $0$ vector in $R$? I think I could use help with this part of the
proof. In the case where we assume that the kernel is 0, we know that only
the $O$ vector in $R$ is the only vector that maps to the $0$ vector in $R$,
but I can't seem to see how this would imply that the rest of the values
in $W$ that are mapped onto are mapped 1-to-1. I guess I could use some
clarification on the path to take on both of these directions.
Comment: For the first direction, assume that there are two vectors in $R$ which map to the same element, and use linearity of $T$ and the fact that the kernel is $0$ to show that they must be the same. For the other direction, by linearity $0$ is mapped to $0$, and you can use injectivity together with linearity to show that no other element can be mapped to $0$.
Answer: Hint: Use linearity of $T$.

Suppose $\ker T = \{0\}$, then consider $T(x) = T(y)$ for any $x,y \in R$. Then $$T(x) = T(y) \implies T(x) - T(y) = 0 \implies T(x-y) = 0 \implies x-y = 0 \implies x= y$$
 Thus $T$ is injective.
On the other hand, if $T$ is injective and $x$ is any element in $\ker T$ then $$T (x) = 0  = T(0) \implies x = 0$$
 Thus $\ker T$ has only $0$.
Answer: HINT: Try to prove that any linear transformation sends $0$ to $0$ (that is, if $T: V\rightarrow W$ is linear, then $T(0_V)=0_W$). To do this, use the fact that part of the definition of linearity is that for all $a, b$ in the domain of $T$,  $$T(a+b)=T(a)+T(b).$$ Do you see how to use this to get what you want?
Answer: You need to use the fact that the map is linear (without that hypothesis the result would not be true). If $v,v'\in R$ would be distinct vectors with $T(v)=T(v')$, what would $T(v-v')$ be?

Nullity and an Isomorphism