Any way to make the border nearer to the body content ? (HTML/CSS) Pictures provided

Question: What I have done so far : http://goo.gl/sDhLA
What I am supposed to achieve : http://goo.gl/tqo7m
Thanks in advance for any help, newbie in html/css here.
Cheers.
UPDATE
My bad. I forgotten to mention that I am actually aiming for the results with the least amount of major edits to the code, as there are some code which I can't change. ( stipulated in my assignment ) .
On the other hand, there isn't any harm in learning more stuff though. Learnt more about new commands like line-height,  box-sizing: border-box is really interesting.
However, I was quite sad that negative padding doesn't occur. It would have solved the gap at the left and right edges eh ? :O
Comment: Welcome to Stack Overflow! Please post the code relevant to the question. Ideally, **in addition** to the code in the question body itself, please add a [jsFiddle](http://jsfiddle.net/api/post/jquery/1.7.1/) example of your problem. It will help us help you.
Comment: Could you bung the code into something like jsfiddle, would make it easier to edit and and understand what you have so far.
Comment: It's very difficult to comment on that without being able to see the code. There could be a whole bunch of reasons why the border is so far out.
Comment: I am not too sure how to go about using jsfiddle, but here is the link =) .  http://jsfiddle.net/LGFLB/
Answer: Looks like you need to reduce the width for your container (or increase the width of your content).
You should post your code here though, only then I will be able to be sure this answer is correct.
Your code is a mess. Here's what I made (I have the units in cm because it will gives better control when printing, you may change the units)
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Revisions Bookstore and Cafe</title>

Revisions Bookstore and Cafe

Custom brewed coffee and hand-selected books.

Special orders are our specialty.

412 N. 25th St.
Richmond, VA 23223
(804) 555-2565

Comment: Not sure if I can use pastebay, but it looks clearer compared to jsfiddle ? http://www.pastebay.net/717519
Comment: Are you trying to produce a printable card? Any reason you're not using `cm` as your value but `em`?
Comment: No, this is actually for an assignment =)
Oh I thought the trend nowadays is to use em .. guess I was wrong in that aspect haha.
Comment: @TheKraven: There are 3 types of units, absolute units (px, cm), **elastic** units, (em, rem) and **fluid** units (%). Setting the widths of elements as `em` is great for websites where they allow they user to change the font-size (or in website where ie6/7 support is mandatory). Usually, you'd want to use PX for better display on screen, or fluid if you wish to address a wider range of screen sizes (although there're @media queries for that today)
Comment: What does the * refer to ? Under  * {
            padding: 0;
            margin: 0;
        }.
And why do you separate the declaration into #card div,#card,#card div p and #card > p ?
Can't all of them be declared under #card ? Gotta need work more on my coding lol.
Comment: * in css simply means that those styles are applied to all elements.
Comment: no worries c:, it helps alot with normalizing css and be super useful when dealing with many elements that all have common css. Also keep in mind that you can use it anywhere within any kind of rule in your css. i.e `#ul li * { *rules* }`
Comment: Am i right to assume that the margins declared under * overides all other margin declarations ?
Comment: @TheKraven: `#card div p` literally means "p element inside of div element inside of  element with ID of 'card'". CSS does not support nested declarations. (Though there are CSS frameworks which does, see LESS).
Comment: I see.. thanks =D . Btw, I can't figure out #card > p . Mind explaining it to me ? =)
Comment: @TheKraven: Sure, the `>` operator in CSS means the **direct child operator**, meaning it would only match the `p` element which is directly under `#card`, so that the 2 description lines will not be affected (because they are inside of another nested div).
Comment: Also, if this answer is correct, please consider accepting it by pressing the large (hollow) green tick under the score value.
Answer: Well I looked at achieving the result you are wanting so i've basically manually set things to the same width as your original but with a couple of modifications (mainly just setting margins and widths) while keeping things in em format.
but heres the new css:

  @font-face {
            font-family: 'ChunkFiveRegular';
            src: url('Chunkfive-webfont.eot');
            src: local('?'), url('Chunkfive-webfont.woff')format('woff'),url('Chunkfivewebfont.ttf') format('truetype'), url('Chunkfive-webfont.svg#webfontb5K2fJwj')format('svg');
            font-weight: normal;
            font-style: normal;
            }

  h1 {
    text-align: center;

    border: 0.1em solid rgb(65,105,225);
    margin-top: 8px;
    margin-left:8px;
    margin-right:8px;
    padding: 0.25em;

    font-family: ChunkFiveRegular;
    background-color: rgb(189,204,212);
    font-weight: normal;
    font-size: 2em;
    }

  #contact {
    text-align: right;

    margin: 0 8px 8px;
    padding: 1em;
    font-family: ChunkFiveRegular;
    color: white;
    background-color: #212100;
    margin-bottom: 8px;
    }

  #box {

    margin: 0 8px;
    padding: 0.5em;
    }

  .maintext {
    text-align: left;
    }

  #body {
  font-family: Verdana;
  border: 0.07cm solid black;
  margin: 2.5em;
  margin-left: 23em;
  margin-right: 4em;
  width: 33.4em;

  }

</style>

Comment: Hi, the border seem to have disappeared =X . Or I copied the code wrongly somewhere..
Comment: haha the border is definitely still there, maybe due to bram's tip above you removed the id #body from the body tag in which case simply taking away the '#' in my css should fix it. c:
Comment: Oh you are spot on =P . On a sidenote, under #contact, there's margin: 0 8px; and margin-bottom: 8px; . I assumed that margin-bottom would be redudant, but it isn't. Why is this the case ? I thought the 1st margin declaration with 0 8px covers the bottom margin with 8px ?
Comment: I just found your question again, and yes you are right it is redundant however the new margin css would be `margin: 0 8px 8px;` to compensate for the removal of `margin-bottom: 8px;`
Answer: I updated your jsfiddle: http://jsfiddle.net/BramVanroy/LGFLB/1/
A hint: do NOT use an ID 'body' (or any html tag as ID for that matter)! It gets confusing! You can easily target the body by simply using body.
I have kept the HTML structure you proposed. I changed quite a lot of the CSS. Especially the width, margins and size. Also note box-sizing!
body {
  font-family: Verdana;
  border: 0.07cm solid black;
  margin: 2.5em;
  margin-left: 17em;
  margin-right: 4em;
  width: 45em;
}

h1 {
  text-align: center;
  border: 0.1em solid rgb(65,105,225);
  width: 96%;
  margin: 0.2em auto;
  padding: 0.25em;
  font-family: Rockwell;
    font-weight: bold;
    letter-spacing: 2px;
  background-color: rgb(189,204,212);
  font-weight: normal;
  font-size: 2.5em;

    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}

#contact {
  text-align: right;
  width: 96%;
  margin: 1em auto 0;
  padding: 0.25em;
  font-family: Rockwell;
  color: white;
  background-color: #212100;
  margin-bottom: 8px;
}

#box {
  width: 92%;
  margin: 0 auto;
  padding: 0.5em;
  line-height: 2;
}

.maintext {
  text-align: left;
}

Comment: Please copy the relevant parts of your code into your answer.


Drilldown search with Search API and Facets

Question: I have a type 'projects' referencing two other types ('kustomer','products') via entity reference.
Now I want to implement a drilldown search.
I therefore use search API with facete api. I build a index and a view for Type 'project'. The filtering works well on this view. I have facetes for types 'customer' and 'product' and can filter.
The target is a workflow where you start at a list of 'products'. When you select one you will get a list of 'customers' where a 'project' exists that contains that 'product'. After that you select a 'customer' and you get a List of all 'project's having that 'product' and 'customer' preselected as facetes.
Can someone point out a module or configuration that does that?
Thanks in advance
Clemens
Answer: I use CER,  "Corresponding Entity References" to achieve similar results, but not with Search_API.. for that, I just tell the search-page to render the "teaser", and modify the teaser display to include the entity_reference list of associated entities as links, that way, if you search for a "Kustomer", it will show you a list of Kustomers and each project will also appear as a list of links underneath the title, or visaversa, you can also use Facets to filter by taxonomy etc.. handy!


What is the opposite of $set in Vue.js?

Question: In a blog app, I'd like to show/hide comments of each post inside a loop of posts. I know how to show the div containing the comments by setting a showComments on the fly:
this.$set(post, 'showComments', true) ;

But I don't know how to hide the post's comments when the div is already open. What I tried is this:
 if (this.$get(post, 'showComments')==true) {
       this.$set(post, 'showComments', false) ;
      return
    }

The code above thoes not work and I get this error:
Uncaught TypeError: this.$get is not a function

