How to get the node ids of answers for a question in Drupal Services (REST)?

Question: I have a Drupal setup that is currently having a question and answers module.
I am able to read the question and answers by accessing http://mysite.tld/rest_endpoint/node/{nodeid} . However when I access a question, I am not able to get the nodeIds of all the answers to that question.
So I am looking to get the Node Ids for all the answers for a specific question.

What params/filters do I need to use in the Drupal Services GET call? I have services module.
Can I achieve this by doing a database query? I am not able to find a link between questions and answers in the DB too!

Any suggestions?
Answer: I didn't know what are question and answers modules that you used. My assumption is your answer and your question has a content type and they linked together. So if my assumption is correct here is the way that you can use for solving your problems:

Create a views will list all the answers of specific question(your question nid).
using Views Services to get the views that you created before and use your question (question nid) for the views parameter.

In case my assumption is wrong. Your have to create custom resource by your own to get the list of answers. In this way you must create your SQL sentences too. The reference for creating custom resource here
Comment: Thanks for your answer. Your assumption is correct. However as i am restricted on installign new modules, I was able to figure out the Mysql table for question/ answer references. I did a join with field_data_field_reference and node table to achieve this.
Answer: Have a look at this (exported) custom view related to the Answers module, which lists all existing answers for any of the existing questions:
$view = new view();
$view->name = 'answers';
$view->description = '';
$view->tag = 'answers, answers_best_answer, answers_userpoints, answers_voting';
$view->base_table = 'node';
$view->human_name = 'Answers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'All Answers';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'datatables';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'name' => 'name',
  'value' => 'value',
  'flagged' => 'flagged',
  'nid' => 'nid',
  'created' => 'created',
  'changed' => 'changed',
  'new_answers' => 'new_answers',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'value' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'flagged' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'desc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'changed' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'new_answers' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['elements'] = array(
  'search_box' => 1,
  'table_info' => 1,
  'save_state' => 1,
  'table_tools' => 0,
);
$handler->display->display_options['style_options']['layout'] = array(
  'autowidth' => 0,
  'themeroller' => 0,
  'sdom' => '',
);
$handler->display->display_options['style_options']['pages'] = array(
  'pagination_style' => 'full_numbers',
  'length_change' => 1,
  'display_length' => '25',
);
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['label'] = 'No Questions Blurb';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'No questions have been entered yet';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Relationship: Userpoints total: User */
$handler->display->display_options['relationships']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['relationships']['uid_1']['table'] = 'userpoints_total';
$handler->display->display_options['relationships']['uid_1']['field'] = 'uid';
/* Relationship: Content: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'node';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
  'function' => 'sum',
);
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['answers_related_question_target_id']['id'] = 'answers_related_question_target_id';
$handler->display->display_options['relationships']['answers_related_question_target_id']['table'] = 'field_data_answers_related_question';
$handler->display->display_options['relationships']['answers_related_question_target_id']['field'] = 'answers_related_question_target_id';
$handler->display->display_options['relationships']['answers_related_question_target_id']['required'] = TRUE;
/* Relationship: Flags: best_answer */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'node';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['required'] = 0;
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_answer';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Relationship: Userpoints total: User */
$handler->display->display_options['relationships']['uid_2']['id'] = 'uid_2';
$handler->display->display_options['relationships']['uid_2']['table'] = 'userpoints_total';
$handler->display->display_options['relationships']['uid_2']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'answers_related_question_target_id';
$handler->display->display_options['fields']['title']['label'] = 'Question';
/* Field: Userpoints total: Current total reputation */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_total';
$handler->display->display_options['fields']['points']['field'] = 'points';
$handler->display->display_options['fields']['points']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = 'Answered by';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['text'] = '[name]
([points])';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: Vote results: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['relationship'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['label'] = 'V';
$handler->display->display_options['fields']['value']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['value']['precision'] = '0';
/* Field: COUNT(Flags: Flagged) */
$handler->display->display_options['fields']['flagged']['id'] = 'flagged';
$handler->display->display_options['fields']['flagged']['table'] = 'flagging';
$handler->display->display_options['fields']['flagged']['field'] = 'flagged';
$handler->display->display_options['fields']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['flagged']['group_type'] = 'count';
$handler->display->display_options['fields']['flagged']['label'] = '';
$handler->display->display_options['fields']['flagged']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['flagged']['alter']['text'] = '';
$handler->display->display_options['fields']['flagged']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['flagged']['empty_zero'] = TRUE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = 'Answer';
$handler->display->display_options['fields']['nid']['link_to_node'] = TRUE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Content: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'node';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
$handler->display->display_options['fields']['changed']['label'] = 'Updated';
$handler->display->display_options['fields']['changed']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['changed']['date_format'] = 'short';
/* Field: Answers: Has new content */
$handler->display->display_options['fields']['new_answers']['id'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['table'] = 'answers';
$handler->display->display_options['fields']['new_answers']['field'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['label'] = 'New';
/* Sort criterion: Content: Nid */
$handler->display->display_options['sorts']['nid']['id'] = 'nid';
$handler->display->display_options['sorts']['nid']['table'] = 'node';
$handler->display->display_options['sorts']['nid']['field'] = 'nid';
$handler->display->display_options['sorts']['nid']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'answers_answer' => 'answers_answer',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Answers */
$handler = $view->new_display('page', 'Answers', 'page');
$handler->display->display_options['display_description'] = 'List of all answers';
$handler->display->display_options['defaults']['arguments'] = FALSE;
$handler->display->display_options['path'] = 'answers';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Answers';
$handler->display->display_options['menu']['description'] = 'All Answers';
$handler->display->display_options['menu']['weight'] = '1';
$handler->display->display_options['menu']['name'] = 'menu-answers-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';

/* Display: Answers by User */
$handler = $view->new_display('page', 'Answers by User', 'page_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Answers by author (uid = %1)';
$handler->display->display_options['display_description'] = 'List of all answers from a specific user';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'datatables';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'value' => 'value',
  'flagged' => 'flagged',
  'nid' => 'nid',
  'created' => 'created',
  'changed' => 'changed',
  'new_answers' => 'new_answers',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'value' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'flagged' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'desc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'changed' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'new_answers' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['elements'] = array(
  'search_box' => 1,
  'table_info' => 1,
  'save_state' => 1,
  'table_tools' => 0,
);
$handler->display->display_options['style_options']['layout'] = array(
  'autowidth' => 0,
  'themeroller' => 0,
  'sdom' => '',
);
$handler->display->display_options['style_options']['pages'] = array(
  'pagination_style' => 'full_numbers',
  'length_change' => 1,
  'display_length' => '25',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'answers_related_question_target_id';
$handler->display->display_options['fields']['title']['label'] = 'Question';
/* Field: Vote results: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['relationship'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['label'] = 'V';
$handler->display->display_options['fields']['value']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['value']['precision'] = '0';
/* Field: COUNT(Flags: Flagged) */
$handler->display->display_options['fields']['flagged']['id'] = 'flagged';
$handler->display->display_options['fields']['flagged']['table'] = 'flagging';
$handler->display->display_options['fields']['flagged']['field'] = 'flagged';
$handler->display->display_options['fields']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['flagged']['group_type'] = 'count';
$handler->display->display_options['fields']['flagged']['label'] = '';
$handler->display->display_options['fields']['flagged']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['flagged']['alter']['text'] = '';
$handler->display->display_options['fields']['flagged']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['flagged']['empty_zero'] = TRUE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = 'Answer';
$handler->display->display_options['fields']['nid']['link_to_node'] = TRUE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Content: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'node';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
$handler->display->display_options['fields']['changed']['label'] = 'Updated';
$handler->display->display_options['fields']['changed']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['changed']['date_format'] = 'short';
/* Field: Answers: Has new content */
$handler->display->display_options['fields']['new_answers']['id'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['table'] = 'answers';
$handler->display->display_options['fields']['new_answers']['field'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['label'] = 'New';
$handler->display->display_options['path'] = 'user/%/answers';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Answers';
$handler->display->display_options['menu']['description'] = 'Answers';
$handler->display->display_options['menu']['weight'] = '5';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';

You can see it at work in the demo site of the Answers module. It uses the dataTables format, but you could easily replace that with any views display format you'd want.
By using this view, you should be able to:

tune the fields, sorting, etc to fit your needs.
addng a filter for the question for which you want to retrieve all answers.
use the Services Views  module to get the nodeIds of all the answers to that question.


Pegar id dos ckeck box marcado

Question: Preciso pega o id dos check box marcados. Estou montando os check dinamicamentes da forma a seguir:

        <input id="codigoPessoaPresente" value="'+pessoa.COD_IDENT_PESSO+'" type="hidden">
        <input type="checkbox" checked>
     '+ pessoa.TXT_NOMEX_PESSO +'

Como posso fazer isto ?
Comment: Veja este código usando jquery. http://codepen.io/anon/pen/bVWXaK?editors=101. O Funcionamento é bem simples.
Answer:

function cbx1(){
    var arr = []; /* Cria array com todos os names dos check selecionados */
    var itens = document.querySelectorAll('.check:checked'); /* Busca todos os elementos com o class .checked e que possuam um atributo checked. Nesse caso somente radio e checkbox possuem tal atributo */
    for(var i in itens)
       arr.push(itens[i].name); /* Inclui name do elemento em um array*/

    alert(arr);
    return arr /* Retorna esse array */;
}

function cbx2(){
    var arr = [];/* Cria array com todos os names dos check selecionados */
    $('.check:checked').each(function(item){ /* Busca todos os elementos com o class .checked e que possuam um atributo checked. Nesse caso somente radio e checkbox possuem tal atributo */
        arr.push($(this).attr("name"));/* Inclui name do elemento em um array*/
    });
    alert(arr);
    return arr /* Retorna esse array */;
}

function cbx3(){
    var arr = []/* Cria array com todos os names dos check selecionados */;
    var inputElements = document.getElementsByClassName('check') /* Busca todos os elementos com o class check */;
    for(var i=0; inputElements[i]; ++i){
        if(inputElements[i].checked) /* Verifique se o elemento em questão está com o atributo checked marcado */
        arr.push(inputElements[i].name) /* Inclui name do elemento em um array*/;
    }
    alert(arr)
    return arr/* Retorna esse array */;
}
<input class='check' type='checkbox' name='check1' />
<input class='check' type='checkbox' name='check2' />
<input class='check' type='checkbox' name='check3' />
<input class='check' type='checkbox' name='check4' />
<input class='check' type='checkbox' name='check5' />
<button onclick='cbx1()'>Pegar cbx1</button>
<button onclick='cbx2()'>Pegar cbx2</button>
<button onclick='cbx3()'>Pegar cbx3</button>

No HTML:
 <input type="checkbox" checked class="messageCheckbox">

Navegadores mais novos:
function cbx1(){
    var arr = [];
    var itens = document.querySelectorAll('.check:checked');
    for(var i in itens)
        if(itens[i].checked)
            arr.push(itens[i].name);

    console.log(arr);
    return arr;
}

Usando jQuery:
function cbx2(){
    var arr = [];
    $('.check:checked').each(function(item){
        arr.push($(this).attr("name"));
    });
    console.log(arr);
    return arr;
}

Javascript puro sem jQuery:
function cbx3(){
    var arr = [];
    var inputElements = document.getElementsByClassName('check');
    for(var i=0; inputElements[i]; ++i){
        if(inputElements[i].checked)
        arr.push(inputElements[i].name);
    }
    console.log(arr)
    return arr;
}

Comment: Desta forma ele irá pegar todos os checkados ?
Comment: Gostaria que explica-se o código
Comment: Se você vai poder ter mais de um checkbox marcado irá precisar utilizar vários names. Um para cada marcado. Se for isso fale que mudou meu exemplo. Nesse caso que passei seria para pega um valor de um único checkbox
Comment: sim, Porque cada check é para uma pessoa, isso é um sistema de presença.
Comment: OK, vou editar e já posto
Comment: @RenanRodrigues veja agora
Comment: tem como explicar o codigo ?
Comment: Tem sim, mais agora estou enrolado, mais tarde posto auqi OK?
Comment: ok, fico aguardando
Comment: Embora esta resposta esteja a resolver o problema do user, a falta de explicação da mesma é ... mau.
Comment: @RenanRodrigues da uma olhada no código que editei
Comment: Muito obrigado pelo auxilio.
Comment: Tive alguns contra-tempos no meu trabalho ontem e por isso não consegui postar antes. Abraços!
Answer: function getIdCheckBoxByLi(_this){
    var id = null;
    if(jQuery(_this).is(':checked')){
        id = jQuery(_this).parents('li:eq(0)').find('input[type="hidden"]').attr('id');
    }
    return id;
}

jQuery('input[type="checkbox"]').on('click', function(e){
    var id;
    if(id = getIdCheckBoxByLi(this)){
        console.log(id);
    }
});

Pegar id dos ckeck box marcado


assign a double value to timer interval

Question: I am trying to assign a huge number of (milliseconds) to a timer interval, but i got this crash on "timer.Enabled = true" line !
The Exception Says :

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Number must be either non-negative and less than or equal to Int32.MaxValue or -1.

This is my code:
    CurrencyTimer.Interval = 2626086891.0;
    CurrencyTimer.Enabled = true;
    CurrencyTimer.AutoReset = true;
    CurrencyTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
    CurrencyTimer.Start();

The Exception point to this line : CurrencyTimer.Enabled = true;
Thanks,
Comment: You want to wait for `30` days???? `2626086891/1000/60/60/24 = 30...`
Comment: @M.kazemAkhgary: And 9 hours, 28 minutes ;-)
Comment: Possible duplicate of [Why is the data type of System.Timers.Timer.Interval a double?](http://stackoverflow.com/questions/11610611/why-is-the-data-type-of-system-timers-timer-interval-a-double)
Answer: The exception (and the documentation) is fairly clear about that the interval has to be between 0 and int.MaxValue. So, don't assign a value larger than that.
For very long timer intervals you may have to split your interval in shorter intervals and count yourself. I'd also be curious why you think you need a 30-day timer interval ...
Comment: but the interval type is double !
Comment: @Qutaiba oh well, then look at this http://stackoverflow.com/questions/11610611/why-is-the-data-type-of-system-timers-timer-interval-a-double
Comment: you should use schedulers in windows instead or some kind of schedulers like that @Qutaiba
Comment: Reading the docs sometimes helps. _The value must be greater than zero, and less than or equal to Int32.MaxValue_
Comment: @Qutaiba: So what? An array index is also an `int` and the valid values are only a subset of the full range. That's not unusual at all.
Comment: @Steve yes i know that, but the interval type is double !
Answer: Use:
Threading.Timer

The constructor has several overloads two of which accept TimeSpan or Int64 values. The documentation does not mention limits on the values except for the intrinsic limitations of the data types.

assign a double value to timer interval


Getting R square value from ctree

Question: Is there a way to retrieve the R square value from a ctree model? Or is this impossible with how the function runs?
Thanks!
Answer: I don't think so -- however you can extract predictions using predict(your_model) and just calculate it on your own.
Comment: Scott, I think @mbq is referring to the fact that $R^2 = {\rm cor}({\rm predicted \ values}, {\rm actual \ values})^2$
Comment: Could you continue to explain what you mean? Thanks!

Getting R square value from ctree


How to print duplicate letters in a string with their count number in C?

Question: I have been implemnting an algorithim for counting and printing duplicate letters (two times or more) in a C string.
Example :
If input string was : "Hello There"
The output should be :
e - 3
h - 2
l - 2

My current code has been printing what i need,but it doesn't consider capital letters, it also keep giving me the message stack smashing detected (core dumped) . So, it doesn't work properly and I'm not sure why :
#include <stdio.h>
#include <string.h>

int main()
{
   char string[10];
   int c = 0, count[26] = {0};

   printf("Enter a string of size [10] or less:\n");
   gets(string);

   while (string[c] != '\0')
   {
      /**reading characters from 'a' to 'z' or 'A' to 'Z' only
          and ignoring others */

      if ((string[c] >= 'a' && string[c] <= 'z') || (string[c] >= 'A' && string[c] <= 'Z'))

      {
         if (string[c] >= 'a' && string[c] <= 'z')
         {
         count[string[c]-'a']++;
         }
         else if (string[c] >= 'A' && string[c] <= 'Z')
         {
         count[string[c]-'A']++;
         }
      }

      c++;
   }

   for (c = 0; c < 26; c++)
   {
      /** Printing only those characters
          whose count is at least 2 */

      if (count[c] > 1)
         printf("%c - %d \n",c+'a',count[c]);
   }

   return 0;
}

Answer: "Hello There" doesn't fit in a character array of size 10. This is good example of why you should not use gets.
Use:
fgets(string, sizeof(string), stdin);


Calculating income elasticity of demand

Question: My model is as follows:
$$Y=\beta_0+\beta_1X_1+\beta_2X_2+\beta_3X_3+\beta_4X_4.$$
My income variable is represented by $X_2$. When it comes to calculating the income elasticity of demand (demand being represented by $Y$) I am aware that the formula is $\beta \frac{\bar{I}}{\bar{Q}}$, where $I$ is income and $Q$ is the demand variable.
My question is, when running a least squares regression, using EViews, would I run a regression with my $Y$ dependent variable and all my other independent variables ($X_1, X_2, X_3, X_4$ and the intercept) or do I just run the regression with $Y$ and $X_2$? (In this case are we assuming that all other variables do not matter? Or that we are holding these other variables constant?).
Moreover, I am aware that one can log the values in a regression and then extract the coefficient value as the elasticity value without needing to conduct more calculations. In this case, would we run the regression with $\log{Y}$ dependent variable and all my other independent variables logged ($X_1, X_2, X_3, X_4$ and the intercept) or do I just run the regression with $\log{Y}$ and $\log{X_2}$, or do I include the other independent variables and only log the $Y$ variable and $X_2$ variable.
I hope my question makes some sense. Essentially, I want to understand how one would calculate the income elasticity of demand in EViews based on the above model.
Any help with be greatly appreciated. Thank you.
Answer: To get a better estimation on the income elasticity of demand you should include all the X-variables in the model. The estimated coefficient you will get for your income elasticity variable in the complete model will be considered "Income elasticity of demand while holding other X-variables constant". If you omit the other X-variables, you do indeed assume that they do not have an effect on demand and thus do not belong in the model.
If you omit the other X-variables from your model while they do actually have an effect on demand, you will be committing a specification error and your estimations will be biased, inconsistent and your standard error estimations will be invalid. This will basically make your estimations very misleading.
Whether to take the log on one or both sides - or only on individual variables depends on the model and should be based on the specific model and previous research on the topic. Taking the log of a variable is often used to stabilize the variance of the variable or to show some sort of relative change in the variable. Hope this helps!

Calculating income elasticity of demand


Dúvida com Mysqli e PHP OO

Question: Eu tenho o seguinte trecho de código:
public function registerUser($link, $nome, $sobrenome, $apelido) {
    $sql = "INSERT INTO estudo_oo (id, nome, sobrenome, apelido) VALUES ('', '$nome', '$sobrenome', '$apelido') ";
    if(!mysqli_query($link, $sql)) {
        die('Error: ' . mysqli_error($link));
    }
}

E minha duvida é: Eu teria que passar SEMPRE as variáveis por parâmetro ali na função? Porque tipo, se eu tiver um formulário com vários campos por exemplo, eu teria realmente que passar todas variáveis ali?
Eu fiz uns testes e tentei salvar o form sem passar as variáveis por parâmetro, mas não tive sucesso, daí acabou me surgindo essa dúvida.
Answer: Respondendo mais diretamente a sua pergunta:

Eu teria que passar SEMPRE as variáveis por parâmetro ali na função?

Em algum momento você tem que passar os argumentos, seja definindo propriedades da classe, ou como argumentos do método. Qual das duas formas (ou ambas) você vai usar depende apenas das suas decisões para o projeto.
Answer: Na orientação a objetos temos as propriedades da classe, que nada mais são que variáveis dentro do escopo da classe.
O mysqli permite tanto o método procedural (que é o que você está usando) como método orientado à objeto.
Não vou entrar em detalhes mais aprofundados, mas segue um exemplo simples de como utilizar as propriedades:
<?php

class Usuario {

    // A propriedade com uma conexão
    protected $dbConnection;

    // Método construtor para passagem do parâmetro (nesse caso sua conexão com banco)
    public function __construct(mysqli $dbConnection)
    {
        // Injeta a conexão criada na classe
        $this-> dbConnection = $dbConnection;
    }

    public function registerUser($nome, $sobrenome, $apelido)
    {
        // Recomendo o uso de prepared statments para inserir os parâmetros
        $sql = "INSERT INTO estudo_oo (id, nome, sobrenome, apelido) VALUES ('', '$nome', '$sobrenome', '$apelido') ";

        // Procure usar Exceptions para tratamento de erros
        try {
            $this->query($sql);
        } catch (mysqli_sql_exception $e) {
            return $e->message;
        }

        return true;

    }
}

// Como usar:

$link = new mysqli('localhost', 'user', 'pass');

$usuario = new Usuario($link);
$usuario->registerUser('João', 'Lucas', 'Jão');

Essas foram só algumas dicas de como implementar. Outras sugestões são usar PDO ou invés de MySqli e ler um pouco mais do básico no desenvolvimento em PHP moderno.
Answer: Você pode definir valores padrão para os parâmetros que não pretende passar sempre:
public function registerUser($link, $nome, $sobrenome=null, $apelido=null) {

}

Nota: como você está usando mysqli, recomendo fortemente utilizar prepared statements em vez de concatenar as variáveis diretamente na query.
Comment: Se você usar `bind_param` e passar `null`, o valor `NULL` será inserido.
Comment: Bateu uma dúvida: passar uma variável nula em um prepared statement irá inserir o valor null no banco ou uma `string` vazia?

Dúvida com Mysqli e PHP OO


Steps to Create a copy of a Drupal 7 website using cpanel?

Question: I want to create an exact copy of an existing drupal 7 website in a subdomain. What steps should I take to do this using just cpanel?
Comment: Did you install Drupal via Fantastico or cPanel?
Comment: As side note, you are using a unregistered account, which is valid just on a single computer, and a single browser. If you are using an unregistered account with more browsers, or more computers, you are using different accounts, not the same accounts. If you need to use more than one computer, or browser, consider registering an account by adding an [OpenID account](http://drupal.stackexchange.com/users/login?noauto=true&returlUrl=%2Fusers%2Fcurrent), or you will not able to comment on your questions.
Answer: Here are the steps I would take in cloning the site. First, Create the subdomain. Then copy all the files from the live site to the subdomain. Then I would back up the database. Create a new database and import the backup into that. Assign the user from the first database to the second one. Then change the settings.php file to read from the second database. Also, if you have a base url set in settings.php you would need to change that as well. Hope that helps.
Comment: If the original site is live, I would put in maintenance mode first.
Answer: if the site is coming from another cpanel, there are export/import features for entire sites.
otherwise there's no cpanel specific way to move a drupal site that I am aware of.


Robust distribution fitting?

Question: I'm trying to fit a Johnson Unbounded distribution to a set of financial data with kurtosis and skewness, and also outliers. I started using Maximum Likelihood Estimators (MLE) but one outlier has too much influence on the estimated parameters.
Please can you point me to more robust method to estimate the parameters, one where outliers don't have too much influence.
I found a quantile estimator for the distribution parameters. Is this method more robust than MLE?
Comment: The presence of an outlier that badly affects your estimate suggests that the model may not fit well. Quantile estimation is often less affected by outliers, yes, but it's not *always* "more robust" than MLE. In some situations it will also depend on the type of robustness you mean.
Answer: The Johnson $S_U$ density is:
$$ f(x)  =  \frac{\delta  \exp \left(-\frac{1}{2} \left(\gamma +\delta  \sinh ^{-1}\left(\frac{x-\xi }{\lambda }\right)\right)^2\right)}{\sqrt{2 \pi } \lambda  \sqrt{\frac{(x-\xi )^2}{\lambda ^2}+1}}$$
with domain of support on the real line, and where the parameters ($\gamma$, $\delta$, $\xi$, $\lambda$) are implicitly defined as functions of the first 4 moments of the population. So if you know the first four moments, one can find the exact $S_U$ model to arbitrary precision. More usually, though, we have estimates of the first four moments.
For fitting the Johnson $S_U$ (unbounded) system, I'd recommend the Tuenter (2001) state of the art algorithm:

Tuenter, H. J. H. (2001), An algorithm to determine the parameters of SU-curves in the Johnson system of probability distributions by moment matching, Journal of Statistical Computation and Simulation, 70(4), 325-347.

Here is a quick example to illustrate the idea using mathStatica which implements the Tuenter (2001) algorithm to arbitrary numerical precision ...
Example
Here is some raw (pseudo-random) data:
dist =  NoncentralStudentTDistribution[12, 7];
data  = RandomReal[dist, 50000];

We shall assume that we do not know the distribution from which this data has been drawn, and see how well we do in fitting it. The sample mean is:
mean = Mean[data]

7.4801

An estimate of the vector ($\mu_2$, $\mu_3$, $\mu_4$) is given by:
muvec = Table[UnbiasedCentralMoment[data, r], {r, 2, 4}]

{4.07636, 9.40789, 100.322}

Step (i): JohnsonPlot[muvec] calculates $\beta_1$ and $\beta_2$ from muvec, and then indicates which Johnson Type is appropriate for this data set by plotting a large black dot at ($\beta_1$, $\beta_2$):
JohnsonPlot[muvec]

Step (ii): The large black dot lies in the Johnson $S_U$ zone. The fitted Johnson $S_U$ density $f(x)$ and its domain of support are then given by:
{f, domain[f]} = JohnsonSU[mean, muvec, x]

Finally, the FrequencyPlot function compares the empirical pdf (blue) of the data with the fitted Johnson $S_U$ pdf $f(x)$ (red dashed) we have just derived:
FrequencyPlot[data, f]

and

Outliers can be a problem with any method, including method of moments estimation and MLE. If you do not know the actual population moments, and you have very large kurtosis, the problem is not really method of moments estimation per se ... but rather that your estimates of the 3rd and 4th central moments can be unreliable ... the software will actually warn you ... and perhaps an appropriate course of action is to consider removing one or two large outliers from your data and trying again, and perhaps trying multiple different methods including MLE. Which leaves the questions in reply:

How large is the kurtosis for your data?
Do you know the first 4 raw moments for your data set?
And how large is your data set?
Comment: Thank you wolfies for this great answer. However, do you know more robust curve fitting method? I haven't tried Tuenter's method, but seems to me that a moment-matching method is less robust than a percentile estimation method, due to the unreliability of the estimation of the moments.

Robust distribution fitting?


What is the name of the transformation $B \mapsto C^TBC$?

Question: (Note: in what follows, $B$ can be an arbitrary $n \times n$ matrix over $\mathbb{R}$ or $\mathbb{C}$, but $C$ must be an invertible matrix over the same field, for reasons I will discuss.)
If $C$ is orthogonal, and thus $C^T=C^{-1}$, I know that this coincides with a similarity transformation $B \mapsto P^{-1}BP$, which is the change of coordinates formula for a linear operator.
However, I am interested in the change of coordinates formula for quadratic forms (and in particular projective changes of coordinates for conic sections in $\mathbb{CP}^2$) and this is definitely only $B \mapsto C^T B C$ and not the same thing as matrix conjugation/similarity transformation.

Question: What is the name of the operation $B \mapsto C^TBC$?
I want to know the name of this operation so I can read up about it more.

What I know already: this type of transformation, unlike a similarity transformation, does not preserve the exact numerical value of the spectrum of $B$, but it preserves the number of zeroes in the spectrum (at least for symmetric and other diagonalizable matrices, but I suspect this holds in general due to the multiplicative rule for determinants). This fact can be used to show that the conic sections in $\mathbb{CP}^2$ form three distinct classes under projective changes of coordinates. Also, the fact that bilinear forms transform this way under changes of coordinates, instead of via similarity transformations like linear operators do, shows that they are a different type of second-order tensor compared to linear operators.
Anyway, I would like to know a specific way to refer to this transformation so I can look it up in the literature and feel more confident about my ability to tell it apart it from similarity transformations.
Answer: The standard terminology for a change of basis for the matrix representation of a quadratic form is matrix congruence.


Is the WASP calculation in cricket logically correct?

Question: During the first ODI of India's tour of New Zealand 2014, I could see a new term named WASP on the right side of the TV screen on Sony Six - the channel broadcasting the match.

When I was searching about that, I found that it means, Winning And Scoring Prediction whose value will be changed during the match.
ie, during first innings the predicted score will be displayed and during the second innings the winning percentage will be shown.
The formula for calculating WASP is mentioned here.
I can't understand it clearly.
Can anyone explain it with an example?

Is it logically correct?
  How does a mathematical formula differentiate
  a player with form and without form?
   How much values will be given for
  pitch conditions according to the situation and climate?
  The
  performance of players like Kohli may be same in all countries, but
  what about players like Ashwin and Rohit in overseas pitches?

I have many more questions, but all of them are under one topic,

Logical explanation of the formula used for calculating WASP in
  cricket.
Answer: Any number of new metrics can be introduced to predict the winning percentages.
A very basic metric would be to use the extrapolation of the current run-rate of the chasing team to determine the winning percentage.
Another metric would be to calculate the current form(average of the batsmen-to-come over the past N games(or N months)) and use it to find a projected score. Based on this, one could probably calculate another winning percentage metric. We could add more variables to the mix, such as bowling strike rate, batting strike rate, average score at that stadium, average score by that team in that particular country, and so on.
Even if I added a few more variables to WASP account for a person's form, it would still be incomplete, since it doesn't account for his overseas form/home form, pitch conditions, his mental state and so on.
The point is that at the end of the day, WASP is just yet another metric to make a guess of the probable winning percentage and that there can be no all-encompassing metric.
Answer: They might have considered all the conditions. But still I personally don't think its logical especially when a batsman like MSD is playing at the crease. And how could they judge a batsman(Binny)'s ability who hasn't played a match at all in the today's match with a mathematical formula?
It might be closer to the actual results in many cases, but still Mathematics can't be applied on everything.


WebSockets JSR 356 Spring integration @ServerEndpoint

Question: Problem: @Autowired beans in @ServerEndpoint class are null
How can I make sure that this WebSocketController class below will be injected with beans, that is how can I make it managed by Spring? I can connect to the websocket so it works but gameService is always null inside the WebSocketController class instance, so I think that it is created by tomcat somehow and not Spring.
I'm using Spring boot. I just need to figure out how to inject beans into this websocket controller class.
WebSocketController class
@Component
@ServerEndpoint("/sock")
public class WebSocketController {

    @Autowired
    private GameService gameService;

    private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());

    @OnMessage
    public void handleMessage(Session session, String message) throws IOException {

        session.getBasicRemote().sendText(
                "Reversed: " + new StringBuilder(message).reverse());
    }

    @OnOpen
    public void onOpen(Session session) {
        clients.add(session);
        System.out.println("New client @"+session.getId());
        if (gameService == null) System.out.println("game service null");
    }

    @OnClose
    public void onClose(Session session) {
        clients.remove(session);
        System.out.println("Client disconnected @" + session.getId());
    }
}

GameService interface and implementation
public interface GameService {
    List<Character> getCharacters();
}

@Service
public class GameServiceMockImpl implements GameService {

    @Override
    public List<Character> getCharacters() {
        List<Character> list = new ArrayList<>();
        list.add(new Character("aaa","1.png",100));
        list.add(new Character("aaa","2.jpg",100));
        list.add(new Character("aaa","3.jpg",100));
        return list;
    }
}

Application class
@SpringBootApplication
public class App  {

    public static void main(String args[]){
        SpringApplication.run(App.class,args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

EDIT:
Using Spring 4 WebSockets doesn't work at all, I can't even connect via a browser.
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/myHandler");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new MyHandler();
    }

}

public class MyHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println(message.getPayload());
    }

}

Answer: You are trying to integrate Spring and Java WebSocket API. A class annotated by @Component is registered to a spring bean and its instance is managed by spring but if a class is annotated by @ServerEndpoint it is registered to a server-side WebSocket endpoint and every time the corresponding endpoint's WebSocket is connected to the server, its instance is created and managed by JWA implementation. We you can't use both annotations together.
Either you can use CDI injection(your server should also support)
@ServerEndpoint("/sock")
public class WebSocketController {

    @Inject
    private GameService gameService;

Or have a look on this doc, Spring 4 has support for WebSocket
Comment: I had to allow connections from other origins and it works. So in the end I'm using Spring 4 websockets.
Comment: But just for tests. Eventually everything will be on the server
Comment: Thanks for answering. I'd rather use Spring 4 WebSocket and I want to use the 'direct approach' without SockJS and stuff like that. So I created TextWebSocketHandler and WebSocketConfigurer. But it doesn't work. I cannot connect from a browser. It says in console that it mapped the given url to a text handler but still can't connect. I added code in the main post.
Answer: Maybe this article can help:
https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support
You can use dependency (with spring version > 4)
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${spring.version}</version>
</dependency>

And then simply
@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)
public class WebSocketEndpoint {

    @Inject
    private BroadcastService broadcaster;

Comment: Nice and easy. That's the one that made it work for me!
Comment: Could you briefly explain this code.Please! i not figure out how to use this piece of code.
Comment: @Sushant You can read the article https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support - all explanations there in the best form


How to cancel added product to cart if previous order has same commerce-product creator id

Question: I need this rule on before add product to cart react event, not after save commerce order.
I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.
With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.
Any suggest how to solve this using rule??
Answer: tl;dr - Rules is really the place to handle this. You need to hook into the add to cart form's validate/submit handlers and take care of it in there.
The best way to handle this is to look into the answer provided here: How do I prevent a product from being added to the cart?
This answer was originally written to do that very thing: to prevent a product from being added to an order if some criteria were met (and the context was a marketplace multi-cart as well).


Restrictions on Windows Web Server 2008?

Question: I'm considering replacing a dedicated windows web server server I run for several clients - the server is hosted at an ISP, and I currently I have a Windows 2003 standard server with SQL Server 2000 standard edition installed.  There is a very limited amount of other software, including

A third party SMTP server
PHP
ScriptFTP (automatic ftp for backups)

The server is accessed by remote desktop. It's getting a little long in the tooth now - just 1Gb ram - but there's been no significant performance issues.  The server runs one moderate use/visibility public webservers, a couple of server based application sites (using PHP/SQLServer) and a dozen or more very low traffic sites.
The ISP, who I'm pretty happy with, is now offering a higher spec machine for about 30% less than I'm paying, with the exception that the OS would be Windows Web Server 2008 x64.  I've no experience with this edition but from Microsoft's spec it would seem ok.  Can anyone tell me -

Are there any significant restrictions with the web edition I should be aware of?
Would there be any issue installing SQL Server 2005 standard x32 on the server?
Any problems with PHP - or other software?

The temptation to reduce costs and increase spec is significant, but the web edition restriction is an unknown.
Answer: There are some restrictions from both a licensing perspective and a technical perspective. The basic licensing restriction is that whatever is installed must be used for your web sites that are in use on that machine. So for example, the SQL Server you install can only be used by the web sites on the server, not by sites on other systems. The SMTP server can only be used to send emails from the sites on the system, not by other servers, etc.
From a technical perspective, the 3 big limitations I can think of (that probably don't affect your use case) are:

limited to 10 open file shares at a time
no terminal services installation (you can use remote desktop administrative services)
cannot be a hyper-v host

Here is the Microsoft licensing information for Web edition:
http://www.microsoft.com/windowsserver2008/en/us/licensing-web-server.aspx
And here is the list of technical limitations (compared to other editions):
http://www.microsoft.com/windowsserver2008/en/us/r2-compare-specs.aspx
I'm certainly no licensing expert but your use case seems to fit into the web edition model.


How the input file gets split into chunks by the map-reduce framework?

Question: I have an iterative mapreduce job in which, when a chunk, let's say Chunk i, is read by a mapper some information regarding the records within this chunk is stored in an auxiliary file, called F_i. In the next iteration (job), a different mapper might read Chunk i. However, this mapper must update some information in auxiliary  file Fi. Is there any mechanism to do this?
I believe if we can get a way to distinguish between different chunks we can get it solved. e.g. if each chunk has a unique name, then the mapper can simply read the auxiliary  file for the chunk it has fed by.
Comment: I don't understand what you are asking.
Comment: Seems a little clearer.  What would you like from us?
Comment: I edited the question, it is more clear now.
Comment: I would like to see whether there is any way (mechanism) for doing this.
Answer: Use a custom counter. Update the counter in each map as you keep processing your splits starting from 1. So, for split#1 counter=1. And name the file accordingly, like F_1 for chunk 1.
Apply the same trick in the next iteration. Create a counter and keep on increasing it as your mapppers proceed. Check the counter value everytime you enter in a mapper and read the file which has the same number in its name as this counter's value. For example :
Suppose in the first iteration you processed 5 chunks. This means you end up with 5 files, F_1, F_2 and so on. Now, in the second phase you'll again start from the chunk 1. Create the counter update it by 1. Now check the counters value inside the mapper itself and if the value is 1, you know that you have to read the file named File_1.
Comment: in the next iteration, how can a mapper knows which chunk it is processing?
Comment: Thanks, but is there any guarantee that the mapper which is given the first chunk always has value 1 as its counter? (when we run multiple mappers in parallel) That is, in the 1st iteration, a mapper may get chunk 1 and counter 1 and in the next iteration gets chunk 1 and counter 3.
Comment: Better check it for yourself.
Comment: You would have that guarantee if your custom counter is thread-safe, and you includ thread-locking mechanisms that insure data integrity


Heart rate monitor doesn't give feedback

Question: I'm trying to get a display of the heart rate of the person wearing the smartwatch (LG Urbane). However the sensor never gives any feedback. I tried multiple solutions on stackoverflow, but none made a difference. I have added a request for permission to use body sensors in both my mobile and my wearable Manifest, but I have never received a popup asking for said permission. Uninstalling the app and reinstalling it didn't help either.
This is my Activity:
public class Monitor extends WearableActivity implements SensorEventListener{

    // /Users/Lieven/Library/Android/sdk/platform-tools/adb connect 192.168.1.15
    // /Users/Lieven/Library/Android/sdk/platform-tools/adb -s 192.168.1.15:5555 uninstall be.ehb.dt.finalwork_lievenluyckx_v001

    private final String LOG_TAG = "Monitor";

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

        Log.d(LOG_TAG, "onCreate");

        //JUISTE LETTERTYPE IN TEXTVIEWS ZETTEN
        Typeface custom_font = Typeface.createFromAsset(getAssets(),  "fonts/brusselineregular.ttf");

        TextView monitor_emotion_text = (TextView) findViewById(R.id.monitor_emotion_text);
        TextView monitor_bpm_counter = (TextView) findViewById(R.id.monitor_bpm_counter);
        TextView monitor_bpm_label = (TextView) findViewById(R.id.monitor_bpm_label);

        monitor_emotion_text.setTypeface(custom_font);
        monitor_bpm_counter.setTypeface(custom_font);
        monitor_bpm_label.setTypeface(custom_font);

       /*
       * SENSOR TUTORIAL
       * https://www.tutorialspoint.com/android/android_sensors.htm
       * DOOR tutorialspoint
       * */

        SensorManager sensorManager;
        sensorManager = (SensorManager)  this.getSystemService(SENSOR_SERVICE);

        Sensor heartRateSensor;
        heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);

        sensorManager.registerListener(this, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
        Log.d(LOG_TAG, "Listener registered");

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        //Log.d(LOG_TAG, event.sensor.getType() + "");
        if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
            String msg = "" + (int)event.values[0];
            Log.d(LOG_TAG, msg);
        }
        else{
            Log.d(LOG_TAG, "Unknown sensor type");
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.d(LOG_TAG, "Accuracy changed to " + accuracy + "");
    }

    @Override
    public void onEnterAmbient(Bundle ambientDetails) {
        super.onEnterAmbient(ambientDetails);
        updateDisplay();
    }

    @Override
    public void onUpdateAmbient() {
        super.onUpdateAmbient();
        updateDisplay();
    }

    @Override
    public void onExitAmbient() {
        updateDisplay();
        super.onExitAmbient();
    }

    private void updateDisplay() {
        if (isAmbient()) {
           /* CODE VOOR WANNEER HET SCHERM IN STANDBY VALT */
        } else {

        }
    }

}

This is my Wearable Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="be.ehb.dt.finalwork_lievenluyckx_v001">

    <uses-feature android:name="android.hardware.type.watch" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.BODY_SENSORS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/billie_coverdefault"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@android:style/Theme.DeviceDefault">
        <uses-library
            android:name="com.google.android.wearable"
            android:required="false" />

        <activity
            android:name=".Monitor"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.DeviceDefault.Light">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

This is my first time creating an application for a wearable device, and it feels like it's very hard to get any helpful documentation on it.
build.grade (WEAR)
apply plugin: 'com.android.application'

android {
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    }

    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "be.ehb.dt.finalwork_lievenluyckx_v001"
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:wear:26.0.0'
    compile 'com.google.android.support:wearable:2.0.3'
    provided 'com.google.android.wearable:wearable:2.0.3'
}

build.gradle (MOBILE)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "be.ehb.dt.finalwork_lievenluyckx_v001"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        jackOptions {
            enabled true
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    wearApp project(':wear')
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.mpatric:mp3agic:0.9.0'
    testCompile 'junit:junit:4.12'

}

Comment: What are your minimum and target API levels?
Comment: Edited them into the post!
Comment: Are you sure that the person wearing the device is alive?
Comment: Well, since I'm typing this, I'm pretty sure I am :(
Answer: From the Android guide for permissions:

If the device is running Android 6.0 (API level 23) or higher, and the app's targetSdkVersion is 23 or higher, the app requests permissions from the user at run-time.

Your target API is 25 and body sensors are considered "dangerous permissions," so you have to request permissions at run-time. Take a look at this for guidance on requesting permissions at run-time.
Comment: Oh, I must've read over the "run-time" part. I'ill check it out now!
Comment: They do _not_ make it obvious. I had a similar issue not that long ago. Let me know if it works!


Constructing sets involving predicates. Let $P(x),Q(x)$ be predicates over a set $X$?

Question: Let $X$ be a set and $P(x),Q(x)$ be predicates over $X$. Consider the sets $$Y = \{y\in X\mid P(y)\}$$ $$Z = \{z\in X\mid Q(z)\}$$
Complete the following sentences with quantified propositional formulas involving P, Q

$Y \subseteq Z$ if and only if
$Y \cap Z = \emptyset$ if and only if
$Y \cup Z = X$ if and only if

Questions

What does the set notation look like for: Let $X$ be a set and $P(x),Q(x)$ be predicates over $X$ ?
I'm given that the statement $Y\cap Z = X \Leftrightarrow\forall x \in X [P(x) \land Q(x)]$, but I don't why this is; I get $Y\cap Z = \{(y,z)\in X\mid P(y)\land Q(z)\}$. What is the proof for this equivalence? How do I go from one to the other?
Comment: Why would you like to express "Let $X$ be a set and $P(x)$,$Q(x)$ be predicates over $X$" in set notation? As for the second question $Y\cap Z = \{x \in X \mid P(x) \land Q(x)\}$, i.e. $(y,z)\in X$ would mean that $X$ is a set of pairs, which might not be true.
Comment: @dtldarek I want to visualize the set $X$ like the given sets $Y$ and $Z$ because the problem's wording is confusing and I don't know what it means. For the 2nd part isn't $Y\cap Z=\{y\in X\mid P(y)\}\land\{z\in X\mid Q(z)\}=\{(y,z)\in X\mid P(y)\land Q(z)\}$ or am I thinking about it in the wrong way?
Comment: You are mixing notation, operators and ideas. For example the connective $\land$ takes two Boolean values (i.e. truth/falsehood), while a similar operator that would take two sets is $\cap$. In other words writing $\{1,2\} \land \{2,3,4\}$ is meaningless, because $\land$ is not defined to operate on sets and "does not know" what to do with them. Also $(y,z)$ is a pair which is a different type of an element, perhaps you wanted to write $\{x \in X \mid x = y \land x = z \land P(y) \land Q(z)\}$?
Answer: We must use the definitions:

$Y \subseteq Z \equiv \forall x(x \in Y \rightarrow x \in Z)$.

So, if $Y = \{y \in X : P(y) \}$ and $Z = \{z \in X : Q(z) \}$, we have that :

$Y = \{y : y \in X \land P(y) \}$,

and similarly for $Z$.

$Y \subseteq Z$ iff $\forall x((x \in X \land P(x)) \rightarrow Q(x))$.
$Y \cap Z = \emptyset$ iff $\forall x((x \in X \land P(x)) \rightarrow \lnot Q(x))$.
$Y \cup Z = X$ iff $\forall x((x \in X \rightarrow P(x) \lor Q(x))$;

this shows that $X \subseteq Y \cup Z$, but by contsruction, being $Y$ and $Z$ subsets of $X$, so is $Y \cup Z$.


Subversion server connection problems

Question: I have just set up Subversion server, and test repository, on a Windows server. However I can't connect to it from any computers. Using TortoiseSVN, I get the error message:

Error: Can't connect to host '[host]': A connection attempt failed because the
  Error: connected party did not properly respond after a period of time, or established
  Error: connection failed because connected host has failed to respond.

I can connect to another SVN repository on a different server, so it's surely a problem with this server and installation.

The Subversion service is running and listening on port 3690.
I can ping the server's IP address just fine from various PCs.
Firewall is disabled on the server and my PC (and nothing is blocked by the router).

Any ideas why I might not be able to connect?
Update: More info as requested by AlberT:

netstat -a lists, among other lines, TCP    GOWANPOINT:3690        GOWANPOINT:0           LISTENING
I'm using TortoiseSVN to connect, as noted above. I'm trying to check out the new repository I created, and connecting to: svn://[server-ip]:3690/project_name
Tried telnet-ing (using putty) and got a similar timeout error.
OS: Windows Server 2003
Answer: You should provide some additional informations, such as:

netstat output on the server, making clear on which port of which interface the server is listening on
the svn command line you are using, so that we can exclude any typo and verify the port, protocol and path you are trying to use
try to telnet to the server on svn port and tell us if the connection success. Possibly C&P the output
the OS of the server
try to exclude DNS problems using the server IP, not the name
Comment: OK, question updated.
Comment: Ok, if telnet times out too I'd try a tracert or, better, a tcptracert in order to see where your packets are deaded. You can use level four traceroute (http://pwhois.org/lft/ ) for example. In order to see if your PC can effectively reach via TCP connections the server try to telnet to the server-ip on a different port you know has a service enabled, or run a server through netcat -l to accomplish this task.
What is the net topology between your PC and the server?
Comment: `tracert [ip]:3690` simply returns "Unable to resolve target system name [ip]:3690". I don't see any options about port numbers, was that correct usage?
Comment: as I said you have to use a TCP tracing program, *not* the MS bundled tracert as it uses ICMP packets and you can't in any way probe tcp ports as you need
Answer: There is probably a firewall between the client and the server which doesn't allow to use the SVN port.
To verify this, try to run the subversion server on port 80 (you can use netcat to create a temporary reroute).
You can also use telnet <host> <port> to check that you can connect. In this case, you must see the connection on the server with netstat. If that doesn't work, there is definitely a firewall somewhere.
Answer: That looks like as if the Subversion server is not running. I've done that quite a few times myself. I've done this so much, that I created a page for me to look it up. I use the custom svnserve.exe server. If this is what you're using then look at the URL below for how to turn it into a Windows Service.
http://systemwidgets.com/Support/SubversionArticles/RunningsvnserveasaWindowsService/tabid/84/Default.aspx?PageContentMode=1
I've settled on the CollabNet binaries, as they have a nice install package for both the svnserve and Apache editions of the server.
Comment: I'm sure the service is running. Under Services is "CollabNet Subversion svnserve", which is Running, with the path `"C:\Program Files (x86)\CollabNet Subversion Server\svnserve.exe" --service -r "c:\svn_repository" --listen-port "3690"`
Comment: That command-line tells me that you are running Windows 2003 x64. What is the Subversion version? I had problems with 1.4 with x64 OS. Subversion 1.5 fixed the issues I had.

Also you don't need --listen-port "3690", as that is svnserve's default port.
Comment: IMHO if the server was not listening on the port and you *can* reach the server and there is no fw in the middle as reported then the client has not to hang, but an ICMP message should be received in a few ms.
Comment: I'm using Subversion 1.6.5, using the CollabNet binaries. And the "--listen-port" thing is added by svn by default.

Subversion server connection problems


How to get programatically 'display_options' for a specific page in Views

Question: I am a bit confused on how I should code this...
I have a view based on a custom content entity with 4 displays: default (hidden), Page (page_1), Export Entité (rest_export_1) and Export pour Maps (rest_export_2).

Devel shows this for this view:

I'd like to get the value of the path for 'rest_export_1' to use it in $name.
My code:
function association_exportCSV($view, $page)
{
  $view = \Drupal\views\Views::getView($view);
  $name = ???
  $page = $view->preview($page);
  file_unmanaged_save_data($page , 'private://' . $name . '.csv', FILE_EXISTS_REPLACE);

}

What should I do next? How to get $name from 'path'?
Answer: Try with:
function association_exportCSV($view, $page) {
  $view = \Drupal\views\Views::getView($view);
  // $display_id in this case is  'rest_export_1
  $view->setDisplay($page);
  $path = $view->getPath();
  file_unmanaged_save_data($page, 'private://' . $path . '.csv', FILE_EXISTS_REPLACE);
}

Comment: Finally, I came to the same result with
`$view = \Drupal\views\Views::getView($view);
 $display = $view->storage->getDisplay($page);
 $path = $display['display_options']['path'];`
but in both cases, I get this message: `Notice : Array to string conversion dans file_unmanaged_save_data()`.
Any idea?
Comment: $page passed to `file_unmanaged_save_data`  should be a string, if you want to save result of view should do something like `file_unmanaged_save_data( $data, 'private://' . $path . '.csv', FILE_EXISTS_REPLACE);` `$data` should be string of view result .
Comment: `$data = $view->preview($page)['#markup'];`does the trick!
Answer: function association_exportCSV($view, $page)
{

  $view = \Drupal\views\Views::getView($view);

//Solution 1
  $display = $view->storage->getDisplay($page);
  $path = $display['display_options']['path'];

//Solution 2
  $view->setDisplay($page);
  $path = $view->getPath();

  $data = $view->preview($page)['#markup'];
  file_unmanaged_save_data($data , 'private://' . $path, FILE_EXISTS_REPLACE);

}


Toggle values of a matrix

Question: Ok the problem goes as follows. There's a matrix of N*M, with each element as "0" or "1". we select a specific x,y( x<=N y<=M) and starting from (0,0) to (x-1,y-1) ,we toggle the values.that is 0 becomes 1,and 1 becomes 0. I need to know an algorithm to calculate minimum number of moves such that all elements of the matrix are 1.
Comment: Please try to be be more clear. Try to add some details, otherwise is really difficult to answer!
Answer: If I understand correctly, the toggle affects the submatrix with lower left corner $(0,0)$ and the upper right corner $(x-1,y-1)$.
Look at the top row of the matrix: say, it's 0 1 1 0 0 0 1 1 1 0 0. Read it from right to left: you'll have to  toggle the rightmost, which means toggling the entire matrix. The top row becomes 1 0 0 1 1 1 0 0 0 1 1. You'll also have to toggle at the rightmost zero, making the row 0 1 1 0 0 0 1 1 1 1 1. And so on: the number of necessary toggles is equal to the number of transitions (01 or 10) in the top row, plus one if the rightmost entry is 0.
Now that you see what exactly needs to be done with the top row, you perform these toggles, then cut off the top row and   call the same procedure recursively.
To reduce the recursion level to $\min(M,N)$, you can do the above for the top row and rightmost column, and cut both off before the recursive call.

Toggle values of a matrix


One tuba for everything: CC or F?

Question: I'd like to buy a single tuba which will last the rest of my life.  I'm trying to decide on which key: CC, or F.
I've only played BBb tubas before, and that was 15 years ago.  I want to play orchestral and solo stuff at home, which tends to be higher-pitched and so the F tuba makes sense, especially with my out-of-shape chops.  But I also want to play casually in concert bands.  Concert bands will probably need some of the lower notes (Bb2 down to F1).
How low can good F tubas comfortably go?  Can that be improved with a 5th and 6th valve?
Comment: I'm seeing Eb ones for general use, C for pro symphony.
Answer: This is a famous question for tuba players, but I'm not sure there's a single answer for you; I ultimately think it depends on what you want to privilege. (And before I proceed with my answer, I'll go ahead and say that I'm a tubist who only owns a CC, even though I'd love to own an F! I subbed for some professional orchestras back in the day, but these days my career is spent teaching music theory as opposed to playing.)
But to address your ultimate question, F tubas can go pretty low; with a fifth valve, it can play everything down to that pedal F with relative ease (if with a lot of fingers involved!). The problem is that, even in the hands of a great player, these lower notes tend to sound a little hollow, lacking the timbre that's so characteristic in those notes on a CC (or BB♭) horn.
As an example of this hollowness, check out this recording by Michael Lind of the second movement of the Vaughan Williams Tuba Concerto. Lind is my all-time favorite tuba sound, but check out those last three notes (starting around 4:15); you hear how wobbly they are, and they just lack the "beef" of a typical tuba sound. And believe it or not, this is only the D–C♯–B below the staff!
It also may be worthwhile to check out Lind's cadenza in the first movement. Watch with the music (it begins with the C below the staff) to see the sound that Lind is able to create on these lower notes to see if that's something you're interested in. Just remember that these are the sounds created by one of the all-time greats!
But ultimately, my recommendation is this: if possible, spend a week or two playing all kinds of repertoire on a CC tuba. Then, spend a week or two playing that same repertoire on an F tuba. (You could even meet in the middle and try it on an E♭ tuba; I know of at least one performer/teacher that spends most of her time on an E♭, and she both solos and plays in an orchestra.) Ultimately this is a personal decision, and so that time spent determining which is the best fit for you will be worth the hassle.
Comment: Do people  play the Vaughan Williams on a CC?
Comment: @PiedPiper Students do, but professionals tend not to. That is, they typically only do it on CC if they don't have an F!
Comment: Thanks for the response.  I ended up getting an F.  I was surprised how easy the pedal F was to hit.  I had a hard time hitting the low C with rotary valves, but it was easy with the piston valve tuba (melton 2250) that I ended up getting.  Low range really isn't an issue (just lots of fingers) and high range is much easier.    Your answer gave me the confidence to take the plunge.  I couldn't borrow a tuba for weeks, but about an hour in the store was enough to convince me that I could do everything I want with this tuba.  The limits of my playing are my own abilities, not the tuba.
Comment: @Stewart Congrats on the new F, and consider me properly envious!
Comment: Short followup after some time with the tuba:  The low end sounds great.  The pedal notes actually sound better than I could ever make them with my BBb tuba.  The limitation I notice in that range is more about the dexterity associated with using 5 valves.  I've heard that CC tubas rarely use the 5th valve because playing so low isn't usually required, but it's frequent on F tubas.  It'll take some time before I get the muscle memory in so I can do things quickly.  I certainly won't be playing trills down there.

One tuba for everything: CC or F?


could not find config.h file (ssh source codes)

Question: I am exploring SSH source codes that I cloned from github repo (https://github.com/openssh/openssh-portable.git). I want to compile a file but it includes a <config.h> header file that doesn't exist in cloned directory. How can I fix this ? Thank you in advance.
Comment: Read the INSTALL docs.
Answer: openssh-portable/configure.ac#L21:
AC_CONFIG_HEADERS([config.h])

config.h is created by autoconf utility program (see here). You need to run
autoreconf
./configure

to configure your build env before you run make command.
Check out the official INSTALL and README.md for more information.


Como configurar NSPredicate para realizar filtro?

Question: Estou implementando um filtro, onde preciso fazer a busca dos registros no Core Data, que tenham "sim" em determinadas colunas.
Tabela:

Por exemplo, retornar os elementos que tenham sim nas colunas ATRIBUTO1, ATRIBUTO3 e ATRIBUTO 5
Neste exemplo retornaria os registros:
linha1 e linha3.

Tentei usar a seguinte configuração com NSPredicate:
NSPredicate* argumentosBusca = [NSPredicate predicateWithFormat:@"atributo1 == %@&&atributo2 == %@&&atributo3 == %@&&atributo4 == %@&&atributo5 == %@",[arrayEscolhas objectAtIndex:0],[arrayEscolhas objectAtIndex:1],[arrayEscolhas objectAtIndex:2],[arrayEscolhas objectAtIndex:3],[arrayEscolhas objectAtIndex:4] ];

Mas deste modo so permite retornar os registros quando todas as colunas estão idênticas a configuração do NSPredicate.
Comment: Acho que não compreendi direito. Primeiro você disse pra buscar os argumentos que combinem com `sim, nao, sim, nao e sim`, e é só a **linha1** que está assim. Mas por outro lado você disse que precisa de resultados com valor "sim".
Comment: Perdão. Eu vou reformular. Eu dei uma olhada, revisei algumas vezes mas ainda assim não ficou claro...
Answer: Neste caso você precisa de um OR e não AND em suas condições. Seu predicate teria algo mais ou menos assim:
atributo1 == 'sim' || atributo3 == 'sim' || atributo5 == 'sim'

Pois neste caso, pode haver sim em qualquer uma das três colunas e não exatamente nas três, o que irá te retornar as linhas 1 e 3, como você citou.
Comment: Uma outra observação, eu também troquei o `"não"` com um `x` na strings que configura a busca para que a comparação com `"nao"` não fosse realizada. Deste modo so a comparação com o sim seria considerada.
Comment: Eu fiz um teste com `||` mas vou verificar novamente, pois vi um erro na busca. Vou ver como fica novamente.
Comment: Funcionou, o problema foi que eu mudei o conteúdo do banco, e fiz a verificação errada. Agora está ok!!


mixed effect model?

Question: I have 365 days of bike sharing demand data for 15 stations. I am thinking of taking each day data as a data point (n=365*15=5475) and relate daily weather variable as well as land use variable. The land use variable for each station will be the same across the data point. My objective is to develop a Poisson or NB model to see how weather and land use variable affect demand for each station.
Does it violate the independence assumption as I have multiple data point for a station? Do I need mixed effect Poisson model?
Answer: Controlling for weather and station-features (what you call land use variables, since the stations never move) will reduce the conditional dependence between stations. Chances are, however, it will not make them conditionally independent. You can use some exploratory analyses to determine whether autoregressive or intraclass effects persist. (lorellograms, variograms, etc.) by performing the independent data analysis and inspecting the residuals.
With residual dependence, it is safest and best to use some methods for dependent data on top of the fixed effects, like random effects by day and by site. It is interesting and curious to note that when the fixed effects do not sufficiently control for the concept they intended to capture, it can attenuate the fixed effect. It is something to note when comparing the two analyses.

mixed effect model?


Formulário fazendo INSERT vazio no Banco de Dados

Question: Estou criando uma página de cadastro simples e criei um Form para armazenar o que foi digitado no Banco de Dados. Entretanto, mesmo com a validação do Form em PHP para ver se tem algum campo vazio, quando eu clico em Cadastrar, ele armazena dados em branco no Banco de Dados. Vocês poderiam me dar uma mão nesse caso?
Este é o formulário em html e as validações dos campos em PHP.
<form method="post" name="formCadastro" action="inserir_dados.php" >

            <input type="text" id="nome" name="nome" placeholder="Seu nome completo"

                    <?php
                        if(!empty($_SESSION['value_nome'])){
                            echo "value='".$_SESSION['value_nome']."'";
                            unset($_SESSION['value_nome']);
                        }
                     ?>>
                     <?php
                        if(!empty($_SESSION['vazio_nome'])){
                            echo "
".$_SESSION['vazio_nome']."
";
                            unset($_SESSION['vazio_nome']);
                        }
                     ?>

            <input type="text" id="email" name="email" placeholder="Email comercial"

                    <?php
                        if(!empty($_SESSION['value_email'])){
                            echo "value='".$_SESSION['value_email']."'";
                            unset($_SESSION['value_email']);
                        }
                     ?>>
                     <?php
                        if(!empty($_SESSION['vazio_email'])){
                            echo "
".$_SESSION['vazio_email']."
";
                            unset($_SESSION['vazio_email']);
                        }
                     ?>

            <input type="text" id ="fone" name="fone" placeholder="Telefone com DDD"

                    <?php
                        if(!empty($_SESSION['value_fone'])){
                            echo "value='".$_SESSION['value_fone']."'";
                            unset($_SESSION['value_fone']);
                        }
                     ?>>
                     <?php
                        if(!empty($_SESSION['vazio_fone'])){
                            echo "
".$_SESSION['vazio_fone']."
";
                            unset($_SESSION['vazio_fone']);
                        }
                     ?>

            <input type="submit" value="Cadastrar">

        </form>

Aqui é o código para armazenar no BD.
<?php

session_start();
include_once 'conexao.php';

$nome = null;
$email = null;
$fone = null;

if(empty($_POST['nome'])){
    $_SESSION['vazio_nome'] = "Campo nome é obrigatório";
    $url = 'index.php';
    echo "
    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=$url'>
    ";
}else{
    $_SESSION['value_nome'] = $_POST['nome'];
}

if(empty($_POST['email'])){
    $_SESSION['vazio_email'] = "Campo e-mail é obrigatório";
    $url = 'index.php';
    echo "
    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=$url'>
    ";
}else{
    $_SESSION['value_email'] = $_POST['email'];
}

if(empty($_POST['fone'])){
    $_SESSION['vazio_fone'] = "Campo e-mail é obrigatório";
    $url = 'index.php';
    echo "
    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=$url'>
    ";
}else{
    $_SESSION['value_fone'] = $_POST['fone'];
}

$nome = mysqli_real_escape_string($conexao, $_POST['nome']);
$email = mysqli_real_escape_string($conexao, $_POST['email']);
$fone = mysqli_real_escape_string($conexao, $_POST['fone']);

$result_sql = "INSERT INTO cliente (nome,email,fone) VALUES ('$nome','$email','$fone')";

$resultado_sql= mysqli_query($conexao, $result_sql);

if($conexao->query($result_sql) == TRUE){
    echo "Usuário OK";
}else{
    echo "Erro".$result_sql."
".$conexao->error;
        }
$conexao->close();

?>
Comment: Na tabela do seu banco de dados, pelo menos um campo deveria ser `não nulo` por exemplo o campo nome. Isso já resolveria muita coisa!
Answer: A validação pelo PHP de um formulário, deve ser feita no servidor e não vai funcionar porque você a colocou no lado cliente. Do lado cliente, você deve usar o javascript para fazer a validação.
Considerando que a validação do lado cliente não é totalmente confiável, você deve fazer novamente no servidor, antes de salvar as informações no banco de dados.
Você pode fazer apenas um arquivo PHP que englobe todos os itens, isto é, o form., a validação cliente (javascript), a validação no servidor (PHP), a gravação dos dados e as mensagens de erro.
Você também pode fazer a validação apenas no servidor (PHP), omitindio-a do cliente. O contrário não é recomendado.
Answer:
O seu formulário HTML está correto, dentro do que você se propôs a fazer.

só falta você colocar session_start(); na primeira linha e corrigir
$_SESSION['vazio_fone'] = "Campo telefone é obrigatório";

Já na página PHP inserir_dados.php  você faz a validação dos dados do lado servidor.
if(empty($_POST['nome'])){..  if(empty($_POST['email'])){ ..  if(empty($_POST['fone'])){...

Até ai tudo bem. Só que o script PHP continua sendo executado e vai ao encontro do insert.
Como nenhuma restrição foi imposta, o insert vai ser executado de qualquer forma, isto é, se foram ou não enviados os campos do formulário.
Você pode impedir que o script continue sendo executado simplesmente colocando exit(); após os metas refresh
echo("<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=$url'>");
 exit();
Esse trecho de código $resultado_sql= mysqli_query($conexao, $result_sql); está sobrando e fazendo insert repetido no banco.

Você poderá gostar desse modelo ao invés de usar exit();

Repare que se algum dado não foi enviado é criado uma variável $insert="nananinanao";
É essa variável que vai impedir o insert na tabela caso algum dado não seja passado
inserir_dados.php
session_start();

include_once 'conexao.php';

$nome = null;
$email = null;
$fone = null;

  if(empty($_POST['nome'])){
       $_SESSION['vazio_nome'] = "Campo nome é obrigatório";
       $insert="nananinanao";
  }else{
       $_SESSION['value_nome'] = $_POST['nome'];
  }

  if(empty($_POST['email'])){
       $_SESSION['vazio_email'] = "Campo e-mail é obrigatório";
       $insert="nananinanao";
  }else{
       $_SESSION['value_email'] = $_POST['email'];
   }

   if(empty($_POST['fone'])){
       $_SESSION['vazio_fone'] = "Campo e-mail é obrigatório";
       $insert="nananinanao";
   }else{
       $_SESSION['value_fone'] = $_POST['fone'];
   }

   if ($insert!="nananinanao"){
       $nome = mysqli_real_escape_string($conexao, $_POST['nome']);
       $email = mysqli_real_escape_string($conexao, $_POST['email']);
       $fone = mysqli_real_escape_string($conexao, $_POST['fone']);

       $result_sql = "INSERT INTO cliente (nome,email,fone) VALUES ('$nome','$email','$fone')";

    }else{
        $url = 'index.php';
        echo("<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=$url'>");
        exit();
    }

    if($conexao->query($result_sql) == TRUE){
         echo "Usuário OK";
    }else{
         echo "Erro".$result_sql."
".$conexao->error;
    }
    $conexao->close();

Comment: Fiz as alterações que você sugeriu e funcionou perfeitamente aqui, muito obrigado!


CSS files defined in .info file are being ignored

Question: Having followed a number of different guides to try and create a Bartik sub theme that allowed me to use the Color module, the following was the last one I attempted that worked: http://drupal.org/node/800510#comment-3277090
However despite this working, none of the CSS files specified in my sub theme are working. Following is my info file:

; $Id: bartik.info,v 1.5 2010/11/07 00:27:20 dries Exp $

name = crxtr
description = A bartik sub theme
core = 7.x
base theme = bartik

stylesheets[all][] = css/crxtr.css
stylesheets[all][] = css/colors.css
stylesheets[all][] = css/crxtr-views.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

; Information added by drupal.org packaging script on 2011-01-05
version = "7.0"
project = "drupal"
datestamp = "1294208756"

Now the CSS from my front page reads:

The 3 CSS files specified in the info file are present and contain rules.
Following is an excerpt also from the head, which shows that at least on some level, the info file is being parsed and the CSS files are being recognized:
<![CDATA[//><!]]>

I've tried clearing the cache about a billion times to no effect. I just tried adding the following line to my info file and corresponding CSS file, and the only effect was that it actually removed the bartik/css/style.css from the HEAD, rather than substituting or adding the crxtr/css/style.css:
stylesheets[all][] = css/style.css

Please let me know if I can provide any more info to diagnose.
Edit: Followed the same process to create a subtheme using NineSixty and have had no problems with it finding and loading my sub-theme CSS files.
Answer: Please rename your css file name style.css to blah.css, it will works.
Answer: I'm new to Drupal 7, and those days I also had problems subtheming Bartik myself or copying and modifying the whole Bartik folder into my themes folder. At the end, I did using the only 'official' Bartik sub-theme I found (Antonelli) and then changing CSS and stuff in the info of Antonelli instead.
Comment: Thanks for the info! Did you need to do anything special to get theme preprocess hooks working?
Answer: I'd just like to point out that it appears Drupal is quite particular about the location and/or name of your css file when including it via a module's .info file. This is what worked for me:
Directory
sites/all/modules/custom/my_module/

Files
my_module.info
my_module.module
css/my_module.css // DOES NOT WORK
css/foo.css

my_module.info
name = My Module
description = My awesome module
core = 7.x
package = Other
stylesheets[all][] = css/my_module.css // DOES NOT WORK
stylesheets[all][] = css/foo.css

For some reason, .css files included via a module's .info file, cannot have the same filename as the module itself. This means the my_module.css file will not be loaded.
Be sure to flush all of Drupal's caches after making changes to a .info file.


Home page not displaying after successful installation of IBM HTTP server

Question: I have installed IBM HTTP on a Red Hat Linux server . The installation was successful but I was not able to view the home page . Whenever I tried to view the home page , it always displayed ' Forbidden ' message like ' You don't have permission to access / on this server. ' On checking the logs , it showed an error the following error message ----
[Fri May 11 03:18:34.955151 2018] [core:error] [pid 23748:tid 140394669549312] (13)Permission denied: [client 172.16.100.25:56320] AH00035: access to / denied (filesystem path '/root/IHS') because search permissions are missing on a component of the path
Can anybody help me in this ?
Answer: Don't install to /root since it is normally not readable/executable by non-root users such as the webserver processes that handle requests.  Reinstall in e.g. /opt.
Apache-based servers like IHS generally start as root then transition to a lower-privileged users to handle requests -- like "nobody" or "www-data".
Apache requires not just read access to the file being served and execute access to the document root, but read and execute access to EVERY directory between the root of the filesystem and the document root.
Comment: Thanks for your answer . You are right . The permission was not present in '/root ' because of which I was not able to see the welcome page . I checked the other locations of the path but did'nt checked the permissions for /root . ' nobody ' user comes in ' others ' category & /root did'nt had execute permissions for ' others ' category . However , I have provided the permissions now and the issue is solved.