Type aware string to number conversion in C++

Question: Let's assume all the numbers in this world are positive integers and they can be represented by uintX_t C++ types.
Let's consider next awesome code to convert a std::string to a number:
#include <string>
#include <cstdint>
#include <iostream>

template <typename T>
T MyAwsomeConversionFunction(const std::string& value)
{
    T result = 0;
    for(auto it = value.begin(); it != value.end() && std::isdigit(*it); ++it)
    {
        result = result * 10 + *it - '0';
    }

    return result;
}

int main(int argc, const char * argv[])
{
    std::cout<<MyAwsomeConversionFunction<uint16_t>("1234")<<std::endl;
    std::cout<<MyAwsomeConversionFunction<uint16_t>("123456")<<std::endl;

    return 0;
}

As you can see there are multiple errors in this function, but I'm interested in a particular one: How to detect when my type is not large enough to contain the value (second conversion call as example) and avoid UB when making result = result * 10 + *it - '0';. I would like to know if that operation will exceed maximum value of T before making it. Is this possible?
EDIT: please check Is signed integer overflow still undefined behavior in C++? for more info about UB on arithmetic operations in C++. I want to avoid executing the line result = result * 10 + *it - '0'; when the result will overflow. In the answer the line is still executed...
EDIT2: I found the answer here: How to detect integer overflow?
EDIT3: The accepted answer applies for signed types. For unsigned types Cheers and hth. - Alf answer is correct.
Comment: Note that the standard library has [even more awesome code](http://en.cppreference.com/w/cpp/string/basic_string/stol) that will detect overflow and throw an exception.
Answer: I'll take a whack at this, although I may get picked apart for mistakes. This does not deal with negative values in the string (your original code doesn't either). And it's limited to ASCII digits, as Alf mentioned in a comment on his answer.
template <typename T>
T MyAwsomeConversionFunction(const std::string& value)
{
    T maxBeforeMult = std::numeric_limits<T>::max / 10;
    T result = 0;
    for(auto it = value.begin(); it != value.end() && std::isdigit(*it); ++it)
    {
        // Check if multiplying would overflow
        if (result > maxBeforeMult)
        {
            // throw overflow
        }

        result = result * 10;
        T digit = *it - 0;

        // Check if adding would overflow
        if (std::numeric_limits<T>::max - result < digit)
        {
            // throw overflow
        }

        result += digit;
    }

    return result;
}

Comment: This is needlessly inefficient and needlessly verbose and complex, but I understand how the OP, acting on a false belief about UB, voted it as a "solution". Such is SO. Readers should be aware of this, so that they don't choose this approach.
Comment: @Cheersandhth.-Alf: Feel free to suggest (or even edit in) improvements. And I'm not sure what you mean by "false belief about UB", since signed overflow appears to be exactly his concern (although that was not made clear in the original question).
Comment: the OP has asserted repeatedly, including in the question itself, that the types will only be unsigned. an efficent and simple solution for signed is to do the conversion as unsigned and then check signed limits. general solution is to use the standard library.
Comment: Quote from the C++ standard, section 5, Expressions: "If during the evaluation of an expression, the result is not mathematically defined or not in the range of
representable values for its type, the behavior is undefined."
Comment: @Cheersandhth.-Alf: I can see nowhere where such an assertion has been made. You seem to have inferred that from the `main()`, but further edits and comments refer to signed overflow (such as the link the the question about signed overflow).
Comment: @Felics: check out C++11 footnote 46 in §3.9.1/4 " unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type". That contradicts your interpretation of what you quoted. As a language lawyer I would argue that my own evidence is not valid because by the rules of ISO notes are non-normative. Still. I chose that because it fits nicely the comment size and the level of this discussion.
Comment: @FredLarson: "all the numbers in this world are positive integers and they can be represented by uintX_t C++ types" from the start of the question. and so on. apparently you failed to notice numerous such assertions, *and* read statements about signed arithmetic that are nowhere to be found.
Comment: In summary, this answer is needlessly inefficient and needlessly verbose and complex, and readers will do well to not adopt such solution.
Comment: @Cheersandhth.-Alf http://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c: "Just because a type is defined to use 2s complement representation, it doesn't follow that arithmetic overflow in that type becomes defined.

The undefined behaviour of signed arithmetic overflow is used to enable optimisations; for example, the compiler can assume that if a > b then a + 1 > b also; this doesn't hold in unsigned arithmetic where the second check would need to be carried out because of the possibility that a + 1 might wrap around to 0..."
Comment: @Felics: unsigned types do not use two's complement representation. two's complement is a representation of signed values.
Comment: @Felics: Do you understand that there is a difference in the standard between overflow of signed types and overflow of unsigned types? Are you in fact excluding signed types in your question?
Comment: Yes, the quote from the SO answer was for signed types. My bad. The quote from the standard was for any type.
Comment: @Felics: do you understand now *why* your standard's quote does not imply UB for unsigned arithmetic?
Comment: @Cheersandhth.-Alf The quote from the standard doesn't not say anything about the type. This is how I interpret the quote: I have uint16_t value = 65535; value = value + 1 -> the result is not representable using uint16_t, UB is triggered. I might be wrong - I will try to find an example but now I have to go home... I'll post the sample here if I can find one.
Comment: @Felics: okay. with "uint16_t value = 65535; value = value + 1" the addition produces 65535 + 1 modulo 2^16, not because of an overflow and wrapping but because that's how unsigned addition is defined by the C++ standard (it is of course usually implemented as hardware level wrapping, and that is equally of course the rationale for having the definition of unsigned arithmetic). So, the +1 result is 0, and entirely within the range of the type. That's what C++11 note 46 tries to explain.
Answer: You just need to work backwards, asking if a given digit will overflow:
// When result exceeds this thresh, appending a digit will always overflow.
static const T thresh = std::numeric_limits<T>::max() / 10;
// When result equals this thresh, appending a digit larger than
// thresh_last_digit will overflow.
static const T thresh_last_digit = std::numeric_limits<T>::max() - 10 * thresh;

for(auto it = value.begin(); it != value.end() && std::isdigit(*it); ++it)
{
    if(result > threshold)
        throw std::overflow_error(value);
    T digit = *it - '0';
    if(result == threshold && digit > thresh_last_digit)
        throw std::overflow_error(value);
    result = result * 10 + digit;
}

Answer: For unsigned type T you can always do
T const original = result;
result = result * 10 + *it - '0';
if( result / 10 != original ) { throw 666; }

Except, replace the throw 666 with something.

For the apparent original problem of converting string → integer with overflow detection, see strtol and family.
Comment: Won't this be UB if `T` is a signed type?
Comment: @FredLarson: not only that, but if the template is instantiated with floating point type the `/` will not do the assumed integer division, and if it's instantiated with some user-defined type with custom `/`, or for that matter custom `+` or `-` or `*`, it could do *anything*. Yikes!
Comment: Could be, but I don't think the OP thought about such issues. I wasn't entirely serious. But one real problem with the code given is the call `std::isdigit(*it)`. Works fine for ASCII (7-bit) input, but more generally it's Undefined Behavior. Such are the issues of subtlety.
Comment: @Cheersandhth.-Alf After reading in detail CERT document about integer overflows I found out I was completely wrong when it comes to unsigned integers - their arithmetic is well defined as modulo 2^number of bits. The UB is triggered only for unsigned integer. Unfortunately I can't up vote your answer without it being edited. I also think the standard should contain a note on the section 5, Expressions saying that for unsigned types that doesn't apply.
Comment: @FredLarson: yes, but then that's not asked about.
Comment: The example uses only unsigned types, but it seems like it would be a nasty gotcha to leave in a function template.
Comment: result = result * 10 + *it - '0'; will trigger UB because of overflow. I need to avoid running this code when overflow will happen. Please check http://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c for more info
Comment: @Cheersandhth.-Alf The template will not be instantiated with floating point types because they don't exist in our awesome world. All the numbers are positive integers.
Comment: @Felics: re "result = result * 10 + *it - '0'; will trigger UB because of overflow.", no  that's not the case for unsigned type.
Comment: @Felics: I see no need to check any link you provide, because I'm not going to answer you more extensively (correcting misconceptions) than I already have. Well, except for the idea of SO as an authority. It's not, it's Herb Schildt-land, the largest on the net.
Comment: Isn't it more efficient to check for overflow by `result * 10 < result` ?
Comment: @Slava result * 10 might trigger UB when result * 10 > max value of type.
Comment: @slava: yes, but not correct. ;-) consider the value 2^(N-1)+1, where N is the number of bits. 10 times that gives you what, modulo 2*N?
Comment: I meant, "modulo 2^N"
Comment: @Cheersandhth.-Alf I'm am the downvoter. The UB is still present here. The overflow "check" is done AFTER executing the statement that may trigger it. The computer my catch fire before executing the if.


Residuals and Homoscedascity in SEM with lavaan

Question: I intend on investigating longitudinal effects through a cross-lagged panel design, facilitating the lavaan package in R. Currently, I have set up a simple Model given the scheme and code below, in accordance to the lavaan tutorial, as well as various lecture notes by the package's author. I am using a robust method as my input data is not on all variables normally distributed - lavaan is suited to handle this, there should be no problem. There are no latent variables, as there is only one observed variable each, so it is an autoregression, really.

library(lavaan)

model <- '
  # linear part
    A2 ~ A1 # a12
    A3 ~ A2 # a23
    B2 ~ B1 # b12
    B3 ~ B2 # b23
  # cross-lagged part
    A2 ~ B1 # d12
    A3 ~ B2 # d23
    B2 ~ A1 # c12
    B3 ~ A2 # c23
  # variance
    A1 ~~ A1
    A2 ~~ A2
    A3 ~~ A3
    B1 ~~ B1
    B2 ~~ B2
    B3 ~~ B3
  # covariance
    A1 ~~ B1
    A2 ~~ B2
    A3 ~~ B3
'

fit <- sem(model, data = Data, estimator = "MLR")
summary(fit, fit.measures = T)