So I'm wondering how can I acheive this functionaliry.
Comment: Vue.delete() is the opposite of Vue.Set() check [here](https://vuejs.org/v2/api/#Vue-delete)
Answer: You should be able to simply read the dynamic property and reapply the value.

new Vue({
  el: '#app',

  data() {
    return {
      posts: [
        { content: 'Post #1' },
        { content: 'Post #2' },
        { content: 'Post #3' }
      ]
    }
  },

  methods: {
    toggleComment(post) {
      if ('showComment' in post) {
        post.showComment = !post.showComment;
      }
      else {
        this.$set(post, 'showComment', true);
      }
    }
  }
})
.post {
  background-color: lightgreen;
  margin: 10px 0;
  padding: 5px;
}

    {{post.content}}

      Hidden comments.

    <button @click="toggleComment(post)">Toggle comment</button>

Comment: `post` is inside a loop of `posts`. It is not defined in the data.
Comment: That should make no difference. Let me see.
Comment: Both `this.$set` and `if` are unneeded here. The whole `toggleComment(post)` should be just `post.showComment = !post.showComment`. It even could be done in `@click` without using method at all.
Comment: @Styx `Both this.$set and if are unneeded here`... Really? The `showComment` property is not initially available you know. I think you need to read the docs again.
Comment: @jom Yes, you're right. I've missed that `showComment` is nonexistent initially.
Answer: Use property name to get property value
if ( typeof this.post.showComments !== 'undefined' && this.post.showComments ) {
   Vue.set(post, 'showComments', false);
   return;
}

Also note that you should try to avoid using this.$set because it was deprecated due to conflicts with other libraries. Consider using Vue.set instead.
https://v2.vuejs.org/v2/api/#Vue-set
Comment: This does not work for me. Please that `post` does not have a `showComments` when it is fetched from server rendered. It is only added by $set.
Comment: Updated answer, try like this
Comment: still does not hide.
Comment: So maybe you have some errors in console or something else that I should to know?
Comment: Updated one more time, please try like this
Comment: Now I get this error: `Uncaught TypeError: Cannot read property 'showComments' of undefined` . Note that `post` is inside a loop. It is not defined in the data.

What is the opposite of $set in Vue.js?


High dimensional, correlated data and top features/ covariates discovered; multiple hypothesis testing?

Question: I have a dataset with about 5,000 often correlated features / covariates and a binary response. The data was given to me, I didn't collect it.  I use Lasso and gradient boosting to build models.  I use iterated, nested cross validation. I report Lasso's largest (absolute) 40 coefficients and the 40 most important features in the gradient boosted trees (there was nothing special about 40; it just seemed to be a reasonable amount of information).  I also report the variance of these quantities over the folds and iterations of CV.
I kind of muse over the "important" features, making no statements about p-values or causality or anything, but instead considering this process a kind of---albeit imperfect and sort of random---insight into some phenomenon.
Assuming I have done all this correctly (e.g., executed cross validation correctly, scaled for lasso), is this approach reasonable?  Are there issues with, e.g., multiple hypothesis testing, post hoc analysis, false discovery? Or other problems?
Objective
Predict the probability of an adverse event

Foremost, estimate the probability accurately
More minor--as a sanity
check, but also to perhaps reveal some novel predictors that could be
investigated further, inspect coefficients and importances as
mentioned above.

Consumer

Researchers interested in predicting this event and the people who end up having to fix the event if it occurs

What I want them to get out of it

Give them the ability to predict the event, if they wish to repeat the modeling process, as described, with their own data.
Shed some light on unexpected predictors.  For example, it might turn out that something completely unexpected is the best predictor.  Modelers elsewhere therefore might give more serious consideration to said predictor.
Comment: It would be useful to know what the intent is here.  You did these things, why?  Who is the consumer, and what do you want them to get out of the analysis?
Answer: There are no problems with the accuracy of the predictions. The uncertainty in your predictions is estimated well by crossvalidation. Maybe one caveat there is that if you test a lot of parameter settings, then you overestimate the accuracy, so you should use a validation set to estimate the accuracy of your final model. Also, your data should be representative of the data that you are going to do predictions on.
It is clear to you, and it should be clear to the reader, that your predictors are not causes of the effect, they are just predictors that make a good prediction, and work well empirically. While I completely agree with your caution, inferring any causation from observational data is problematic in any case. Things like significance and such are "valid" concepts in well-designed, controlled studies, and outside of that they are merely tools that you, and others, should interpret wisely and with caution. There can be common causes, spurious effects, masking and other things going on in a normal linear regression with reported confidence intervals, as well as in a lasso model, as well as in a gradient boosted tree model.


Fixed length parsing in spark scala

Question: I have created the dataframe and the input is like this:
   +-----------------------------------+
   |value                              |
   +-----------------------------------+
   |1   PRE123                    21   |
   |2   TEST                      32   |
   |7   XYZ                       .7   |
   +-----------------------------------+

and on the basis on the below metadata information we need to split the above data frame and create a new dataframe, having columns name id,name and class and it start and index loction is given in this json meta data.
   {
    "columnName": "id",
    "start": 1,
    "end": 2
  },
  {
    "columnName": "name",
    "start": 5,
    "end": 10
  },
  {
    "columnName": "class",
    "start": 20,
    "end": 22
  }

OUTPUT :
  +---+------+-----+
  | id|  name|class|
  +---+------+-----+
  |  1|PRE123|   21|
  |  2|  TEST|   32|
  |  7|   XYZ|   .7|
  +---+------+-----+

For loading the df, I have created the list:
   list.+=(loadedDF.col("value").substr(fixedLength.getStart, (fixedLength.getEnd - fixedLength.getStart)).alias(fixedLength.getColumnName))

and from this list, I have created the dataframe
var df: DataFrame = loadedDF.select(list: _*)

Need to know the order better approach for creating the dataframe from the metadata.
As the list created will bring all the data to the driver node.
Comment: Hi Etisha it is not clear what you are trying to achieve. Can you provide a simple example with the input and the desired output? Also what is fixedLength/metadata and how are they related with your requirements?
Comment: @AlexandrosBiratsis Please see the post again.
Comment: Etisha do you have strict requirement to maintain a fixed length for all your data? The solution below is more flexible and does not require to provide any fixed start/end variables. In this case the only metadata you need is the column name. The code then would be more maintainable and simple
Comment: Yes.  We have strict requirement to maintain a fixed length for all your data and it will be dynamic.
Comment: Related: https://stackoverflow.com/questions/56147168/how-to-extract-efficiently-multiple-columns-from-a-single-string-column-rdd
Answer: If I understood correctly you requirements you are trying to extract the columns from a string separated by an arbitrary number of spaces.
Here is one solution with substr function:
val df = Seq(
  ("1   PRE123         21"),
  ("2   TEST           32"),
  ("7   XYZ            .7"))
.toDF("value")

val colMetadata = Map("id" -> (1,2), "name" -> (5,10), "class" -> (20,22))

val columns = colMetadata.map { case (cname, meta) =>
  val len = meta._2 - meta._1
  $"value".substr(meta._1, len).as(cname)
}.toSeq

df.select(columns:_*).show

And a generic solution when you don't have the column boundaries available using the split function:
import org.apache.spark.sql.functions.split

val df = Seq(
  ("1   PRE123         21"),
  ("2   TEST           32"),
  ("7   XYZ            .7"))
.toDF("value")

val colNames = Seq("id", "name", "class")

val columns = colNames.zipWithIndex.map { case (cname, idx) =>
      split($"value", "\\s+").getItem(idx).as(cname)
}

df.select(columns:_*).show

Output:
+---+------+-----+
| id|  name|class|
+---+------+-----+
|  1|PRE123|   21|
|  2|  TEST|   32|
|  7|   XYZ|   .7|
+---+------+-----+

Notice that I used \\s+ as separator. This represents a regex for one or more spaces.

Fixed length parsing in spark scala


Drupal Registration Module Email Registrants tab

Question: The character count for the subject field in email registrants is 40 characters and that is hard coded into the module.
I need some guidance for figuring out how to change that. I am not a hard core developer and do not know the best way to change that without going into the module code.
Can anyone help guid me to what could be done?
Thanks
Tim
EDIT***
I am in Drupal 7 Registration module 7.x-1.3.
Under Manage Registration/Email Registrants/ - there is a subject field. In the modules registration.forms.inc file on line 354 it the character limit size set to 40.
I am trying to figure out how to change it without editing the module code.
Thanks
Comment: Drupal 6? Are you mean subject field in User settings admin page? There's subject limited by 180 characters. Please explain
Comment: I have to use hook_form_alter in the Registration module.
Answer: Not being a developer I had to figure this out using hook_form_alter. Too some digging and a little help.
<code>function ecg_registration_form_registration_registrations_broadcast_form_alter(&$form, &$form_state) {
  //dpm($form);
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#description' => t('The subject of the message.'),
    '#required' => TRUE,
    '#size' => 80,
    '#maxlength' => 80,
  );
}
</code>
Hope that helps someone.


is it the case that increasing degrees of freedom always makes every tail of a t-distribution smaller?

Question: As per the title. Say I have  X a random variable that is a 0-centered t-student.
Can I affirm that P(X>a) decreases when I increase the degrees of freedom of X?
Looking at the image in the wikipedia case makes me think this is the case (https://en.wikipedia.org/wiki/Student's_t-distribution) but I am not sure.
Also, I have been told that assuming less degrees of freedom is "conservative", which also points in that direction.

If this is indeed the case, a proof would also be appreciated
Comment: The answer is yes when $a$ is positive.  I suspect a fairly short proof might be afforded by representing the Student t as a [variance mixture of Gaussians](https://stats.stackexchange.com/questions/52906).
Comment: I have a vague recollection that it's possible to show that for given $x$ in the tail of the t density $K(\nu)\left(1 + \frac{x^2}{\nu}\right)^{-(\nu+1)/2}$ $= K(\nu)\left(1+\frac{x^2}{\nu}\right)^{-1/2}\left(1+\frac{x^2}{\nu}\right)^{-\nu/2},$ where the last factor converges to $e^{-.5x^2},$ is decreasing in $\nu.$
Answer: As degrees of freedom $\nu$ increase, the tails of Student's t distribution contain
less probability, with the normal distribution being the limiting case.

As $\nu = n-1$ increases, quantile 0.975 $q$ decrease to the normal value 1.96. For example, a t confidence interval $\bar X \pm qS/\sqrt{n}$ gets closer to
the z confidence interval $\bar X \pm 1.96 \sigma/\sqrt{},$ for known population standard deviation $\sigma.$

For the standard normal distribution, the probability $p = P(-1.96 < Z < 1.96) = 0.95.$
As $\nu$ increases, $p = P(-1.96, < T < 1.96)$ increases to the normal value.

Many elementary textbooks say that, for $\nu = 30,$ the t distribution is sufficiently close
to normal for some practical purposes. But $\mathsf{T}(\nu=30)$ is hardly the same
as $\mathsf{Norm}(0,1).$
Here are graphs of $q$ and $p$ for $\nu = 1, 2, \dots, 200.$ The R code used to make the plots is shown below.

<code>df = 1:200
q = qt(.975, df)
pu = pt(1.96, df);  pl = pt(-1.96, df);  p = pu-pl
par(mfrow=c(1,2))
 plot(df,q, type="l", ylim=c(1.96,2.25), xaxs="i", main="Quantile 0.975")
  abline(h = 1.96, col="blue")
 plot(df,p, type="l", ylim=c(.925,.95), xaxs="i", main="P(-1.96< T < 1.96)")
  abline(h = diff(pnorm(c(-1.96,1.96))), col="blue")
par(mfrow=c(1,1))
</code>
Comment: I think the $n=30$ criterion comes from 1) testing at 5% level and 2) the need to limit the size of the tables at the end of the book ...


