$_GET & "=" -- Syntax Error

Question: For example link;
http://example.com/cast?Channel=STACKo
ChannelDatas.php;
 $STACKo_YAYIN = 'overflow';

Index.php;
  include '/***/Library/ChannelDatas.php';

  158 $_GET['Channel'] . '_YAYIN' = $insalik;
  159 $url = 'http://example.com/data/'.$insalik.'.info/weekly_'.$insalik.'.info_tvprofil.net.xml';

Target print:
$url = 'http://example.com/data/overflow.info/weekly_overflow.info_tvprofil.net.xml'

Error page:
 Parse error:  syntax error, unexpected '=' in /***/v1/Index.php on line 158

What's wrong? Thank you!
Comment: You should explain what you are trying to do here...
Comment: You've a wrong assigning on line 158. It should be `$insalik = $_GET['Channel'] . '_YAYIN';`
Answer: I think you need like this
$insalik = $_GET['Channel'] . '_YAYIN';

You are using $insalik for $url.So you need to assign that value to $insalik.You made it reverse.
Answer: You should refer to $STACKo_YAYIN in this way:
$STACKo_YAYIN = 'overflow';
$insalik = ${$_GET['Channel'] . '_YAYIN'};
$url = 'http://example.com/data/'.$insalik.'.info/weekly_'.$insalik.'.info_tvprofil.net.xml';

Comment: If you have a bunch of config values you want to address: Put them into an array! Don't create individual variables, because these can only be addressed with variable variables, and this actually is a security nightmare! You make available EVERY existing variable via a GET parameter (if it has the suffix "_YAYIN").
Comment: @Sven Totally, this kind of variable defining has security issues and that's another subject. But we just answered the OP needs.
Comment: You shouldn't do that. Don't recommend insecure practices! Others will read this and say "This is how it works, because it was written on Stackoverflow!" The least thing you should do is alert the OP that his intention is very dangerous! I did this by downvoting and commenting. And giving a better answer.
Comment: @Sven you can alert him by not commenting here but at his post.
Answer: The bad things start here:
ChannelDatas.php;
$STACKo_YAYIN = 'overflow';

This should rather be:
$YAYIN = array(
    "STACKo" => 'overflow',
);

And then access is easy:
if (isset($YAYIN[$_GET['channel']]) {
    $url = 'http://example.com/data/'.$YAYIN[$_GET['channel']].'.info/weekly_'.$YAYIN[$_GET['channel']].'.info_tvprofil.net.xml';
} else {
    // what if there is no value for the channel?
}

Answer: use following
$_GET['Channel'] = '_YAYIN'.$insalik;

Answer: $_GET['Channel'] . '_YAYIN' is a string. You cannot assign (=) values to a string.
You need it the other way around (assign this string to a variable)
or maybe ${$_GET['Channel'] . '_YAYIN'} = $insalik
Answer: You need to use a variable variable:
$insalik = ${$_GET['Channel'].'_YAYIN'};

http://php.net/manual/en/language.variables.variable.php
Answer: Try refrence variable
$temp = $_GET['Channel'] . '_YAYIN';
$insalik = $$temp;

Comment: Nobody really needs variable variables. Maintenance hell ensues.
Comment: @Sven he is trying to make a variable on run time so its good to use variable referencing to a varibel.

$_GET & "=" -- Syntax Error


Function to list contents of txt file recursively and return number of opened files

Question: I need to write a function that will recursively display the contents of files whose names are contained in the first file. Additionally, I want the function to return the number of opened files.
eg.
first.txt:
    pull.txt
    predict.txt
    suppress.txt
    mount.txt
    transfer.txt

predict.txt:
    constitute.txt
    determine.txt
    swim.txt

Result:
    pull.txt
    predict.txt
        constitute.txt
        determine.txt
        swim.txt
    suppress.txt
    mount.txt
    transfer.txt

    Number of files: 2

So far I have managed to display the files, but I have no idea how to return the number of files.
int read_file(const char *filename){
    if(filename==NULL){
        return 0;
    }
    FILE *file;
    char tempName[31];
    if((file= fopen(filename,"r"))==NULL){
        return 0;
    }
    while (!feof(file)){
        fgets(tempName,31,file);
        tempName[strcspn(tempName, "\n")] = 0;
        printf("%s\n", tempName);
        read_file(tempName);
    }
    return 1;
}

P.S.
I'm just starting to program, so please forgive me if my code is simple or poorly secured. This is part of an assignment that just needs an idea of how to execute and that's what I'm missing :)
Thanks for any advice given in the comments.
I found the solution, thanks for all the hints :)
int read_file(const char* filename){
    if(filename==NULL){return -1;}
    FILE* file;
    char buffer[31];
    int counter=0, res;
    if((file= fopen(filename,"r"))==NULL){return -1;}
    while (!feof(file)){
        fgets(buffer,31,file);
        for (size_t i = 0; i < strlen(buffer); ++i) {
            if(*(buffer+i)=='\n'){*(buffer+i)=0;}
        }
        printf("%s\n", buffer);
        res= read_file(buffer);
        if(res!=-1){
            counter+=res;
        }
    }
    fclose(file);
    return counter;
}