Now even without constraints (such as a = a12 = a23 and such) the CFI is above 0.95 and P-value > 0.01 (not great, but it's a start). I suppose this means the autoregression did work.
So for checking for homoscedascity, I would need the residual plot (residuals vs. fitted), given a predicted dependent variable from my model distribution in compairison to residuals of my acutal data. I don't really know how I would go about generating a model distribution like that given in my CLP-model, let alone the fact that it is bivariate. Or is homoscedasticity no longer a necessary assumption for this kind of model?
Could anyone please explain this to me and maybe even help me solve this?
Answer: Robust methods in SEM are sandwich estimators, and the standard errors are robust to violation of the homoscedasticity assumption. (You can try this by generating simple data and replicating a t-test in regression
Here's some code:
library(lavaan)
set.seed(2020)
d <- data.frame(x = c(rep(0, 100), rep(1, 900)),
                y1 = rnorm(1000))
d$y2 <- ifelse(d$x == 0, d$y1 / 10, d$y1)

with(d, t.test(y1 ~ x))
with(d, t.test(y1 ~ x, var.equal = TRUE))

with(d, t.test(y2 ~ x))
with(d, t.test(y2 ~ x, var.equal = TRUE))

fit1 <- "y1 ~ x"
summary(lavaan::sem(fit1, data = d, estimator = "ML"))
summary(lavaan::sem(fit1, data = d, , estimator = "MLR"))

fit2 <- "y2 ~ x"
summary(lavaan::sem(fit2, data = d, estimator = "ML"))
summary(lavaan::sem(fit2, data = d, , estimator = "MLR"))

Just looking at the p-values (I won't paste all the output).
First two t-tests, (where homogeneity of variance is not violated), and I do unequal (Welch's) t-test, which does not assume HoV, and equal variance, which does: 0.20 and 0.17 - pretty similar. Second two, where HoV is violated: 0.14, 0.60. Big difference.
First two p-values from lavaan, with ML and MLR: 0.14, 0.20 - pretty much the same. Second two, with HoV violated: 0.61, 0.14. Same as the t-test.


Windows Server 2008 R2 Datacenter 64Bit - Apache not starting with PHP module

Question: I am running Windows Server 2008 R2 Datacenter 64Bit.
On it I installed Apache 2.2.25-win32-x86-openssl, the Apache server runs fine without a PHP-module. But when I try to load the php-5.2.17-Win32-VC6-x86 module the Apache server does not start with the error-message "The requested operation has failed!"
in the httpd conf I added
<code>#
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "c:/php"
</code>
PHP was copied to the folder c:/php/
Has anyone an idea how to start the apache with the php-module?
Answer: From https://bugs.php.net/bug.php?id=51516

[2013-09-16 08:57 UTC] john at mcmillantech dot co dot uk
  There are major compatibility issues with Apache and PHP. You must use the thread safe version of PHP. Only the later versions of Apache work with Windows 7. I have written up some instructions at http://johnrmcmillan.wordpress.com/2013/07/25/installing-apache-and-php-on-windows.<


Erro ao exportar parra o excel

Question:
Esse abaixo é meu controller.
 public function atletaExport(AtletaModalidadeRequest $request){

    $alunosModalidade = $this->alunoequipes->alunosModalidadeFase($request->get('modalidade'),$request->get('fase1'), $request->get('municipio'),
                                                                  $request->get('regional'), $request->get('sexo'),
                                                                  $request->get('categoria'))->get();
    //dd($alunosModalidade);

    \Excel::create('AtletasModalidades', function ($excel) use ($alunosModalidade) {

        $excel->sheet('New sheet', function ($sheet) use ($alunosModalidade) {

            $sheet->loadView('relatorios.atletaexport')->with('alunosModalidade', $$alunosModalidade);

        });

    })->download('xlsx');

}

Abaixo onde ele faz a coleta das informações
    public function atletasModalidade(AtletaModalidadeRequest $request)
{
    $v['title'] = 'Atletas por Modalidade';

    if (Auth::user()->perfil_id == Perfil::ESCOLA) {
        Notification::error('Acesso não permitido.');
        return back()->withInput();
    }

    $fase_id = $request->input('fase1');
    $municipio_id = $request->input('municipio');
    $regional_id = $request->input('regional');

    $modalidade_id = $request->input('modalidade');
    $v['sexo'] = $request->input('sexo');
    $v['categoria'] = $request->input('categoria');

    $v['fase'] = $this->fase->find($fase_id);

    $v['local'] = null;
    $v['municipio'] = false;
    $v['regional'] = false;

    $modalidade = $this->modalidade->find($modalidade_id);
    $v['modalidade'] = $modalidade;

    if($municipio_id != '') {
        $v['local'] = $this->municipio->find($municipio_id);
        $v['municipio'] = true;
    }

    if($regional_id != '') {
        //$v['local'] = $this->regional->find($regional_id);
        $v['regional'] = true;
    }

    $v['municipio_id'] = $municipio_id;
    $v['regional_id'] = $regional_id;

    return view('relatorios.atletasModalidade', $v);

}

aqui é minha consulta
 public function alunosModalidadeFase ($modalidade_id, $fase_id,$municipio,$regional,$sexo, $categoria)
{

    $alunos = $this->join('equipes','equipes.id','=','aluno_equipe.equipe_id')
        ->join('escolas','escolas.id','=','equipes.escola_id')
        ->join('alunos','alunos.id','=','aluno_equipe.aluno_id')
        ->join('municipios','municipios.id','=','escolas.municipio_id')
        ->join('dirigente_fase', 'dirigente_fase.id','=','equipes.tecnico_id')
        ->leftJoin('dirigentes', 'dirigentes.id', '=','dirigente_fase.dirigente_id')
        ->join('fases', 'fases.id', '=', 'equipes.fase_id')
        ->where('equipes.modalidade_id','=',$modalidade_id)
        ->where('fases.id','=',$fase_id);
    if($sexo)
    {
        $alunos = $alunos->where('equipes.sexo','=',$sexo);
    }

    if($categoria)
    {
        $alunos = $alunos->where('equipes.categoria','=',$categoria);
    }

    if($municipio)
    {
        $alunos = $alunos->where('escolas.municipio_id','=',$municipio);
    }

    if($regional)
    {
        $alunos = $alunos->where('municipios.regional_id','=',$regional);
    }

    $alunos = $alunos->select('alunos.nome','alunos.data_nascimento','alunos.sexo',
                              'equipes.categoria as categoria','escolas.nome as escola','dirigentes.nome as tecnico','municipios.nome as municipio')
        ->orderBy('municipios.nome')
        ->orderBy('escolas.nome')
        ->orderBy('alunos.nome')
        ->get();

    return $alunos;

e finalizando minha blade de exportação

      Nome Aluno
      Data Nasc
      Sexo
      Categoria
      Escola
      Técnico
      Município

      @foreach ($alunosModalidade as $alunoModalidade)

          {{ $alunoModalidade->nome }}
          {{ $alunoModalidade->data_nascimento }}
          {{ $alunoModalidade->sexo }}
          {{ $alunoModalidade->categoria }}
          {{ $alunoModalidade->escola }}
          {{ $alunoModalidade->tecnico}}
          {{ $alunoModalidade->municipio }}

      @endforeach

Passo os 6 parâmetros mas mesmo assim ele espera um na função get().
Answer: Ta um pouco complicado de entender onde ta o erro. Uma coisa que reparei que não esta fazendo sentido são os dois ->get que estão usando.
 $alunosModalidade = $this->alunoequipes->alunosModalidadeFase($request->get('modalidade'),$request->get('fase1'), $request->get('municipio'),
                                                                  $request->get('regional'), $request->get('sexo'),
                                                                  $request->get('categoria'))->get();

Reparei que aqui você está dando um ->get() no final. E la no seu model:
$alunos = $alunos->select('alunos.nome','alunos.data_nascimento','alunos.sexo',
                              'equipes.categoria as categoria','escolas.nome as escola','dirigentes.nome as tecnico','municipios.nome as municipio')
        ->orderBy('municipios.nome')
        ->orderBy('escolas.nome')
        ->orderBy('alunos.nome')
        ->get();

    return $alunos;

Você deu outro ->get(). Ou seja no final ta saindo $alunos->get()->get().
Da uma reduzida na função de model, substitui por $alunos::find(1) e traz um resultado e transforma para o Excel. Tem que ir eliminando código até achar qual parte está errando.
Comment: Ah sim, entendi muito obrigado pela ajuda.

Erro ao exportar parra o excel


Training, testing, validating in a survival analysis problem

Question: I've been browsing various threads here, but I don't think my exact question is answered.
I have a dataset of ~50,000 students and their time to dropout. I am going to be performing proportional hazards regression with a large number of potential covariates. I am also going to do logistic regression on dropout/stay in. The main goal will be prediction for new cohorts of students, but we have no reason to believe they will vary much from last year's cohort.
Usually, I don't have such luxury of data and do model fitting with some sort of penalization, but this time I thought splitting int training and test data sets and then doing the variable selection on the training set; then using the test data set for estimating parameters and predictive capacity.
Is this a good strategy? If not, what is better?
Citations welcome but not necessary.
Answer: With a similar outcome frequency I have found that data splitting can work if $n > 20,000$.  And it provides an unbiased estimate of model performance, properly penalizing for model selection (if you really need model selection; penalization is still more likely to result in a better model) if you only use the test sample once.  BUT don't use the test sample for any re-estimation of parameters.  Data splitting relies on the model built using the training sample to be put into "deep freeze" and applied to the test sample without tweaking.
Comment: I have not kept up with the literature regarding optimum split configuration.  But some general principles apply.  For the validation sample you need $n$ large enough so that you can estimate the calibration curve with great precision, then you need to see that what's left is more than adequate for reliable model fitting (using, say a 20:1 ratio of events:candidate parameters if you don't penalize).
Comment: Thanks. Would you recommend 80-20? 90-10? Something else? Any references on this?
Answer: I've been looking at this paper myself for the similar task of cross-validating survival prediction.  The good bits start at Chapter 2.
Comment: The take-away I found from this, and why I originally was attracted to this paper, was how to deal with censorship in survival predictions, i.e. what loss function to use (though rereading your question, you may not have censorship).
Comment: This appears to compare 5 fold to model CV based estimation (and it concludes that 5 fold is better). But I was more interested in just splitting the data in 2 parts and using one to validate the other.
Comment: I do have censorship and the dissertation is interesting, but it's not an answer to my question, I don't think.
Answer: I have since found this paper which not only answers my question, but provides a method for figuring out the optimal split for particular data sets.  I found this thanks to @FrankHarrell 's use of the term "optimum split configuration" which I then Googled.
Comment: Peter I think that paper used an improper scoring rule.  Different results may be obtained when using proper scoring rules.  Also, the paper did not address "volatility" of the analysis.  With small total sample sizes considered there, repeating the process using a different random split will result in much different models and much different accuracy when compared to the first split.  I see that is very undesirable.
Comment: @FrankHarrell: I see your point and it is indeed a very good point. What then do you recommend doing? Peform Monte Carlo runs of train/test splits and then on each run do i x k-folds CV (or bootstrapping)? But then this would contaminate the entire dataset.... I see no better solution than to find an appropriate way to split the dataset into train and test sets (what would the criteria be?) I'm just not confortable in using all the dataset to train and validate (using CV or boot) the models (from which one (or several) will be used to predict unknown output values based on some input data).
Comment: I addressed that in the post you just put on another topic page.


User-Profile-Form.tpl.php not working. Help!

Question: I am not rendering any results. This is my template.php:
function fueldeluxe_theme($existing, $type, $theme, $path) {
  $items = array();

  /**
   *  Account edit Forms
   */

  $items['user_profile_form'] = array(
    'render element' => 'form',
    'template' => 'user-profile-form',
    'path' => drupal_get_path('theme', 'fueldeluxe') . '/templates'
  );

  return $items;
}

function fueldeluxe_preprocess_user_profile_form(&$variables) {
  $variables['account'] = drupal_render($variables['form']['account']);
  $variables['picture'] = drupal_render($variables['form']['picture']);
}

This is my user-profile-form.tpl.php:

    <?php echo $picture; ?>

    <?php echo $account; ?>

As you can see I'm trying to load the user profile field forms. However I'm not able to render any results. The page loads okay when I add dummy text but no account field forms.
Do I need a module for this to work?
Also what would the variable look like for calling the custom field added to a user?
Comment: Consider re-wording your questions title.  I would also recommend 'recapping' the question you're referencing.
Answer: I'm struggling with what you're asking in the first portion of your question, but looking into the previous Stack Exchange page you referenced you can use the Panels module to quickly accomplish two column layouts for these forms.  You can also use template overrides to change the layout of the registration pages.
If you're specifically looking to quickly implement a tabbed UI for the user profile, I believe the Profile2 module may offer a built-in solution.

"Also what would the variable look like for calling the custom field
  added to a user?"

You may need to use load_user() first to get a complete user object to access custom profile fields.
$account = user_load(<USER-ID>); //$node->uid or $user->uid

Comment: I edited to question for clarity.


Mutiple force layouts in multiple svg in single page not working

Question: I want to implement two force layouts in single page in two different SVGs. I have created to different objects for below function.
//object for handling
var forceGraph = function(){

var force = d3.layout.force();

var width,height,vis;
var nodes = force.nodes();
var links = force.links();
this.disNodes = nodes;
this.disLinks = links;
var removedNodes = [];
var removedLinks = [];
var newNodes=[],newLinks=[];

this.setWidth = function(w){
    width = w;
}
this.setHeight = function(h){
    height = h;
}
this.setCanvas = function(c){
    vis = c;
}
//adds new node to force.nodes of not existing in force.nodes
this.addNode = function(id){
    if(!isNodeExisting(id)){
        nodes.push({'id':id,'type':'circle'});
        this.update();
    }
}
//adds new square node to force.nodes
this.addSquareNode = function(id){
    if(!isNodeExisting(id)){
        nodes.push({'id':id,'type':'rect'});
        this.update();
    }
}

//remove extra nodes from force.nodes
this.removeNodes = function(switches,hosts){
    var obj = this;
    for(i=nodes.length-1;i>-1;i--){
            if(switches.indexOf(nodes[i].id)==-1 && hosts.indexOf(nodes[i].id)==-1){
                removedNodes.push(nodes[i]);
                nodes.splice(i,1);
                obj.update();
            }
        }
}
//removes extra links from force.links
this.removeLinks = function(){
    var obj = this;
    $.each(removedNodes,function(i,val){
        for(i=links.length-1;i>-1;i--){
            if(links[i].source.id==val.id || links[i].target.id==val.id){
                var temp = links.splice(i,1);
                removedLinks.push(temp[0]);
                obj.update();
            }
        }
    });
    removedNodes.splice(0,removedNodes.length);
}
//determines if node is existing in force.nodes
var isNodeExisting = function(id){
    for (var i in nodes) {
        if (nodes[i]["id"] === id) return true;
    }
    return false;
}
//determines if links is existing force.links
var isLinkExisting = function(linkId){
    for (var i in links) {
        if (links[i].linkId === linkId) return true;
    }
}

//adds a link to force.links if link is not existing
this.addLink = function(source,target,linkId){
    if(!isLinkExisting(linkId)){
        links.push({
            'source':findNode(source),
            'target':findNode(target),
            'linkId':linkId
        });
        this.update();
    }

}

//returns index of switch by taking its id
var findNode = function (id) {
    for (var i in nodes) {
        if (nodes[i]["id"] === id) return nodes[i];
    };
};
var dragstart= function(d) {
        d3.select(this).classed("fixed", d.fixed = true);
}
var dblclick = function(d){
        d3.select(this).classed("fixed",d.fixed=false);
}
var displayHintText = function(d){
        d3.select(this).select('.hintText').text(d.id);
}
var hideHintText = function(d){
        d3.select(this).select('.hintText').text('');
}
//bring nodes to top of links.
this.keepNodesOnTop =function() {

    $(".node").each(function(index) {
        this.parentNode.appendChild(this);
    });

}

var drag = force.drag()
            .on('dragstart',dragstart);

this.update = function(){

    link = vis.selectAll('.link')
              .data(links,function(d){ return d.linkId});

    //remove extra links from SVG
    link.exit().remove();

    //add extra links to SVG
    link.enter()
        .append('line')
        .attr('class','link');

    var node = vis.selectAll('g')
          .data(nodes,function(d){return d.id});

    //remove extra nodes from SVG
    node.exit().remove();

    //add extra nodes to SVG
    var nodeEnter = node.enter()
                    .append('g')
                    .attr('class','node')
                    .on('dblclick', dblclick)
                    .on('mouseover',displayHintText)
                    .on('mouseout',hideHintText)
                    .call(drag);

    //append text element to node group element
    nodeEnter.append('text')
             .attr('class','hintText');

    //append circle to node group element
    nodeEnter.append(function(d){

            if(d.type=='circle'){
                return document.createElementNS("http://www.w3.org/2000/svg",d.type);
            }else if(d.type=='rect'){
                return document.createElementNS("http://www.w3.org/2000/svg",d.type);
            }

            }).attr('class','node')
              .each(function(d){
                    if(d.type=='circle'){
                        d3.select(this).attr({
                          r:8,
                        });
                    }else if(d.type=='rect'){
                        d3.select(this).attr({
                          width:16,
                          height:16
                        });
                    }
              });

    force.on('tick',function(e){

        node.attr("transform", function (d) {

            if(d.index==0){
                damper = 0.1;
                d.x = d.x + (width/3 - d.x) * (damper + 0.71) * e.alpha;
                d.y = d.y + (height/3 - d.y) * (damper + 0.71) * e.alpha;
            }

            d.x = Math.min(width,Math.max(d.x,10));
            d.y = Math.min(height,Math.max(d.y,10));
            return "translate(" + d.x + "," + d.y + ")";
            });

        link.attr("x1", function (d) {
                 return d.source.x;
            })
            .attr("y1", function (d) {
                return d.source.y;
            })
            .attr("x2", function (d) {
                return d.target.x;
            })
            .attr("y2", function (d) {
                return d.target.y;
            })
            .attr("id",function(d){
                return d.linkId;
            })

    });
    force.gravity(0.06)
        .charge(-1000)
        .linkDistance( function(d) { return 90 } )
        .size([width, height])
        .start();

}

};

I am able to get two different force graphs which are dynamic(draggale) but the problem is only links of latest drawn graph are being connected to nodes. Former graph is dynamic but links are static.
I have referred below links, they did'nt work:
Multiple instances of d3 force layout on the same page
Multiple force-layout graphs with d3 in seperate svg/div's
Below is a picture of how right side graph is behaving where is left is working properly. I have also given prefix for links as right and left but of no use.
Answer: In update() function I have defined link without var because of which, it is available globally and is always taking latest graph links. Changing it to var link worked fine.


Hudson on Dreamhost

Question: Have you successfully installed Hudson on a Dreamhost VPS? If you have, what are the steps to make it run continuously, even if the server restarts? They run debian on the servers.
Answer: Here is an manual how to install Jenkins/hudson on debian.
Main page jenkins-ci.org
Comment: Thanks for the link, I'm voting up your answer - but I am specifically asking for Dreamhost VPS-specific implementation.
Comment: Do you have a complete vps? With root access?
Comment: @Stony Yes, I do have a VPS with root access.
Comment: so then whats the problem? Then follow the installation guide. When you insert the source they load all depencies.
Comment: Does that restart jenkins automatically too?
Comment: yes when you install it over the repo then its inserted as init script. then you can start over /etc/init.d/jenkins restart something like this. And when you install it over the repo you get updates, too.

Hudson on Dreamhost


app runs as debug, but crashes as release

Question: I have a program which runs fine on the device in Debug configuration, but fails as a Release. Anyone have this experience, and how do I fix it?
Thx
Comment: You should see my answer to this question and it will (sorta) give you the answer to what you are looking for: http://stackoverflow.com/questions/3261557/why-is-windows-phone-7-emulator-so-slow-compared-to-um-iphone-os-emulator/3261644#3261644
Comment: I've looked at it, but it's no help. Both versions I mention are running on the device, not in the simulator. Everything's perfect in the simulator.
Comment: I am getting at this point: They are both different and that is why it is failing.
Comment: I was hoping for more enlightenment than that. I know that sometimes debug mode automatically clears variable on allocation for instance, but non-debug mode might not. Just saying it's different does not help. We all know that. WHERE is it different is the $99 question?
Comment: @thyrgle -- He's failing on device in release mode but not debugger. The link you provided is talking about the emulation needed by the simulator. That's not relevant to this problem.
Comment: Crashes on launch? Crashes a particular spot? Can't you still extract and symbolize your crash log off your device?
Comment: @TechZen: Well, my argument is that it explains that stuff works significantly different on the iPhone compared to the computer. And that, in a sense, explains why their are some stuff that work well in the simulator but not on the actual iPhone.
Comment: @Nick: it crashes at a particular point, trying to access a certain variable. I've done the stack trace and I cannot see how that variable has anything to do with anything.
Comment: @John Smith -- You might not see how the variable causes a problem but maybe we can. A fresh set of eyes may see things you do not. The more info we have the better the chance we can spot something.
Comment: yeah and what the crash is bad access etc. More info definitely needed. Minimally the stack trace but w/ code we'll have a better chance at helping.
Answer: I ran into the same problem - App worked fine on simulator and device in Debug mode, but neither in Release mode (it would install, but just display the splashscreen)

Xcode 4.3.2
iOS Deployment Target 4.3

I kept seeing answers on StackOverflow that said this was a memory management issue, but that didn't make any sense to me since the debug version worked perfectly fine when loaded to my iPhone 4S. I also checked Build Settings to see what differed between the two modes, and I skipped over the one difference that mattered in the end - compiler optimization.
In Build Settings -> under Apple LLVM compiler 3.1 code generation -> Optimization Level, change the Release setting from the default Fastest, Smallest [-Os] to None[-O0] . Fixed my issue.
Found that solution in this blog post: http://www.mindjuice.net/2011/11/30/how-to-fix-an-app-that-crashes-in-release-but-not-debug/.
The Apple Documentation helps, but doesn't explain why doing just the opposite fixes things:

Code optimizations of any kind result in slower build times because of the extra work involved in the optimization process. If your code is changing, as it does during the development cycle, you do not want optimizations enabled. As you near the end of your development cycle, though, the release build configuration can give you an indication of the size of your finished product, so the Fastest, Smallest option is appropriate.
None: The compiler does not attempt to optimize code. Use this option during development when you are focused on solving logic errors and need a fast compile time. Do not use this option for shipping your executable.
Fastest, Smallest: The compiler performs all optimizations that do not typically increase code size. This is the preferred option for shipping code because it gives your executable a smaller memory footprint.
Comment: The documentation you quoted says `Do not use this option [None] for shipping your executable`. But is that what you did?
Answer: Post
Some
Clues!
What do you mean by "fail"?   Crash? Hang? Jettisoned for memory use?   What are the symptoms of the failure?  Got backtrace? Do you have anything in your code that behaves different in debug vs. release?  Any #ifdef DEBUG type shenanigans?   asserts with side effects?  Did you mess with the compiler settings?  Got C++? Assembly?

I see a hint of a clue in the comments;  illegal access of a variable.   Most likely, this is caused by the optimizer re-using a stack slot more quickly in release than debug.   Which, generally, boils down to an over-release issue.
Even when building for release, you can still turn on zombie detection.
Also, have you done a build and analyze and fixed any problems it indicates?


Is it mandatory to check for Multicollinearity and Normality in the independent variables for all types of Machine Learning Algorithms?

Question: Is it mandatory to check for Multicollinearity and Normality in the independent variables for all types of Machine Learning Algorithms ?
Comment: What do you think you need normality of IVs on? It's not an assumption for ordinary mutliple regression, for example
Comment: I have seen a few Data Scientists Advocating the need to check Normality and also Multicollinearity. But in my experience so far, I have seldom encountered datasets in which the independent variables are normally distributed. What should I do in such a case ? Should I leave the dataset as it is or should I try to apply some type of a transformation to make the variables Normal ? Also on multicollinearity, should I be worried about it ? If so, in what types of Machine Learning Algorithms it might cause problems.
Comment: @NithyaSubramanian I think preprocessing has an important role to play. and it should be applied wherever possible. Because subsequent analytical actions depend heavily on the same. So whether its classification or clustering, I think preprocessing is a "necessary evil".
Comment: Thanks @Ashish. It would be helpful if we can delve into some specific details here. What issues do you have practically encountered due to Non-Normality and/or Multicollinearity ? Also, in case you encounter non-normality in your independent variables, how do you take care of the same?
Comment: @NithyaSubramanian Your question is too broad. Narrow down to a specific model.
Comment: Multicollinearity is not necessarily a bad thing. We have algorithms for extracting latent components from them.
Comment: @NithyaSubramanian Multicollinearity (also collinearity) is a phenomenon in which two or more variables are highly correlated such that one variable can be linearly predicted from the other. If not addressed it definitely reduces the reliability of individual variable's contribution to the regression model. See [Variance Inflation Factor](http://www.statisticshowto.com/variance-inflation-factor/) which helps in detecting it.
Answer: No statistical or ML method requires IVs to be normally distributed.
(What is often important is that certain test statistics, like the sample mean, be asymptotically normally distributed. A sufficient but not necessary condition for this is that residuals be normal. This is often confused.)
If a "data scientist" believes that IVs should be normally distributed, I would recommend you probe more deeply. Either he has a reason in a particular application that I have never come across, or he is propagating a misunderstanding.
multicollinearity increases the variance of a parameter estimate. In extreme cases, the estimate can be totally meaningless. It is often good practice to check for multicollinearity. It is even better to first understand your data and think about which IVs might be multicollinear.
Answer: No. I never did that on decision trees.
Comment: @NithyaSubramanian Multicollinearity in regression is well documented on this site. Hundreds of questions about it. Glen_b may give you some help.
Comment: What for other types of Machine Learning Techniques, like Linear / Logistic Regression ? Do you check for Normality and Multicollinearity for them ?
Comment: @NithyaSubramanian No regression requires normality as far I know.
Comment: @NithyaSubramanian I do check for multicollinearity for regression but certainly not "all" machine learning algorithms. As said, I don't think I would have it do it on DT.
Comment: Thanks @SmallChess. Can you also elude into what issues you expect due to multicollinearity in a regression ? I believe that you do not see the same issue with DT and therefore you do not perform this check there.
Comment: Thanks @SmallChess. I have found a lot of write-ups on how to treat multicollinearity. But I have had mixed reactions on whether it is a problem at the first place. How does it affect outcome of a Linear Regression, whereas it doesnt affect DT ?
Comment: @NithyaSubramanian Your question is too complicated for me to answer in a comment. I'd suggest you accept my answer (which is correct), and then ask a new question. Otherwise, please edit your question.
Comment: @NithyaSubramanian you'll be better of by narrowing down the focus of your question. I recommend to edit it.


A question about independence of a function of random variables.

Question: Let $X$, $Y$ and $Z$ be random variables, with $Z$ independent from $X$ and from $Y$ (i.e. $P(X≤x,Z≤z) = P(X≤x)P(Z≤z)$ and $P(Y≤y,Z≤z) = P(Y≤y)P(Z≤z)$).
Is it true that a function $f(X,Y)$ is independent from $Z$ (i.e. $P(f(X,Y) ≤ a, Z ≤ z) = P(f(X,Y) ≤ a)P(Z ≤ z)$)?
I'm asking this question because a proof I'm studying derived the independence of sample variance ($s^2$) and sample mean ($m$) from the fact that differences $X_i - m$ were independent from $m$, and $s^2$ was a function of $X_1 - m,...,X_n - m$.
EDIT: I forgot to add that the sample is supposed to be random normal, but that wasn't the main point of my question. I understand all the proof, save that step I mentioned.
Comment: In my last comment, take $X=(X_1-\overline X,\ldots,X_n-\overline X)$ and $Y=\overline X$. Since $X_i-\overline X$ is independent of $\overline X$ for every $i$, the random vector $X$ is independent of $Y$. And therefore $s^2=f(X)$ is independent of $Y$.
Comment: The proof you are referring to regarding independence of sample mean and sample variance in normal distribution is based on the fact that if two random variables $X$ and $Y$ are independent, then $f(X)$ and $Y$ are also independent for any (measurable) function $f$: https://math.stackexchange.com/q/8742/321264.
Comment: Yes, I forgot to add that sample is supposed to be random normal. However my problem is that $X'=f(X_1,...,X_n)$ with $Y$ ind. $X_1$,..., $Y$ ind. $X_n$, and to me is not obvious that this implies $Y$ ind. $X'$.
Answer: In two independent tosses of  a fair coin the events $A,B,C$ of getting heads in the first toss, that of getting tails in the second and the event HH+TT are pairwise independent but not jointly independent. Take $X=I_A,Y=I_B, Z=I_C$ and $f(x,y)=x+y$ for a counter-example. You can see that $P(f(X,Y)=0, Z=1) \neq P(f(X,Y)=0) P(Z=1)$.
Answer: Reading the purpose of  your intent,

I'm asking this question because a proof I'm studying derived the independence of sample variance (s^2) and sample mean (m)

$\overline{X}_n$ and $S^2$ are not independent in general. They are independent in a gaussian model and this can be proved observing that

$\overline{X}_n$ is a complete and sufficient statistic for $\mu$ (Canonical Statistic of an Exponential Family Model)

$\frac{(n-1)S^2}{\sigma^2}\sim \chi_{(n-1)}^2$ thus $S^2$ is ancillary for $\mu$

Thus using Basu's Theorem, $\overline{X}_n$ and  $S^2$ are independent


How to load an XML file from a remote site

Question: There is site , shop.test.com.au  (not a real name)
when ever i tried to take the site  through
http://shop.test.com.au/ , it will change to shop.test.com.au in the browser
They providing an xml page link on that site
I need to access that xml from my php page
Following is my code
<code>$doc = new DOMDocument();
$doc->load('shop.test.com.au/1.xml');
</code>
Then it will return an error "failed to open stream: No such file or directory", may be it is checking in my local machine.So i changed the code to
<code> $doc = new DOMDocument();
 $doc->load('http://shop.test.com.au/1.xml');
</code>
Then i gets an error "failed to open stream: HTTP request failed!"
How can i solve it?
Answer: the best would be to use CURL, make sure you have CURL installed and then use this
<code>$curl = curl_init();

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, "http://shop.test.com.au/1.xml");

$xml = curl_exec($curl);

curl_close($curl);
</code>
And there you go - $xml should be having the data you desire.
Answer: Try:
<code>$f = file_get_contents("http://shop.test.com.au/1.xml");
</code>
Then, at the very least, that should give you the HTTP status code of the error.
Once you get the XML (hopefully by resolving the error), use:
<code>$doc->loadXML($f);
</code>
You may find that the site blocks requests with no User Agent specified (I know my site does), so you might need to use cURL or Socket functions to pass a User Agent.
Comment: failed to open stream: HTTP request failed!
Comment: See, whenever I've had such things, it always follows "HTTP request failed" with the status code, such as "HTTP request failed! HTTP/1.1 403 Forbidden"


Código de Fila em Python - Como verificar se existe um elemento com nome específico na fila e a sua posição do index?

Question: Estou fazendo um código de fila de um banco onde é preciso digitar o nome, idade, peso e gênero de classe Pessoa e classe Fila e esse código tem algumas opções que devem ser inseridas de acordo com o vontade do usuário. (Aparentemente o código funciona)
Eu queria saber como fazer com que esse código em fila permita que haja uma verificação se um nome específico do elemento está na fila e mostre o índex de onde o nome está?
a linha de código está em elif opcao == 6:
# Código de fila
class Fila:
    inicio = None
    fim = None

class Pessoa:
    nome: str
    idade: int
    peso: float
    genero: str
    proximo = None

def inserir_elemento(fila, pessoa):
    if fila_vazia(fila):
        fila.inicio = pessoa
        fila.fim = pessoa
    else:
        fila.fim.proximo = pessoa
        fila.fim = pessoa
    print(f"Elemento {pessoa.nome} foi inserido\n")

def excluir_elemento(fila):
    if fila_vazia(fila) == True:
        print("A fila está vazia")
    else:
        elemento_excluido = fila.inicio
        proximo_fila = fila.inicio.proximo
        del fila.inicio
        fila.inicio = proximo_fila
        if fila.inicio == None:
            fila.fim = None
        print(f"O elemento ({elemento_excluido.nome}) foi excluído\n")

def fila_vazia(fila):
    verificar_fila = (fila.inicio == None and fila.fim == None)
    return verificar_fila

def tamanho_fila(fila):
    if (fila_vazia(fila) == True):
        return 0
    else:
        contador_fila = 0
        ver_pessoa = fila.inicio
        while ver_pessoa != None:
            contador_fila += 1
            ver_pessoa = ver_pessoa.proximo
        return contador_fila

def imprimir_elemento(fila):
    if fila_vazia(fila):
        print("A fila está vazia\n")
    else:
        ver_pessoa = fila.inicio
        while ver_pessoa != None:
            print(ver_pessoa.nome, ver_pessoa.idade, ver_pessoa.peso,
            ver_pessoa.genero, end=" " if ver_pessoa.proximo != None else print())
            ver_pessoa = ver_pessoa.proximo

fila_encadeada = Fila()
opcao = 1
while opcao != 6:
    print ("1 - Inserir")
    print ("2 - Excluir")
    print ("3 - Imprimir")
    print ("4 - Informar tamanho da fila")
    print ("5 - Informar se a fila está vazia")
    print ("6 - Sair")
    opcao = int(input("Informe a opção: "))
    if opcao == 1:
        nome_informado = str(input("Informe o nome da pessoa: "))
        idade_informada = int(input("Informe a idade de {}: ".format(nome_informado)))
        peso_informado = float(input("Informe o peso de {}: ".format(nome_informado)))
        genero_informado = str(input("Informe o gênero de {}: ".format(nome_informado)))
        novo_elemento = Pessoa()
        novo_elemento.nome = nome_informado
        novo_elemento.idade = idade_informada
        novo_elemento.peso = peso_informado
        novo_elemento.genero = genero_informado
        inserir_elemento(fila_encadeada, novo_elemento)
    elif opcao == 2:
        excluir_elemento(fila_encadeada)
    elif opcao == 3:
        imprimir_elemento(fila_encadeada)
    elif opcao == 4:
        print(f"Tamanho da Fila: {tamanho_fila(fila_encadeada)}\n")
    elif opcao == 5:
        if(fila_vazia(fila_encadeada) == True):
            print(f"A fila está vazia\n")
        else:
            print(f"A fila não está vazia e possui {tamanho_fila(fila_encadeada)} elemento(s)\n")
    elif opcao == 6:
        print("Saindo...\n")
    else:
        print("Opção inválida, digite uma opção válida no menu\n")

Comment: Pela convenção do nome de `Fila` e `Pessoas`, elas são classes. E pelo erro você não as definiu. Você tem certeza que não está pulando etapas para aprender Python? Caso queira aprender passo a passo, com calma, recomendo os vídeos do [Gustavo Guanabara, do Curso em Vídeo](https://www.youtube.com/user/cursosemvideo/playlists).
Comment: O python não vem com nenhuma classe ou função chamadas `Fila()` ou `Pessoas()`, por isso é lançado um erro, pois o python não consegue identificar o que são essas classes. Se você criou estas classes é necessário importá-las no seu código para que você possa usá-las. Pesquise sobre `import` e depois que você entender, adicione os imports no seu código. Ficaria algo como `from meu_modulo import Fila, Pessoas`
Comment: Me parece que você está aprendendo muito aleatoriamente e está perdendo uns conceitos interessantes. Como por exemplo, [como identificar mensagens de erro](https://docs.python.org/3/tutorial/errors.html). Ou em português na [Wiki](https://wiki.python.org.br/Tutorial_Python) (seção 8.3)
Comment: Onde estão os arquivos que contém o código do Fila() e Pessoas() ?
Comment: Não sei do que você está falando
Answer: Acredito que não está importando a classe Fila() do modulo.
Ex:
from <modulo onde está a classe> import Fila
O seu erro se parece com esse, e está correto pois não declarei o modulo dá classe Fila
>>> filaencadeada = Fila()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Fila' is not defined
>>>

Comment: É verdade, você deve importar sua classe para q ela seja vista por esse módulo. Outra coisa que você deve olhar e nas validações das opção, lembrando que os inputs sempre retornam ``` str``` é você está comparada como int, converts as entradas do usuário para interior ou faça as comparações como string.
Comment: Acho que ainda não entendi
Answer: Dada a implementação, diria que uma lista já resolveria suficientemente bem o seu problema, não precisando implementar uma lista encadeada para tal, mas considerando que a lista encadeada faça parte do problema e deve ser implementada eu recomendo que você separe as responsabilidades.
O atributo proximo pertence ao nó de uma lista encadeada, não da pessoa, tanto que não faz sentido uma pessoa ter valor em proximo se ela não estiver em uma fila. A instância de Pessoa será apenas o valor armazenado no nó da fila, ela não deve ser o próprio nó.
Utilizando as dataclasses introduzidas no Python 3.6, você pode implementar a classe Pessoa da seguinte forma:
from dataclasses import dataclass

@dataclass
class Pessoa:
    nome: str
    idade: int
    peso: float
    genero: str

Perceba que quando utilizado as dataclasses, você apenas precisa fazer as anotações dos tipos dos campos da sua classe, diferente do que você fez que foi definir atributos de classes; se não for trabalhar com dataclasses, recomendo que leia como trabalhar com atributos de instância e quais são as diferenças dela para as de classe.
Para implementar a lista encadeada, você precisará de duas classes: a nó, que representará cada item da lista, e a lista por si só. O nó só precisará de dois campos: o valor armazenado, que neste exemplo será uma pessoa, e uma referência ao nó posterior.
from typing import Any

@dataclass
class No:
    valor: Any
    proximo: 'No' = None

E para a lista em si poderia fazer algo como:
class Lista:
    def __init__(self):
        self.primeiro = None

    def inserir(self, no: No):
        if self.primeiro is None:
            self.primeiro = no
            return

        cursor = self.primeiro
        while cursor.proximo is not None:
            cursor = cursor.proximo
        cursor.proximo = no

    def __len__(self):
        if self.primeiro is None:
            return 0

        tamanho = 0
        cursor = self.primeiro
        while cursor.proximo is not None:
            cursor = cursor.proximo
            tamanho += 1
        return tamanho

Podendo completar com os métodos que necessita.
Comment: Cara por enquanto não estou usando nenhum tipo de importação em fila, por isso não entendo muito o que você fez
Comment: @AlexF. O que seria "importação em fila"?
Comment: esses `imports` de seu código, seria isso não?
Comment: @AlexF. Apenas importações de módulos nativos do Python
Answer: Formatação
Seu código não atende ao estilo sugerido pela PEP 8. Os programadores Python costumam usar a PEP 8 como um guia pra formatação do código. Eu recomendo fortemente que você refatore o seu código para atender a essas orientações. Por exemplo, a função inserirElemento se tornaria inserir_elemento.
Orientação a objetos
Note que você fez uma separação clara entre dados e comportamento. Ao ler o seu código, nota-se que as classes descrevem dados, enquanto as funções descrevem comportamentos. Isso fica ainda mais claro se você observar que todas as tuas funções exigem uma instância da classe Fila.
Não há nada de errado em separar dados e comportamentos. Aliás, linguagens de paradigma declarativo geralmente privilegiam este tipo de abordagem. No entanto, no caso do Python, eu recomendo transformar essas funções em métodos das suas classes. (especialmente da classe Fila).
Separação de responsabilidades
Quando se está criando um programa de computador, os elementos do código geralmente podem ser divididos em categorias. Ao ler o seu programa, identifico três categorias:

Negócio: Elementos responsáveis por representar o domínio do problema que você está resolvendo.
Mecanismo: Elementos responsáveis por modificar e alterar dados de maneira genérica e reutilizável.
Apresentação: Elementos responsáveis por se comunicar com o mundo exterior.

Exemplos:

Aquele while com um monte de ifs é um elemento de apresentação.
A classe Pessoa é um elemento de negócio.
A classe Fila é um mecanismo.

Você deve organizar o seu código de modo que os elementos de cada categoria não se misturem, apenas se relacionem e se encaixem, como se fossem pecinhas de lego.
Veja essa função aqui, por exemplo:
def imprimirElemento(fila):
    if filaVazia(fila):
        print("A fila está vazia\n")
    else:
        verPessoa = fila.inicio
        while verPessoa != None:
            print(verPessoa.nome, verPessoa.idade, verPessoa.peso,
            verPessoa.genero, end=" "if verPessoa.proxima != None else print())
            verPessoa = verPessoa.proxima

Essa função imprime dados na tela (apresentação), itera por uma fila (mecanismo) e formata os dados da pessoa (negócio).
Se você mudar a implementação da fila, essa função vai quebrar. Se você mudar a implementação da pessoa, essa função vai quebrar. Se você mudar a forma como os dados são exibidos, essa função vai quebrar. Ou seja, essa função é um emaranhado de responsabilidades. Você deve separar estas responsabilidades.
Há vários livros sobre este assunto. Caso queira se aprofundar, pode começar por Object-Oriented Reengineering Patterns.
Exemplos de implementação
Vou dar dois exemplos de implementação: Classes Fila e Pessoa.
Lembre-se que a fila é um mecanismo. Você sabe de antemão que precisará usar uma fila, e sabe quais operações essa fila terá que realizar. A fila deve ser genérica e sem qualquer dependência das classes de negócio. Em outras palavras, crie essa classe tendo em mente que você deve ser capaz de reutilizá-la em qualquer programa que precise de uma fila.
class Nodo():
    def __init__(self, valor):
        self.valor = valor
        self.proximo = None

class Fila():
    def __init__(self):
        self.primeiro = None
        self.ultimo = None
        self.contador = 0

    def enfileirar(self, valor):
        novo = Nodo(valor)

        if self:
            self.ultimo.proximo = novo
        else:
            self.primeiro = novo

        self.ultimo = novo
        self.contador += 1

    def desenfileirar(self):
        if not self:
            raise IndexError()

        primeiro = self.primeiro

        if primeiro == self.ultimo:
            self.ultimo = None
            self.primeiro = None
        else:
            self.primeiro = primeiro.proximo

        self.contador -= 1

        return primeiro.valor

    def __len__(self):
        return self.contador

    def __bool__(self):
        return len(self) > 0

    def __iter__(self):
        temp = self.primeiro

        while temp:
            yield temp.valor
            temp = temp.proximo

Perceba que todas as operações foram definidas dentro da classe Fila. Ela é totalmente autocontida.
A classe Pessoa deve ser responsável não apenas por guardar os dados da pessoa, mas também por conter todos os comportamentos esperados de uma pessoa. No caso do domínio do seu problema, identifico que os comportamentos são:

Gerar uma representação textual da pessoa
Decidir se duas instâncias representam a mesma pessoa no mundo real

Note que não é responsabilidade desta classe printar coisas no terminal.
class Pessoa():
    def __init__(self, nome, idade, peso, genero):
        self.nome = nome
        self.idade = idade
        self.peso = peso
        self.genero = genero

    def __eq__(self, outro):
        if not isinstance(outro, type(self)):
            return False

        return (
            self.nome == outro.nome and
            self.idade == outro.idade and
            self.peso == outro.peso and
            self.genero == outro.genero
        )

    def __str__(self):
        return f'Nome: {self.nome}; Idade: {self.idade}; Peso: {self.peso}; Gênero: {self.genero}'

Veja que esta forma de implementação permite que você teste cada pedaço do código isoladamente. Isso é muito, muito importante em sistemas mais complexos, e você deve obter desde já o costume de criar códigos facilmente testáveis.
Respondendo a sua dúvida

Eu queria saber como fazer com que esse código em fila permita que haja uma verificação se um nome específico do elemento está na fila

Você pode criar uma função pra isso.
def procurar_por_nome(fila, nome_procurado):
    for pessoa in fila:
        if pessoa.nome == nome_procurado:
            return pessoa

    return None

fila = Fila()

fila.enfileirar(Pessoa('Bianca', 24, 50, 'F'))
fila.enfileirar(Pessoa('Jéssica', 28, 54, 'F'))
fila.enfileirar(Pessoa('Maisa', 22, 44, 'F'))
fila.enfileirar(Pessoa('Tatiane', 34, 55, 'F'))

nome_procurado = input('Nome: ')

pessoa = procurar_por_nome(fila, nome_procurado)

if pessoa:
    print(pessoa)
else:
    print('Pessoa não encontrada')

(Perceba que eu utilizei as classes que sugeri)
No entanto, seria muito melhor se você criasse um método de busca na própria classe Fila que recebe um predicado e retorna o primeiro elemento que atende ao predicado.
class Fila():
    # ... outros métodos que já mostrei...

    def encontrar(self, predicado):
        for item in self:
            if predicado(item):
                return item

        return None

Agora você pode usar este método pra encontrar uma pessoa sob qualquer critério, não apenas por nome.
nome_procurado = input('Nome: ')

pessoa = fila.encontrar(lambda pessoa: pessoa.nome == nome_procurado)

if pessoa:
    print(pessoa)
else:
    print('Pessoa não encontrada')

Observação
Há muitas melhorias a serem feitas no código que eu sugeri. A minha intenção não era mostrar um código perfeito, mas sim abrir seus olhos pra outras formas de abordar o problema.
Comment: Uma dúvida sobre **respondendo a sua dúvida** é preciso criar um `def` para isso?
Comment: @AlexF. Eu reescrevi essa parte pra tornar mais claro.
Comment: Não deu certo..
Answer: Ao criar classes é uma boa prática começar com letra maiúscula class Pessoa, todo método de uma classe que faça parte da instancia(métodos não estáticos) devem ter como primeiro parâmetro self, alguns de seus métodos estão faltando isso, propriedades da classe também devem ter o self e devem estar dentro do método __init__, a classe Pessoa estar faltando o método __init__ coloque aqueles atributos dentro dela, existe alguns erros como pessoa.fila = [] nesse comando você esta acessando a propriedade que a classe Pessoa tem mas na sua implementação a classe não possui essa propriedade, há outro também nessa parte print (fila.excluirElemento()) onde você usa a variável fila que nem mesmo foi definida, dê uma olhada nessa pergunta sobre como usar o self
Classe Pessoa(implementação recomendada)
class Pessoa:
    def __init__(self, nome, idade, peso, genero):
        self.nome = nome
        self.idade = idade
        self.peso = peso
        self.genero = genero

davi = Pessoa("Davi", 27, 89, 1)

Comment: a classe `fila` tá certa?
Comment: como eu falei na resposta, vc esqueceu de colocar o `self` nos métodos e ta usando um atributo da classe Pessoa que não existe que no caso é `pessoa.fila` sua implementação da classe Pessoa não tem o atributo `fila`


The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Question: I have developed an application that uses Oracle Data Provider for .NET. I copy the application file (.exe) and ODP library (Oracle.DataAccess.dll) on another computer that Oracle client and ODP.NET are NOT installed on. When I run the application, I got the error msg: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception.
*****************Exception Text***************
System.TypeInitializationException: The type initlializer for 'Oracle.DataAccess.Client.OracleConnection at Oracle.DataAccess.Client.OracleConnection..cctor()
  --- End of inner exception stack trace ---
  at Oracle.DataAccess.Client.OracleConnection..ctor(String connectionString)
  ...

Do I have to install ODP.NET and Oracle client on the computer that I want to run my application? If yes, is there other way that I don't have to install them but still can run my application?
Thank you
Answer: Easiest Way!!!

Right click on project and select "Manage NuGet Packages..."
Search for Oracle.ManagedDataAccess. Install it.

If you are using Entity Framework and your Visual Studio Version is 2012 or higher,then

Again search for Oracle.ManagedDataAccess.EntityFramework.
Install it.
Use below name spaces in your .cs file:
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.EntityFramework;

Its done. Now restart your visual studio and build your code.
What do these packages do?
After installing these packages no additional Oracle client software is required to be installed to connect to database.
Answer: Both Oracle Data Provider for .NET (from Oracle) and .NET Framework Data Provider for Oracle (from Microsoft) require Oracle Client installed on machine.
Answer: Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...
I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:
http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html
Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)
Include these 3 files within your project:

oci.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oci.dll)
oraociei11.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oraociei11.dll)
OraOps11w.dll (ODAC1120320Xcopy_32bit\odp.net4\bin\OraOps11w.dll)

When I tried to create another application with the correct reference and files I would receive that error message.
The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.
I also ran into a registry error, this fixed it.
public void updateRegistryForOracleNLS()
{
    RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
    oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}

For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm
After that, everything worked smooth.
I hope it helps.
Answer: Two options:

Install Oracle client on the PC you want to run your program on

Use Oracle.ManagedDataAccess.dll

You can get it on NuGet (search 'oracle managed') or download ODP.NET_Managed.zip  (link is to a beta version, but points you in the right direction)
I use this so that the computers I deploy onto don't need Oracle client installed.
N.B. in my opinion this is good for console apps but annoying if you intend to install your application, so I install the client in that case.
Answer: You need the oracle client driver installed for those classes to work.
There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.
Comment: Note that you can also get this error on a 64 bit machine if you have only installed the 32 bit oracle client.
Answer: You need an Oracle Client: (before 2016) http://www.oracle.com/technology/oramag/oracle/08-nov/o68odpnet.html
(circa 2019) Renamed to "Oracle Instant Client" https://www.oracle.com/database/technologies/instant-client/downloads.html
Comment: Hi @tuinstoel, please note that the link you provided above is now dead.
Comment: Newer link added below the broken link (for reference)
Answer: This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.
1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?
YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).
But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.
2. If yes, is there other way that I don't have to install them but still can run my application?
Yes, there is at least one way. And it is the Managed port of ODP.NET.
Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.
But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of  the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!
References:

ODP.NET Details: http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
ODP.NET is backward and foward-compatible: http://www.oracle.com/technetwork/topics/dotnet/multipledbs-089665.html
Advanced Configuration: https://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm

Troubleshooting:
That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).
Common solutions I have found to this problem:
App is 64-bit?

Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.
Answer: Check the machine.config too for old/bad installation targets. Remove everything related to this DLL.