What alternatives are there for if else statements?

Question: This is a method within my program and I cannot use a bunch of if-else statements for my code. I need alternatives.
    public String bedRoom1(){

        int newChoice10 = JOptionPane.showConfirmDialog(null,"Would "
        + "you like to explore this room?",
        "question",JOptionPane.YES_NO_OPTION);

        if (newChoice10 == JOptionPane.YES_OPTION){  //if the user would lieke to
    // explore then they are given the option for which objects they woul like to explore

            int newChoice4 = JOptionPane.showConfirmDialog(null,"Explore"
             + " the Rocking chair(type YES) or Window(type NO)?"
             , "question",JOptionPane.YES_NO_OPTION);

    //The following if else statments are still within
     //the first statement of the first if statement
            if (newChoice4 == JOptionPane.YES_OPTION){
                JOptionPane.showMessageDialog(null,"Chair starts "
               + "rocking with no one in it");

            }else{

                JOptionPane.showMessageDialog(null, "You see a child outs"
                  + "ide on a swing and he suddenly vanishes.");
            }
        }else if (newChoice10 == JOptionPane.NO_OPTION){
            JOptionPane.showMessageDialog(null,"You have chosen not "
         + "to explore Bedroom 1 and therefore continue "
         + "into the following room");

        }

        return null;

  }

Can you please provide examples. Thank you in advance.
Comment: Why can't you use if else statements?  They work fine for me!
Comment: Look up switch/case
Answer: you can use showOptionDialog with all your choices instead of showConfirmDialog
and use switch - case instead of if then else


Ordenação de dicionario obtendo as values

Question: Eu tenho a seguinte função que já fiz que é esta :
def funcao(elemento):
    x = []
    for i in grafico:
            timestring = i["CrimeTime"]
            x.append(timestring)
    x= sorted(x)

    y= Counter(x).values()
    return x,y

E  o que me dá é :
(['16:40:00', '16:45:00', '17:30:00', '18:30:00', '18:38:00', '20:00:00', '21:30:00', '21:30:00', '21:51:00'], [1, 1, 2, 1, 1, 1, 1, 1])

Sendo o que me deveria dar é :
Código :
(['16:40:00', '16:45:00', '17:30:00', '18:30:00', '18:30:00', '20:00:00', '21:30:00', '21:30:00', '21:51:00'], [1, 1, 1, 2 , 1,2, 1])

O objetivo é obter as horas ordenadas que dá correto ,e o numero de vezes que cada hora se repete , sendo que os valores estao bem , não estão é corretamente posicionados( poderá ter a ver com o facto de ir buscar os valores a dicionario) mas não estou a ver como obtenho os valores corretamente ordenados
Answer: Cara,
o que está acontecendo ao meu ver é, quando você chama Counter(x) está sendo criado um dicionário, utilizando os valores que estavam na sua lista como chaves e o número de vezes que aquele valor aparece na lista como o valor.
Quando você chama .values() no dicionário que foi criado, ele retorna os valores que estão presentes para cada chave, porém o dicionário não garante a ordenação.
Se você fizer o acesso chave por chave você verá que os valores estão corretos.
def funcao(elemento):
    x = []
    for i in grafico:
        timestring = i["CrimeTime"]
        x.append(timestring)
    x = sorted(x)
    unique_x = sorted(set(x)) #remove os valores duplicados de x mantendo a ordenação
    count_x = Counter(x)
    y = [count_x[value] for value in unique_x]

    return x,y

Eu não sei quais são as suas reais necessidades, mas eu talvez retornaria apenas o dicionário, que já contem todas as informações desejadas.


Ativar campo ao carregar pagina caso input esteja preenchido com palavra especifica

Question: Tenho um formulário de cadastro que ao clicar em tipo de documento, caso seja "RG" tem uma função em JS que mostra um campo que esta definido em css como style="display: none".
Porem ao carregar da base ao fazer na pagina de update gostaria que ao carregar a pagina se o campo tipo de documento estiver preenchido com "RG" ai ativa a função para mostrar o campo emissor.
Utilizo esta função para ao trocar o campo tipo documento, se escolher "RG" mostra o campo emissor.

Answer: Adicione isso dentro da função window.onload:

var campoRG = document.getElementById('SEU_CAMPO_RG').value;
var display = campoRG.length > 0 ? 'block' : 'none';

document.getElementById('CAMPO_EMISSOR').style.display = display;

Qualquer dúvida estou a disposição!
Comment: Perfeito funcionou muito bem obrigado


What would be the essential things to learn to get good enough to play on a small football team?