Comment: Obligatory: [Why is "while ( !feof( file ) )" always wrong?](https://stackoverflow.com/q/5431941/9952196)
Comment: Pay attention to infinite loop is a file already seen is seen in other. You should keep track of the list of seen files.
Comment: What is the problem you have with the code you show? Do you get build errors? Wrong output? Crashes?
 Something else? Please read the [help pages](http://stackoverflow.com/help),
 take the [SO tour](https://stackoverflow.com/tour),
 read [How to Ask](https://stackoverflow.com/questions/how-to-ask),
 as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/).
Comment:  see https://stackoverflow.com/q/5431941/3476780
Comment: I see that predict.txt has other file names in it. How about the rest, are they simply empty files? Do you need to logically determine if each file contains file names or some other text data?
Comment: @yano I only need to determine if any line of text is a filename of the existing file and if yes print its content. So far I got it more or less, my main concern is that function must return the number of files opened in the process. Also, I can't modify the function prototype :/
Comment: I'm guessing `read_file` should return the number of files opened? You're using recursion, so you're going to want to add what each `read_file` returns to the one before it. I don't think you want to simply `return 1;`
Answer:
I have no idea how to return the number of files.

Use a counter and pass a pointer to it as second argument of the function. Increment the counter each time a file is opened. Don't forget to initialize the counter to zero before calling the function at the top level.
Comment: If you don't want (or can't) use the counter as an argument, you can use a global variable.
Comment: Any way to rewrite the function so it returns this value without modification to its declaration? Unfortunately, I have to do it that way. I've been returning to this problem for a month now and couldn't think of any more solutions than the second argument or global variable.


Lower bound on certain exponential sums and expressions related to them

Question: Let $$G(\alpha, x) = \sum_{n\le x}e(\alpha n^2)$$ Clearly, $r_k(n)$, the number of representations of a number as the sum of $k$ squares is given by the following expression:  $$r_k(n) = \int_0^1 G(\alpha, n)^k e(-\alpha n) d\alpha$$ However, the only bounds that I have seen on $G(\alpha, n)$ and to some extent $r_k(n)$ have been upper bounds. Does anyone know of any nontrivial lower bounds on $r_k(n)$, or asymptotic representations for $G(\alpha, n)$ if $|\alpha - \frac{a}{q}|\le \frac{\ln^B n }{n}$ and $q\le \ln^B n$.
Answer: What you are asking corresponds to estimating the exponential sum $$\sum_{n\leq N}e(\alpha n^{2})$$ on the Major arcs $$\mathfrak{M}_{q,a}=\left\{ \alpha\in[0,1]\ :\ \left|\alpha-\frac{a}{q}\right|\leq\frac{1}{N^{1-\eta}}\right\}$$  where $\eta\leq\frac{1}{10}.$ Note that this set is larger than what you are asking for, since I allowed $$\frac{N^{\eta}}{N}\text{ instead of }\frac{\left(\log N\right)^{B}}{N}.$$ I assume you were looking at the latter because that appears as the Major arcs in the proof of Vinogradov's three prime theorem. When working with Waring's problem, we are not constrained by the lack of uniformity in the prime number theorem for arithmetic progressions.
The Hardy-Littlewood Circle method tells us that for any $k\geq6,$ the number of representations of $n$ as a sum of $k$ squares asymptotically equals $$r_{k}(N)=\mathfrak{S}(N)\Gamma\left(\frac{3}{2}\right)^{k}\Gamma\left(\frac{k}{2}\right)^{-1}N^{k/2-1}+O\left(N^{k/2-1-\delta}\right)$$ for an explicit $\delta>0$, where $\mathfrak{G}(N)$ is a constant called the singular series.
As usual let $e(x)=e^{2\pi ix}.$ Then for any $\alpha\in\mathfrak{M}_{q,a}$  $$\sum_{n\leq N}e\left(\alpha n^{2}\right)=\frac{1}{q}S_{a,q}T(\beta)+O\left(x^{2\eta}\right)$$ where $T(\beta)=\frac{1}{2}\sum_{n\leq N}\frac{e(\beta n)}{\sqrt{n}}$ and $S_{a,q}=\sum_{n=1}^{q}e\left(\frac{a}{q}n^{k}\right).$ Note that the asymptotic comes from the Major arcs. The above quantities $T(\beta)$ and $S_{a,q}$ give rise to the so called singular integral $$\int_{0}^{1}T(\beta)^{k}e\left(-\beta x\right)d\beta=\Gamma\left(\frac{3}{2}\right)^{k}\Gamma\left(\frac{k}{2}\right)^{-1}N^{k/2-1},$$ and singular series
$$\mathfrak{S}(N)=\sum_{q=1}^{\infty}\left(\sum_{\begin{array}{c}
a=1\\
(a,q)=1
\end{array}}^{q}\left(\frac{S_{a,q}}{q}\right)^{s}e\left(-\frac{a}{q}N\right)\right).$$
There are similar such expressions for writing $n$ as a sum of $s$ $k^{th}$ powers, and I recommend reading about the Hardy-Littlewood circle method applied to Waring's problem to find out more.
Comment: Thanks. The singular series was the sort of thing I was looking for.


Any easy way to get grouped box plot using plotly and cufflinks?

Question: I now that for scatter plot, you can write something like
df.iplot(kind='scatter', x='myX',y='myY',categories='myGroup')

supposing that df is a dataframe with those variables.
However, this won't work if I change to
df.iplot(kind='box', x='myX',y='myY',categories='myGroup')

it will end up with a scatter plot. Is the categories setting not supported in box plot yet or I missed something?
Answer: I was looking for that solution too, but could not find any help. But I was able to find a hack; For example in case of popular titanic data set from kaggle. Box plot of age by passenger class:
import cufflinks as cf
cf.go_offline()

box_age = train[['Pclass', 'Age']]
box_age.pivot(columns='Pclass', values='Age').iplot(kind='box')

You can do it in one step but in two (or three step by storing the pivot table in a object) step code looks clean. So Second step I am pivoting the data. So there will be 1 non-null value per rows. iplot can take care about the null values. I have tested with seaborn and iplot the give me the same answer. So its reliable. In case if you want to try both. Here is seaborn code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

plt.figure(figsize=(12, 7))
sns.boxplot(x='Pclass', y='Age', data=train, palette='winter')

Note: I am using Jupyter Notebook that's why there is %matplotlib inline


Componente em ReactJs re-renderizando componentes filhos sem necessidade, como contornar isso?

Question: Quando um componente Pai atualiza consequentemente seu(s) Filho(s) também e(são) atualizado(s), sem que no minimo mude qualquer valor de suas props e states, por exemplo:

function Filho({item}) {
  React.useEffect(() => {
    console.log('atualiza');
  });
  return (

{item.id} - {item.name}

  );
}
function Pai() {
  const [items, setItems] = React.useState([
    { id:'1', name:'example 1'},
    { id:'2', name:'example 2'}
  ]);
  const [value, setValue] = React.useState('');
  return (

        <input type="text"
          onChange={e => setValue(e.target.value)}
          value={value}
        />

        {
          items.map((item, i) =>
            <Filho key={i} item={item}/>
          )
        }

 );
}

ReactDOM.render(<Pai/>, document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Aguarde ...

todas as vezes que é digitado o componente <Filho /> também renderiza todos os itens novamente, propondo um retrabalho desnecessário tem como resolver essa re-renderização?
Answer: Tem sim, com o React.memo (ou em classes com PureComponent que compara o state e props superficialmente, tomando os devidos cuidados com objetos complexos, ou seja, esse recurso são para componentes com objetos simples) da seguinte forma:

let Filho = React.memo(({item}) => {
  React.useEffect(() => {
    console.log('atualiza');
  });
  return (

{item.id} - {item.name}

  );
});
function Pai() {
  const [items, setItems] = React.useState([
    { id:'1', name:'example 1'},
    { id:'2', name:'example 2'}
  ]);
  const [value, setValue] = React.useState('');
  return (

        <input type="text"
          onChange={e => setValue(e.target.value)}
          value={value}
        />

        {
          items.map((item, i) =>
            <Filho key={i} item={item}/>
          )
        }

 );
}

ReactDOM.render(<Pai/>, document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Aguarde ...

nesse caso, ao digitar no <input/> o componente não é re-renderizado (como não houve mudanças) e isso tem um ganho em desempenho, mas, como foi dito tem suas restrições.


How can I AND two OR statements with the #states feature of Drupal 7?

Question: This page explains nicely how to use OR with the #states feature. However, when I try to AND two OR statements, It doesn't seem to AND them together. Is there a way to do this? This is what I tried.
<code> 'visible' => array(
    array(
      array(':input[name="vehicle"]' => array('value' => 'truck')),
      array(':input[name="vehicle"]' => array('value' => 'car')),
    ),
    array(
      array(':input[name="mileage"]' => array('value' => '10')),
      array(':input[name="mileage"]' => array('value' => '20')),
    ),

  ),
</code>
Answer: I found out that this can be done this way:
<code>$form['non_phd_student'] = array(
    '#type' => 'item',
    // This #states rule says that the "non_phd_student" item should only
    // be shown if the "student_type" form element is set to "Undergraduate" or "graduate".
    '#states' => array(
      'visible' => array(
        array(
          array(':input[name="student_type"]' => array('value' => 'undergraduate')),
          array(':input[name="student_type"]' => array('value' => 'graduate')),
        )

      ),
    ),
);
$form['non_phd_student']['thanks'] = array(
  '#type' => 'item',
  '#description' => t('Thanks for providing your graduate status and your country');
  '#states' => array(
  //Because this has ['non_phd_student']
  //The or in $form['non_phd_student'] is ANDed into the or of this statement.
  // Action to take: Make visible.
  'visible' => array(
    array(
      array(':input[name="school_country"]' => array('value' => t('Other'))),
      array(':input[name="school_country"]' => array('value' => 'UK')),
    )
  ),
),
);
</code>
There is another answer that takes more work. We can do this because AND statements can be inside the OR statements. Also, because of Propositional Logic we can get the same results this way:
<code>'visible' => array(
  array(
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '10'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'truck'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '20'),
    ),
    array(
      ':input[name="vehicle"]' => array('value' => 'car'),
      ':input[name="mileage"]' => array('value' => '10'),

    ),
  ),

),
</code>


saving data in one transaction and fetching data in another transaction using jpa annotation

Question: I m working on Spring MVC using JPA where m using annotation based structure. I have to upload excel file in data base in which i need to update a column called status using update column method then save data in table then need to fetch all records (updated) from table with status. In this case everything works fine except when i fetch records from database it fetches old data it does not fetch updated records from table. I m using transaction annotation here in method.
I have tried using @transaction(propagation = propagation.required_new) but it also fetches old data.
Any person can suggest me anything?
<code>@Transactional
    @Override
    public void updateStatus() {
        lotAcceptanceRateRepository.updateStatus();
    }

@Transactional
    @Override
    public void saveList(List<LotAcceptanceRate> lotAcceptanceRateList) {
        lotAcceptanceRateRepository.save(lotAcceptanceRateList);
    }

@Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public List<LotAcceptanceRate> getAllRecordsFromTable() {
        return lotAcceptanceRateRepository.OrderByStatusAsc();
    }
</code>
These all are the methods which i m using to run transaction.
Answer: Try to use
<code> @Modifying
 @Transactional
</code>
when you save and update
Comment: In case of update i have tried using but result remains same where as not tried in case of save do you want me to use it in case of save as well?
Comment: if i understand correctly, your save method updates the column with new data, right? then u need to use @Transactional@Modifying there. I had problem. When i had the same problem i even used HQL @Query ("UPDATE User u SET u.password=:p where u.email =:e")  just to make sure it works propely and it did.
And im not sure but is it allowed to save a LIST via hibernate? Have u tried to save each object of your list via foreach?
Comment: Saving data is not problem the problem is when it fetches data it fetches old data even not totally old actually it fetches new row added correctly but updated data is not correct....
Comment: Any solution for this problem. I am facing something similar. Save works but fetch sometimes doesn't work . Fetch is in different transaction which is just after some milliseconds


How to dynamically Prepopulate / Prefill addressfields

Question: I have an single entityform of type 'letter generator' this contains two addressfields:

'To' addressfield
'From' addressfield

I would like to prepopulate / prefill these addresses with content from elsewhere on my site.

'From' addressfield populated from the 'User addressfield' attached to my 'user' entity type.
'To' addressfield populated from the 'School addressfield' attached to my 'School  info' 'node' entity type (also the parent node for the letter generator)

I am new to php and programming so this is my first attempt at a custom module. So far I have the following php that attempts to address point (1.)
function letter_address_form_alter(&$form, &$form_state, $form_id) {

// Check to see if the form alter function is actually running
dsm($form);

    // Only do this for a new, not-yet updated entityform -NB might need a 'return' here
    if (!isset($form['#entity']->is_new)) {

        //Ensure, we're updating field info on the correct entity type
        if ($form_id == 'letter_generator_entityform_edit_form') {

            // load user information
            global $user;
            $current_user = user_load($user->uid);

            //Populate the entityform addressfield with values from the user addressfield
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['thoroughfare']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['premise']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['locality'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['locality']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['administrative_area']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['postal_code'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['postal_code']['value'];

        }
    }

}

...
Ok I got this working:
global $user;
$user_fields = user_load($user->uid);
//useful ...
dsm($user_fields);
$userthoroughfare = $user_fields->field_user_address['und']['0']['thoroughfare'];
$userpremise = $user_fields->field_user_address['und']['0']['premise'];
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $userthoroughfare;
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] = $userpremise;

NB adding ['value'] to the line:

$form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area']['value'] = $useradministrativearea;

will select the state for you...
Answer: I cant find any reference of hook_form_entityform_alter if it is available you will want to take out the hook part and replace this with you module name.
I have re written the code using hook_form_alter. You will need to replace $address1 etc with your own code.
function letter_addresses_form_alter(&$form, &$form_state, $form_id) {

// Ensure, we're updating field info on the correct entity type
//This needs to be more specific incase more entity forms are created
if ($form_id == 'yourformname_entityform_edit_form') {

// Only do this for a new, not-yet updated entityform -NB might need a 'return' here
if (!isset($form['#entity']->is_new)) {
//Populate the entityform addressfield with values from the user addressfield
$address1 = "address1";
$address2 = "address2";
$county = "county";
$postcode = "postcode";
$form['field_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $address1;
$form['field_address'][LANGUAGE_NONE][0]['#address']['premise'] = $address2;
$form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = $postcode;
  }
}

Comment: In your answer where is the reference to the user addressfield?
Comment: The above code sets the fields the variables that are named as they they appear in the front end. Each variable is currently being set to a string, you will need to replace the string with the values that you want. To get the values from the current user grab the user id from Global and do a user_load if you print the array that is returned to the screen or watchdog you will be able to see how to access the data that you need.
Comment: Ok thanks alot, +1 for your edits, i've changed the code i'm using to reflect what i've learned. Unfortunately it's still not going through. When I pass my current_user address_fields value am I right in using ['value'] or is this a placeholder?
Answer: You can use the default value to set it - see here for an example: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#default_value
<?php

         $form['body'] = array(

          '#type' => 'textarea',
          '#title' => t('Body'),
          '#default_value' => $node->body,  //$user->addressField or $node->school_address
          '#required' => TRUE,
         );

  ?>

Answer: This may be a duplicate of this question and I posted there a working solution for one node field, should be very easy to add the second field.


firestore query inside of streambuilder for getting additional informations in flutter

Question: i have problems with my code. i receive only the data of my first query inside the streambuilder if statement. do i need to use a loop ???
With listenStream i receive for example 4 results. 2 of the results have the value in field 'kategorien' = 'Keine'. These 2 fields i need to complete to show in my programm with the results from the query inside the if statement of the streambuilder. i hope i explained a little to understand my targets.
The problem is, that i receive only the first 'kategorie' for the first entry in the database.
can someone help my please?
Here is my code:
StreamBuilder<QuerySnapshot>(
              stream: listenStream,
              builder: (context,snapshot){
                if (snapshot.hasError) {
                  return Text('Something went wrong');
                }

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Text("Loading");
                }

                return ListView.builder(
                  itemCount:snapshot.data?.docs.length,
                  itemBuilder: (context,index){
                    String? falscheKat = snapshot.data?.docs[index]['kategorie'].toString();
                    if(falscheKat=='Keine')
                      {
                        FirebaseFirestore.instance.collection('artikel').where('item', isEqualTo: snapshot.data?.docs[index]['item'].toString())
                            .get().then((value) {
                          neueKat = value.docs[0].get("item");

                        });
                      }
                    return ListTile(

                      title: Text(snapshot.data?.docs[index]['item']),
                      subtitle: Text(neueKat.toString()),
                    );
                  },
                );
              })

and here my Firestore query listenStream:
final Stream<QuerySnapshot> listenStream = FirebaseFirestore.instance
        .collection('listen1')
        .doc('zuhause')
        .collection('artikel').snapshots();

Answer: Use another StreamBuilder for the second Firestore query.


Custom Page inside Module

Question: I'm trying to embed custom content (custom javascript, paragraphs etc) with a Drupal Form. I'm wondering whats the best way to do it in module?
Something like this:
function wow_page() {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
    $output = 'teasdasdst';
    $output = '

';
    $output .= drupal_get_form('wow_cake');
    return array('#markup' => $output);
}

Comment: I think you need to clarify your question. What exactly are you trying to do? Perhaps give an example of a use case?
Answer: ok add hook_menu that call this function
if you have module called wow
function wow_menu() {
  $items = array();
  $items['home'] = array(
    'title' => '',
    'page callback' => 'wow_page',
    'access callback' => TRUE,
  );
  return $items;
}

Comment: I already did that, it's all working but my question is really how to construct the page function so it can output multiple things easily.
Comment: what do you mean output multiple things you display html that can be whatever u want or you can use hook_theme to make a new tpl page

Custom Page inside Module


how to check whether the backend server in a loadbalancer has bypassed the loadbalancer in a DSR mode while replying to client?

Question: I couldn't find much information on how to verify if DSR mode in a loadbalancer works or not.
Is there a way to find whether the loadbalancer is bypassed during a reply from the backend server to the client in case of a Direct Server Return node ?
Answer: When using Direct Server Return, the Backend Server will be configured with an additional (loopback)Interface matching the Virtual IP used on the Load Balancer. This allows it reply from the same IP address that the request was sent to. So by design from the client perspective it will look the same.
Best way imo to verify would be to trace the traffic (TCP Dump) and check MAC address (is it from the Real Server or the Load Balancer)
Otherwise maybe the load balancer metrics can verify.


Likelihood Ratio Criterion in EFA

Question: This is in ref to pp. 54-55 in McDonald,R.P[1] in the context of exploratory factor analysis (EFA) ML estimation.
 The likelihood ratio criteria, to me, seems to be performing dual roles: I. Providing a measure to determine the probability that the sample is from a population that conforms to the model II. Providing a measure of discrepancy between the model based estimated (population) correlation matrix and the sample correlation matrix – this discrepancy calculated in terms of straight forward discrepancy between corresponding cells entries in the two matrices.
What links Roles (I) and (II)? Grateful for reference, preferably at  elementary/conceptual level.
[1] Roderick P. McDonald (1985),
Factor Analysis and Related Methods,
Psychology Press
Answer: Fabrigar & Wegener (2011) present a pretty accessible explanation of the likelihood ratio (or $\chi$$^2$) test statistic. In a nutshell, and as you correctly point out, the $\chi$$^2$ statistic is calculated based on the discrepancy between the model-implied and observed correlation matrix; larger values indicate greater misfit between the model and the actual data. The test statistic is then commonly used to perform a hypothesis test evaluating the null-hypothesis of a perfect fitting model (i.e., zero discrepancy between model-implied and observed correlation matrixes); many think this test is theoretically unreasonable, as no models are actually perfect, and the test is sensitive such that you will reject models with trivial misspecification at larger sample sizes.
References
Fabrigar, L. R., & Wegener, D. T. (2011). Exploratory factor analysis. New York, NY: Oxford University Press.

Likelihood Ratio Criterion in EFA


Vagrant multiple VM config with CoreOS

Question: what I'm trying to do, it's to integrate the standard CoreOS Vagrantfile found here and my own Vagrantfile which boots an Ubuntu box.
This is my Vagrantfile:
<code># Vagrantfile API/syntax version.
VAGRANTFILE_API_VERSION = "2"

### Check if required plugins are installed
unless Vagrant.has_plugin?("vagrant-bindfs")
  raise 'vagrant-bindfs plugin is missing!'
end

unless Vagrant.has_plugin?("vagrant-hostsupdater")
  raise 'vagrant-hostsupdater plugin is missing!'
end

# Setup CoreOS config files
CLOUD_CONFIG_PATH = File.join(File.dirname(__FILE__), "user-data")
CONFIG = File.join(File.dirname(__FILE__), "config.rb")

# Defaults for config options defined in CONFIG
$num_instances = 1
$instance_name_prefix = "core"
$update_channel = "stable"

# Attempt to apply the deprecated environment variable NUM_INSTANCES to
# $num_instances while allowing config.rb to override it
if ENV["NUM_INSTANCES"].to_i > 0 && ENV["NUM_INSTANCES"]
  $num_instances = ENV["NUM_INSTANCES"].to_i
end

# Include Config file
if File.exist?(CONFIG)
  require CONFIG
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

# COREOS
  config.vm.define :coreos do |node|
    node.ssh.insert_key = false
    node.vm.box = "coreos-%s" % $update_channel
    node.vm.box_version = ">= 308.0.1"
    node.vm.box_url = "http://%s.release.core-os.net/amd64-usr/current/coreos_production_vagrant.json" % $update_channel

    node.vm.provider :virtualbox do |v|
      v.check_guest_additions = false
      v.functional_vboxsf     = false
    end

    if Vagrant.has_plugin?("vagrant-vbguest") then
      node.vbguest.auto_update = false
    end

    (1..$num_instances).each do |i|
      node.vm.define vm_name = "%s-%02d" % [$instance_name_prefix, i] do |node|
        node.vm.hostname = vm_name
        ip = "172.17.8.#{i+100}"
        node.vm.network :private_network, ip: ip

        if File.exist?(CLOUD_CONFIG_PATH)
          node.vm.provision :file, :source => "#{CLOUD_CONFIG_PATH}", :destination => "/tmp/vagrantfile-user-data"
          node.vm.provision :shell, :inline => "mv /tmp/vagrantfile-user-data /var/lib/coreos-vagrant/", :privileged => true
        end
      end
    end
  end

# UBUNTU

  config.vm.define :ubuntu do |node|
    node.vm.box = "ubuntu1404-64"
    node.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
    node.vm.network "private_network", ip: "192.168.100.100"
    node.vm.hostname = "wpthor"
    node.bindfs.debug = true

  ### Set a right amount of memory
    node.vm.provider :virtualbox do |vb|
      vb.customize ["modifyvm", :id, "--memory", "1024"]
    end

  ### Fix for Ansible bug resulting in an encoding error
    ENV['PYTHONIOENCODING'] = "utf-8"

  ### Run Ansible provision
    node.vm.provision "ansible" do |ansible|
      ansible.limit = 'all'
      ansible.verbose = "" ### If you notice errors, add "vvv" here to activate verbose mode
      ansible.playbook = "ansible/development.yml"
      ansible.inventory_path = "ansible/hosts"
    end
  end
end
</code>
It works without errors, but it boots only one CoreOS node (instead of 3). Probably it's a stupid syntax error, but I can't come up with a solution. Can you help me?
Answer: Just update the number of machines you want booted up.
<code>
$num_instances = 3
</code>

Vagrant multiple VM config with CoreOS


Prove converge or divergence of the following sequence

Question: $a_n=\frac{\sin(\sqrt{n})}{2n-5}$
So far I've gotten to the point of the whole $\epsilon-N$ proof that it converges to $0$.
$|\frac{\sin(\sqrt{n})}{2n-5}| \lt \frac{1}{|2n-5|}$
let $n \gt \frac{5}{2}$
$\lt\frac{1}{2n-5} = \frac{1}{n} *\frac{1}{2-\frac{5}{n}}$
After all the bounding I got it to the point to say
$N=$ max$(\frac{3}{\epsilon},\frac{5}{2})$
I think I'm stuck here though for proving the case where if $N=\frac{5}{2}$
Comment: Just write $N=\max(3/\epsilon,5/2)+1$. And $N$ need not be an integer. That's just what textbooks say to make it easier to read.
Comment: $N$ is supposed to be an integer and $\frac{5}{2}$ is not an integer. So try choosing $N$ as the next integer larger than both $\frac{3}{\epsilon}, \frac{5}{2}$.
Comment: You have a lot of freedom available when choosing $N$.  If $5/2$ is inconvenient, just skip past it by choosing $N > 3$.
Answer: You don't have to consider $5/2$. Just take the maximum of $3$ or $3/\varepsilon$.
As a side note, this is a common trick and can be applied since you're considering $n\to\infty$. The moral here is that any "bad" points can be avoided since there are finitely many... just take $N$ larger than one plus the largest "bad" point (or similar).


Center a note in lilypond

Question: How do I achieve this in lilypond?

This is my attempt:
{
  \hide Staff.TimeSignature
  d4''
  \bar "||"
}

The issue is with the horizontal spacing - is there a way to hide/delete the time signature and have the note centered like above?
Answer: I'd override extra-spacing-width.
\version "2.22.2"

\layout {
  \context {
    \Staff
    \remove Time_signature_engraver
  }
  \context {
    \Voice
    \override NoteHead.extra-spacing-width = #'(-5 . 5)
  }
}

\new Staff {
  d''4
  \bar "||"
}

About this method, see
http://lilypond.org/doc/v2.23/Documentation/notation/spacing-between-adjacent-columns.html
Also, about \remove: http://lilypond.org/doc/v2.23/Documentation/notation/modifying-context-plug_002dins.html.
Answer: Firstly: d4'' should be d''4, you need to place the duration (number) after the octave designation (quote/comma).

It's not clear why you want the note in the centre of the bar, so it's hard to tell what is the best way to get it to appear there.
One way would be to use invisible rests.
A "spacer rest" is entered like normal rest, but with an s instead of an r. For example s4 will make an invisible quarter note (crotchet) rest.
Applying some spacer rests to your code like this:
    {
        \hide Staff.TimeSignature
        s4 d''4 s2 |
        \bar "||"
    }

will give you something similar to your first image.
However, this isn't going to work in general. This is because while using \hide Staff.TimeSignature does make the time signature invisible, it still takes up the same amount of space that it normal would.  Instead you probably want to use \omit Staff.TimeSignature.  This will remove the time signature and not use up any space for it.

Changing the (omitted) time signature to 3/4 and placing the note between spacer rests will get the note to appear in the middle of the bar.
    {
        \time 3/4
        \omit Staff.TimeSignature
        s4 d''4 s4 |
        \bar "||"
    }

Comment: I learned a lot from your response.  My daughter is writing a music theory quiz app and lilypond looks a good fit for generating lots of examples by hooking up to python - in this case we'd generate images of notes.

Center a note in lilypond


How to check if filefield has a value or not by Rules

Question: I have a cck file field "pic" users can attach up to 3 images to. I would like to set a Rule with the condition depending on whether user has uploaded at least one image or not.
I set the condition "Saved content's field 'field_pic' has value" + "negate"  But no matter the field has a value or not (a file has been attached or not) the debug says "Condition "Updated content's field 'field_pic' has value" evaluated to FALSE."
I also tried this code below but again always the condition is FALSE.
return array(
  0 => array('fid' => 0, ),
);

How can I set the condition to check if the cck file field has at least one file or not?
Answer: I believe that "has value" needs to return TRUE or FALSE. You need to do the assessment yourself, because the value that it should have might not necessarily be a one or a zero (I would use this rule if I wanted to evaluate if a field has the value of 5, say: If yes, return true.)
You can either put in a value in the text input (5) which it will match for you and return true/false, or you can use PHP to evaluate it and return true or false yourself.
Comment: Thanks but I don't see any text input where I can put a value on Rules configuration page. Did you mean a condition other than "field has value"?
Comment: Switch to "direct input" in the rule config.


How to get data from an api in r?

Question: I am new to api stuff and have come across a small piece of code in python to retrieve data which I would like to replicate in r:
python code:
import requests
import json
from datetime import date
import time
import smtplib, ssl

#API URL
url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'
headers = {'accept': 'application/json','Accept-Language' : 'hi_IN','User-Agent': 'Mozilla/4.0'}
result = requests.get(url, headers=headers)
#Print state ID
print(result.content.decode())

Results:

{"states":[{"state_id":1,"state_name":"Andaman and Nicobar
Islands"},{"state_id":2,"state_name":"Andhra
Pradesh"},{"state_id":3,"state_name":"Arunachal
Pradesh"},{"state_id":4,"state_name":"Assam"},{"state_id":5,"state_name":"Bihar"},{"state_id":6,"state_name":"Chandigarh"},{"state_id":7,"state_name":"Chhattisgarh"},{"state_id":8,"state_name":"Dadra
and Nagar Haveli"},{"state_id":37,"state_name":"Daman and
Diu"},{"state_id":9,"state_name":"Delhi"},{"state_id":10,"state_name":"Goa"},{"state_id":11,"state_name":"Gujarat"},{"state_id":12,"state_name":"Haryana"},{"state_id":13,"state_name":"Himachal
Pradesh"},{"state_id":14,"state_name":"Jammu and
Bengal"}],"ttl":24}

Info about API:
url: 'http://cdn-api.co-vin.in/api/v2/admin/location/states'
from: https://apisetu.gov.in/public/marketplace/api/cowin#/Metadata%20APIs/states

from: https://github.com/cowinapi/developer.cowin/issues/339
(Note: cowin API are restricted to be accessed only in INDIA. So I guess many of you will not be able to use it. But it will be still helpful if you could suggest some code changes.)
R
I have googled abit and tried below pieces of code but none of them worked so far:
library(tidyverse)
library(rjson)
library(jsonlite)
library(RCurl)
library(httr)

states_url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'

headers = c({'accept' = 'application/json'},
            {'Accept-Language' = 'hi_IN'},
            {'User-Agent' = 'Mozilla/4.0'})

url(states_url, headers = headers)

GET(states_url)$content

GET(states_url)$headers

Update
I have tried this and it didnt give error but not sure what to do next:
states_url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'

headers = c('accept' = {'application/json'},
            'Accept-Language' = {'hi_IN'},
            'User-Agent' = {'Mozilla/4.0'})

url(states_url, headers = headers)

A connection with
description "http://cdn-api.co-vin.in/api/v2/admin/location/states"
class       "url-wininet"
mode        "r"
text        "text"
opened      "closed"
can read    "yes"
can write   "no"

GET(states_url, header = headers)$content

1 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c  [20] 49 43 20 22 2d 2f 2f 57 33 43 2f 2f 44 54 44 20 48 54 4d  [39] 4c 20
34 2e 30 31 20 54 72 61 6e 73 69 74 69 6f 6e 61 6c  [58] 2f 2f 45 4e
22 20 22 68 74 74 70 3a 2f 2f 77 77 77 2e 77  [77] 33 2e 6f 72 67 2f
54 52 2f 68 74 6d 6c 34 2f 6c 6f 6f 73  [96] 65 2e 64 74 64 22 3e 0a
3c 48 54 4d 4c 3e 3c 48 45 41 44 [115] 3e 3c 4d 45 54 41 20 48 54 54
50 2d 45 51 55 49 56 3d 22 [134] 43 6f 6e 74 65 6e 74 2d 54 79 70 65
22 20 43 4f 4e 54 45 [153] 4e 54 3d 22 74 65 78 74 2f 68 74 6d 6c 3b
20 63 68 61 7

str(GET(states_url))

List of 10
 $ url        : chr "http://cdn-api.co-vin.in/api/v2/admin/location/states"
 $ status_code: int 403
 $ headers    :List of 9
  ..$ server        : chr "CloudFront"
  ..$ date          : chr "Tue, 25 May 2021 12:39:02 GMT"
  ..$ content-type  : chr "text/html"
  ..$ content-length: chr "919"
  ..$ connection    : chr "keep-alive"
  ..$ x-cache       : chr "Error from cloudfront"
  ..$ via           : chr "1.1 85ad220378d99bdabeb6c46016f1cf16.cloudfront.net (CloudFront)"
  ..$ x-amz-cf-pop  : chr "BOM51-C1"
  ..$ x-amz-cf-id   : chr "eeJq5ZtSJHZkLGoJZBTUL2xL5PcU2gjesnY7Qmg_kMnxZxZ1JUHPWA=="
  ..- attr(*, "class")= chr [1:2] "insensitive" "list"
 $ all_headers:List of 1
  ..$ :List of 3
  .. ..$ status : int 403
  .. ..$ version: chr "HTTP/1.1"
  .. ..$ headers:List of 9
  .. .. ..$ server        : chr "CloudFront"
  .. .. ..$ date          : chr "Tue, 25 May 2021 12:39:02 GMT"
  .. .. ..$ content-type  : chr "text/html"
  .. .. ..$ content-length: chr "919"
  .. .. ..$ connection    : chr "keep-alive"
  .. .. ..$ x-cache       : chr "Error from cloudfront"
  .. .. ..$ via           : chr "1.1 85ad220378d99bdabeb6c46016f1cf16.cloudfront.net (CloudFront)"
  .. .. ..$ x-amz-cf-pop  : chr "BOM51-C1"
  .. .. ..$ x-amz-cf-id   : chr "eeJq5ZtSJHZkLGoJZBTUL2xL5PcU2gjesnY7Qmg_kMnxZxZ1JUHPWA=="
  .. .. ..- attr(*, "class")= chr [1:2] "insensitive" "list"
 $ cookies    :'data.frame':    0 obs. of  7 variables:
  ..$ domain    : logi(0)
  ..$ flag      : logi(0)
  ..$ path      : logi(0)
  ..$ secure    : logi(0)
  ..$ expiration: 'POSIXct' num(0)
  ..$ name      : logi(0)
  ..$ value     : logi(0)
 $ content    : raw [1:919] 3c 21 44 4f ...
 $ date       : POSIXct[1:1], format: "2021-05-25 12:39:02"
 $ times      : Named num [1:6] 0 0.242 0.283 0.284 0.321 ...
  ..- attr(*, "names")= chr [1:6] "redirect" "namelookup" "connect" "pretransfer" ...
 $ request    :List of 7
  ..$ method    : chr "GET"
  ..$ url       : chr "http://cdn-api.co-vin.in/api/v2/admin/location/states"
  ..$ headers   : Named chr "application/json, text/xml, application/xml, */*"
  .. ..- attr(*, "names")= chr "Accept"
  ..$ fields    : NULL
  ..$ options   :List of 2
  .. ..$ useragent: chr "libcurl/7.64.1 r-curl/4.3.1 httr/1.4.2"
  .. ..$ httpget  : logi TRUE
  ..$ auth_token: NULL
  ..$ output    : list()
  .. ..- attr(*, "class")= chr [1:2] "write_memory" "write_function"
  ..- attr(*, "class")= chr "request"
 $ handle     :Class 'curl_handle' <externalptr>
 - attr(*, "class")= chr "response"
Show in New Window

http_status(GET(states_url))

$category
[1] "Client error"

$reason
[1] "Forbidden"

$message
[1] "Client error: (403) Forbidden"

stringi::stri_enc_detect(GET(states_url, header = headers)$content)

[[1]]
     Encoding Language Confidence
1  ISO-8859-1       en       0.54
2  ISO-8859-2       ro       0.26
3       UTF-8                0.15
4    UTF-16BE                0.10
5    UTF-16LE                0.10
6   Shift_JIS       ja       0.10
7     GB18030       zh       0.10
8      EUC-JP       ja       0.10
9      EUC-KR       ko       0.10
10       Big5       zh       0.10
11 ISO-8859-9       tr       0.06
12 IBM424_rtl       he       0.02
13 IBM424_ltr       he       0.01

content(GET(states_url, header = headers), encoding = "UTF-8")

{html_document}

[1] \n<meta http-equiv="Content-Type" content="text/htm ...
[2] \n
403 ERROR
\n
The request could not be  ...

content(GET(states_url, header = headers), encoding = "ISO-8859-1")

{html_document}

[1] \n<meta http-equiv="Content-Type" content="text/htm ...
[2] \n
403 ERROR
\n
The request could not be  ...

python code image:
Comment: You call `url(states_url, headers = headers)` which includes the headers, but that does nothing for the subsequent `GET(.)`, where you do *not* use headers. Your call to `url(.)` is completely useless except for giving you some assurance that something is there. Nothing from that `url(.)` call persists or is used anywhere else. Remove your call to `url(.)`, and do `GET(states_url, add_headers(headers))`.
Comment: Try `rawToChar` on  your raw output (`GET(..)$content`).
Comment: by doing that I get  `[1] "\n\nERROR: The request could not be satisfied\n\n403 ERROR\nThe request could not be satisfied.\n\nRequest blocked.\nWe can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.\n< ......`
Comment: @r2evans I have got `403` error in status code earlier and I am not sure why i get this error when its working fine in python.
Comment: See [my other comment](https://stackoverflow.com/questions/67694266/getting-403-error-in-r-script-but-python-works-fine-on-same#comment119653991_67694266) about the suggested need for OTP. The code in your other question is missing that component, I can only imagine that the python code works because you somehow included it previously (or python's `requests` has found or cached it from elsewhere).
Comment: but I have taken this script from someone else and ran it for first time today as it is. So I am not sure if its related to OTP or not. Right now `Python` script is still working in background fetching me live alerts continuously and I have never used any otp in machine or script.
Comment: Adding python code image to update section !!
Comment: there are multiple api listed on that page so i guess OTP is probably required for `https://cdn-api.co-vin.in/api/v2/auth/public/generateOTP`
Comment: thanks @r2evans, when earlier i tried `GET(url(states_url, headers = headers))` I was getting an error and that's where i got stuck with this. Thank you so much for helping me on this. Was stuck on this from so long and now was thinking of trying `reticulate` to combine both `python` for api and then r for more. Really appreciate ur help & efforts. Thanks again :))
Comment: will close this post by accepting the answer if you could add this in the answer as well. Thanks !!
Answer: You make headers but never include them in your call to GET. Use them there.
GET(states_url, add_headers(headers))

How to get data from an api in r?


Django one-to-many relationship on single model

Question: I'm trying to get django model with sections. Each section can have one or no super section and each section can have many sub-section. here is my model
class Section(models.Model):
    section_name = models.CharField(max_length=100)
    sub_sections = models.ForeignKey('self', related_name='super_section', null=True)
    links = models.ForeignKey('Link')

    def __str__(self):
        return self.section_name

class Link(models.Model):
    link_adress = models.URLField(max_length=2083)
    link_text = models.CharField(max_length=50)
    link_description = models.CharField

    def __str__(self):
        return self.link_text

The problem here is trying to get the admin panel working the way i want to. In the admin panel I want to be able to see and edit subsections and (here is my problem) want to be able to edit the super section my current section is under.
Comment: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.StackedInline
Answer: Your ModelClass Section is wrong. Right now a Section object can only have one sub section.
You should replace the sub_sections attribute with this:
super_section = models.ForeignKey('self', related_name='sub_sections', null=True)

Doing it this way a Section object may have many sub-sections but has at most one super-section.
For more information about how ForeignKey works in Django have a look at the docs.
Now to the admin part:
You can modify your admin panel to show related objects (i.e. super-sections and sub-sections) for a Section object as inlines (TabularInline or StackedInline). Please have a look at the docs for more information about the available Inline classes in Django.
Code for an example inline:
from django.contrib import admin
from yourapp.models import Section

class SectionInline(admin.TabularInline):
    model = Section

class SectionAdmin(admin.ModelAdmin):
    inlines = [
        SectionInline,
    ]

Comment: i tried doing the inline, but doesnt provide what im looking for. When adding a section i want to be able to put a name, select the parent section and add child sections if needed. I would prefer to be able to do this in a single admin page
Answer: You've got your models wrong. If I understand right, this is what you want:
           Super-section
                |
             Section
          ______|______
         |      |      |
        Sub    Sub    Sub

This is how your models should look like:
class SuperSection(models.Model):
    # define your fields here
    # it doesn't need to have a ``ForeignKey``

class Section(...):
    super_section = models.ForeignKey(SuperSection)
    # define other fields
    # doesn't need any more ``ForeignKey``

class SubSection(...):
    section = models.ForeignKey(Section)
    # define other keys

Comment: this is not what im looking for as I would be limited to a total of 3 levels. I want to be able to have n levels if needed.


esse algoritmo é para verificar divisor

Question: esse algoritmo é para verificar se o primeiro é divisor do segundo e no final apresentar se é divisor ou não divisor, não apresenta erro, mas não sei como continuar
#include <stdio.h>
#include <conio.h>
int main()
{
int n1,n2,resto,res;
printf ("\nDigite um numero:");
scanf ("%d", &n1);
printf ("\nDigite um numero:");
scanf ("%d", &n2);
res = n1 / n2;
resto= n1%n2;
printf("\nResultado da divisao de %d / %d = %d. \n",n1,n2,res);
getch();
return(0);
}
Comment: Olá Eleny, acredito que a forma como você fez a pergunta não se enquadra nos protocolos de perguntas do SOpt. Dê uma olhada https://pt.stackoverflow.com/help/how-to-ask, talvez ajude. e dessa forma facilite a resposta para sua pergunta.
Comment: Acrescente `if (n1 % n2 == 0)
 printf(%d é divisor de %d\n", n2, n1);
else
 printf(%d não é divisor de %d\n", n2, n1);
`
Comment: Atenção apenas ao que você postou: `verificar se o primeiro é divisor do segundo`, neste caso inverta `n1` e `n2` pois a resposta acima  verifica se `n2` é ou não divisor de `n1`.
Answer: Se A divide B, o resto da divisão de A por B é zero, ou seja a%b == 0.
Apenas faça:
if(resto == 0)
   printf("\n%d é divisor de %d!",n1,n2);
else
   printf("\n%d não é divisor de %d!",n1,n2)

esse algoritmo é para verificar divisor


How do I transform my data so that it has mean zero and standard deviation one?

Question: Given a series of values,
3.00,5.00,7.00,4.00,7.00,5.00,22.00,4.00,6.00,7.00,9.00,6.00,4.00

I need to 'rescale' the data so they have new values with a mean of 0 and a standard deviation of 1. Having followed a number of examples for the equation, I get the following,
Mean    6.85
StdDev  4.85

The standard deviation I worked out the long way via taking an original value, subtracting the Mean, squaring the result, summing all the squares, dividing that sum by the count -1 before finally getting the square root of that.
(3.00 - 6.85) = -3.85    >    -3.85² = 14.79
(5.00 - 6.85) = -1.85    >    -1.85² =  3.41
...
(4.00 - 6.85) = -2.85    >    -2.85² =  8.10

Sum                                   281.69
Variance (using n -1)                  23.47
Standard Deviation                      4.85

I'm sure it's correct as I checked it here http://www.mathsisfun.com/data/standard-deviation-calculator.html
Using the mean and standard deviation I get new values of,
-0.79,-0.38,0.03,-0.59,0.03,-0.38,3.13,-0.59,-0.17,0.03,0.44,-0.17,-0.59

These values were calculated in the following manner
((3.00 - 6.85)/4.85) = -0.79
((5.00 - 6.85)/4.85) = -0.38
....
((4.00 - 6.85)/4.85) = -0.59

So, to my question.
It's the standard deviation that is the confusing part. I want my new values to have a Mean of 0, and a standard deviation of 1. When I work out the SD for my original values, I get an SD of 4.85. What do I need to do to get an SD of 1 ?
Thank you for taking the time to read the question.
John.
Comment: Your new values do have a standard deviation of $1$ because after subtracting the mean from each of your original values you divided by $4.85$. Where does the confusion arise?
Comment: @M. Berk. Thank you. The confusion came about because, this is all rather new to me and I thought I would need to do soemthing to 4.85 to get a value of 1.
Comment: Take a look at [gung's answer](http://stats.stackexchange.com/a/70555/21054). He nicely explains the different transformations. In your case, you are doing a *standardization*. A standardized variable has a mean of $0$ and a standard deviation of $1$, which is also called [standard score](http://en.wikipedia.org/wiki/Standard_score) or $z$-score.
Comment: @COOLSerdash. Brilliant, thanks. Another thing that has confused me are the terms used. Standardization / Normalization I now know are different things, but the terms are used interchangeably on a lot of sites. This will certainly help me.
Comment: @JTT. as mentioned ealier, this is new to me and I guess I expected to do something else to the new values to end up with a standard deviation value of 1, rather than 4.85.
Comment: Tried to mark the question as 'answered' using @M. Berks comment. However, I'm unable to do this for another 7 hours.
Comment: The SD of your new values is $1$, which is what you wanted: what's the problem?
Answer: I think it is best to post an answer. It was M Berk's comment that was the revelation for me ...

Your new values do have a standard deviation of 1 because after subtracting the mean from each of your original values you divided by 4.85.

Thank you to COOLSerdash and JTT for the other comments too.
Comment: +1 Note that division by $-4.85$ would have worked, too. :-)


Should I avoid using git to track individual files with separate history, such as in /var/named?

Question: In January 2012 Randal Schwartz gave a talk called Introduction to Git that I very much enjoyed, but I was left confused about his admonition not to use git to track individual files with unrelated or separate history.
Page 4 of his slides contain the following bullet points. . .

But not for...

Tracking file permissions and ownership
Tracking individual files with separate history
Making things painful

. . . and here is what he says, around 4 minutes in:

It is not optimized for any kind of metadata about the files.  It does not, it does not, track file permissions or file ownership.  That is not its job.  It's managing source files, and sources don't have owners, sources don't have permissions.  Sources are used in recipes to build the real thing that you are going to deploy.  So git does not have technology about that.  People have tried to build structures on top of it to do that, with some degree of success, but really let's look at basically what git is meant for and not what people are building on top of it.
It's also not meant for tracking individual files with unrelated or separate history.  For example, you may think, "Oh, I really like this.  I want to track all my et cetera with it.  But et cetera is really a bunch of separate, unrelated files.  You wouldn't be doing branching and merging. . . add this change to that change and eventually want to back out both of them at the same time.  It doesn't really work that way.  So it's not good for individual files.
I still use RCS to track individual files in my /etc.  It's really fast, it's cheap, and I can get back to the data I need to. It's also not optimized for making things painful.  Ok?  It's designed to be easy and stuff.

Personally, I have no plans to track my /etc with git, but I recently started using git to track /var/named (BIND configs).  Given what Randal has to say above, should I stop using git for this purpose?  Is there a downside, a problem I'm not anticipating, a gotcha?  So far everything is working just as I expect, and I've had no problems, but I actually hesitated to start using git to track /var/named because of the warning above.
I'm influenced by the scm_track_enabled feature of Cobbler which says "enables a trigger which version controls all changes to /var/lib/cobbler when add, edit, or sync events are performed.  This can be used to revert to previous database versions, generate RSS feeds, or for other auditing or backup purposes.  git is the recommend SCM for use with this feature."  My use of git with /var/named is very similar to this.
(As a side note, I've never used RCS and can't imagine bothering to learn it, even if it is easy, when I already have a decent understanding of git.)
Specifically, I'm wondering about using git to track /var/named, but I welcome answers about best practices for using git to track directories like it.
Comment: Related: http://serverfault.com/questions/341199/git-as-a-backup-tool-am-i-a-silly-person
Answer: This is straying into "quite subjective" territory. But...
I see nothing wrong with using git to track this sort of thing. Yes, it was built for tracking large, complex collections of inter-related source files. That doesn't mean it isn't just as suited to tracking small collections of non-related files.
Personally, I use etckeeper to track <code>/etc</code> on my servers, using the git back-end. Works great. When installed from Ubuntu's apt repo, it comes with nice hooks into apt, so it'll automatically kick off a commit coincident with each new package install. Pretty handy.
Anyway, give it a try, it's not going to hurt anything, and if you end up wanting to switch to another version control system in the future, there are plenty of migration tools available.
Answer: Subjective territory indeed. I dislike etckeeper, what it does is it creates a very messy history of /etc. Now for /var/named (I assume this is where your zones are defined) it might be better, especially if you only have a few zones, but it would still be an ugly hack.
I find that the "correct" way of doing it is to use Puppet or similar other configuration management software. Instead of configuring your servers, you write Puppet code that configures your servers. I use mercurial (but you may use git) to manage the repository of Puppet code. It's useful to branch and merge (e.g. you are working on a new configuration, which you are not certain is tested enough, and then you must urgently fix a problem in a production server; in this case you branch from the stable version and later you merge). The combination of Puppet+DVCS is very useful and very clean, but Puppet is a small beast that needs a little time to tame, and bind is particularly tricky to do right with Puppet because of the zone serial numbers.
Update:
I have been thinking about it and I tend to conclude that there is nothing wrong in using git to keep track of /var/named, and that it's not an ugly hack. Yes, the files are related. Yes, you might want to clone in order to make a serious revision of your configuration, branch, in order to maintain your production configuration while revising, and merge, when you finish the revision (although all this might be unusual).
A bit off topic, but there are two things about bind's configuration that I dislike. First, in order to add a zone I need to add/modify two files: named.conf, and the zone file. This is unnecessarily complicated. I'd prefer a setup similar to apache's, with zone files in /etc/bind/zones-available, symlinked from /etc/bind/zones-enabled, without the need to touch named.conf. Second, the serial numbers are a nuisance. We mostly automate their maintenance; in Puppet-managed machines I have a shell script that fixes them, and in others I use a vim plugin. The fact that we automate them means they could well be absent. File timestamps could be used instead. The serial numbers will create some ugliness in the repository history, but this is a problem of bind, and not a problem of git, or of the practice of using git for tracking the bind configuration.
Comment: I agree that managing BIND with Puppet might be tricky.  See also http://serverfault.com/questions/168144/managing-zone-files http://irclog.perlgeek.de/crimsonfu/2012-04-24#i_5488807 and http://irclog.perlgeek.de/crimsonfu/2012-04-25#i_5492463
Comment: Thanks for the update. See also this "BIND API" question: http://serverfault.com/questions/276995/bind-http-api
Answer: Ask yourself...
Would I ever "revert" to a particular commit in git, if it covered all of /etc?
Would I ever "merge" a commit to my current state, if it covered all of /etc?
I'm guessing the answer is NO, NO, NO.
If so, git is the wrong tool.  Git is tracking a tree of files, not a single file.  This is why I argue for RCS for single files.
Comment: I have to admit that RCS does look pretty simple, having just looked through http://www.madboa.com/geek/rcs/ and Randal is right that RCS seems to handle single files very well.


select element by css

Question: I have many lines on my page generated from database with PHP. Each line is in DIV. I'd like to "select" a line by clicking on it. "Select" means change css for it. What is the easiest way to do it?
Answer: smarter way is to use js frameworks, like jQuery:

...

...

...

Comment: it doesn't work. I have it as you told: ......
both script sections i placed in html head area.
Comment: is it possible with this solution select only one line at the same time?
Comment: what should i place in onclick="" in every line-div?
Comment: oh i'm sorry. i've forgotten :) not onClick(function() ..., but just click(function()...).
Comment: i recommend you to learn jQuery framework, it's very useful, simple, smart and nice
Answer: You could do just a onclick event and change the css class;

content

Comment: great! but what if i need only one selected line? Is it possible to set all lines on "unselected" class?
Comment: @eugenA try my code. toggleCss removes class if it's exists, and adds if it isn't

select element by css


How to get the vocabulary ID of a taxonomy term?

Question: I need to get vocabulary ID by term object.Please see attched screenshot for term object.
Answer: You should be able to use the getVocabularyId() function on the term object like:
$vocabulary_id = $term->getVocabularyId();

See https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/function/Term%3A%3AgetVocabularyId/8.2.x.
Comment: $term->getVocabularyId() is deprecated. Use $term->bundle() instead.
Answer: I think we're supposed to use EntityInterface::bundle now as Term::getVocabularyId is deprecated:

Scheduled for removal before Drupal 9.0.0. Use TermInterface::bundle()
  instead.


Date not changing with object.setDate()

Question: I'm trying to create a calendar object with weeks, days and hours, where each day has a date. I set the starting date to Jan 2. 2017 but after the loop is completed all the days in the calendar has the date Jan 2. 2018.
var calendar = {};
var date = new Date(2017,0,2);

calendar['weeks'] = [];
for (var w = 0; w < 52; w++) {
    calendar['weeks'][w] = {};
    calendar['weeks'][w]['number'] = w+1;
    calendar['weeks'][w]['days'] = [];
    for (var d = 0; d < 7; d++) {
        calendar['weeks'][w]['days'][d] = {};
        calendar['weeks'][w]['days'][d]['date'] = date;
        calendar['weeks'][w]['days'][d]['hours'] = [];
        calendar['weeks'][w]['days'][d]['number'] = d+1;
        for (var h = 0; h < 24; h++) {
            calendar['weeks'][w]['days'][d]['hours'][h] = {};
            calendar['weeks'][w]['days'][d]['hours'][h]['number'] = h+1;
        }
        date.setDate(date.getDate()+1);
    }
}

Comment: Note that you can write `calendar.weeks` instead of `calendar['weeks']`
Answer: You only have one date object. When you link it into your calendar object over and over again in that loop, every reference is to the same object.
You'll need to make new instances on each iteration:
    date = new Date(date);
    date.setDate(date.getDate() + 1);

Alternatively, make a new instance when you set up that "date" property:
    calendar['weeks'][w]['days'][d]['date'] = new Date(date);

which could also be written:
    calendar.weeks[w].days[d].date = new Date(date);

Comment: Since the *set\** methods return the new time value: `calendar.weeks[w].days[d].date = new Date(date.setDate(date.getDate()+1))` will increment and copy in one go. ;-)

Date not changing with object.setDate()


Trouble Installing php-mysql from webtatic

Question: I have a fresh instance on EC2 of "Linux/Unix, CentOS 6 | 64-bit Amazon Machine Image (AMI)"
This is what I did to get it running.
yum install wget
wget http://repo.webtatic.com/yum/el6/latest.rpm
sudo rpm -Uvh latest.rpm
yum repolist
yum update

sudo yum install httpd mod_ssl
sudo /usr/sbin/apachectl start
chkconfig --levels 235 httpd on

vi /etc/sysconfig/iptables
// add -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
// add -A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
/etc/init.d/iptables restart

sudo yum install php54w php54w-mysql php54w-gd php54w-xml php54w-xmlrpc php54w-mbstring php54w-mcrypt php54w-pdo php54w-soap

When I get to the final command it fails because:
Error: mysql55-libs conflicts with mysql-libs-5.1.67-1.el6_3.x86_64
Error: Package: php54w-mcrypt-5.4.13-1.w6.x86_64 (webtatic)
           Requires: libmcrypt.so.4()(64bit)

I tried not installing php54w-mcrypt, but php54w-mysql still fails. If I try installing php-mysql (not php54w) it still fails.
Any ideas how to resolve this?
Edit: Is there an alternate repo to webtatic I can use that has the latest stable releases, that does work? Yum base doesn't include php 5.4, which I'd like to use.
Comment: Curious what the solution is, but for now, decided to go with remi. If anyone has an insight into how to resolve this I'd still be very interested.
Answer: As Electrawn mentions, the libmcrypt package is now in the Webtatic repo, it was depending on the EPEL repository, but not everyone has this installed.
As for the php54w-mysql installing MySQL 5.5 issue, this was resolved 6th May:
http://www.webtatic.com/news/2013/05/latest-updates-php-5-4-14-5-3-24/
Answer: I ran into this issue, and sent an email to Andy who runs the webtatic repository. The libmcrypt missing dependency is now included in webtatic repo.
Turnaround on the email was 16 hours.
Comment: just a correction on that turnaround, 7 hours turnaround from your email.
Answer: If you run into this issue installing php??w-mysql, try the following instead:
yum install php??w-mysqlnd

This will skip the dependency check.


VerificationException "Operation could destabilize runtime" Error with MsgPack and .net Error

Question: Encountered VerificationException "Operation could destabilize runtime" error using MsgPack to serialize some F# types. The compiler also suggests that conflicting class libraries may be loaded, but this appears to be a red herring.
It's not immediately clear what the error is caused by, so posting the solution below for community benefit.

In response to Comments below:
<code>....Sammo\bin\Debug>peverify /verbose Sammo.exe

Microsoft (R) .NET Framework PE Verifier.  Version  4.0.30319.17929
Copyright (c) Microsoft Corporation.  All rights reserved.

All Classes and Methods in Sammo.exe Verified.

....Sammo\bin\Debug>Sammo.exe
Unhandled Exception: System.Security.VerificationException: Operation could destabilize the runtime.
   at _4(MsgPackReader )
   at _3(MsgPackReader )
   at MsgPack.CompiledPacker.Unpack[T](Stream strm)
   at MsgPack.CompiledPacker.Unpack[T](Byte[] buf, Int32 offset, Int32 size)
   at MsgPack.CompiledPacker.Unpack[T](Byte[] buf)
   at <StartupCode$Sammo>.$Program.main@() in ....\Sammo\Pro
gram.fs:line 67

....\Sammo\bin\Debug>
</code>
Comment: Can you run `peverify --verbose` on your compiled assembly and post the results here (if there are any errors)? (If you haven't used `peverify` before, you need to run it from the Visual Studio command prompt instead of the normal command prompt).
Answer: The problem is that MsgPack, a serialization library does not support particular DateTime formats or conventions.
The error message output is misleading however, and it's only when you dig deeper into the Exception that you can find more clues about what is going on.
As an alternative solution, one can instead use a Unix timestamp or the .Net Ticks [100ns] concept for the underlying value/field with an appropriate member definition to expose a System.DateTime.
Comment: Hmm, DateTime is not a template and it is not an attribute.  A very simple type, it hasn't changed since .NET 1.0.  It doesn't sound like you identified the real problem.
Comment: I'm afraid I haven't stated the problem clearly enough - the problem is that MsgPack library doesn't support serializing the System.DateTime type, but I suppose the error produced by VisStudio is a little misleading and could be worth following up.


How to do Iscsi deep discovery?

Question: In our storage array we change the discovery IP. Once the discovery IP is changed, the Multipath connection has to be rebalanced (It should make connection again with new discovery ip). But it is not rebalanced. We had to do Rescan disk and Iscsi deep discovery.
We found diskpart command to rescan disk

(rescan | diskpart)

but we could not find a way to do Iscsi deep discovery. How to do Iscsi deep discovery? Is there any powershell cmdlet to do it?
Comment: Update-IscsiTarget does deep discovery.
Answer: Since iSCSI discovery IP has changed, you need to manually add a new Discovery portal to the MS iSCSI Initiator by using PowerShell or iscsicpl GUI. Here is the topic on how to add a new Discovery portal: (https://blogs.msdn.microsoft.com/san/2012/07/31/managing-iscsi-initiator-connections-with-windows-powershell-on-windows-server-2012/)

How to do Iscsi deep discovery?


Cross-Section Analysis

Question: I have cross-section individual data and   would like to regress individuals' 2011 wages (in logarithm) on the region-varying minimum wage (MW).
The MW variable will be subject to endogeneity (e.g. omitted variable bias, etc.) and I will use OLS IV approach as the identification strategy.
I have multiple observations for the local MW but only the 2011 observation on individual wages.  My question is what is the difference in terms of benefits/costs and interpretation in the respective coefficients if I were to use the real MW level in 2010 versus using the change in the MW from the 2004-2010 period (i.e. first-differencing).
Any direct answer or text recommendation is greatly appreciated.
Answer: By no means an expert at this, but I don't think there is any benefit in using the change in the minimum wage when your dependent variable is cross-sectional. You would still face the same problem of potential endogeneity. Furthermore, I don't see how the relative change in a variable would be an appropriate choice when trying to predict the level of an outcome variable.

Cross-Section Analysis


Cannot create user, email: invalid!! while trying to create a user

Question: Here is the export of my rule:
<code>{ "rules_create_drupal_user" : {
  "LABEL" : "Create Drupal User",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "civicrm" ],
  "ON" : { "civicrm_contact_edit" : [], "civicrm_contact_create" : [] },
  "IF" : [
    { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm_contact" ] } }
  ],
  "DO" : [
    { "civicrm_entity_action_create_user" : {
        "USING" : {
          "civicrm_contact" : [ "civicrm_contact" ],
          "is_active" : "1",
          "notify" : "0",
          "signin" : "0",
          "username_format" : "first last"
        },
        "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
      }
    }
  ]
}
}
</code>
An "Cannot create user, email: invalid!!" error occurs soon after submitting the webform. Drupal user has to be created soon after Civicrm contact is created. After submitting webform as I have used civicrm integration, civicrm contact is created.
Any help?
Answer: Here is a rule that fires when civicrm contact is created. It works off Tag, ie the webform adds a Tag to the Contact. Rules then runs off that event. Note this rule also auto logs the person in but you should be able to get some clues from this. You need civicrm_entity module.
<code>    { "rules_self_create_user_account_and_login" : {
    "LABEL" : "Create User Account",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_entity_tag_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-entity-tag:entity-id-contact" ] } },
      { "data_is" : {
          "data" : [ "civicrm-entity-tag:entity-table" ],
          "value" : "civicrm_contact"
        }
      },
      { "data_is" : { "data" : [ "civicrm-entity-tag:tag-id" ], "value" : "525" } }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-entity-tag:entity-id-contact" ],
            "is_active" : "1",
            "notify" : "1",
            "signin" : "1",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      },
      { "redirect" : { "url" : "civicrm\/user?reset=1" } }
    ]
  }
}
</code>


Android multitouch: no ACTION_POINTER_DOWN and UP events

Question: Here is my code:
public boolean onTouch(View v, MotionEvent event) {

    switch(event.getActionMasked()) {

    case MotionEvent.ACTION_DOWN:
        Log.d("getButtonCode", "catch ACTION_DOWN");
        break;
    case MotionEvent.ACTION_POINTER_DOWN:
        Log.d("getButtonCode", "catch ACTION_POINTER_DOWN");
        break;
    case MotionEvent.ACTION_POINTER_UP:
        Log.d("getButtonCode", "catch ACTION_POINTER_UP");
        break;
    case MotionEvent.ACTION_UP:
        Log.d("getButtonCode", "catch ACTION_UP");
    case MotionEvent.ACTION_CANCEL:
        Log.d("getButtonCode", "catch ACTION_CANCEL");
    case MotionEvent.ACTION_MOVE:
        break;
    default:
        break;
    }
    return true;
}

and I never catch ACTION_POINTER_DOWN and ACTION_POINTER_UP. If I remove breakfrom ACTION_DOWN, I catch ACTION_POINTER_DOWN always after ACTION_DOWN, even if it is first pointer. I think it should be so: first pointer catch only ACTION_DOWN, every next pointer only ACTION_POINTER_DOWN, if non-primary pointer has gone up, I should catch ACTION_POINTER_UP.
But it doesn't work. What is wrong in my code?
PS: I saw other similar questions, but no answer helped me.
Answer: Instead of using a switch statement, I flowed through a series of if statements. This let me test against event.getAction() or event.getActionMasked() and it allowed multiple possible actions through at once.
public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startingX = (int) event.getX();
                startingY = (int) event.getY();
            }
            if(event.getAction() == MotionEvent.ACTION_MOVE) {
                int scaleX = 1;
                int scaleY = 1;
                if(touchStateScale == true){
                    scaleX = (int) (event.getX(0) - event.getX(1));
                    scaleY = (int) (event.getY(0) - event.getY(1));
                }
                int endingX = (int) event.getX();
                int endingY = (int) event.getY();

                int newX = endingX-startingX;
                int newY = endingY-startingY;

            ((ImageView) v).setImageBitmap(drawNewImageScaled(baseImage, newImageResourceId, newX, newY, scaleX, scaleY));
            }
            if(event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN){
                Log.i(TAG, "second pointer detected");
                touchStateScale = true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                touchStateScale = false;
                return false;
            }
            return true;
        }
    };


Non overlapping Clustering/ Segmentation of image points

Question: I have this simple image from map building that I wish to cluster to extract the black dots as points in image co-ordinates (ie. the x,y coordinates of the cluster centers). I have tried many functions in opencv, sklean and ndimage. These manage to cluster well but I cannot get any to have non overlapping clusters ie. one for each black dot, there are either too many or they're not all covered.
I have tried playing with parameters but feel like there must be a good way of doing this since after thresholding the black points are extremely clear, the problem is that they are not actually together but lots of smaller points which means clustering finds them as many clusters. Wondering if anyone has any insight.

Many thanks
Answer: Approach 1: Threshold the image such that only the black pixels remain on a white background. Smooth the image with a gaussian kernel/filter, which will have the effect of blurring the scattered pixels together within each cluster. The kernel width should be wide enough that points in each cluster merge into a single bump, but not so wide that multiple clusters blur together. Each cluster now corresponds to a blurry spot in the image. Find cluster centers as the local extrema or centers-of-mass of these spots. For example, this could be done using image processing functions to find connected groups of non-white pixels (each group corresponds to a cluster). Find the center of each cluster as the blackest pixel, or take the average pixel location weighted by blackness. This method is essentially performing density-based clustering on a kernel density estimator of black pixel locations.
Approach 2: Threshold the image such that only the black pixels remain on a white background. Extract the xy location of each black pixel. The $(x,y)$ pair for each black pixel is a point in 2d space. Cluster these points using a standard statistical clustering method like k-means, Gaussian mixture models, DBSCAN, etc. You may have to select hyperparameters of the algorithm to obtain a good clustering. For example, some methods require you to specify the number of clusters (there are also automated procedures for choosing this; search this site for details). Cluster centroids are returned by the clustering algorithm (or can otherwise be computed from the points assigned to each cluster).


Which result to choose when Kruskal-Wallis and Mann-Whitney seem to return contradicting results?

Question: I have these groups where the values are responses to a 10-point Likert item:
g1 <- c(10,9,10,9,10,8,9)
g2 <- c(4,9,4,9,8,8,8)
g3 <- c(9,7,9,4,8,9,10)

Therefore I used Kruskal-Wallis to determine any differences between responses in the groups, and the result was:
Kruskal-Wallis chi-squared = 5.9554, df = 2, p-value = 0.05091

However, if I run an exact Mann-Whitney test between groups g1 and g2 I get:
Exact Wilcoxon Mann-Whitney Rank Sum Test (using coin::wilcox_test)
Z = 2.3939, p-value = 0.02797

which returns a significant difference at alpha = 0.05.
Which test should I choose, and why?
Comment: For some laughs and on the topic of black and white cut offs: https://mchankins.wordpress.com/2013/04/21/still-not-significant-2/
Answer: The Mann-Whitney or Wilcoxon test compares two groups while the Kruskal-Wallis test compares 3.  Just like in the ordinary ANOVA with three or more groups the procedure generally suggested is to do the overall ANOVA F test first and then look at pairwise comparisons in case there is a significant difference.  I would do the same here with the nonparametric ANOVA.  My interpetation of your result is that there is marginally a significant difference between groups at level 0.05 and if you accept that then the difference based on the Mann-Whitney test indicates that it could be attributed to g$_1$ and g$_2$ being significantly different.
Don't get hung up with the magic of the 0.05 significance level!  Just because the Kruskal-Wallis test gives p-value slightly over 0.05, don't take that to mean that there is no statistically significant difference between the groups.  Also the fact that the Mann-Whitney test gives a p-value for the difference between g$_1$ and g$_2$ a little below 0.03 does not somehow make the difference between the two groups highly significant.  Both p-values are close to 0.05.  A slightly different data set could easily change to Kruskal-Wallis p-value by that much.
Any thought you might have that the results are contradictory would have to come from thinking of a 0.05 cut off as black and white boundary with no gray area in the neighborhood of 0.05.  I think these results are reasonable and quite compatible.
Comment: You will better communicate your answer when you re-read it for errors (in punctuation, grammar, typography, and spelling) and use effective formatting. Please review the [Markdown help page](http://stats.stackexchange.com/editing-help).
Comment: @whuber Sorry for not editing the post earlier.  I hope it looks a lot better now.
Comment: The more classic view is that you failed to find statistical significance with your first test, so you should not report (in a professional publication) any further tests as statistically significant indications of between group differences.  To do so is to use an alpha other than .05.  This is particularly problematic (from the classical view) because you did not choose the higher alpha before conducting the test, so your alpha is unknown.  Of course, when you try to understand your data, to guide your own future research program, you can take note of the difference between groups 1 and 2.
Comment: @JoelW.  Are you trying to tell me that 0.05091 is really different from 0.05?  Anyway my point is not how to report the conclusions but rather to say that the two tests don't conflict. I agree that how you analyze the data should be specified in advance before looking at the data.
Comment: @JoelW Your 'more classic' view is actually Neyman's 'inductive behaviour' approach to inference. It is relevant to a small subset of the uses of statistics in support of inference. It is most unfortuate that it is presented so often as being classic.
Comment: @MichaelLew, do you mean there are recommended ways to select your alpha level (other than in advance of calculating your test statistic) in making inferences?  If so, what are those ways?
Comment: @MichaelLew, what are the types of "uses of statistics in support of inference" that you are referring to (other than null hypothesis testing)?
Comment: @JoelW The only thing I can imagine that he is referring to would be Bayesian inference where prior belief in the null hypothesis is combined with observed data leads to posteriori odds favoring the null hypothesis vs alternatives.
Comment: @MichaelChernick, are you saying, or are you suggesting MichaelLew is saying, that it is ok to select your alpha level after running your (Bayesian) statistical test?
Comment: No Joel all i am doing is suggesting that he may be referring to taking a Bayesian approach to hpyothesis testing rather than the Neyman-Pearson  frequentist approach.  Significance levels for tests have nothing to do with Bayesian ideas.
Comment: @MichaelChernick, but decision rules can be used in Bayesian statistics (e.g., Kruschke's article on [Bayesian data analysis](http://www.indiana.edu/~kruschke/articles/Kruschke2010WIRES.pdf), see the example pp. 10-11).  Are you suggesting it is proper to set up these decision rules (akin to significance tests) after the fact, that is, after the Bayesian analysis is run?
Comment: @JoelW. Your link doesn't work.  Why are you trying to read so much into what I say.  The common Bayesian approach to hypothesis testing is to construct an odds ratio for the null hypothesis. If you like you can specify that it will be the analysis approach you will take prior to doing the analysis. What decision rule do you think the Bayesian would like to make regrading hypothesis testing?  I suppose you could set a threshold on the odds against the null hypothesis and reject if the posterior odds are greater than that specified value.
Comment: @JoelW. I fixed your broken link. It's easier to use [Markdown](http://stats.stackexchange.com/editing-help), for linking to external reference (e.g., `[Markdown](http://stats.stackexchange.com/editing-help)`).
Comment: @MichaelChernick, it just seemed that you may have been treating decision rules as flexible.  I wondered the extent to which your flexibility extended.  Thanks, Chi, for telling me about the markdown page.  How do I find other such pages on this site?
Comment: @JoelW The Kruschke article is a highly opinionated anti-frequentist article. I do not agree with much of what he says. But putting that aside and assuming the Bayesian approach is taken what specific decision rules do you have in mind other than the odds of the null hypothesis being true?
Comment: @JoelW. I'm not advocating choosing of alpha after the experiment. I am advocating not using an alpha at all. Neither did I advocate a Bayesian approach, although if real prior probabilities are available then that would obviously be sensible. The N-P approach is not useful in many circumstances because scientists almost never adhere to the behavioural expectation that allows the N-P approach to deliver type I error rate equal to or less than alpha. Error rates are rarely interesting to a scientist. Evidence is.
Comment: Neyman-Pearson hypothesis testing is not the only frequentist framework for statistics. Frequentists ideas relate to the nature of probability as the long run frequency of events (real and notional). The type I and type II error rate ideas are one way of using that frequentist notion of probability, but they are not necessary or desirable in many cases. See my paper linked in my answer to the original question above for more detail and a good starting set of references.
Comment: I am perfectly happy with the Neyman-Pearson approach to hypothesis testing. There may be other ways to look testing in the frequentist framework but if you view it in terms of rejecting versus not rejecting the null hypothesis of no difference then to some extent you are trading off between type I and type II error.
Comment: @MichaelChernick I'm definitely _not_ advocating rejection or non-rejection of the null hypothesis. I think that you should read my paper because you seem to be mixing incompatible models of inference.
Comment: @MichaelLew I would read your paper if I were interested in your argument but I am not.  Given that I am not in any position to argue about your approach to hypothesis testing.
Answer: I agree with Michael Chernick's answer, but think that it can be made a little stronger. Ignore the 0.05 cutoff in most circumstances. It is only relevant to the Neyman-Pearson approach which is largely irrelevant to the inferential use of statistics in many areas of science.
Both tests indicate that your data contains moderate evidence against the null hypothesis. Consider that evidence in light of whatever you know about the system and the consequences that follow from decisions (or indecision) about the state of the real world. Argue a reasoned case and proceed in a manner that acknowledges the possibility of subsequent re-evaluation.
I explain more in this paper:
http://www.ncbi.nlm.nih.gov/pubmed/22394284
[Addendum added Nov 2019: I have a new reference that explains the issues in more detail https://arxiv.org/abs/1910.02042v1 ]
Comment: @MichaelLew I don't share your dim view of the Neyman-Pearson approach to hypothesis testing.  I still think it is fundamental to frequentist inference. It is only the strict adherence to the 0.05 level that I object to.
Comment: Scientists are interesting in evidence but they are not hung up on the methodology used to decide significance.
Comment: @MichaelChernick I have became to learn from you that there is much more on statistics than just looking for "p<0.05". Michael Lew: I've downloaded your paper and will give it a read for sure. I'll follow your suggestion to have a good reasoning about my data in this situation. Thank you all!
Comment: @MichaelChernick So, are you saying that one should choose a cutoff for significance prior to the experiment, or that you can choose it after the results are in. The first is OK, but the second is not. Neyman-Pearson approach deals with error rates, and the type I error rate is only protected when the cutoff for significance is chosen in advance. Thus if you advise someone that a little over 0.05 is close enough because they might have chosen a higher cutoff, then you are not actually using the Neyman-Pearson approach, but an ill-formed hybrid approach as I explain in the paper linked.
Comment: People can choose 0.01, 0.05 or 0.10 if they want.  This should be done without being influenced by the data.  But the choice of 0.01 or 0.05 is not the issue I refer to.  It is the black and white belief in the significance level as those 0.049 means statistical significance and 0.0501 is not!
Comment: @MichaelChernick If you use the Neyman-Pearson approach, as your comment below the other answer implies, then when alpha is 0.05 a result of P=0.049 _is_ different to a result of P=0.051. That is because the Neyman-Pearson approach eschews the concept of evidential meaning of data in favour of error rates. You cannot use Neyman-Pearson and talk about evidence. If you won't read my paper, then perhaps you can read this one by Steve Goodman:
Comment: @MichaelLew No the Neyman-Pearson appraoch has nothing to do with people being overly strict about alpha. Yes it does say to fix alpha but interpretation of 0.049 vs 0.0501 is not the fault of the method.
Answer: Results of Kruskal-Wallis and Mann-Whitney U test may differ because

The ranks used for the Mann-Whitney U test are not the ranks used by the Kruskal-Wallis test; and
The rank sum tests do not use the pooled variance implied by the Kruskal-Wallis null hypothesis.

Hence, it is not recommended to use Mann-whitney U test as a post hoc test after Kruskal-Wallis test.
Other tests like  Dunn's test (commonly used), Conover-Iman and  Dwass-Steel-Citchlow-Fligner tests cane be used as post-hoc test for kruskal-wallis test.
Answer: This is in answer to @vinesh as well as looking at the general principle in the original question.
There are really 2 issues here with multiple comparisons: as we increase the number of comparisons being made we have more information which makes it easier to see real differences, but the increased number of comparisons also makes it easier to see differences that don't exist (false positives, data dredging, torturing the data until it confesses).
Think of a class with 100 students, each of the students is given a fair coin and told to flip the coin 10 times and use the results to test the null hypothesis that the proportion of heads is 50%.  We would expect p-values to range between 0 and 1 and just by chance we would expect to see around 5 of the students get p-values less than 0.05.  In fact we would be very surprised if none of them obtained a p-value less than 0.05 (less than 1% chance of that happening).  If we only look at the few significant values and ignore all the others then we will falsely conclude that the coins are biased, but if we use a technique that takes into account the multiple comparisons then we will likely still judge correctly that the coins are fair (or at least fail to reject that they or fair).
On the other hand, consider a similar case where we have 10 students rolling a die and determining if the value is in the set {1,2,3} or the set {4,5,6} each of which will have 50% chance each roll if the die is fair (but could be different if the die is rigged).  All 10 students compute p-values (null is 50%) and get values between 0.06 and 0.25.  Now in this case none of them reached the magic 5% cut-off, so looking at any individual students results will not result in a non-fair declaration, but all the p-values are less than 0.5, if all the dice are fair then the p-values should be uniformly distributed and have a 50% chance of being above 0.5.  The chance of getting 10 independent p-values all less than 0.5 when the nulls are true is less that the magic 0.05 and this suggests that the dice are biased, we just did not have enough power to detect this in the individual trials, but grouping the information shows the null is false.
Now coin flipping and die rolling are a bit contrived, so a different example:  I have a new drug that I want to test.  My budget allows me to test the drug on 1,000 subjects (this will be a paired comparison with each subject being their own control).  I am considering 2 different study designs, in the first I recruite 1,000 subjects do the study and report a single p-value.  In the second design I recruite 1,000 subjects but break them into 100 groups of 10 each, I do the study on each of the 100 groups of 10 and compute a p-value for each group (100 total p-values).  Think about the potential differences between the 2 methodologies and how the conclusions could differ.  An objective approach would require that both study designs lead to the same conclusion (given the same 1,000 patients and everything else is the same).
@mljrg, why did you choose to compare g1 and g2?  If this was a question of interest before collecting any data then the MW p-value is reasonable and meaningful, however if you did the KW test, then looked to see which 2 groups were the most different and did the MW test only on those that looked the most different, then the assumptions for the MW test were violated and the MW p-value is meaningless and the KW p-value is the only one with potential meaning.


Views exposed filters without "Apply" button

Question: I have created a view with exposed filters of term select list. How can I make the select list to work directly on selecting an item, instead of clicking on the "Apply" button?
Answer: Under advanced portion of view choose following
<code>**Exposed form**

 Exposed form style: Basic | Settings
</code>
Then Choose autosubmit in Settings as shown below

This will hide the Apply button and the select list to work directly on selecting an item, instead of clicking on the Apply button.
Comment: Is there a solution for this problem in drupal 8? There doesn't seem to be an autosubmit checkbox and a hide submit button checkbox. Thanks.
Comment: yes it is available without better exposed filter also. i updated the answer
Comment: I just configured as mentioned above, but now the filter is invisible. I use Views: 7.x-3.5 and BEF: 7.x-3.0-beta3
Comment: you mean exposed filter? please recheck. The above solution works here properly
Comment: Yes, exposed filter is invisible
Comment: I think you enable Exposed form in block: Yes, and it moved to blocks. in your case you can disable this option to Exposed form in block: No. Please try and let me know
Comment: I got the problem, actually I am trying to do that on page view so the exposed filter is not appearing
Comment: change Exposed form in block: to No
Comment: The good part is, I am able to disable the 'Apply' button without using the 'Better Exposed Filters' module. By selecting the Autosubmit option under Exposed form style:Basic | Settings. All this works on block view
Comment: views exposed filters started working on page again, after removing and re-adding them again.
Comment: Thanks  Anoop Joseph, Actually it all works without using 'Better Exposed Filters' module.
Comment: yeah...:) i edited answer
Answer: For Drupal 8/9, You need the following module:
https://www.drupal.org/project/views_autosubmit
Comment: thank you! You da man
Answer: If you're using Drupal 8. Choose Exposed form style as Autosubmit and then in Settings check Hide submit button checkbox.


Using and Running Visual Basic on Mac

Question: This may seem like an absolutely stupid question, but it is one I really need to ask.
I have to find a way to be able to write and run a Visual Basic program on my Mac (Sierra). I have downloaded Visual Studio Community, and have even installed the Mono Project for VB, although honestly I am not quite sure how to use it.
I need to be able to write the VB code and create an editable form to work with it. I will need to compile it and run it on Mac, but I do not have to turn it into an executable.
So, without Boot Camp or Parallels or anything like that, is there ANY way to get Visual Basic, as described above, to work on Mac Sierra?
Comment: Have you installed Monodevelop? From here you should be able to run your code and debug through this.
Comment: @Jaxi I have now installed Monodevelop, but I can't find a way to open a digital designer for the form. I am able to open the code, though. Am I actually able to create a form GUI I can use for VB?
Comment: WinForm isn't well supported for Mac OSX, since Mac OSX usually uses GTK+ for design. You can read here for any more info that you may need: http://www.mono-project.com/docs/gui/winforms/
Comment: You can only perform .NET Core development in VB, https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new?tabs=netcore2x and use Visual Studio Code.
Answer: You can edit code on VS for Mac, but you can't run it. You should do bootcamp or VM Ware if you have a license for an extra copy of Windows.

Using and Running Visual Basic on Mac