Non-degenerate solutions to constant Hamiltonian flow

Question: As I'm trying to work my way through Dietmar Salamon's "Notes on Floer Homology", I'm having trouble with the very first exercise.
Let $(M, \omega)$ be a compact symplectic manifold. Let $H$ be a real function on $M$, let $X$ be the vector field associated to $dH$ under the isomorphism $TM \simeq T^{*}M$ induced by $\omega$.
Let $x \in M$ be a critical point for $H$, ie. $dH(x) = 0$. If $\phi _{t}: M \times \mathbb{R} \rightarrow M$ is the flow associated to $X$ (that is, $\frac{\partial}{\partial t} \phi _{t} = X \circ \phi_{t}$), then $x$ is a fixed point of this flow. In particular $\phi_{1}(x) = x$. We will say that $x$ is non-degenerate if $det(id - d\phi_{1}(x)) \neq 0$. This happens exactly when $d\phi_{1}(x)$ has no fixed vectors. The problem is as follows.

Show that under these assumptions $x$ is also a non-degenerate critical point for $H$. One possible way to state that is that in any local coordinate system $x_{i}$ around $x$, the matrix $(\frac{\partial^{2}}{\partial x_{i} \partial x_{j}} H) _{i, j}$ is non-singular.

I tried to reason as follows. Since $X(x) = 0$, infinitesimally at time $0$ and around $x$ points are (up to first order) not moved by $\phi$ at all. However, as I let the flow run for one unit of time I perform some form of "integration" that makes the second order changes by $\phi$ "go up an order" and become visible in $d\phi_{1}$. Thus, I should interpret the condition that $d\phi_{1}$ has no fixed vectors as a sing that $X = dH$ moves all vectors around $x$ in a second-order change, ie. $dH$ is non-degenerate.
I was trying to formalize the "implication"