Question: Alright. So for a bit of backstory I am 16 and until this point in my life I have been a rugby player in the UK, and honestly a very good one. I truly believe I had a shot at a professional career, and was lined up for some scholarships. However a recent seizure led to me being taken to a hospital where it was discovered I had a partially inoperable benign brain tumour. It is above the brain mass that controls movement on the left side of my body and as I am left handed they want to avoid surgery at all costs unless my seizures become more frequent, so basically it stays and I take pills forever. At my age even if I did get surgery (which they don't want) it would be a minimum of 2 years before I'd be allowed to play rugby again. That basically means I've missed my shot and I won't get another, pro rugby is done for me.
Now it took me some time but I've accepted it and moved past that fact, and I've decided I need to find a new team sport to play, as although I enjoy cycling it misses a certain thing that I love in competitive team sports (I'm not trying to go pro in a different sport, don't worry). As a result I've looked at joining a five aside football team, but I know very little about football. As in I probably have about 200 minutes combined time on a football pitch my whole life. Never played it with my family, got out of it at school, played rugby with all my friends, etc. So I am clueless. I've been googling the rules for the last 45 minutes.
I've tried to ask friends and PE teachers, but I am an anomaly in England, someone who managed to just never play football is very, very rare.
I know I've gone on but basically what would be the essential things to learn before even trying to join a five a side team if you were absolutely, completely new to the sport?
Comment: Could heading a ball make things worse?
Comment: Also I have been suggested touch rugby by people as it is non contact, and as much as I appreciate the support from people I am a very heavy prop forward and am simply not fast enough to play touch rugby, I've tried.
Comment: Maybe don, who knows. So far I haven't actually had anything happen from contact, its been from submersion in cold water, so I have no idea why I can't plug rugby, but whatever. I guess I'll find out when I try header a ball.
Answer:
The rules/laws and regulations you'll be playing under. This gives you a sense of the structure behind the game, and for example, why it's being kicked in from there instead of here, or why that player got a card when this one isn't, and an idea of what you can or can't do, when and where.Full rules/laws can usually be found on official international governing body websites, with national and local changes often on their respective association websites.
Basic skills. How to move in possession, how to pass, how to receive, how to shoot, how to dispossess opponents, how to block shots.
Basic tactics. These can vary by code and by team structure, but some universals include switching play, counter attack, offside trap, set-play positioning and motive.
Comment: Alright, thank you. I will try and get a hold of a copy of the official rulebook.
Comment: As addendum to reading the rules/laws: I mean the full rulebook itself and the official guidance that accompanies it. Ignore anything a commentator, journalist or pundit says (the few that know are never the ones asked about it).
Answer: Coming from Rugby football, you've got at least a head start compared to someone completely new to team sports. A couple of things you can take with you are

Passing. Like Rugby, if a team mate is in space pass him the ball.       Then try to support him by getting in space to get a pass back.
Defending as a team. You need to account for all opponents, avoid    getting beaten 1 on 1, and support each other when possible.
Playing    as a team. You can make up for a lack of skill by playing    unselfishly    (pass when possible), tracking back and playing    competetively.

There are many skills you need to learn, and you need to find a team that practice regularly and will give you time to learn from them. Passing, receiving a pass, shooting and tackling are all obvious things that any player needs to do.
But coming from Rugby I would suggest two things that may be alien at first

Jockeying. My image of a prop-forward moving to football is something like this: rush the player with the ball. But any half-decent player who can see you coming will be able to sidestep you, and move past you. It is often better to try to jockey the player with the ball, and wait for him to make a mistake or until you have a chance to take the ball
Shielding the ball. Not a good idea in Rugby, as some heavy prop forward will slam into your kidneys within a couple of seconds. But in football, you can't tackle from behind, so it can be a good way to buy some time until you can find a teammate to pass to.
Comment: Thank you. I will try practicing some of these things and I will look for a team who are ok with me being terrible.


Iterating over enumeration values

Question: Say I have this enum in Ceylon:
abstract class Suit()
        of hearts | diamonds | clubs | spades {}

object hearts extends Suit() {}
object diamonds extends Suit() {}
object clubs extends Suit() {}
object spades extends Suit() {}

I would like to iterate over the values. In Java, I would do Suit.values(). Is there something similar in Ceylon?
I tried to define it my self, but that didn't work because there are no static members in Ceylon? Should I just define at the top level:
Suit[4] suites= [hearts, diamonds, clubs, spades];

Comment: http://stackoverflow.com/questions/19402031/ceylon-iterate-enumerated-instances
Comment: I am at a loss as to how that question did not come up in my searches as it is as duplicate as any question could possibly be. Embarrassingly identical...
Answer: for (suit in `Suit`.caseValues) {
    // ...
}

Try online
Note: since this uses the metamodel, it's somewhat slow – certainly not as fast as Enum.values(). Cache the result if you're going to use it a lot.

Iterating over enumeration values


jsrcollpane scroll to specific div when link is clicked

Question: How can I get jsrcollpane to scroll to a specific div when a link is clicked? I have IDs for divs in a scroll pane and links on the page that I want to control the scrolling. I have found how to scroll a specific amount of pixels, but not how to scroll to a divs coordinates.
Answer: You cane use the API of jQueryscrollpane
http://jscrollpane.kelvinluck.com/api.html
There ar the method scrollToElement or scrollTo or scrollY
Example:
 api.scrollToElement('#elem', false, true, 115);


SQL inner join creates duplicates

Question: I have three tables, Suppliers, Products and Deliveries. I'd like to show the suppliers names and the quantity from the delivery table. There are 5 different suppliers and there are 12 deliveries. I expect that the joined table should contain 12 rows with names and deliveries.
This is my code.
SELECT  Suppliers.SNAME, Deliveries.QTY
FROM Suppliers, Deliveries
INNER JOIN  Products
ON Deliveries.P=Products.Penter (typo, should be Products.P)

The output is 60 rows with many duplicates and some incorrect matches.
Tables:
Comment: 5x12 = 60, sounds like your `JOIN` could use additional criteria.  Post table structure/sample data and we can nail it.
Comment: You need to specify the `JOIN` condition betweeen the Suppliers and the other two tables.
Comment: I think you must define a join between suppliers and deliveries too. Since you cross joined them in your example
Comment: You are mixing implict joins (in the where clause) and explicit joins using `JOIN` keyword. Don't do that.
Comment: use `group by` and that would solved the issue
Answer: Kill off deprecated implicit joins, and specify JOIN criteria, not sure of your table structures, something like:
SELECT  s.SNAME, d.QTY
FROM Deliveries d
INNER JOIN Suppliers s
 ON d.s = s.s
INNER JOIN  Products p
 ON d.p = p.p

An unspecified implicit JOIN ie:
SELECT  Suppliers.SNAME, Deliveries.QTY
FROM Suppliers, Deliveries

Will result in every record from each table joining to every record in the other, in your case, 5 records and 12 records = 60 combinations.
Comment: `Suppliers` alias `p` should be `s`. Would fix myself but there is a minimum of 6 character edits.
Answer: Use proper join syntax consistently.  You are mixing old-style joins (, with condition in the where clause) with proper ANSI join syntax.
You mean something like this:
SELECT s.SNAME, d.QTY
FROM Suppliers s join
     Deliveries d
     d.SupplierId = s.SupplierId join
     Products p
     ON d.P = Products.Penter;

I'm making up the join field between Suppliers and Deliveries.  And, I'm only guessing that those are the tables that need to be connected (perhaps it is Suppiers and Products).

SQL inner join creates duplicates


powershell new-item with -value and sub parameter

Question: I want to aliasing the following command:
new-item -path alias:rmn  -value "Enter-PSSession -ComputerName NUC"

What must be done that this works?
Answer: Thats not what aliases are for in powershell. you need to créate a function for that:
function rmn {
    Enter-PSSession -ComputerName NUC
}

Aliases are only for commands, you cannot use parameters with aliases
alternatively you can créate alias rmn for enter-pssession and use it like so:
rmn -computername nuc


Qual a importância do uso de interfaces em java ou c#?

Question: Sei como implementar e usar as interfaces, mas não consigo compreender qual o real motivo delas existirem no c# ou java, já que uma vez que você estende sua classe a uma interface é preciso implementar todos os métodos da interface.
Answer: Basicamente, uma interface é um contrato, estabelecido normalmente para uso entre dois componentes distintos, como um sistema e uma biblioteca, por exemplo, ou ainda para diminuir restrições no uso de objetos.
Há vários usos. Um dos mais interessantes é o de IEnumerable<T> no C#. A implementação de uma enumeração pode não ser um objeto, mas uma função geradora. Vários objetos implementam IEnumerable<T>, como List<T>, arrays, Collection<T>, Queue<T>, Stack<T> e qualquer função cujo retorno seja baseado em yield return, que acumula vários retornos de objetos que resultam em uma enumeração pelo método chamador. Este é um caso de redução de restrição: quando declaro:
IEnumerable<Objeto> lista;

Posso atribuir a ele quaisquer um dos objetos já citados:
lista = new List<Objeto>();
lista = new Collection<Objeto>();
lista = new Queue<Objeto>();
lista = new Stack<Objeto>();
lista = new Objeto[10];
lista = MinhaFuncaoComYieldReturn();

public static IEnumerable<Objeto> MinhaFuncaoComYieldReturn()
{
    for (var i = 0; i <= 10; i++)
        yield return new Objeto();
}

Além disso, Java e C# são duas linguagens que não suportam herança múltipla. Interfaces são uma boa maneira de garantir que uma classe seja uma composição de várias implementações diferentes.
Um caso emblemático disso é a classe SortedDictionary<TKey, TValue>, também do C#:
public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>,
IReadOnlyCollection<KeyValuePair<TKey, TValue>>

Ela precisa ser um dicionário, uma enumeração, uma coleção, ter suporte a ordenação e ainda ter métodos em modo somente leitura. Isto garante uma grande quantidade de usos da mesma estrutura de dados.
O Java funciona da mesma forma.
Por último, vale ainda a pena falar de troca de componentes. Suponha por exemplo que temos uma classe implementada em uma biblioteca que por algum motivo não queremos mais usá-la:
public class ClasseDaBibliotecaASerRetirada
{
    public void Metodo1(int i, int j) { ... };
    public int Metodo2() { ... };
    public int[] Metodo3(params int[] parametros) { ... };
}

Podemos extrair a interface dela:
public interface IClasseDaBibliotecaASerRetirada
{
    void Metodo1(int i, int j) { ... };
    int Metodo2() { ... };
    int[] Metodo3(params int[] parametros) { ... };
}

E implementar outra classe, sem modificar muito do código dependente dessa classe:
public class MinhaNovaClasse : IClasseDaBibliotecaASerRetirada
{
    public void Metodo1(int i, int j) { ... };
    public int Metodo2() { ... };
    public int[] Metodo3(params int[] parametros) { ... };
}

Answer: O conceito de desenvolver o código voltado para interfaces vem da necessidade organizar as classes de forma mais coesa, com baixo acoplamento e funcionalidades bem encapsuladas (fundamentos da Orientação a Objeto).
Programar voltado a interface exige abstrair a ideia da implementação. Vou tentar resumir de uma forma bem simplista:
public class Empresa {

    public void efetuaPagamento(CNPJ cnpj, double valor){
        String cnpj = cnpj.getNumero();
        ...
    }

    public void efetuaPagamento(CPF cpf, double valor){
        String cnpj = cpf.getNumero();
        ...
    }

}

A classe Empresa está acoplada as CPNJ e CPF. Para cada novo tipo de documento  será necessário copiar o método. Para evitar isso, podemos criar uma interface.
public interface Documento {

    public String getNumero();
}

E então as classes podem implementa-las.
public class CNPJ implements Documento {

    public String getNumero(){
        //implementação
    }

    public void validaCNPJ(String cnpj){
        //implementação
    }
}

public class CPF implements Documento {

    public String getNumero(){
        //implementação
    }

    public void validaCPF(String cpf){
        //implementação
    }
}

Simplificando assim a classe Empresa
public class Empresa {

    public void efetuaPagamento(Documento documento, double valor){
        String documento = documento.getNumero();
        ...
        }
}

Não se apegue muito no conteúdo dos exemplos, o ponto é entender que qualquer mudança na implementação será feita em um único ponto (Classes CNPJ ou CPF). A classe Empresa está desacoplada, para ela só interessa receber o número do documento, não importando o tipo do documento. Além de que qualquer novo documento, bastará criar uma classe e implementar o Documento, que não afetará em nada a classe Empresa.
Comment: Eu não sabia que uma interface poderia receber uma classe que implementa a mesma, agora vou poder programar de forma mais otimizada, obrigado.
Comment: @Fells, dessa forma o código fica mais limpo e organizado. Sempre tive a dúvida de como utilizar interfaces. Vou me aprofundar mais nesse assunto porque quero passar a utilizar interfaces nos próximos projetos que desenvolver.
Comment: @DiegoFarias Na minha opinião, a curva de aprendizado da Orientação a Objetos é um pouco longa. Eu mesmo demorei bastante para entender o conceito na prática. Você até compreende quando lê algum artigo ou vê exemplos mas a absorção mesmo só vem depois que você começa a perceber a necessidade de melhorar a qualidade do código no dia a dia.

Essa apostila da Caelum exemplifica de uma forma bem didática - https://www.caelum.com.br/apostila-java-orientacao-objetos/heranca-reescrita-e-polimorfismo/


Decrypt encrypted text in java

Question: i have an assignment. i have done all the parts of the assignment. but i am strucked in below part of my assignment. can you help me
Assignment guidelines
III.Write one constructor method for the EncryptedNode class. This constructor should take a String as an argument.
Unlike other constructors you have written, this constructor should function conditionally. If the message is one character long, simply assign that character to the letter instance variable. If the message is two characters long, assign the first character to the letter, and the other character as a string to the right EncryptedNode. In any other case, find the middle value of the input String, assign the character at the first index to letter, characters
from 1 up to the middle character should go to the right EncryptedNode, and the remaining unclaimed
characters should go the left EncryptedNode. Note: you will be instantiating new EncryptedNode objects from
this constructor, thus creating a recursive construction.
IV. Write the following methods:
a. The decrypt method takes no arguments and returns a String. This method should re-build the original unencrypted String by adding the letter, left and right elements of each EncryptedNode recursively. This process will be left to you to solve.
my sample code is
class EncryptedNode {

public EncryptedNode left, right ;
public char letter ;

// EncryptedNode Class constructor method.
public EncryptedNode (String message) {

    // get String length
    int message_length = message.length() ;

    if (message_length == 1) {
        this.letter = message.charAt(0) ;
    }else if (message_length == 2) {
        this.letter = message.charAt(0) ;
        this.right = new EncryptedNode (message.substring(1));
    } else {
        this.letter = message.charAt(0) ;

        // get the middle index of the message string.
        int middle_index = message.substring(1).length() /2 ;

        // get left and right strings
        String rightStr = message.substring(1,middle_index+1);
        String leftStr = message.substring(middle_index+1);

        this.left = new EncryptedNode (leftStr);
        this.right = new EncryptedNode (rightStr);
    }

    System.out.println (this.letter);
    // System.out.println (this.right);

}

public static void main (String [] args) {

    EncryptedNode en = new EncryptedNode("ABCDEF") ;

    en.decrypt();
}

public String decrypt () {
    if (this.left == null && this.right==null) {
        return this.letter;
    }else if (this.left == null && this.right != null) {
        return this.letter + this.right;
    }else if (this.left !=null && this.right != null) {
        return this.left + this.letter + this.right;
    }
}

}
Comment: i got errors. need to fix them. i need to return decrypted message in string format
Answer: I'm not going to write the code for you, since this is a classroom assignment, but I can explain how you should go about solving it.
You want to work backward through the encryption method in order to decrypt it. Right now, you're just returning "st" no matter what the encrypted string is.
I misread the code before.
This is a recursive method, so you have to start your way from the bottom and work your way up. You're going to have to decrypt the left side and then decrypt the right side and add them together.
In the decrypt method, you have to recursively call this.left.decrypt(); and this.right.decrypt(); until you get to the base case. The base case is when the left and the right are equal to null. At that point you just return the letter. This is the bottom of the recursion.
So to write your decrypt method, you want to return this.left.decrypt() + this.letter + this.right.decrypt();unless this.left or this.right are null.
If this.right is null, you'll return this.letter;
If this.left is null, you'll return this.letter + this.right.decrypt();
Sorry for the initial confusion, I thought this was an easier assignment than it really was.
Hopefully I helped this time!
Solution:
public String decrypt () {

    if (this.right == null) {
       return this.letter;
    }
    if (this.left == null) {
        return this.letter + this.right.decrypt();
    }
    return this.left.decrypt() + this.letter + this.right.decrypt();
}

Comment: Fixed my response, I didn't realize this was recursive.
Comment: Wrote it up for you.
Comment: No problem! Please select this as a working solution if you got it working.
Comment: @chinthaka Can you select this answer as the answer for the question so I can receive reputation?
Comment: return "st"
just for returning purposes. need decrypted message to return as string.
Comment: i got messed up with this. can you send me simple code snippet to do this. :(
Answer: You are very close to a valid solution. Keep in mind that according to your specs you store the text as letter + right + left and not (left + letter + right).
I am posting a solution, take a close look to understand how it works. If you are allowed to use StringBuilder (or the thread-safe StringBuffer) use those when you need to change the value of a String (I am putting the StringBuilder concatenation version in comments).
public static void main (String [] args) {

    EncryptedNode en = new EncryptedNode("ABCDEF") ;

    System.out.println(en.decrypt());
}

public String decrypt () {

    //if you are not allowed to use StringBuilder
    String s = String.valueOf(this.letter);
    if (this.right != null) {
        s = s + this.right.decrypt();
    }
    if (this.left != null) {
        s = s + this.left.decrypt();
    }
    return s;

    /*
    StringBuilder sb = new StringBuilder();
    sb.append(this.letter);
    if (this.right != null)
        sb.append(this.right.decrypt());
    if (this.left != null)
        sb.append(this.left.decrypt());
    return sb.toString();
    */
}

Decrypt encrypted text in java


Large scale SVM classification problem

Question: Problem
I am now working on a sentiment analysis task where the largest dataset involves 36 million custom reviews and associated sentiment (positive or negative).
The feature extraction process is completed after some efforts. Individual review is encoded into a dense 300 dimension vector and this will serve as a feature for classification.
The SVM seems to be a good choice for classification. However, the runtime is endliess even on very powerful cloud computing facility. Therefore, there are three questions

If I insist on working with SVM, what trick could I do to improve the runtime. By the way, I am using sklearn.svm.SVC with linear kernel.
Is it okay to reduce the number of training samples in practice? I once took statistical learning theory course, it told me that the error rate grows with $O(\frac{1}{\sqrt{n}})$, so it seems it is okay to reduce to 10% or even 1% of the original dataset?
If SVM is hopeless in terms of runtime. Are there other classifiers that could do the job with good speed. Further, is there some results that pinpoint the runtime of different sklearn based algorithms?

Thank you, any input is appreciated.
Answer: For large scale SVM classification, you can use shrinking factor = True. modify the cache_size and tolerance levels and small C values.
Comment: Welcome to this venue! Thank you for your advice, I will try that in future projects.

Large scale SVM classification problem


How to set block display of inline elements in shadow root

Question: I have a few
 tag in shadow root,they are inline codes. When I tried to style them like display:block for each. And it failed. How to set them one item below other? Thanks.
This is the code I have used:
polyfill-next-selector{content: '.card-header #phone';}
.card-header ::content #phone
{
  display:block;
  font-size: 0.7rem;
}

polyfill-next-selector{content: '.card-header #building';}
.card-header ::content #building
{
  display:block;
  font-size: 0.7rem;
}

polyfill-next-selector{content: '.card-header #office';}
.card-header ::content #office
{
  display:block;
  font-size: 0.7rem;
}

polyfill-next-selector{content: '.card-header #skype';}
.card-header ::content #skype
{
  display:block;
  font-size: 0.7rem;
}

polyfill-next-selector{content: '.card-header #computerName';}
.card-header ::content #computerName
{
  display:block;
  font-size: 0.7rem;
}

polyfill-next-selector{content: '.card-header #businessMobile';}
.card-header ::content #businessMobile
{
  display:block;
  font-size: 0.7rem;
}
</style>

  <content select="img"></content>
  <content select="h2"></content>
  <content select="#phone"></content>
  <content select="#building"></content>
  <content select="#office" ></content>
  <content select="#skype" ></content>
  <content select="#computerName" ></content>
  <content select="#businessMobile" ></content>

<content></content>

Comment: Can we have your code please.
Comment: I've added the code above.
Answer: You need to target nods distributed inside content tags, instead of ::content itself.
They are logically not inside content nodes though, but css selectors understand it that way.
So instead of
::content
{
  display:block;
  font-size: 0.7rem;
}

it should be
::content > p
{
  display:block;
  font-size: 0.7rem;
}

Here is a working jsfiddle as well for the same.
Take a look on this nice tutorial on styling distributed nodes also, if you haven't already.


Gini index in classification tree

Question: In Gareth etc.'s book "An introduction to statistical learning", when it's talking about Gini index, I clipped the paragraph in the following image:

My question is the statement that "For this reason the Gini index is referred to as a measure of node purity -- a small value indicates that a node contains predominantly observations from a single class." I don't understand the logic behind this. So when $\hat p_{mk}$ is close to 1 (and thus Gini index is small), which means by its definition that most of the training observation in the mth region are from the kth class. If it's in income statistics, does it mean the training observation is from high-income or low-income class? If yes, however, a contradiction to this is that if Gini index is high in income statistics, it means most people are either in the high-income class or low-income class (wealth gap is large). What am I misunderstanding here?
It's even more obscure to me when $\hat p_{mk}$ is close to 0.
Comment: Of possible interest: https://stats.stackexchange.com/a/6610/930 (regarding node impurity and deviance in CART).
Answer: I would shy away from any specific label interpretations and just look at it from a general classification stand point. You have $K$ classes (I omit the region index, because its not important) and empirical multinomial distribution $\hat{p}_1,\ldots,\hat{p}_K$. Gini index, apart from some other impurity measures like mutual information, is just one of the more sensible measures (its concave, which is very important) you can use.
If you want to interpret it in some way then it is an average number of classification errors you make when you sample a random example from the region and assign it a label at random using the empirical distribution $p_k$.
I always found Gilles Louppe's PhD Thesis - Understanding Random Forests: From theory to practice (https://arxiv.org/pdf/1407.7502.pdf) one of the best reference to understand how the tree-based methods actually work (not only theoretically but how to implement them efficiently).
Answer: If, in a given node of the tree, a vast majority of individuals have "high income", Gini index is small. So is it if a vast majority of individuals have "low income". The highest value for the Gini index will be achieved when half of the observations are "high income" and the other half are "low income".
So I think you got the idea right. You may feel uncomfortable about this result because income is actually a numerical variable and we are only splitting the population in "high" and "low" on an arbitrary threshold. However, think of light vs brown eyes and you will see that it makes the most sense to see a high Gini index when the node is "least pure" or "most diverse" (this meaning half of the individuals in the node have brown eyes and the other half have blue ones)
In summary, you got it right, except for the fact that there is no contradiction. Let's think it otherwise to make it more intuitive.
Imagine there are only two possible yearly incomes, "low" corresponding to €10,000 and "High" corresponding to "€90,000" (remember that, when using the labels "high" and "Low", your model cannot distinguish any further than this) A population with half of €90K earners and half of €10K earners is more "unequal" than another one with millions of people making €10K and one lucky guy who makes €90K, isn't it?

Gini index in classification tree


How do you determine if an instrumental variable is randomly assigned?

Question: For an IV to be valid, it must be:

Randomly assigned
Correlated with the endogenous variable in the model
Uncorrelated with the dependent variable in the model

What does the random assignment of an IV mean?
How does one assess whether an IV is actually randomly assigned or not?
For example, given the model:
$T_i = \beta_0 + \beta_1STR_i + u_i$
where $T_i$ is average test score in school district i and $STR_i$ is student-teacher ratio in school district i.
Suppose $E(u_i|STR_i)\neq0$. Let an IV be the birth rate in school district i, $BR_i$.
What argument can be given for the random assignment of $BR_i$?
Answer: To restate the requirements you've listed (for linear models), an instrument must be

exogenous in the sense that it is independent of the error term $u_i$,
correlated with the endogenous explanatory variable $STR$ after conditioning on the other covariates,
and uncorrelated with the dependent term except through the explanatory variable (again, conditioning on the other variables).

Condition (1) is "instrument exogeneity" and condition (2) is "instrument" relevance.
The last condition here (3) is in essence just a restatement of (1).
The idea is that the instrumental variable cannot suffer from the same problem that the endogenous variable
suffers from. Is needs to be uncorrelated with that error. In a laboratory, random assignment solves this problem. In the typical social sciences setting, an instrument must be found that approximates random assignment. This condition is similar to condition (3) because, notice that if $BR$ affects $STR$, then $BR$ affects $T$ (through $STR$). However, the trouble arises when $BR$ affects $T$ through the error $u$.
Answer: To add to @jmbejara's answer, there is no formal statistical test for the validity of an instrument (beyond, obviously, that there shouldn't be any apparent correlation with the outcome except through the endogenous variable).  Selection of a valid instrument depends on subject matter knowledge.
To your example, I can imagine scenarios in which the birth rate could affect test scores.  Maybe parents who are busy with new children spend less time with their kids?  And why would student-teacher ratio be affected by birth rate, unless there are lags involved? (Infants don't go to school).  The point is that instrument validity involves qualitative reasoning.


Is it possible to "add up" posterior distributions?

Question: I've modeled a Bayesian mixed model where my outcome is count data (using a negative binomial model) in R using the rstanarm package. My data consists of multiple observations within sections of an organization on a monthly basis. Using the predict_posterior function, I have established a posterior distribution of fitted values for each observation section for each month.
Now, these sections are grouped into regions, and my client is interested in getting a yearly count in total for the entire organization and then broken down to yearly counts per regions and per sections. I could just add up the MAP estimates, but I want to keep the uncertainty around these estimates. My question is: Is it possible to add up each section's monthly posterior distributions? If so, how would one do this in R, given that each distribution consists of a vector of X draws?
Answer: Starting from a sample of monthly whatever, for each month, assumed to be independent, it is straightforward to generate the sum over the year, by simply picking one value for each month at random from the monthly sample.
Comment: Hi @Xi'an, just out of curiosity, what would need to be done if the months are not independent of each other (let's say there are seasonal variations)? Thanks.
Answer: If I understand your question correctly, the answer is yes. If you have draws from distributions of the components and are interested in distribution of their sum, then sums of the components would form the distribution of sums. The only question is if there is no some kind of correlation between components that is unaccounted in your model, since this may influence the results.


Using Biopython to parse a PDB file

Question: I need to parse through a PDB file using biopython in order to extract each line that pertains to an alpha carbon (CA). Here is the code that I use
from Bio.PDB import *

parser=PDBParser()
io = PDBIO()

structure_2 = parser.get_structure('Y', 'A.pdb')

for l in structure_2:
   if atom.get_id() == 'CA':
       io.set_structure(atom)
       io.save("alpha.pdb")

My idea is that the for loop will go through each line of the PDB file write each line that pertains to an alpha carbon ('CA') to a new PDB file called alpha.pdb. Here is a short preview of what structure_2 looks like:
ATOM      1  N   LYS A  35      -5.054  29.359  -1.504  1.00 61.86           N
ATOM      2  CA  LYS A  35      -5.430  28.077  -0.842  1.00 61.30           C
ATOM      3  C   LYS A  35      -4.188  27.450  -0.230  1.00 59.47           C
ATOM      4  O   LYS A  35      -3.142  27.339  -0.875  1.00 59.94           O
ATOM      5  CB  LYS A  35      -6.055  27.113  -1.860  1.00 63.54           C
ATOM      6  CG  LYS A  35      -7.354  26.443  -1.409  1.00 65.88           C
ATOM      7  CD  LYS A  35      -7.126  25.382  -0.339  1.00 66.83           C
ATOM      8  CE  LYS A  35      -8.363  24.507  -0.172  1.00 67.47           C
ATOM      9  NZ  LYS A  35      -8.010  23.158   0.355  1.00 68.07           N
ATOM     10  N   TYR A  36      -4.293  27.093   1.042  1.00 56.18           N
ATOM     11  CA  TYR A  36      -3.183  26.472   1.741  1.00 52.61           C
ATOM     12  C   TYR A  36      -3.455  24.992   1.893  1.00 51.51           C
ATOM     13  O   TYR A  36      -4.561  24.580   2.250  1.00 51.93           O
ATOM     14  CB  TYR A  36      -2.986  27.111   3.117  1.00 49.10           C
ATOM     15  CG  TYR A  36      -2.305  28.456   3.074  1.00 45.23           C

As you can see, the relevant information (CA) is in the third column of the PDB file. Whenever I run my code, it does not write any new files, but it doesn't give me any errors. What could I be doing wrong here?
Comment: Relevant [Reading .pdb files using BioPython](https://stackoverflow.com/a/44673302/7414759)
Answer: Below you can find a script that loads a protein structure 1p49.pdb (from script directory), then parses it and saves only alfa carbon atom coordinates to the 1p48_out.pdb file
#!/usr/bin/env python3
import Bio
print("Biopython v" + Bio.__version__)

from Bio.PDB import PDBParser
from Bio.PDB import PDBIO

# Parse and get basic information
parser=PDBParser()
protein_1p49 = parser.get_structure('STS', '1p49.pdb')
protein_1p49_resolution = protein_1p49.header["resolution"]
protein_1p49_keywords = protein_1p49.header["keywords"]

print("Sample name: " + str(protein_1p49))
print("Resolution: " + str(protein_1p49_resolution))
print("Keywords: " + str(protein_1p49_keywords))
print("Model: " + str(protein_1p49[0]))

#initialize IO
io=PDBIO()

#custom select
class Select():
    def accept_model(self, model):
        return True
    def accept_chain(self, chain):
        return True
    def accept_residue(self, residue):
        return True
    def accept_atom(self, atom):
        print("atom id:" + atom.get_id())
        print("atom name:" + atom.get_name())
        if atom.get_name() == 'CA':
            print("True")
            return True
        else:
            return False

#write to output file
io.set_structure(protein_1p49)
io.save("1p49_out.pdb", Select())

Using Biopython to parse a PDB file


How to configure nginx so it works with Express?

Question: I'm trying to configure nginx so it proxy_pass requests to my node apps. Question on StackOverflow got many upvotes: https://stackoverflow.com/questions/5009324/node-js-nginx-and-now and I'm using config from there.
(but since question is about server configuration it is supposed to be on ServerFault)
Here is the nginx configuration:
server {
  listen 80;
  listen [::]:80;

  root /var/www/services.stefanow.net/public_html;
  index index.html index.htm;
  server_name services.stefanow.net;

  location / {
    try_files $uri $uri/ =404;
  }

  location /test-express {
    proxy_pass    http://127.0.0.1:3002;
  }

  location /test-http {
    proxy_pass    http://127.0.0.1:3003;
  }
}

Using plain node:
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3003, '127.0.0.1');

console.log('Server running at http://127.0.0.1:3003/');

It works!
Check: http://services.stefanow.net/test-http
Using express:
var express = require('express');
var app = express(); //

app.get('/', function(req, res) {
  res.redirect('/index.html');
});

app.get('/index.html', function(req, res) {
  res.send("blah blah index.html");
});

app.listen(3002, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3002/');

It doesn't work :(
See: http://services.stefanow.net/test-express

I know that something is going on.
a) test-express is NOT running

b) text-express is running

(and I can confirm it is running via command line while ssh on the server)
root@stefanow:~# service nginx restart
 * Restarting nginx nginx                                                                                [ OK ]

root@stefanow:~# curl localhost:3002
Moved Temporarily. Redirecting to /index.html

root@stefanow:~# curl localhost:3002/index.html
blah blah index.html

I tried setting headers as described here: http://www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/ (still doesn't work)
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;

I also tried replacing '127.0.0.1' with 'localhost' and vice versa

Please advise. I'm pretty sure I miss some obvious detail and I would like to learn more. Thank you.
Comment: Any log in `nginx` error log?
Comment: In this setup - how are you running your express application? Do you need to have a separate process like `forever` or `pm2` that runs it, then `nginx` just proxies to it?
Comment: I cannot recall exactly... I remember the accepted answer did work for me.
Answer: You express configured to serve path /index.html, but you requires /test-express/index.html. Either configure express to serve /test-express/index.html or make nginx to strip /test-exress from proxied request. Latter is as simple as add trailing slashes to location and proxy_pass.
location /test-express/ {
  proxy_pass    http://127.0.0.1:3002/;
}

See http://nginx.org/r/proxy_pass for details.
Comment: **Q:** "I'm pretty sure I miss some obvious detail" **A:** "as simple as add trailing slashes" (thank you, I was literally stuck)