$(\frac{\partial}{\partial t} \phi_{t} = X \circ \phi_{t}) \  \Rightarrow  \ \phi_{1} = \int\limits_{0}^{1} X \circ \phi_{t} \ dt$

so that later I could differentiate both sides with respect to $x$, but I quickly run into trouble because I am not working in the euclidean space, where - up till now - I have always "gotten by" using coordinate-free descriptions, since the problem I worked on were rather simple-minded. I would be very interested in a coordinate-free and proof with coordinates, but it would be most useful if it was formal, because I think my problems stem from a large lack of experiance with these kinds of problems.
Feel free to retag the question as needed.
Answer: Your idea was good and here is a formal proof. However, it does use local charts and I would be also interested in seeing a coordinate-free solution.
Choose Darboux coordinates around the critical point $x_0$, so that its neighbourhood is identified with $\mathbb{R}^{n}$, the symplectic form $\omega$ is locally represented by a constant $n\times n$ antisymmetric matrix and $X = \omega^{-1} \nabla H$.  For fixed $x$ from a small neighbourhood of $x_0$ we have
$\psi_1(x) - x = \psi_1(x) - \psi_0(x) = \int_0^1 \frac{d}{dt}\left( \psi_t(x) \right) dt = \int_0^1 X(\psi_t(x)) dt = \int_0^1 \omega^{-1}\nabla H (\psi_t(x)).$
Differentiating both sides with respect to $x$ (note that $\omega$ is constant), we obtain
$d \psi_1(x) - I = \int_0^1 \omega^{-1} \text{Hess}(H)(\psi_t(x)) \frac{d \psi_t(x)}{dx} dt,$
where $\text{Hess}(H)$ denotes the Hessian matrix of $H$. Now put $x = x_0$. As it is a critical point, $\psi_t(x_0) = x_0$ for all $t$ and we get
$ d \psi_1(x_0) - I = \text{Hess}(H)(x_0)  \left( \int_0^1  \frac{d \psi_t(x_0)}{dx} dt \right),$
which proves that the matrix $\text{Hess}(H)(x_0)$ is non-singular.
Comment: It's nice, thank you! I accept it, of course, although I would also like to see a coordinate-free solution.
Answer: An alternative way of stating the non-degeneracy condition is that the following self-adjoint unbounded operator on $L^2(S^1, \gamma^*TM)$ does not have $0$ in the spectrum. (This formulation is actually what one uses in the proofs where the non-degeneracy assumption is used.)
Let $\nabla$ be an arbitrary torsion-free connection on $M$. Then, define the differential operator by
\[
\cdot \mapsto -J(\nabla_t \cdot + \nabla_{\cdot} X_H).
\]
If I haven't made a mistake, this should be just $-J L_{\cdot} X_H$ (and thus doesn't depend on the connection). (I learned this formulation from Siefring's paper on asymptotics, but I don't believe it is an original observation from him.)
In particular, if we don't impose the condition that this operator act on periodic sections of $\gamma^*TM$, the linearized flow acting on any vector i.e.~$d\phi_t \cdot v$ for any $v$, is in the kernel of this operator. The kernel is then non-trivial if and only if there is some vector such that $d\phi_t \cdot v$ is of period 1 in $t$, which is precisely equivalent to having an eigenvector of eigenvalue $1$.
With this formulation, it becomes immediate: if $x_0 = \gamma(t)$ is a constant solution, then this operator becomes
\[ h \mapsto -J (\nabla_t h + \nabla_h X_H. \]
However, we know that $X_H = J \nabla H$ and $X_H(x_0) = 0$, so $\nabla_h (J \nabla H) = (\nabla_h J) \nabla H(x_0) + J \nabla_h \nabla H = J \nabla_h \nabla H$. This means the differential operator just simplifies to
\[
-J \nabla_t + \nabla \nabla H.
\]
Since the eigenvalues of the Hessian are real, this operator has non-trivial kernel if and only if $\nabla^2 H$ has a zero eigenvalue.


How can I re-indent Vue.js code in VSCode?

Question: The title tells it all. I have installed a couple of Vue.js related plugins for Visual Studio Code, but still can not format the code, as I used to do it easily in SublimeText.
Appreciate your hints?
Comment: Does CTRL SHIFT i not work for you? That works for me (Arch Linux, latest VS Code).
Comment: no. it does nothing. BTW, I'm on Ubuntu.
Comment: Sorry, it's i, not j.
Comment: still no result.
Answer: You can either use an extension called "Prettier" or "Beautify", then follow the instruction to set it up/
Just open the Extension window and look it up there, after you installed it you can right click on the opened file window and choose "Format Document" or simply press "Ctrl + Alt + F"
Comment: I have installed Beautify, but not tweaked it. When I press  `Ctrl + Shift + F` I get only search form. Also right click and `Format Document` does not indent neither html nor js part.
Comment: sorry my mistake, i meant "Ctrl + Alt + F", try tweak it on setting just follow the documentation
Comment: have you had vetur installed?
Comment: `Ctrl + Alt + F` does nothing either. Yes, I have alos installed `vetur`, though not tweaked it either.
Comment: @Buddy vetur did very well. Thanks a lot


Specific field tag based naming conventions (overriding views-view-field.html.twig for specific fields)

Question: I've scoured the documentation and I simply cannot find an answer to this question regarding naming convention for twig files given a tagged view with the override of a specific field.
Let me create a scenario to explain the problem.
Given Viewname with tag viewtag with a block display and a fieldname field.
I can override the theme as follows
Original file --> Overridden file name

views-view-unformatted.html.twig --> views-view-unformatted--viewtag.html.twig
views-view-field.html.twig --> views-view-field--fieldname.html.twig
views-view-field.html.twig --> views-view-field--viewname--block--fieldname.html.twig
views-view-field.html.twig --> views-view-field--block--fieldname.html.twig

I cannot figure out how to override views-view-field for a specific fieldname by specifying the viewtag. The following names do not work:

views-view-field--viewtag--fieldname
views-view-field--viewtag--block--fieldname
views-view-field--fieldname--viewtag
views-view-field--block--fieldname--viewtag
views-view-field--block--viewtag--fieldname

I've run out of possible combinations and yet I'm simply not able to get the viewtags to override the specific field. Surely there has to be a way to do this given that you can use the viewname to override the templates. I'd rather avoid having 50 versions of a view template when 1 could do the same thing.
Comment: Have you enabled Twig debugging? That will give you all possible template names and you can even write custom theme hook suggestions if necessary.
Comment: I have twig debugging enabled. The problem is that it doesn't give anywhere near all of the possible naming conventions. Almost none of the naming conventions I have listed above which do work are listed on twig debugging.
Answer:
I am able to use the tag to create template files for everything other
  than the specific field templates. – John Millnik

Your comment gave me the following thought: When you tag something, you tag the node and not the fields themselves. Fields do not have any tags, which makes me think that what you're trying to do is not possible.
Comment: @JohnMillnik that's because name and display type are related/part of/assigned to the view. While tags are not related/part of/assigned to fields. `I'll follow up with developers to see if this is currently possible.` I highly doubt it, but let us know what you hear back.
Comment: This is not correct. I am able to use the tag to create template files for everything other than the specific field templates.
Comment: @JohnMillnik updated my answer.
Comment: But you also are attributing the name to the view and you can modify the template via the name + display type. And views aren't nodes, are they? Either way I'm thinking this might actually just be an oversight on the views for Drupal 8. I'll follow up with developers to see if this is currently possible. It's certainly by design supposed to be possible. The point of tagging is to prevent twenty identical template files.
Answer: If I'm understanding your question correctly, you are looking to add a theme suggestion for a field based on a "viewtag".
I can't say I'm 100% sure what you mean by a "viewtag", but I think you are probably looking for hook_theme_suggestions_HOOK_alter or more specifically hook_theme_suggestions_views_view_field_alter().
More in for in Adding Theme Suggestions Programmatically For Views (Rows & Fields)
Answer: I am pretty sure you cannot target a specific field in a view. Is this view being pulled into a global sidebar or into the content area of a specific content type? If it's being pulled into the content area then you can add the view block as an entity reference field in the content type itself and target the field that way, like targeting a field inside of a field. Let me give an example and explain.
Let's say you want track titles (field_track_title) and their albums (field_album) to appear on a bio page. (The bio page and the tracks are separate content types, bio page machine name being bio.) Create your view block displaying the track titles and albums as normal. Go ahead and place this block in a hidden region under block layout- this must be done in order to render it anywhere.
Then, in the bio content type, create a field referencing "other."

On the next screen select Block as the type of item to reference and set allowed number of values to 1.
When you get to the edit field screen you can select your newly created view block as the default (so you don't have to select it each time you create a new content type instance) and save. Make sure to place this field somewhere in your Manage Display screen.
Finally, to answer your question, you now can target this view's field because it renders as a field in the content type.
field--node--field_album--bio.html.twig
Comment: As mentioned - I am able to explicitly target any field by using several combinations including views-view-field--fieldname and views-view-field--viewname--displaytype--fieldname ... So I'm not sure this has anything to do with the actual question ;-)


I literally can't understand the Independence Probability

Question: They say the coin flipping are independent events each other. (Gambler's fallacy).
And they also say that a set of probabilities is independent each other, if they satisfy P(A∩B) = P(B│A)×P(A) = P(A)×P(B).
But let's go back to the coin flipping for a second. There exists two elements in the S set, Head and Tail, and the probability of flipping Head, P(H), has only 1 element, H, so that P(H) = 1/2, which means H out of H and T.
Here, flipping a coin once again should be independent to the first one. But if they really are independent each other, it should satisfy P(H∩H) = P(H│H)×P(H) = P(H)×P(H) = 1/4, which is wrong, because P(H∩H) = P(H) = 1/2. What am I missing?
Comment: I think you may be confusing yourself by using the symbol $H$ to mean both a head on the first toss and a head on the second toss.  Try using $H_1$ and $H_2$.  Then $\Pr(H_1\cap H_2)=\frac14$.  Does this help?
Comment: Your events are not clear.  What does the event $H$ refer to?  You need to distinguish between the first toss coming up Heads and the second toss coming up Heads, those are the independent events.
Comment: So this is an issue with sloppy labelling. When you try to write out the meaning in English, your error becomes obvious. When you write $P(H\cap H)$, do you mean the probability of some random variable taking on the value $H$ and also the value $H$? Or do you mean two separate random variables both taking on the value $H$? You are confusing the two cases.
Answer: When you say $P(H \cap H)$ you really mean $P(H_1 \cap H_2)$ with $H_1$ indicating that the first toss is heads, and $H_2$ indicating that the second toss is heads. In this case, indeed, $P(H_1 \cap H_2) = 1/2*1/2 = 1/4$
Comment: This is why I prefer the notation $P(X_1,X_2=H)$ for novices, where $X_1,X_2$ are coin-flipping RVs.
Comment: Thanks. But if there exist H1 and H2, how do you draw the whole set? Does S still have only two elements, H and T? And what about the subsets of them? Does there exist a countless subsets that have only H as their elements? Or there is just one subset for P(H) and you just use it like P(H1) P(H2) P(H3) depending on how you approach the problem?
Comment: Some possible events in the set would be (H1 & H2), (H1 & T2), (T1 & H2), (T1 & T2) each with probability 1/4. Or you could just have the events H1, H2, T1, T2 by themselves each with probability 1/2. Or you could construct an event (H1 or H2) which would have probability 3/4. I added a picture that might help
Comment: So you mean the whole set, S, keeps growing(?) in its amount of elements whenever you add an event?
Comment: The whole set S is of a finite fixed size, containing every possible event. What you're asking is essentially construction of a sigma-algebra https://en.wikipedia.org/wiki/%CE%A3-algebra
Comment: We need to be careful when we're talking about what S means. Here, I'm assuming you're referring to every possible event. Each event is a subset of all the possible outcomes. An outcome refers to the outcome of the full experiment. There are only 4 outcomes here (HH,HT,TH,TT) but there are many many events (choose any subset of the outcomes and you make an event).


What are the advantages of using a Bayesian neural network

Question: Recently I read some papers about the Bayesian neural network (BNN) [Neal, 1992], [Neal, 2012], which gives a probability relation between the input and output in a neural network. Training such a neural network is through MCMC which is different from the traditional back-propagation algorithm.
My question are: What is the advantage of using such a neural network? More specifically, could you provide some examples which better fit BNN rather than NN?
Answer: Bayesian neural nets are useful for solving problems in domains where data is scarce, as a way to prevent overfitting. They often beat all other methods in such situations. Example applications are molecular biology (for example this paper) and medical diagnosis (areas where data often come from costly and difficult expiremental work). Actually, Bayesian nets are univerally useful and can obtain better results for a vast number of tasks but they are extremely difficult to scale to large problems.
Comment: Can you expand on why Bayesian nets are difficult to scale?
Answer: One advantage of the BNN over the NN is that you can automatically calculate an error associated with your predictions when dealing with data of unknown targets.
With a BNN, we are now doing Bayesian inference. Let's define our BNN prediction as $\bar{f}(x′|x,t)=∫f(x′,ω)p(ω|x,t)dω$, where $f$ is the NN function, $x'$ are your inputs, $ω$ are the NN parameters, and x,t are the training inputs and targets. This should be compatible with the syntax used by Neal in the links provided by @forecaster. Then we can calculate a standard deviation of the posterior predictive distribution, which I would naively use as an accuracy on the prediction : $\sigma(x′)=\sqrt{∫[f(x′,ω)−\bar{f}(x′|x,t)]^2p(ω|x,t)dω}$
Comment: This is an interesting addition to the conversation, but it is a bit short by our standards. Could you elaborate a bit and perhaps include a reference?
Comment: Sure. With a BNN, we are now doing Bayesian inference. Let's define our BNN prediction as $\bar{f}(x'|x,t) = \int{f(x',\omega)p(\omega|x,t) d\omega}$, where f is the NN function, x' are your inputs, $\omega$ are the NN parameters, and $x,t$ are the training inputs and targets. This should be compatible with the syntax used by Neal in the links provided by @forecaster. Then we can calculate a standard deviation of the posterior predictive distribution, which I would naively use as an accuracy on the prediction : $\sigma(x') = \sqrt(\int{[f(x',\omega)-\bar{f}(x'|x,t)]^2p(\omega|x,t) d\omega})$
Comment: Please edit this into your answer.


get id from a nested div using jquery

Question: I don't know how to put this. This has got a bit messy. I couldn't use the right words to ask the question. Here is my code:

            <select name="0" style="margin: 20px" id="0">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <input style="margin: 7px" id="1" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
                   type="text">

            <iclass="fa fa-times">

            <select name="2" style="margin: 20px" id="2">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <input style="margin: 7px" id="3" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
                   type="text">

            <select name="4" style="margin: 20px" id="4">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <input style="margin: 7px" id="5" placeholder="Value" onkeyup="check_if_value_set(this); return false;"
                   type="text">

    Add New Field

You can see there is a function named "show_new_text_field(this)" at the bottom of the code. Using this function, i need to get the id of say, div4 or select box of id 4. How can this be done ? I tried using prent() and closest(). Nothing worked. Any type of suggestions would be appreciated.
Thanks in advance !!
Comment: If you're doing it by `id` you don't need relative references, you can specifically select it by doing `$('#div4')...` - However, your question hasn't clearly defined what you're trying to select and under which circumstances. Please elaborate.
Comment: Is there some reason you can't just target the div directly with `$('#div4')?`
Comment: You probably want `$(that).closest('[id]').attr('id')`
Comment: Those ids are generating dynamically... and i need the name of the last id created...
Comment: And also the first select box within that last div...
Comment: @PlabonDutta Check out my answer and see if it helps. I'm still a bit unclear on exactly what you need, between names, ID's, etc, however you should be able to work with the answer I've provided to achieve your goal.
Comment: @Santi actually its complicated.. i've created the name of those ids dynamically with numbers... when the function is called, based on certain criteria, the first select box, of the last id becomes an input box....also there are some other stuffs... your ans looks fine...i think it will work...except i dont know how would i want to select only the last id if it hadn't had a name starting with "div"...
Answer: Something like this?
var lastDiv = $("[id^=div]").last(); //Get Last div whose ID begins with "div"
var lastDivId = lastDiv.attr('id'); //Get ID of that div
var firstSelect = lastDiv.find('select').first(); //Get the first 'select' of that div
var firstSelectId = firstSelect.attr('id'); //Get that select's ID

console.log("Last Div: " + lastDivId); // "Last Div: div4"
console.log("First Select in " + lastDivId + ": " + firstSelectId); //"First Select in div4: 4"

In the event your div won't always start with "div", you could just select the last child div of your parent (addDropdownfield) by doing this:
var lastDiv = $("#addDropdownfield div").last(); //Get all children divs of addDropdownfield - from that list, just the last one

Comment: @Santi- looks great...i'll put it in my code...however, what if my id hadn't started with "div" ? How would it be selected then ? I mean how could i select the last div id belonging any name ?
Comment: If the div you are looking for will always be a child of `addDropdownfield`, you could do `$("#addDropdownfield div").last();` - `$("#addDropdownfield div")` selects all divs that are a child of `addDropdownfield`, and then `.last();` grabs the last one. I've adjusted my answer above.
Comment: @Santi- sorry to bother you again...what if I run through a loop and need to select only a particular div from them say, number 3 ?
var divs = $("#addDropdownfield div")[2]; can something like this be done ?
Comment: Yes, that is fine. If you had a variable that stored this changing number, and your div's id *contained* that number, you could also do something like `$("#div"+i);` - If `i` was 3, it would select id `div3`, etc.

get id from a nested div using jquery


Preventing ARP reply messages for IP address from unauthorized port/mac

Question: I have a number of servers running on Dell switches which are used by clients for their projects. Occasionally some clients put other client IP addresses on their server (presumably by accident) and even though I can prevent them from using those IP addresses with ACL rules I can not prevent them from responding to ARP messages with stolen IP address, which messes server accessibility of original IP owner. All of the switch ports are on the same VLAN and I can't split ports into different VLANs for routing and IP limitation reasons.
I was wondering what are the possible ways of preventing the unauthorized ports/mac from replying to "ARP who has" messages with someone else's IP.
EDIT:
I mostly use Dell S4810 switches. I, of course, tried looking up the manual about the solution to my problem, however, the best that I could find is "dynamic arp inspection" which uses DHCP database to validate IP addresses to MACs. My clients often use large portions of external IP addresses on virtual machines, so locking them directly to a single MAC address is a little complicated. To add to the problem is their ability to move IP addresses from one server to another on another switch port.
I have implemented heavy SNMP logging of alerts and traps. I am now leaning towards a complex scripting solution which would check collected
"IP to MAC" address logs and compare them with client-owned server/VM MACs for any irregularities and based on some sort of calculation determine whether someone is stealing someone else's IP and simply turn off the port of malicious activity source.
The general idea of this post was to gather ideas of other solutions. Appreciate all the input.
Answer: Many switches have ARP protection/ARP inspection/IP source guard mechanisms which can be enabled to police all ARP traffic passing through the switch and enforce the MAC-to-IP bindings. These can learn appropriate bindings dynamically from DHCP (snooping), or you can statically set them which is probably what you need here.
However, I'm not sure about the availability of this feature on Dell's products. I grabbed a PowerConnect 5448 manual (admittedly pretty old now) and couldn't find mention of it...
Comment: It's Dell S4810 - FTOS 9.11. Tried going over the manual, however, couldn't find anything useful besides "dynamic arp inspection" which isn't that great.
Comment: I had a look in the manual and `arp inspection` is what I was thinking of. You would be able to use that with the `ip dhcp snooping binding ...` command to enforce IP address to MAC address bindings for all ARP traffic flowing through the switch.

However, your latest comment on mfinni's answer below makes me think this is still not the ideal solution because you want clients to be able to change addresses freely between their own servers, which this would prevent. In that case only separate VLANs and routing, I'm afraid!
Answer: Will your Dell switches allow you to put in static ARP entries for all of your servers? You didn't post the models or OS version, so I can't look it up for you. I know on Cisco switches, you can also limit the number of ARP entries per port, so if you're not virtualized, you could set each client port to "1" and that might not let changes happen.
That will be a pain to manage, of course.
This sort of problem is pretty much what VLANs are for, so see if you can resolve the obstacles to implementing them.
Comment: That won't stop other machines in the same network segment seeing the rogue ARPs so is arguably not a complete solution. Well behaved clients are supposed to probe for other devices on an address before they start using it themselves but even if they can be trusted to do that it's a who-gets-there-first situation...
Comment: Sure - I'm running on the assumption that the first one to get the IP was correct, and it's a subsequent typo by a different customer; that's why I couched it as a "might work, won't work well" solution, and that they should try to get to VLANs.
Comment: As "Mintra" stated, it won't stop this sort of activity from happening on my network. It's a rather complex network, meaning that clients can easily move their IP addresses from one server to another they own. I am trying to catch ideas on it. Thanks for the input!