Impacto do Garbage Collector

Question: O projeto aqui da empresa é feito em Windows Forms e não gerenciamos muito bem a memoria, pois é um sistema legado que tem vários anos rodando.
Atualmente estamos enfrentando problemas com falta de memoria nos computadores onde roda o sistema pelo fato do consumo de memoria quando o sistema está rodando ser muito alto.
Tenho dúvidas quanto ao uso do GC, pois comecei a colocar em quase todos os lugares, mas parei para pensar e não sei se é a melhor forma, ainda mais projetos em Windows Forms.
Minhas dúvidas são:

Em que momentos é bom limpar a memoria?
O momento ideal é quando abrir e fechar a tela?
Em todos os botões da tela?
Quais problemas podem ser causados com o uso excessivo do GC?

Como eu poderia resolver esses erros de falta de memoria?
Comment: "comecei a colocar em quase todos os lugares" o que isso quer dizer?
Comment: Empolguei e coloquei em botões e construtores, por exemplo... Onde achei que era critico, coloquei... Mas não sei se está certo.
Comment: Colocar o que?.
Comment: O GC.Collect();
Answer:
Em que momentos é bom limpar a memoria?

Nunca. Já respondi isso antes.

O momento ideal é quando abrir e fechar a tela?

Nunca!

Em todos os botões da tela?

Nunca!

Quais problemas podem ser causados com o uso excessivo do GC?

Pausas e perda de performance.
Que mal pode causar em liberar a memória?
Essa é a real pergunta que deve ser feita. O problema está mais em fazer a liberação manual da memória do que em deixar sem fazer. As pausas serão mais frequentes e mais longas. Se havia um problema de memória, agora há um problema de gerenciamento dela. Não vou entrar em detalhes porque isso já está explicado na outra pergunta.
Pode ser que tenha um exagero na utilização na memória por arquitetura errada ou por falha em liberação. A liberação é automática, mas o programador tem que saber fazer. Ele não pode manter referências para os objetos.
Real problema
Já vi casos de uma janela chamar outra que chama a primeira, aí vira um ciclo vicioso terrível. Mas a maioria dos casos nem é tão terrível, mas os objetos são mantidos vivos por mais tempo do que precisa.
Tem caso que deixam vazando mais tempo do que deveria. Tem objetos pre precisam de liberação explícita, pelo menos usando o using.
Eu vejo a maioria dos programadores fazendo códigos sem pensar em como elevai funcionar. Só querem ver o resultado. Isso não dá certo. É preciso planejamento. Sem saber como tudo funciona fica à mercê da coincidência. Pode dar certo ou não.
Não sei qual é o caso dessa aplicação, mas é possível que tenha sérios problemas de gerenciamento dos objetos. Talvez vá ter que fazer um profiling. tem ferramentas para isso:

CLR Profiler
dotMemory
JustTrace
ANTS
.NET Memory Profiler
.NET Profiler
BenchmarkDotNet

Não dá para descartar a possibilidade de simplesmente a aplicação estar precisando de mais memória mesmo. Tem casos assim. Mas antes de investir no hardware precisa ter certeza que resolveu todos de software.
Agora tem melhores subsídios para começar pensar no problema certo e quem sabe fazer perguntas específicas.
Coloquei no GitHub para referência futura.
Comment: É técnica. É entender todo o funcionamento da memória, cada aspecto da aplicação. Não tem um *link*, tem milhares que precisam ser seguidos até entender tudo. Pelo menos falando genericamente. Claro que perguntas específicas sempre cabem.
Comment: Isso pode ajudar um pouquinho: http://pt.stackoverflow.com/q/135572/101. Referências costumam ocorrer em grafos, o que é algo extremamente complicado quando se perde o controle. Por isso tem que saber onde cada objeto está referenciado e ter certeza que não está por engano. Não é só sair fazendo as coisas funcionarem, tem que saber se elas estão funcionando do jeito adequado.
Comment: Essas ferramentas se encarregariam de liberar a memoria de forma segura então?
Comment: Não. Nada vai magicamente resolver o problema. Elas ajudam você descobrir onde está o erro na aplicação para não começar no escuro. Normalmente nesses casos tem que reescrever muita coisa, rearquitetar a aplicação. Tem casos que é tão complicado que é melhor deixar pra lá e começar fazer de novo, desta vez entendendo todo funcionamento antes, caso contrário os problemas vão acontecer de novo. Claro que nem todos casos são tão terríveis assim.
Comment: Poxa entendi.. É porque tenho duas telas que quando há o uso excessivo delas, erros de falta de memoria começam a pipocar a ponto de fechar o sistema... Para resolver o erro temos que sair do sistema e abrir de novo para limpar tudo... Por isso achei que usar o GC nos construtores ajudaria a manter a memoria em um nível aceitável para não dar erro... Mas o melhor é não mexer manualmente com o GC e usar essas ferramentas para encontrar aonde está o gargalo né?
Comment: Só piora a situação. Se leu o que respondi antes verá que esse `GC.Collect()` é só para experimento, testes, não para uso em produção. Tem que ver quais objetos estão vivos mais tempo que o necessário. Nem sempre é fácil achar isso, porque a maioria dos programas são feitos sem pensar no todo. O primeiro passo é tomar consciência sobre tempo de vida de objetos. Não é só ir criando e esperar que uma hora eles sumam, Tem que garantir que as condições para isso se estabeleçam. Se as condições não acontecerem, o objeto não é liberado. Vive tendo vazamento de memória, poucos casos ficam aparentes.
Comment: Existe alguma forma de controlar o ciclo de vida do objeto? Um link onde eu possa me basear?
Comment: Show! Muito obrigado!

Impacto do Garbage Collector


How to install SquirrelMail on ubuntu 18.04

Question: I'm trying to install SquirrelMail on Ubuntu 18.04LTS but when i run the next command:
sudo apt-get install squirrelmail

I got this:
Unable to locate package squirrelmail

I was trying to investigate but never asked before so i want to know how and if this is possible. Thanks.
Answer: Install with sources indeed:
Dowload: https://sourceforge.net/projects/squirrelmail/files/stable/1.4.22/squirrelmail-webmail-1.4.22.zip/download?use_mirror=nchc
Unzip: unzip squirrelmail-webmail-1.4.22.zip
And run config: ./configure
Comment: I'll check it today. thanks.
Comment: The console give next error `unzip:  cannot find or open squirrelmail-webmail-1.4.22.zip, squirrelmail-webmail-1.4.22.zip.zip or squirrelmail-webmail-1.4.22.zip.ZIP` after `wget https://sourceforge.net/projects/squirrelmail/files/stable/1.4.22/squirrelmail-webmail-1.4.22.zip/download?use_mirror=nchc`  any help?
Comment: have you move to the right folder you downloaded it


Comparing relative frequencies between two groups

Question: If i have the relative proportion for two sample.
For example :
group 1:

Male: 50%
Female: 25%
children: 25%

group 2:

Male: 50%
Female: 20%
children: 30%

How can I measure the % of similarity between the two group?
Answer: You can use a Pearson's chi-squared test. Calculate the average number of people in each demographic across both groups (e.g., how many women were there overall)? Suppose that it's 23%. See how many women that would imply would be in group 1, 11 say. But you actually observed 13 (I'm assuming that there are 50 people in group 1 for concreteness). Take 13, subtract off 11, square this number (2 squared is 4), then divide by the number of women that you expected on average (11). Do this for group 2's women and add these fractions together. Then do the same procedure for men and children and add all these number together. Your result has a chi-squared distribution with 3 degrees of freedom. See the Wikipedia article here for more information
Comment: Can this be also used for continuous variable. like distribution of wage in each group?
Comment: @Skyde,, it can be used for any summary statistic that you use to fill the cells in the group-by-demographic table.
Comment: I understand that as long as i split the value for wage in bin i can use each bin as a demographic.
But this would mean finding the optimal bin width. :(
Comment: @Skyde, I thought that you meant that you wanted to have a table with, say group (1 or 2) along the top and demographic (men, women, or children) along the side, with, say, average wage for each cell inside. That would work. I'm not sure what you're trying to describe now.
Comment: if i have 50 people in each group and for each people the wage. And i want to measure the % of similarity between the two group. The only way i see of doing the chi-squared test is to split wage in demographic 2 (rich and poor) before doing the analysis but it seem like there should be a better way to do that.
Comment: If you want to compare the full distribution of wages between two groups, you can use the non-parametric Kolmogorov–Smirnov test. This looks for any difference in the distribution of wages in the two groups. Wikipedia article here: http://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test


Ajax is not working in Webix

Question: I am trying my first webix programm. I follow the get start document. As per the document I place my code in HTML page and two json file. Here is my complete code.
<!DOCTYPE HTML>

  <link rel="stylesheet" href="../webix_v4.2.4_pro/codebase/webix.css" type="text/css">

My page is loading but one error

Uncaught ReferenceError: tree_data is not defined

Also page is not oading. Am I missing anything in ajax or something. Can anybody please help me in this.
If you need I will place my json data also.
My tree_data.json
[
  { id: "1",
    type: "folder",
    value: "Music",
    css:"folder_music",
    data:[{
            id : 6,
            type: "folder",
            value: "Music",
        },{
            id : 3,
            type: "folder",
            value: "Music",
        },{
            id : 4,
            type: "folder",
            value: "Music",
        },{
            id : 5,
            type: "folder",
            value: "Music",
        }]
 },{ id: "2",
    type: "folder",
    value: "Music",
    css:"folder_music",
    data:[{
            id : 7,
            type: "folder",
            value: "Music",
        },{
            id : 8,
            type: "folder",
            value: "Music",
        },{
            id : 9,
            type: "folder",
            value: "Music",
        },{
            id : 10,
            type: "folder",
            value: "Music",
        }]
 }
]

My grid_data.json
[
  { id:1, title:"The Shawshank Redemption", year:1994, votes:678790, rating:9.2, rank:1},
  { id:2, title:"The Godfather", year:1994, votes:678790, rating:9.2, rank:1},
  { id:3, title:"The Godfather part : 2", year:1994, votes:678790, rating:9.2, rank:1},
  { id:4, title:"The good, the bad and the Ugly ", year:1994, votes:678790, rating:9.2, rank:1},
  { id:5, title:"My Fair Lady", year:1994, votes:678790, rating:9.2, rank:1},
  { id:6, title:"12 Angery Man", year:1994, votes:678790, rating:9.2, rank:1}
]

Answer: I'm assuming tree_data is the json data you're trying to get with the ajax request. You need to return the data or store it somewhere for later use. In the code you have, you have not defined tree_data or grid_data. Try getting the data similar to how its done here:

<!DOCTYPE HTML>

  <link rel="stylesheet" href="http://cdn.webix.com/edge/webix.css" type="text/css">

The JSON you have isn't loading because it isn't valid json; the keys need to be strings like this:
tree_data
[{
  "id": "1",
  "type": "folder",
  "value": "Music",
  "css": "folder_music",
  "data": [{
    "id": 6,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 3,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 4,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 5,
    "type": "folder",
    "value": "Music"
  }]
}, {
  "id": "2",
  "type": "folder",
  "value": "Music",
  "css": "folder_music",
  "data": [{
    "id": 7,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 8,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 9,
    "type": "folder",
    "value": "Music"
  }, {
    "id": 10,
    "type": "folder",
    "value": "Music"
  }]
}]

grid_data
[{
  "id": 1,
  "title": "The Shawshank Redemption",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}, {
  "id": 2,
  "title": "The Godfather",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}, {
  "id": 3,
  "title": "The Godfather part : 2",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}, {
  "id": 4,
  "title": "The good, the bad and the Ugly ",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}, {
  "id": 5,
  "title": "My Fair Lady",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}, {
  "id": 6,
  "title": "12 Angery Man",
  "year": 1994,
  "votes": 678790,
  "rating": 9.2,
  "rank": 1
}]

If this isn't the solution for you the problem you should look into is making sure you get the data tree_data and grid_data into the scope of your webix.ready(). Hope this helps.
Comment: Thanks a ton. Now url is fetching in ajax. Grid is not loading but I will check whats cause that. I will accept this in sometime.
Comment: Don't know for some reason data is not loading.
Comment: Thanks  a ton Jonthan. I know these are silly mistakes, but i make sure i come over from these mistakes. Thanks!! working
Comment: @Jonthan When I am checking in network these url which passed in ajax itself is not loading. therefore I am getting error like "Uncaught TypeError: treeData.getData is not a function"
Comment: @shankysingh I updated the code I had a few typos in the last one, but whats the path to your `tree_data.json` ??
Comment: @Jonthan `tree_data.json` is in same folder where I place index.html
Comment: @shankysingh can you add the json you're working with ? If you're running this on a server `tree_data.json` should load, the new issue should be with `webix` and what you're trying to accomplish with the `tree_data.json` data
Comment: I update my question. funny is when i am declear this in variable things are working. when loading by this method i am getting `Uncaught TypeError: Cannot read property '$count' of undefined`  error
Comment: @shankysingh you had invalid `json` to start with, if you use update your `json` to how I mentioned in my answer you'll see the data you want is there  . Just `console.log` it in the `ajax` call so you can see that you have it. Now whatever it is that you want to do with that data that's another question entirely.

Ajax is not working in Webix


Getting specific part of a data-attribute on hover

Question: I am having a div with a data-attribute which has several double quotes inside it, so the information is therefore not escaped, but it is necessary to do it this way in my project.
I am trying to get the "jj-storefront-hero-rethinking-denim" value when i hover on the div.

This is the jQuery which i wrote:
$( ".test" ).hover(function() {
  var contentAsset = $(this).attr("data-layer-promotion-view");
  console.log(contentAsset)
});

Is there some way to select a certain set of double quotes inside a data-attribute?
See codePen here: http://codepen.io/fennefoss/pen/evMLww?editors=1111
Comment: Try change `data-layer-promotion-view="{` to `data-layer-promotion-view='{`
Comment: Since data contains the perfect JSON. You can call `JSON.parse()` on it and can access the attributes.
Comment: Why don't you escape double quotes like this: `\"`? That should work.
Comment: @abhishekkannojia How would I go about doing this? can you make an example?
Answer: Use combination of ' and " quotes, then you can use .data(key) to retrieve it.

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.

var data = $('.test').data('layer-promotion-view');
console.log(data.row_type);
console.log(data);

Comment: Hi Satpal I cant get this example to work on my codepen, do i need something more?
Comment: @MikkelFennefoss, it's because you're still not correctly escaping the value of the attribute. Now you have `data-layer-promotion-view='"{"row_type":"row-type-3-dynamic-smart","row_id":"home-page-row-01-widget","column_id":1,"id":"jj-storefront-hero-rethinking-denim","name":null,"creative":"/on/demandware.static/-/Library-Sites-bestseller-content-library/default/dw871109fc/jackjones/store-assets/w09/smart-widget/hero/rethinking_denim-dk.jpg"}"'`
Comment: and it should really be `data-layer-promotion-view='{"row_type":"row-type-3-dynamic-smart","row_id":"home-page-row-01-widget","column_id":1,"id":"jj-storefront-hero-rethinking-denim","name":null,"creative":"/on/demandware.static/-/Library-Sites-bestseller-content-library/default/dw871109fc/jackjones/store-assets/w09/smart-widget/hero/rethinking_denim-dk.jpg"}'` (observe the start and end quotes difference). You can also check my answer if you want a solution for `hover()` using `attr()`.
Answer: Just use single quote, when defining attribute

Answer:

$( ".test" ).hover(function() {
  var contentAsset = $(this).attr("data-layer-promotion-view");
  console.log(contentAsset);
});
.test {
  width: 500px;
  min-height: 100px;
  padding:10px;
  background: red;
}
.test:hover:after {
  content: attr(data-layer-promotion-view);
  width: 500px;
}

Note : There is an error for using ". View your page source code in Browser, You will understand the error for declaring HTML attribute. Your attribute string is invalid for using "
Answer: You can add single quotes instead of double quotes arround the attribute data-layer-promotion-view value to correctly escape it and then use JSON.parse() to parse the string into an object, no need to change attr() to data():

$(".test").hover(function() {
  var contentAsset = JSON.parse($(this).attr("data-layer-promotion-view"));
  console.log(contentAsset.id);
});

test


Calculating intermittent average

Question: I have a huge dataframe with a lot of zero values. And, I want to calculate the average of the numbers between the zero values. To make it simple, the data shows for example 10 consecutive values then it renders zeros then values again. I just want to tell python to calculate the average of each patch of the data.
The pic shows an example
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: first of all I'm a little bit confused why you are using a DataFrame. This is more likely being stored in a pd.Series while I would suggest storing numeric data in an numpy array. Assuming that you are having a pd.Series in front of you and you are trying to calculate the moving average between two consecutive points, there are two approaches you can follow.

zero-paddding for the last integer:

assuming circularity and taking the average between the first and the last value

Here is the expected code:
<code>
import numpy as np
import pandas as pd

data_series = pd.Series([0,0,0.76231, 0.77669,0,0,0,0,0,0,0,0,0.66772, 1.37964, 2.11833, 2.29178, 0,0,0,0,0])
np_array = np.array(data_series)

#assuming zero_padding
np_array_zero_pad = np.hstack((np_array, 0))
mvavrg_zeropad = [np.mean([np_array_zero_pad[i], np_array_zero_pad[i+1]]) for i in range(len(np_array_zero_pad)-1)]

#asssuming circularity
np_array_circ_arr = np.hstack((np_array, np_array[-1]))
np_array_circ_arr = [np.mean([np_array_circ_arr[i], np_array_circ_arr[i+1]]) for i in range(len(np_array_circ_arr)-1)]
</code>
Comment: It so so huge data with multiple column that will later do other operation on them. what I want to do here simply: I want to calculate the average for each patch. the average of [0.762, 0.766] alone, and [0.66, 1.37, 2.11, 2.29] alone and so forth till the end of the Dataframe.
Comment: Ok this is actually no problem. One question beforehand: does this repeat according to the same index? if yes than it's pretty easy. You only select the specific indices and apply np.mean()
Comment: no nothing here is repeating, I tried to find any anchor for the selection but I could not. I just want python to create extra column and put these averages accordingly because later I will plot it with other columns and a lot to happen.
Comment: well what you could do is to always add the values as long as its not zero and append it to a list. is that something that helps you?  It's difficult to give you advice if the minimal example doesnt really sute your problem correctly.
Comment: please have a look here, I reposted the question. I am new here and I am struglling :D https://stackoverflow.com/questions/69057749/calculating-average-for-segments-in-dataframe

Calculating intermittent average


How would I go about getting a domain like lu.re?

Question: (*couldn't decide if this belongs in stackoverflow or here, but landed here. so if this Q belongs elsewhere I'll remove it)
How do I go about getting a domain like lu.re? I work for a non-profit and I'm thinking of setting up something like an in house shortening domain for publishing longer links in our print materials, and even for sharing stuff on our website (like videos).
I'm not talking about the process of shortening - we got all that covered. What I'm asking about specifically is how to obtain this domain?
I looked into it a little, and some of the drawbacks I found are...

*.re domains are hard to register. Most registrars don't register this ending.
The difficulty of obtaining a two letter domain. It seems that two letter domains are either all taken up, or not being sold, as seems to be the case with *.re domains.

So how would I work around the obstacles and get this thing? I know it is possible - proved by sites like ow.ly (hootsuite's shortening service).
Any tips here?
Just for the record, I checked at http://www.101domain.com/re.htm and when I type lu.re it comes up with .re are not accepting two letter domains. I'm willing to believe that may be a restriction of the registrar, not the *.re extension itself.
Comment: All one and two letter domains have specifically been reserved (though a few were issued before the reservation was official). So if it isn't registered yet, it never will be.
Answer: Unfortunately, two-character .re domains must be one number and one letter, or two numbers.
Accurate as of November 2016.
As of 6 Dec 2011, .re was opened to registration by anyone in the world, but two-character domains are special.
I recently tried to register a two-character domain name (fi.re :P). AFNIC's website says .re allows two-character domains, but all registrars/domain checkers were erroring out.
So I emailed AFNIC to request clarification, who (promptly!) replied with the following information:

You need to choose a domain name with at least 3 characters.
Only 2 characters domain names in .re, with at least one number are
  eligible to registration.
Examples :

domain names such as "m7.re" or "58.re" (2 characters with at least one number) are eligible to registration
domain names such as "7.re", "b.re" (1 character) or "am.re" (2 letters characters) are not eligible
Answer: Taken from this Link

Companies and organizations having a head office in the country or having a physical address in the country, mentioned in the public electronic databases of the registrars of the commercial courts or National Intellectual Property Institute, or National Statistical and Economic Studies Institute (INSEE), are entitled to apply for .re domain names. The .re registration is also reserved for the state departments, institutions, local authorities or associated establishments in the Reunion Island and for those residing in the country and owning a trademark registered with the National Intellectual Property Institute.

So, if you aren't located in Reunion Island, it looks like you are out of luck.
Comment: Please see my answer elsewhere in this question. **As of November 2016, anyone in the world can register a .re domain, but two-character domains must be one letter and one number, or two numbers. NOT two letters. These are the requirements.**
Answer: .re is for the Reunion Island, a French territory. The registry is the AFNIC. It is not an "open for everyone" extension, the registrant does indeed have to be an institution or company located on the island (official contract for registration - in French). Legal proxys are not an option - French law does not AFAIK allow it.
There have been no "domain party" for this extension as it is still regulated by the state.
Additionally, domains in the .fr or .re zones have to be more than 2 letters long. So yeah, you're out of luck.
Answer: You are a little late to that domain party.  Short domain names are now considered gold dust.
Those kinds of restriction are based on the fact they want to charge a lot of money.
However in this case the domain has been restricted to people or organisations that are from the Reunion Islands.  Probably the route to take would be to setup a company of some sort there (if that is allowed) and register the domain you want.
Comment: There are some domain registrars who will handle that for you.  They have registered offices in the necessary countries which you can use as proof of residency.  My preferred registrar does that for a number of European countries, but not Reunion Islands.  If you can find a friendly geek there you can probably launch something making a nice profit.
Comment: Thanks for the tip. I work for a nonprofit and we're not even looking to profit from this directly - just to use as a convenience for our audience by shortening URLs used in our publications.
Answer: I'm from Reunion Island,
2 letters domain on .re are not allowed by registry, in such case, on availability test you get default "domain taken" message but be certain that there is not 2 letters domain taken/allowed on .re.
maybe you can choice another name like : 1lu.re  or 1stlu.re ,.....
regarding local service requirement for .re registration, I see here at the end of post someone I know that offer it in Reunion island :
http://www.namepros.com/domain-name-discussion/640709-re-for-real-estate-parte-deux.html