Find a polynomial in $\mathbb Q[x]$ such that $2^{1/2} + 3^{1/3}$ is a root

Question: What would be a way to find a polynomial in  $\mathbb Q[x]$ such that $2^{1/2} + 3^{1/3}$ is a root.
Answer: We can say that $x=\sqrt[3]{2}+\sqrt[3]{3}$ and proceed from there.
$$x^3 = 5+ 3\sqrt[3]{12}+3\sqrt[3]{12}$$
$$x^3 -5 = 3(\sqrt[3]{12}+\sqrt[3]{18})$$
$$x^3 -5 = 3\sqrt[3]{6}(\sqrt[3]{2}+\sqrt[3]{3})$$
Now, since we already defined that $x=\sqrt[3]{2}+\sqrt[3]{3}$, we say that
$$x^3 -5 = 3\sqrt[3]{6}(x)$$
$$x^3-3\sqrt[3]{6}x-5 = 0$$
And cubing,
$$x^9-15x^3-87x^3-125$$
Comment: OP wanted $x=\sqrt{2}+\sqrt[3]{3}$ not $x=\sqrt[3]{2}+\sqrt[3]{3}$. Furthermore there is a typo: should be $-15x^6$ in the last line
Answer: Think in terms of conjugates.  $2^{1/2} + 3^{1/3}$ lives in the field $L := \Bbb{Q}(2^{1/2}, 3^{1/3}, \frac{-1+i\sqrt{3}}{2})$, so we could just take the product of all six linear factors of the form$$(x - a2^{1/2} - b3^{1/3}),$$ where $a = \pm 1$, $b = (\frac{-1 + i\sqrt{3}}{2})^k$ for $k = 0, 1, 2$. Since this polynomial's coefficients will be invariant under any automorphism $\sigma \in \operatorname{Gal}(L : \Bbb{Q})$, all the coefficients must actually live in $\Bbb{Q}$.
Answer: Usually what you want to do to find a polynomial such that a given $\alpha$ is a root, you take powers of $x-\alpha$ and play around with both sides of the equation. In this case:
$$ x-\alpha=0 \Longleftrightarrow x-\sqrt2=\sqrt[3]{3} $$
$$ (x-\sqrt2)^3 = 3 $$
You'll still have some radicals left here, but all you have to do is to move all of them on one side of the equation and take powers again of both sides, i.e.
$$ x^3-3\sqrt2 x^2+6x-2\sqrt2 = 3 $$
$$ x^3+6x-3=\sqrt2 (3x^2+2) $$
$$ (x^3+6x-3)^2= 2(3x^2+2)^2, $$
which will finally give the degree-6 polynomial that you were looking for.


Creating a scope in Ruby on Rails, that returns an instance of an object only if all the associated instances fit a certain condition

Question: I have a table called Carts with a has_many relationship to another table called Subcarts. I want to create a scope that returns all instances of the Cart table where all the associated Subcarts fits a particular condition (ex: subcart.status == 1). If even one subcart that is associated to a Cart instance has a status of 1, the query should not return the cart instance.
scope :cart_bucket, -> {
   includes(:subcarts).
   where.not('subcarts.status = ?', 1).
   references(:subcarts)

I've also tried to use select within the query but had an error returned because of the return array data type. I would like to keep this within a scope and not create a method if at all possible.
Comment: What DB are you using? On Postgres this sounds like a job for a lateral join. Also `scope` is just a widely abused syntactic sugar for declaring class methods. Use it for simple oneliners. Don't use it for this job. Mulitline stabby lambdas are unreadible.
Comment: It is a postgrasql DB, I'll look into lateral joins. I'm trying to stick to an existing convention by using scope instead of using a method. But I get what you mean.
Answer: You can select all the carts ids from those subcarts where the status is not 1 and use that as the where clause to leave out all the carts matching those ids:
Cart.where('NOT EXISTS (SELECT s.cart_id FROM subcarts s WHERE s.cart_id = carts.id AND s.status = 1)')

The ActiveRecord version might change a bit:
Cart.where.not(id: Subcart.where(status: 1).select(:cart_id))

There the SQL generated uses a NOT IN clause instead of NOT EXISTS.
Comment: You can get the former with `Cart.where.not(Subcart.arel_table.project(Subcart.arel_attribute(:cart_id)).where(Subcart.arel_attribute(:cart_id).eq(Cart.arel_attribute(:id)).and(Subcart.arel_attribute(:status).eq(1))).exists)`


R-squared of mixed model using lmmfit package

Question: I am fitting my data using nlme package. The syntax is as follow:
 model<-lme(Energy efficiency ~ADF + CP + DE, random =~1|Study, data=phuong).

Can someone tell me how to find the R-squared for this model?.
I've found the lmmfit package of Aleksandra Maj (2011):  But there are several functions to estimate R-squared. Could you please tell me which one should I apply.
fm2<-lme(Eeff~ADF+CP+DE+ADF2+DE2, random=~1|Study,data=na.omit(binh))
summary(fm2)
Linear mixed-effects model fit by REML
 Data: na.omit(binh)
       AIC      BIC    logLik
  888.6144 915.1201 -436.3072

Random effects:
 Formula: ~1 | Study
        (Intercept) Residual
StdDev:    3.304345 1.361858

Fixed effects: Eeff ~ ADF + CP + DE + ADF2 + DE2
                Value Std.Error  DF   t-value p-value
(Intercept)  -0.66390 18.870908 158 -0.035181  0.9720
ADF           1.16693  0.424561 158  2.748556  0.0067
CP            0.25723  0.097524 158  2.637575  0.0092
DE          -36.09593 12.031791 158 -3.000046  0.0031
ADF2         -0.03708  0.011014 158 -3.366625  0.0010
DE2           4.77918  1.932924 158  2.472513  0.0145
 Correlation:
     (Intr) ADF    CP     DE     ADF2
ADF  -0.107
CP   -0.032  0.070
DE    0.978 -0.291 -0.043
ADF2  0.058 -0.982 -0.045  0.250
DE2  -0.978  0.308  0.039 -0.997 -0.265

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max
-2.28168116 -0.45260885  0.06528363  0.57071734  2.54144168

Number of Observations: 209
Number of Groups: 46

Comment: [This question](http://stats.stackexchange.com/q/37944/11849) might be of interest.
Answer: Maybe I am stating some obvious but at the following link http://glmm.wikidot.com/faq under the section How do I compute a coefficient of determination (R2), or an analogue, for (G)LMMs? provides a quite good treatment of the issue. Just to quote some of the final lines from there to avoid possible link rot and provide the reference they present:

The bottom line is that there are some simple recipes (and some more complex recipes that may or may not have been coded up by someone), but that '''you have to think carefully about what information you want to get out of the coefficient of determination''', because no recipe will have all of the properties of $R^2$ in the simple linear model case.

A rather helpful reference of the subject seems to be Xu's: Measuring explained variation in linear mixed effects models (2003) where the author computes the residual variance of the full model against the residual variance of a (fixed) intercept-only null model (in R syntax):
1-var(residuals(m))/(var(model.response(model.frame(m)))
Answer: [Disclaimer: it has been a couple years since I have worked on a project using mixed effects models.]
A simple summary(model) should provide much of what you need. Check out this SE/CV answer which is a good example of how to extract the covariance estimates for the random effects, etc.
Word of advice: you probably need is available between lme, nlme, and lme4 -- I have never used lmmfit myself ...
Studying contribution of each param to variance in the response is not so straightforward with mixed effect models because of the random effects.  The variance in your random intercept is contributing to that variance in your response.  This is more of an art, and requires you to get familiar with the relationships in your data.
If you want to understand the contribution of each of the params to the variance in your response, you are better off building a full linear model with all the (scientifically relevant) params, then comparing with a statistic like Mallow's $C_{p}$.  You need to rescale/center appropriately, to compare the structure of relationships between your variables (e.g., geometric?)  You then need to pre-define your model selection procedure, and compare ML estimates between the models (not REML, as @Roland mentioned, because we want the "nuisance" random effects included when we are selecting our model based on BIC/AIC/etc. -- as opposed to our final REML estimate, where we want to understand the loglik of our fixed effects).
It sounds like you are new to mixed effects models; I would strongly suggest you work through all of Gelman's magnum opus -- tons of live R examples, clear explanations, only as much theory as you need to develop an intuition for the techniques.
Comment: @egbutter It is my understanding that ML fits should be used for model selection and a REML fit is appropriate for the estimation of parameters.
Comment: Hi egbutter, thanks for your comments but I wonder how can you get R-squared with summary(model). An example I made is follow:
Comment: I posted the example on my original post because I could not add it here in the "add comment" part. COuld you please have a look.
Comment: Hi user12714, your output is very hard to read without the "code" `{}` formatting, but the "Correlation" line is what you want.  Big warning: REML is not appropriate for "final" estimates but rather for model selection -- I strongly suggest you read Gelman before you get too deep into this project.
Comment: Dear Egbutter, thank you very much again for your comments. yes, I could imagine the problem with the output, but I do not know why I could not pots in the commnent. Anyway, probably you misunderstood me about R-squared I need. I need to evaluate how well my model fit (explain the variation) the data. In fixed model it is given, but not mixed effect model
Comment: @Roland Sorry -- you are totally right!  I just looked at some old code ... answered the q too quickly.
Comment: @user12714 I'm sorry -- just being short. :)  I just updated my answer.
Comment: That said, correlation between parameters [can] suggest redundant information in the model.  As I mentioned in my answer, these kind of structural relationships "should" be studied before even deciding on your model selection procedure.


O meu código é orientado a objeto?

Question: Tenho um código e gostaria de saber se o mesmo é um código orientado a objetos. Segue a estrutura. Trabalho com 3 arquivos.
1º chama save.php, segue o código:
include_once('dao.php');
include_once('modelo.php');
$post = new Post();
$post->setDescricao($_POST['custo_descricao_html']);
$post->setMes($_POST['custo_mes_atual']);
$post->setLocal($_POST['custo_local_html']);
$post->setPreco($_POST['custo_custo_html']);
$post->setObservacao($_POST['custo_observacao_html']);
$post->setColaborador_id($_POST['colaborador_logado_custo']);

$dao = new DaoCusto();

if ($_POST['custo_controle_html'] == 0) {
 $post->setId(rand(0, time()));
 $resultado = $dao->insert($post);
 echo($resultado == 'salvo') ? '0' : $resultado;
} else {
 $post->setId($_POST['custo_idUpdate_html']);
 $resultado = $dao->update($post);
 echo($resultado == 'salvo') ? '0' : $resultado;
}

2ª arquivo que faço os gets e sets, modelo.php:
<?php

    class Post {

    private $id;
    private $descricao;
    private $mes;
    private $local;
    private $preco;
    private $observacao;
    private $colaborador_id;

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
        return $this;
    }

    public function getDescricao() {
        return $this->descricao;
    }

    public function setDescricao($descricao) {
        $this->descricao = $descricao;
        return $this;
    }

    public function getMes() {
        return $this->mes;
    }

    public function setMes($mes) {
        $this->mes = $mes;
        return $this;
    }

    public function getLocal() {
        return $this->local;
    }

    public function setLocal($local) {
        $this->local = $local;
        return $this;
    }

    public function getPreco() {
        return $this->preco;
    }

    public function setPreco($preco) {
        $this->preco = $preco;
        return $this;
    }

    public function getObservacao() {
        return $this->observacao;
    }

    public function setObservacao($observacao) {
        $this->observacao = $observacao;
        return $this;
    }

    public function getColaborador_id() {
        return $this->colaborador_id;
    }

    public function setColaborador_id($colaborador_id) {
        $this->colaborador_id = $colaborador_id;
        return $this;
    }

    }

E o terceiro arquivo que é onde realizo meu CRUD , dao.php
     <?php

     require_once '../../../conexao/conexao.php';
     require_once 'modelo.php';

    class DaoCusto {

    public static $instance;

    public function __construct() {

    }

    public function insert(Post $custo) {
        try {

            $sql = "INSERT INTO  tb_custo (custo_id , custo_descricao , custo_mes , custo_local , custo_preco , custo_observacao , colaborador_colaborador_id)   values (:custo_id , :custo_descricao , :custo_mes , :custo_local , :custo_preco , :custo_observacao  , :colaborador_colaborador_id)";

            $p_sql = Conexao::getInstance()->prepare($sql);

            $p_sql->bindValue(':custo_id', $custo->getId());
            $p_sql->bindValue(':custo_descricao', $custo->getDescricao());
            $p_sql->bindValue(':custo_mes', $custo->getMes());
            $p_sql->bindValue(':custo_local', $custo->getLocal());
            $p_sql->bindValue(':custo_preco', $custo->getPreco());
            $p_sql->bindValue(':custo_observacao', $custo->getObservacao());
            $p_sql->bindValue(':colaborador_colaborador_id', $custo->getColaborador_id());

            return ($p_sql->execute()) ? 'salvo' : false;
        } catch (PDOException $e) {
            return 'Erro, contate o suporte!Código:' . $e->getCode() . 'Mensagem:' . $e->getMessage();
        }
    }

    public function Update(Post $custo) {
        try {

            $sql = "UPDATE tb_custo SET   custo_descricao= :custo_descricao , custo_mes= :custo_mes , custo_local= :custo_local , custo_preco= :custo_preco , custo_observacao= :custo_observacao , colaborador_colaborador_id= :colaborador_colaborador_id WHERE custo_id= :custo_id ";
            $p_sql = Conexao::getInstance()->prepare($sql);

            $p_sql->bindValue(':custo_descricao', $custo->getDescricao());
            $p_sql->bindValue(':custo_mes', $custo->getMes());
            $p_sql->bindValue(':custo_local', $custo->getLocal());
            $p_sql->bindValue(':custo_preco', $custo->getPreco());
            $p_sql->bindValue(':custo_observacao', $custo->getObservacao());
            $p_sql->bindValue(':colaborador_colaborador_id', $custo->getColaborador_id());
            $p_sql->bindValue(':custo_id', $custo->getId());

            return ($p_sql->execute()) ? 'salvo' : false;
        } catch (PDOException $e) {
            return 'Erro, contate o suporte!Código:' . $e->getCode() . 'Mensagem:' . $e->getMessage();
        }
    }

   }

Essa estrutura é orientada a objetos?
Comment: É sim, ficou com dúvida em algum ponto? desconfiou que não era pq?
Comment: Está faltando alguns ajustes ... mas, você separou a classe modelo da classe operação ... é bacana ir nesse caminho. Precisa ver a classe Conexão. Uma coisa não coloque a classe conexão na classe DAO. coloque ela como include no inicio do seu código.
Comment: Valeu o feedback Virgilio Novic
Comment: @MarlonCastro está faltando alguns detalhes, mas, está no caminho, poderia ser melhorado com `namespace` se assim preferir algumas, coisas que acho legal implementar, mas, cara tá legal.
Comment: Eu estava vendo na net e vi outra maneiras de se montar uma estrutura OO , ai fiquei com duvida nessa minha estrutura.
Comment: http://pt.stackoverflow.com/questions/163660/namespace-com-php/163662#163662 dê uma lida nisso também @MarlonCastro
Comment: Muito obrigado pela atenção @VirgilioNovic , vou estudar sobre tudo isso :)
Answer: Na medida do que é possível fazer orientação a objeto em PHP, a classe Post é bem OOP, só não é mais porque não está usando herança e polimorfismo, ainda bem. Há encapsulamento e alguma abstração. O ganho de ter feito desta forma me parece próximo de zero, mas não dá para dizer que tem algo errado. Um array associativo teria sido muito mais simples, o que me faz pensar que o ganho possa ser considerado negativo.
DaoCusto é um pouco menos. Tudo que é estático é menos orientado a objeto, mas é um pouco. Teria sido muito mais simples criar uma função simples. Está forçando o uso de um mecanismo que não cabe aí. Funciona, tem gente que gosta de fazer assim, mas não há ganho, pelo contrário.
A questão é: qual a relevância disto? O objetivo é seguir uma fórmula sem entender bem porque ou fazer algo que ajude o código ficar melhor? OOP não faz o código ficar melhor por mágica e há casos que ele pode piorar o que está fazendo. Não parece ser tanto o seu caso, quando precisou ser pragmático, até foi, pelo menos em partes.
Veja: O que é "Orientado a objeto" e quais outros métodos?
Entenda que orientação a objeto é algo secundário para a programação. Em PHP mais ainda.
Comment: Exatamente , fiz isso no pouco que aprendi vendo na net. Mas estava pesquisando e vi coisas mais aprofundados, e queria saber se esse codigo pode ser considerado OO , mas valeu pelos links , vou estuda-los.
Comment: "e há casos que ele pode piorar o que está fazendo" - Em PHP eu diria que é o que mais acontece.
Comment: Um código orientado a objetos procura reaproveitar comportamentos aumentando a coesão do código que é escrito. Se você tem uma classe DAO que recebe um objeto concreto, toda vez que você for implementar um novo terá que escrever uma nova classe com códigos praticamente idênticos, pois como o Maniero disse: não há vantagem em implementar isso dessa forma. Um array associativo passado para uma abstração que recebe um objeto genérico e não um em especifico seria mais adequando e ajudaria a remover essa granularidade desnecessária.Tome como exemplo uma abstração vantajosa para esse exemplo os ORMs

O meu código é orientado a objeto?


Remove grafana cookie for user logout API

Question: I'm using grafana HTTP API to build a front-end application on grafana.
User authentication is with the basic Auth model (default grafana authentication). I need the logout API, which cause grafana_session cookie expire.
I can not remove the grafana_session cookie from my scripts, because the httpOnly flag is on. Could you please help me to handle the user logout?
The only grafana configs that I've changed are two bellow configs:
# set cookie SameSite attribute. defaults to `lax`. can be set to "lax", "strict", "none" and "disabled"
cookie_samesite = none

# set to true if you want to allow browsers to render Grafana in a <frame>, , <embed> or <object>. d$
allow_embedding = true

Comment: Cookie is for the UI auth, so it doesn't make sense to have API for UI logout.
Comment: So how can I delete an HttpOnly cookie from my script?
Answer: I found the solution and share it here to help if anybody had the same question.
As Jan said in the comment, Cookies are for the UI auth, and are set from the server. The HttpOnly flag makes cookies secure among the risk of cross-site scripting (XSS) and can not be deleted or overwritten from js scripts.
Grafana's default authentication uses the grafana_session cookie, which is an HttpOnly cookie. So If anybody else needs to know how we can delete the grafana_session cookie for user signout, you should only call /logout endpoint.
axios.get('http://localhost:3000/logout')

It will automatically set the cookie in request header, which will delete geafana_session token and user needs to login for the next requests.
headers: {
  Cookie: 'grafana_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax'
}

Following links helped me out to understand the HttpOnly cookies. May be useful for others:
https://stackoverflow.com/a/1085792/16994002
https://security.stackexchange.com/questions/211356/delete-secure-cookie-using-javascript
https://www.sjoerdlangkemper.nl/2020/05/27/overwriting-httponly-cookies-from-javascript-using-cookie-jar-overflow/


Are my hands too small for chord embellishments?

Question: I've been playing guitar for about a year and I'm learning to play RnB style chord embellishments and right now they seem absolutely impossible. Playing an Emin7 and hammering on the 10th fret seems so hard. Any help?
Comment: What are the dimensions of your fingers and your palm size? Hard to tell from this picture. I will say this though - your fingering for that chord seems too cluttered, and you don't have much economy of movement with the slant your fingers are on. Try straightening up your fingers so they are more parallel with the frets. It may take more strength, but you will get there eventually.
Comment: You need a pic of you seating posture.  Your entire hand and arm look very contorted and I suspect that it is because of the way you are sitting.
Comment: Index is about 5 Cm and middle is 6. Palm size is about 8 cm. Straightening my fingers feels very uncomfortable and i feel a strain in my wrist  but i will try.
Comment: Do [your](https://music.stackexchange.com/questions/1419/best-method-to-learn-to-play-barre-chords) hands [hurt](https://music.stackexchange.com/questions/1533/why-does-my-thumb-hurt-when-i-play-bar-chords)?
Comment: you dont state your gender and females tend to have smaller hands, however my petite 14 year old can do that chord so I cannot see why you could not do so also, physiologically. I suggest you do hand stretches and  see  a teacher for a few lessons at least
Answer: Your hands don't seem extremely small. It's your hand-position that makes things impossible for you. I can't see your thumb but it seems to be stretched completely to the left, and your wrist is totally straight. Your fingers shouldn't be pressed against each other. Try to bend your wrist a bit, put your thumb behind your middle finger, and let it point upwards. Also point the neck of your guitar a bit upwards instead of downwards or parallel to the floor. This should help fix many of your problems.
Maybe something like this:
Comment: @user69889 One year of playing guitar isn't much. Especially when it comes to barre chords. They take a lot of strength to play right, and the vast majority of non-guitarist fingers simply don't have that strength. That strength comes with training, only. More training than just a year of casual practicing. Try to have fun with what you *can* do, keep pushing at the boundaries of your strength (start with songs that only have one easy barre for a short time, then more and more), and the hand position that Matt shows will become natural in time.
Comment: Wow those nails are long.  But good answer.
Comment: Well the problem with that is that it's super hard for me to play barre chords with my index finger flat on the fretboard. I have to slant it a bit or i lose all strength.
Comment: @user69889: I think that your index finger position is similar to mine. It's more about your whole hand position, the position of your thumb, and of the other two fingers.
Comment: Surely my technique was crap (+1), but for ten years I wrapped my 1st and 2nd knuckle of my left index finger, 1st on middle finger, and my thumb to drum twice a week, at least, to go over the calluses I kept burning off. But I wouldn't have traded that for one second of what it feels like to play a guitar.
Comment: But i've already mastered barre chords. I play them all the time. Just not like everyone else.
Comment: @user69889 yes, and now you're struggling to advance because of poor technique picked up when "mastering" them. Unfortunately, you're going to have to unlearn what you've done in order to proceed. This applies to pretty much every skill - if you go too far down the wrong path, you reach a dead end.
Comment: @user69889 yes, and now you're struggling to advance because of poor technique picked up when "mastering" them. Unfortunately, you're going to have to unlearn what you've done in order to proceed. This applies to pretty much every skill - if you go too far down the wrong path, you reach a dead end.
Answer: Trying to understand why your fingers slant over like in the picture, I get the impression you may be "gripping" the chord with a lot of force squeezing the ball of your thumb onto the back of the guitar neck.
When you position your hand like in @MattL's photo you should have the tip of the thumb (your thumb print area) on the neck. It may take some time to get used to this position, but eventually when your hand becomes trained it should not take much force.
Think of your finger position when making a fist compared to wrapping your hand around a tennis ball. With a fist your fingers collapse against the palm. Holding a ball the fingers are arched away from the palm. You want to fingers more in that arched position.
Pay attention to your whole arm and elbow position. You might try holding your elbow away from your body a bit to get your whole forearm more perpendicular to the neck. Instead of gripping with just the hand, think of your whole arm sort of pulling back. I'm exaggerating things, but it's like pulling your forearm back instead of only gripping a fist.
Also, if are not already playing these embellishment in open position, try that first and then move into the barre chords. Barre chords can be tough to play. If you first get your fingers coordinated to embellish with hammers and pull offs in open position, embellishing the barre chords should be easier.
Comment: Thanks! Will definitely take some practice to get used to the position but i'm already seeing improvements.
Answer: Looking at the tips of your fingers, you are pressing way too hard. There's no blood left in them! Bear in mind with that shape, only 3 strings need pressing hard enough to sound - 5, 3 and 1. You could also do with having the neck higher, the lower it goes, the harder it is to get your hand round.
Maybe also rotate the guitar so the neck isn't parallel to the floor, but the head of the guitar is higher. That will help the whole of your hand from having to be bent in the way shown in the pic. For tht shape, fingers need to be almost perpendicular to the fretboard, which then brings pinky in line for that 10th fret.
Maybe the action on the guitar is bad enough for you to have to press really hard - in which case, lower it.
Checking dimensions, yes, your hand is small - even smaller than mine, which is not even medium. Consider looking at other guitars with different profile necks and different radius fingerboards.
Comment: What would you say is a good action? Checking on the 12th fret low e mines looks like 3.5 mm. I'm pushing about as hard as i need to. I think the biggest issue i've discovered is that from the start i learned to play barre chords with my other fingers resting on my index for extra strength, and now when i straighten my hand i can't do that anymore
Answer: Usually I would recommend lighter strings to aid a beginner.
But in this case it looks like your wrist is too bent, forcing your hand to 'claw' the neck. Try positioning the guitar to allow your elbow to move further away from your body, straightening your wrist. This will give extra free movement for your fingers to achieve the better position in the photo someone else shared.
It will be difficult and feel unnatural at first, partly because you have to unlearn your existing position.
Answer: Not at all, your hand is good enough. The issue is in the angle of the wrist. It is not perpendicular to the neck. If you keep the wrist straight then the pinky finger can get to the 10th fret.
During my early days, I would try this method.

First practice normal bar chord. I pick all strings in a clean way.
Next, I reach some higher frets with my pinky finger, keep it there and play clean.
I take of my pinky finger and sound clean.
I then repeat 2 with the pinky fingers and other higher frets as much as I can.

Note not only the requirement is to sound clean, but the requirement is also to hold it quickly.
Some stretching exercises are surely going to help, before you begin your playing.
Answer: It is readily apparent that you don't have a guitar teacher.  You are bunching up your fingers and are pressing them to the frets as a bulk piece.  I'd not even call that bad technique as the name "technique" for something that wrong and ad-hoc seems misplaced.  Every finger should be placed independently.  There is a bit of an exception with the thumb that may be required to provide counterpressure from the back of the neck particularly for barré.  Fingers should go down independently on the frets and be at right angles to the string, pressing down on the fretboard.  That's sort of indispensible.
A bit of a corollary is that you don't lock finger joints: they should all curve inward (your ring finger doesn't).  A locked joint slows down your finger action.  However, keeping all joints curved inward may take extended training of finger strength and position and will not likely work out of the box while your fingers are not trained for it.  There may also be some chords where the distortion of the hand is large enough to leave little leeway.  But as a rule, you should practice your finger strength such that the last joint does not collapse backwards but is always curved: that allows more accurate fingering action.
Answer: I hope some of these answers help me. I have the same problem with small hands. I fear I may have to switch to a much smaller instrument or drop guitar which I like a lot altogether. The reason the initial person has his Barre finger at such an odd angle rather than at a 90 degree angle to the fretboard is because that is the only way he can get his pinky finger in place two frets below.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://music.stackexchange.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://music.stackexchange.com/help/whats-reputation), you can also [add a bounty](https://music.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/76947)


How to standardize selected columns in panel data frame

Question: How do I standardize SELECTED columns in a data frame, when the data frame is a panel? Lets say, that I only want to standardize columns X2, X4, X6, X7, and X9 by explicitly selecting them in the sample data frame below, while I account for the panel data structure.
df <- data.frame(unit=rep(1:250, 4),
             year=rep(c(2012, 2013, 2014, 2015), each=250),
             replicate(10,sample(0:50000,1000,rep=TRUE)))

To be sure: With standardizing I mean the usual subtract the mean and divide by standard deviation procedure.
Answer: We can use mutate_at
library(dplyr)
df %>%
   group_by(unit) %>%
   mutate_at(vars(X2, X4, X6, X7, X9), funs(as.vector(scale(.))))

Comment: Thanks! And if I want to standardize per group, I simply add group_by(unit) %>%


Overlay with words across multiple images

Question: I am making a instagram type of feed and have a 4 images with a further 4 below those 4. I need to make a overlay which I can put words in front of all 8 images showing instagram followers and a link to their instagram.
I have most of it done but the overlay I cannot seem to get it to work. Any help would be appreciated, thanks in advance.
Josh

Comment: Hello rJosh, please provide some sample code. It will make it easier to help :)
Comment: Hey, I went ahead and put some code that I am using. I didn't want to make it to big but there is a total of 8 separate images.
Comment: https://stackoverflow.com/help/mcve
Comment: The code provided does not look like _*have most of it done*_ ...
Answer: I think the below is what you need. I used flexboxes for layout.

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  justify-content: flex-start;
  flex-flow: wrap;
  width: 500px;
}

.item {
  display: inline-block;
  margin: 0 0.5em 0.5em 0;
  position: relative;
}

.text {
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.6);
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  top: 0;
}

.text:hover {
  border: thin solid red;
  animation: opac 0.3s ease forwards;
}

@keyframes opac {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Bla bla

Bla bla

Bla bla

Bla bla

Bla bla

Bla bla

Bla bla

Bla bla

Answer: Like this? You can put whatever words in the overlay as you want. I used xs columns so you could see it fully.

.overlay{
  display:block;
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  background-color:rgba(0,0,0,.5);
  z-index:10;
}
.overlay h2{
  color:#fff;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Follow me on Insta

Answer: Use o overlay div with position absolute covering the entire images container like the example....

.images{
  position:relative;
  display:inline-block;
}
.overlay{
   position: absolute;
    top: 0;
    left: 0;
    background: rgba(255,255,255,0.5);
    width: 100%;
    height: 100%;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    visibility: hidden;
}
.images:hover .overlay{
  visibility: visible;
}

      some text


WYSIWYG with CK editor Profiles

Question: I am using WYSIWYG with CK editor library. The problem is its showing blank toolbar by default on WYSIWYG editor on node add/edit page. To make the buttons appear on the WYSIWYG toolbar I always have to goto admin/config/content/wysiwyg/profile/full_html/edit
and have to select which buttons to appear on the WYSIWYG editor toolbar.
Is there a way we can select all check boxes at once
Answer: You can do that with Firebug or any other browser that has a console. You need to go to edit page of the WYSIWYG profile and on this page, open Firebug or your browser's web developer tool. And in the console enter this line and run:
jQuery('#edit-buttons input.form-checkbox').attr('checked', 'checked');

This will set all the checkboxes under 'Edit buttons' section and you can save your setings.
Answer: No, there is no way you can do that out of the box.
If you repeatedly need this functionality, you can write a small custom module that will add a checkbox on that page using hook_form_alter() and then through javascript enable all those checkboxes.

WYSIWYG with CK editor Profiles


Javascript RegExp replace. How to carry unknown characters into replacement?

Question: I'm trying to get a much deeper understanding of JS RegExp for a project I'm working on.
So if I were checking for all strings containing foo and then a character that is not a number, I would use /foo[^0-9]/. However, let's say I want to change all strings matching that pattern to foobar and then the original characters, how would I go about that?
str = foozip;
newStr = str.replace(/foo[^0-9]/, "foobar");
console.log(newStr);
//returns foobarip Note the lack of a z.

str = foozip;
newStr = str.replace(/foo/, "foobar");
console.log(newStr);
//this matches foo6zip, which is no good

Do I have to run a separate check to do this? Is there a way to carry unknown characters from one side of a replace to the other?
Answer: You have two options:

Use lookahead:
str.replace(/foo(?=[^0-9])/, "foobar")

Use capture groups:
str.replace(/foo([^0-9])/, "foobar$1")


Link between classification scores and probabilities?

Question: I am aware that classifiers are not necessarily calibrated in probability (see: scikit-learn manual here).
I wanted to know more about what we can say about the link between scores and probabilities. For exemple, are we ensured that probabilities are strictly increasing with the score ?
Answer: What kind of probability? If you ask about subjectivist probability, the degree of belief, then the higher score would mean that you find some output as more likely then other, so it would directly correspond to it.
If you are talking about frequentist probability, so you ask if the scores would correspond to empirical proportions, then it gets more complicated. By minimizing some loss, you are pushing the scores to be close to the target categories (where the definition of closeness depends on choice of the loss function). You'd expect to see higher scores more often in the target classes as compared to lower scores, so they would somehow correspond to the probabilities.
If the probabilities are not calibrated, there's no exact correspondence. For example, decision trees pack similar values into bins, so the probabilities would not be a continuous function of the scores. In other cases, scores may be pushed towards extreme values, or towards moderate values, and the function may be complicated.


Can absolute divs feature in responsive design

Question: I have started to design a photography website and I have included an absolute positioned logo in the top left hand corner. The area is made up of an absolute positioned div and an image within the div.
I was wondering whether I could make that absolute positioned div and logo, scale down depending on the screen size.
Is there anyone who can help? Here is the link so you can see what I am dealing with:
http://www.photographybytaraandclaire.com/newsite/index.html
Answer: When dealing with responsive design you should work with percentages.
If you want to calculate what percentage width your logo should have you can use.
Logo width / Wrapper width * 100

The wrapper width is the width of you wrapper in your design and not the full page.
Answer: you can try giving image width as percentage and no height to keep aspect/ratio.


Tool to automatically inline JavaScript function calls?

Question: Inlining JavaScript function calls speeds up the execution and also reduces the code size after gzipping, as described in this article:
http://blog.calyptus.eu/seb/2011/01/javascript-call-performance-just-inline-it/
However, I can't find a tool which automatically processes a JS source file and inlines all (or better, selected) inlinable function calls in it. Google's Closure Compiler does some inlining, but not always, and nor is it configurable.
Thanks in advance!
Comment: This is a great question deserving better answers. When working with repetitive tasks inlining often makes a huge difference. Such as continuously processing pixels or calculating noise.
Comment: You don't need to inline everything, and it will make reusing the code a lot more difficult. I would suggest you just use something like the Google Closure Compiler which does perform a number of optimisations (including inlining) and makes the code smaller.
Answer: I hardly believe that this "technique" speeds up any execution time. At least not in a real-world scenario. The Blog might be right about code-size & Gzipping tho.
Anyway, I don't think any Javascript minification/compressor will do this alot. The reason is simple and very obvious in the example provided. By replacing the function call with the actually function code, you're setting things into another context. This might end up very evil. What if the parent function(-context) already declares and uses a variable named foo. If the same variable is used within the other function you might overwrite that and cause errors.
Even worse if there is some use of try/catch or eval blocks which creates an additional context with a carefully expressed "dynamic scope" (which is actually not available in ecma-script). However, in this scenario it's pretty much impossible for a JIT or any Javascript implementation to optimize anything.
Comment: JIT engines and static analysis tools (like closure-compiler) take into account the scope change impacts when deciding to inline a function.
Comment: Sure, but the "solution" for all decisions if `try/catch` or `eval` is involved within a context comes down to "don't do anything" afaik.
Comment: "An inlining tool might break your code if it doesn't work correctly" is not really a sensible objection. You should assume that any mature inlining tool works for its intended purpose, just like you assume that your compiler compiles your code correctly or your interpreter runs it correctly.
Answer: Let the JIT figure things like inlining out fr you. Inlining can easily worsen the performance by killing cache performance.
Also, unless you have identified the actual bottlenecks, doing premature optimization like this is hardly ever worth it.
Comment: Same. Question: *how do I solve X*. Answer: *don't solve X*. StackOverflow: *brilliant*! Really? You're not OP to know its motives. Or the motives of someone Googling that question, actually needing the answer. -1
Comment: -1 This doesn't really answer the question. Inlining can be beneficial in some situations, such as inside an iteration in a main loop.
Comment: People coming from Facebook, please don't downvote @Ivo Wetzel. That's called vote brigading and it is not a good thing.
Comment: If you rephrase this answer just slightly then it blatantly answers the question: "yes, there is a tool to automatically inline Javascript functions, it is called the JIT, and you are already using it".
Comment: came here from google looking for how to inline functions in javascript. context: malicious code analysis. i do think that the question deserves a fuller answer.


Best failover strategy for e-mail servers on AWS to ensure high availability

Question: We have our e-mail server hosted on AWS. Last week Amazon had a failure in their East Coast region which brought down our server along with many others.
We now want to implement a failover strategy so that if the mail server becomes unavailable again then we can simply switch to another mail server in a different zone and users can continue sending and receiving mail AS WELL AS still having access to their existing mail items.
Obviously having periodic back-ups of messages isn't a good-enough solution because there is a constant stream of incoming and outgoing emails being written to disk.
We are using a Windows 2008 Server and running Mailenable Enterprise. Configuration for MailEnable (eg. user accounts, passwords, etc.) are stored in an SQL Server Database on the Mail Server.
We are considering the following solution:

Mount S3 storage as a windows drive to store messages using a tool like tntdrive. Unlike EBS-storage (which is restricted to a single availability zone), S3 storage is available across availability zones which would make our storage available even if a single region fails.
We take daily snapshots of the mail server and copy this to S3.
In the case of the mail server failing we create a new instance of the mail server from our snapshot (this means that configuration changes such as password changes or new user account creation that happened since snapshot was taken will not be included, but we can accept that risk)
We mount the S3 storage containing the messages as a drive on the new server.
We switch the elastic ip for the mail server to the new server and we have a mail server that is available again!

Will this solution work? I am a bit worried about the latency and cost of S3 as compared to EBS (see http://jimliddle.sys-con.com/node/1103438/mobile). Is there a different approach we should be looking at? Would you recommend different Amazon tools to solve the problem?
Answer: You can clone the current mail server in another EC2 instance and run it as a backup MX server. Both servers database should be in sync with db level replication, and the disks should be in sync hrly with rsync/deltacopy. When the primary one goes down, sending email servers will automatically try to use secondary MX server, and users can still access old and new emails. When main server comes back, backup server will sync newest emails with main server again.
Comment: How will the backup e-mail server have access to the old e-mails? The problem with a "clone" is that the backup server will only contain e-mails up until the point that the clone was made. Or am I misunderstanding your suggestion?
Comment: @Stanley I have updated my answer, will it solve your problem?
Comment: I have looked at some free software solutions that can mirror folders in windows and could give some of that a try. However, a big part of my question is with the setup and availability on Amazon. An EBS volume is only available in a single availability zone so is insufficient to use as mounted drive. I don't know if it's possible to set up EBS volumes in different AZ's in a RAID1 configuration, is S3 an option or will latency and transfer costs be an issue? I really need an answer from someone that knows AWS and the tools it offers well.
Comment: "You can mirror/copy data [on an EC2 instance across AZs] but not RAID1, too much latency for pure RAID" - My dad, works at AWS (high up under C2S)


Will my system fsck when I reboot?

Question: ...and how do I find out?
Say I am about to reboot a server. I would like to minimize downtime, so thinking about wrapping reboot in an alias that says "hang on buddy, you're going to hit a fsck on boot".
Next question.. what's the best way to say "lets do it next time?" set the last check date?
I know tune2fs can set a bunch of parameters, but how would I get em?
Comment: Which OS are you running, and which filesystem?
Comment: Good point - versions of Linux (mainly deb & derivatives) and ext2 or ext3
Answer: If all you want to do is avoid an fsck, adding the -f option to shutdown should help with that.  shutdown -F to force fsck.
tune2fs -l /dev/foo will tell you the interesting bits of information.
Here's a start at extracting just what you need:
mount -l -t ext3,ext2 | cut -d' ' -f1 | xargs -n1 tune2fs -l | egrep -i 'state|mount|check'

If the "Next check after" date is in the past, there will be an fsck.
If the filesystem state is not clean, there will be an fsck. (this could also happen if there's a problem with the system during reboot/shutdown that prevents a clean unmount)
If the mount count has reached the maximum mount count, there will be an fsck.
Comment: Assuming your system currently meets one of the criteria for getting an fsck, yes, the next reboot would get the fsck instead.  "shutdown -f" creates a file that tells the system startup to skip fsck, but the system startup also removes that file.
Comment: Thanks - if I ussue shutdown -f, will the next reboot get the fsck instead?
Comment: Consider using `ext4,ext3,ext2` these days.
Answer: Using tune2fs -l /path/to/device:

If "Mount count" will be greater than "Maximum mount counts" then use -c to change the max or -C to change the count
If "Last Checked" is not recent enough for the "Check interval" use -i to change the interval or -T to change the last checked
Comment: This does assume ext2 or ext3, but is a fairly good assuption.
Comment: David: the question does mention tune2fs...
Answer: the other option is you can manually make it skip fsck checks at boot by updating the 6th field in your /etc/fstab:
/dev/sda2  /  ext3  defaults,errors=remount-ro 0       1

This is the similar to what most fstabs will have 1 means that it should be checked and is a root file system, 2 means it should be checked but will be done in parallel with other file systems and 0 means skip checking
this is also true no matter the file system
Answer: If you don't want to guess - do this:
touch /fastboot
and you'll be certain to avoid slow checks (or worse - a total failue if a check fails and the reboot halts)
Answer: I use the following perl script to check when the next fsck will occur:
#!/usr/bin/perl -w

use strict;

my $mountcount = 0;
my $maxmount = 0;
my $dev;
my $mountpoint;
my $fstype;
my $debug = 0;

my $cmd = "mount";

open MOUNT, sprintf ( "%s |", $cmd ) or die sprintf ( "ERROR: Cannot execute %s - %s\n", $cmd, $! );
while ( <MOUNT> ) {
    chomp;
    ( $dev, undef, $mountpoint, undef, $fstype, undef ) = split;
    printf "Found device %s\n", $dev if ( $debug > 0 );

    if ( $fstype =~ /^ext/i ) {
        $cmd = sprintf "dumpe2fs -h %s 2>&1", $dev;
        open DUMPE2FS, sprintf ( "%s |", $cmd ) or die sprintf ( "ERROR: Unable to execute %s - %s\n", $cmd, $! );
        while ( <DUMPE2FS> ) {
            chomp;
            if ( /^Mount count:/ ) {
                ( undef, $mountcount ) = split /:/;
                $mountcount =~ s/\s*//g;
                printf "Mount count = %s\n", $mountcount if ( $debug > 0 );
            }
            if ( /^Maximum mount count:/ ) {
                ( undef, $maxmount ) = split /:/;
                $maxmount =~ s/\s*//g;
                printf "Maximum mount count = %s\n", $maxmount if ( $debug > 0 );
            }
        }
        close DUMPE2FS;

        printf "Filesystem %s, mounted on %s will be checked in %s mounts\n", $dev, $mountpoint, $maxmount - $mountcount;
    }
}
close MOUNT;

I have it run in my ~/.bashrc so I always know when my filesystems will be checked, though I use ext4 now which doesn't suffer from extended fsck times, it's still nice to know.
Typical output is something like:
Filesystem /dev/sda1, mounted on / will be checked in 5 mounts
user@localhost ~ $

Comment: Apparently, your script does not evaluate "Next check after:" attributes!
Answer: I regularly use tunefs to reset boot counts and time before doing a mid-day reboot, to prevent fsck. The difference in boot time is stunning. Afterwords I reset them to allow the next boot to fsck.
Answer: I thought about how to get a list of filesystems more comfortably:
for D in $(mount -l -t ext3,ext2 | cut -d' ' -f1 ) ; do \
echo --- $D; tune2fs -l $D | egrep -i 'mount (count|time)|check' ; done \
| awk '
  /^--- / { mydev=$2; checked=0 }
  /^Mount count:/ { mycnt=$3 }
  /^Maximum mount count:/ { if (mycnt >= $3) checked=1 }
  /^Next check after:/ {
    cmd=("date +%s -d\"" $4 FS $5 FS $6 FS $7 FS $8"\"");
    cmd | getline mydate; close(cmd);
    if ((mydate <= (systime()+120)) || (checked == 1)) print mydev;
  }
'

I guess it could be done more elegantly but anyway here it is. If one pipes this into xargs -r df -h one could also quickly see how large the filesystems are.
Note that in the code above the time of "Next check" is compared to (NOW + 120 seconds) assuming that it takes some time until your system gets up again.
HTH
Answer: Here is a script that checks your filesystems for fsck (source):
for x in $(df -t ext4 -t ext3 -t ext2 | tr -s ' ' | cut -d " " -f1 | grep -v "^$" | tail -n +2); do mmc=$(tune2fs -l $x | grep 'mount count' | tr -s ' ' | cut -d ' ' -f4) ; mc=$(tune2fs -l $x | grep 'Mount count' | tr -s ' ' | cut -d ' ' -f3) ; if [ `expr $mmc - $mc` -le 0 ] ; then fsck="0" ; else fsck="1"; fi ; CT=`date +%s` ; LCT=`date -d "\`tune2fs -l $x | grep "Last checked" | tr -s ' '| cut -d" " -f3-\`" +%s` ; CI=`tune2fs -l $x | grep "Check interval"| tr -s ' '| cut -d" " -f3` ; if [ `let $CT-$LCT` -gt `let $CI*3600*24` ] && [ $CI -gt 0 ] || [ $fsck -eq 1 ];  then echo "There will be forced fsck for $x"; else echo "There will be no fsck for $x" ; fi ; done
# Alternative script from friend with sed
# mount -t ext2,ext3,ext4|while read i j; do tune2fs -l $i|sed -n '/[Mm]ount count/{s/.*: *//;p}'|(read c; read m; [ $m -gt 0 -a $m -le $c ] && echofsck,count,$i); c="$(tune2fs -l $i|sed -n '/Next check/{s/.*r: *//;p}')"; [ -z "$c" ] || ([ `date +%s` -ge `date -d"$c" +%s` ] && echo fsck,time,$i); done

Comment: Please dont just post links to external sites - copy over useful information and provide the link for reference.

Will my system fsck when I reboot?


Java Recursion Backtracking with Specific Methods (Sudoku)

Question: I'm working on a Java program for an assignment and I've been stuck on the implementation and don't know where else to look for help. The assignment is to create a Backtracking Java program that will solve a given Sudoku board using a few Required Methods:
Required Methods:
• isFullSolution, a method that accepts a partial solution and returns true if it is a complete, valid solution.
• reject, a method that accepts a partial solution and returns true if it should be rejected because it can never be extended into a complete solution.
• extend, a method that accepts a partial solution and returns another partial solution that includes one additional choice added on. This method will return null if there are no more choices to add to the solution. It should also be sure to make a new partial solution, rather than modifying the original object
• next, a method that accepts a partial solution and returns another partial solution in which the most recent choice to be added has been changed to its next option. This method will return null if there are no more options for the most recent choice that was made.
We're also given our Solve method here:
 static int[][] solve(int[][] board) {
    if (reject(board)) return null;
    if (isFullSolution(board)) return board;
    int[][] attempt = extend(board);
    while (attempt != null) {
        int[][] solution = solve(attempt);
        if (solution != null) return solution;
        attempt = next(attempt);
    }
    return null;
}

I have 3 Major Questions relating to implementing this.
I could easily solve this without having to deal with the Extend, Next, and the premade Solve methods.
1. Would Extend just find the first 0 (0's are used as empty spaces) and replace it with a 1; so the next method could compare that using methods to compare to Row, Column, and Box? And even if I am right in assuming that the Solve method never reaches the Next method in any of my tests and I don't know how to work around it.
My Extend Method:
static int[][] extend(int[][] board) {
  // Initialize the new partial solution
  int[][] temp = new int[9][9];
  for (int i = 0; i < 9; i++) {
    for(int j = 0; j < 9; j++){
      temp[i][j] = board[i][j];
    }
  }
  for (int i = 0; i < 9; i++) {
    for(int j = 0; j < 9; j++){
      if(temp[i][j] == 0){
        temp[i][j] = 1;
        return temp;
      }
    }
  }
  //If we reach this, can no longer extend
   return null;
}

2. The Next method is never reached unless explicitly called by me inside the Extend method. I have written a lot of different methods for this and none of them work for different reasons. I have comparing methods for the row, column, and box to check which value CAN be placed and if none work it is set to 0. However, through all of my tests it never changed any of the 1's set by the Extend method. I honestly just get very confused and lost at this point and any guidance would be great.
3. Finally, how would I know which cases to reject for my Reject method? I feel like there are just an infinite amount of corner-cases for a sudoku board when any board can be put in.
I'm just incredibly lost and have no idea how to proceed. Any and All help is welcome.
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your code and accurately describe the problem.  Specifically, you haven't shown us a single line of your attempts to debug this, just generalities of your (missing) test cases.
Answer: Summary -- my opinions; see caveats below.

Extend can, indeed, just put a '1' in place of a '0' -- or may need to check RCB (Row Column Box) for conflicts first.  You'll save some execution time with the checking.
Your first sentence is incorrect.  See the overview below.  As for the overall confusion, there's no way we can help you without the code and symptoms.  Post a MCVE if you still have trouble.
I expect that you can just check for immediate RCB conflicts.  The logic flow is set up to handle the more complex cases with recursive search.

Overview
I feel that you've confused two sets of problems here: (1) Specification problems, which you need to clarify with your instructor; (2) Coding problems, which you need to specify properly for Stack Overflow.
Under (1) is the extent of work done by each of your methods.  First of all, your assumption about invoking next is incorrect; the main loop of solve will call next whenever a particular board fails to provide a solution.
Top-level Logic
In English (pseudo-code), your given solve routine works something like this:
If the board has no solution, return null.
If the board *is* a solution, return it.
If neither of those ...
    attempt = extend the board one guess
    while there's still a valid attempt ...
        if there is a solution for this attempt, return it.
        else alter attempt to the next guess.

This last line is where next gets called on a regular basis.
Partition of the Issues
Open questions, with my opinions (if I were assigning this to my students):

Does extend check for first-order validity (check RCB -- Row, Column, Box -- for conflict with existing numbers) of the new guess?  If not, then replacing a 0 with a 1 works fine.
Does reject check only for first-order validity, or does it have to determine whether a solution exists?  I suspect that it's the simple check, given the logic flow you've posted.


Choose the correct option:

Question: Consider the function $f (z) = z +2z^2 +3z^3 +··· = \sum_{n≥0} nz^n$ defined on the open disk $\{z ||z| < 1\}$. Choose the
correct option:
(a) f is not injective but attains every complex value at least once.
(b) f is injective but does not attain every complex value.
(c) f is injective and attains every complex value.
(d) None of the above.
My Try: $f(z)=z +2z^2 +3z^3 +··· =z(1+2z+3z^2+...)=z\frac{d}{dz}\frac{1}{1-z}=\frac{z}{(1-z)^2}.$
For injectivity, Consider the equation.
$f(a)=f(b)\implies a(1-b)^2=b(1-a)^2\implies (a-b)(ab-1)=0$. So, when the product of two numbers is 1. then also, above equation satisfies. So, It is not injective. For surjectivity, I consider the equation $c\in \mathbb C$ $c=\frac{z}{(1-z)^2} $. I got $z$ in terms of $c$. So, (a) is the apt answer for this question. Am I judging correctly?
Comment: Can the product of two numbers $a,b$ in the open unit disk have product equal to $1$? ;-)
Comment: No. Thank you. What about surjectivity?
Comment: I think your approach is correct.
Comment: But answer given was (b).
Comment: Well, you need to check that the $z$ in terms of $c$ is again in the unit disk.
Answer: This is the famous Koebe function which is the maximal univalent function - or Riemann map if one wishes - on the disc in many ways (under the usual normalizations, $f(0)=0, f'(0)=1$) - eg for coefficients (Bieberbach conjecture/de Branges Theorem), for integral means (Baernstein theorem) etc; its image omits the part of the negative axis that starts at $-\frac{1}{4}$ and goes to $-\infty$ which can be seen by looking at the image of the unit circle under it or even simpler, noting that $4K(z)=(\frac{1+z}{1-z})^2-1$ and then the function inside the square root is the Mobius transform of the unit disc onto the right half-plane, squaring means the image of the disc omits only the negative axis, then subtract $1$, we omit the part from $-1$ to $-\infty$ and then dividing by $4$ etc; injectivity on the unit disc follows trivially from this representation too

Choose the correct option:


Can I play high e without thumb on soprano recorder?

Question: I've started playing soprano recorder again after a break of nearly 35 years. Notes are coming back easily to me (hurrah!) but I'm playing the high e with no thumb at all which is something I clearly did as a child. I can't hear much difference, if any, to the same note with a pinched thumb, and it's definitely a lot easier to play e-d-e at speed. Is this an acceptable alternative to the standard fingering? Would I be penalised in exams for it? Is there much difference in tone between the two fingerings?
Comment: https://blockfloetengriffe.de/en/F.php?t=aBar.1S.3a seems to show that as an option
Comment: Thanks for that link. Very helpful!
Answer: It is a usable alternative, but you will get the best tone and tuning from the pinched note.
Depending on your individual instrument you may find that it needs a bit more breath pressure than the 'pinched' e would need; you may also find that the tuning is a bit flat.
Would you be penalised in an exam? If the tuning is off, and/or the note is held for any length of time so its shortcomings are audible, then yes you will be. As a passing note in a rapid passage you'll possibly get away with it.


Playing Over Changes and Substitutions

Question: I'm a fairly advanced guitarist/musician and love improvising, as most of us do. However, when a progression goes out of the main key, such as borrowing or substituting, I tend to get lost in my head. It still sounds good because I'll follow the change with my ear well or I'll use some chromatics or figure out the chord structure to fill the change. But theory-wise and thoughtfully I'm lost if it's not within the main key or a modulation of it (I.e. C Major & C Mixolydian).
So my question is: Can I get some examples with chords, progressions, scales and theory to help me thoughtfully bridge the gap? And don't be afraid to go deep because I have a strong understanding of theory as well as playing skill, it's just the application of both together in certain areas that needs work.
Answer: There's a lot of different methods to use when soloing over a given progression however the one I think is the simplest taking the given chord and working backwards to the mode and the scale you can use.
A simple example in the key of C major is the progression C - A♭ - F - G. Three of the four chords are squarely in the C major scale, however the A♭ is not. Obviously when playing you'll want to highlight the chord tones of the harmony so you know you'll be safe playing A♭, C, and  E♭ and also approach tones to each (G, B♭♭, B, D♭, D, F♭). From there assuming the original tonic of C is still implied you want to find a scale/mode that uses this chord and still implies C as tonic which in this case C natural minor does. So if you wanted to go up or down a scale over the chord,  C natural minor would be the most likely and you could even look at it as A♭ Mixolydian as that would be the same scale with  A♭ as the root note. From here just connect the dots between the other chords for example the C is common in the C, A♭, and F chords so using a C to transition from one to the other makes sense.
If you can't see where the chord is coming from on the fly, just go with the chord tones and approach tones and look at it closer later and see what you can learn from it and how it relates to the tonic and the other chords around it.

Playing Over Changes and Substitutions


Question about periodic functions.

Question:
Assume $f:\Bbb R\to \Bbb R$ is periodic and differential.
I need to show $f'(0)=f'(p)$, $p$ being the periodic componenet i.e
$f(x) = f(x+p)$. and that there exist two different $x,y$ in $[0,p]$
such that $f'(x)=f'(y)=0$

How do I approach this question? I'm having trouble even getting started...
Comment: For first part: $f(1/n) = f(p+1/n)$ for all $n$. Likewise, the difference quotients will all be equal so sending $n\to\infty$ gives that $f'(0) = f'(p)$
Answer: For the second part of the question (I already gave a hint for part one in the comments), we can throw out the case where $f'(0)=f'(p) = 0$, as the lemma will then be trivially true. So WLOG assume that $f'(0) = a > 0$. Because $a$ is positive, there exists some $\delta_1,\delta_2>0$ for which $f(\delta_1)-f(0)/\delta_1 > 0$ and $f(p)-f(p-\delta)/\delta_2 > 0$. Consequently, $f(\delta_1) > f(0)$ and $f(p-\delta_2)<f(p)$. Then by the Intermediate Value Theorem, there exists some $x'\in [\delta_1,p-\delta_2]$ such that $f(x')=f(0) = f(p)$. Apply Rolle's theorem to the intervals $[0,x']$ and $[x',p]$ to finish off the proof. The case for $f'(0)<0$ follows a very similar argument.

Question about periodic functions.


Gostaria de adicionar o conteúdo de uma célula na mensagem do Scrip

Question: Criei um script que quando chega determinada data ele envia uma mesagem, só que nessa mensagem eu gostaria de  adicionar o conteúdo de uma célula da planilha onde o script esta executando esse
function EnviaEmail(){
  var resultado,linha,data;
  var assunto = "XXXXXXXXXXX<conteudo da célula> ";
  var mensagem = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"<conteudo da celula>;
  var aba = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(nomeAba);
  var colunas = aba.getLastColumn();

Answer: Não ficou muito clara a diferença entre as variáveis assunto e mensagem, mas para adicionar o conteúdo da célula você pode usar
function EnviaEmail(){
  var aba = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(nomeAba);
  var conteudoCelula = aba.getRange(celula).getValue();
  var resultado,linha,data;  //também não entendi o propósito disso
  var assunto = "XXXXXXXXXXX" + conteudoCelula;
  var mensagem = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + conteudoCelula;
  var colunas = aba.getLastColumn();

Não tenho certeza se a sintaxe "texto" + variável é válida, mas esse é o princípio básico.
Uma dica para futuras perguntas: sempre disponibilize uma cópia da planilha (ou a própria planilha, caso não haja problema), e um [exemplo minimamente reproduzível] (https://pt.stackoverflow.com/help/minimal-reproducible-example), além de exemplos com as entradas e saídas desejadas montadas manualmente, caso seja possível.


How to show Checkboxes with Fulltext Search Filter Exposed?

Question: I have created a simple search with three filter options of "Contains any of the word", "all of the words" and "none of the word", as shown in the figure below.
I used Search API, and later created a view out of it.
For an exposed filter, I just chose "FullText Search" and exposed it as follows:-

It shows me a page likes this:-

Now, it works fine, but I want checkboxes instead of the dropdowns. For that I installed Better Exposed Filters, but it doesn't show me the option to show checkboxes ... as shown:

What am I missing that this is not allowing me to show Checkboxes :(. I will be very thankful for your help. I just need to convert them to checkboxes.
Answer: Currently BEF doesn't support tweaking the display of the filter operator, only the filter itself. But this would be a great addition -- feel free to post a feature request in the BEF issue queue.
Thanks.
Comment: Please note that it is common practice on this site to add some type of disclosure if posting anything about a module for which you are a (co-) maintainer. Something like "Disclosure: I'm the maintainer of BEF". PS: same for various other (interesting) comments you posted.
Comment: I thought the fact I used the same user name on S.O and D.O made it fairly obvious, at least for the folks coming from D.O...

Regardless, your point is valid and I'll try to add a "full disclosure" blurb on post related to modules I maintain.
Answer: Normally I would suggest to do a simple form alter and change the type from select list to radio.
But since it looks like you are trying to do it only using modules I would suggest you to take a look at Dropdown Checkbox module

Convert

multiple select lists into dropdown checkboxes
single select lists into dropdown radio buttons
Comment: Thank you for the assistance. Unfortunately, all I could find was the page to add the ID of  dropdown, which it claimed to turn into checkboxes. It didn't work. Am I missing something?


What's the Piano Term For This Type Of Rhythmic Playing?

Question: What would be the category that this type of playing falls under? I don't think it's called arpeggiation because that would be a single note at a time, as far as I know. Any ideas?
Comment: @NeilMeyer, doesn't an Alberti bass require the chord tones played individually in this specific order: bottom, top, middle, top? For example, an Alberti bass in `C` Maj would be: `C`-`G`-`E`-`G`.
Comment: Could be an Alberti bass but for the fact that it is not in the bass.
Comment: Ostinato?.........
Answer: I'd call it "Broken Chords": (Wikipedia writes)

...broken chords play chord notes out of sequence or more than one note but less than the full chord simultaneously.

It could be called an arpeggio, but some define an arpeggio as a specific kind of broken chord where the notes are played one at a time and in either strictly ascending or descending order. The term broken chord is more general than arpeggio and includes arpeggios (in the strictest sense) as well as other chord elements played separately or together, as in the examples in the question.
Comment: I can't find your definition on Wikipedia. Since I've been playing piano (27 years now) I've always thought that broken chords where more or the less the same as arpeggios except that they could occur with many directional changes. The websites I've looked at have examples with this definition.
Comment: Arpeggiation is also a viable word for this pattern.
Comment: @02fentym This definition appears here: https://en.wikipedia.org/wiki/Arpeggio about halfway through the "Explanation" paragraph.
Answer: I don't believe that there is a single term-of-art for this, particularly that would apply only to piano.  I would describe them as ostinatos.  If I were speaking to one of my piano students, I might refer to the first pattern very informally as a rock, an back-and-forth or a rocking motion (because that's what it feels like to play it).  The second one I might call an Alberti-style ostinato or an arpeggiation.


Generalizing algebraic numbers to multivariate polynomials

Question: Consider the set of (complex) algebraic numbers $\mathbb{A}$, defined as $\mathbb{A} = \{x \in \mathbb{C} \mid p(x) = 0 \text{ for some $p \in \mathbb{Z}[x]$}\}.$ Suppose we now wanted to generalize this to multivariate polynomials via $$ \mathbb{A}_n = \{(x_1, \dots, x_n) \in \mathbb{C}^n \mid p(x_1,\dots,x_n) = 0 \text{ for some $p \in \mathbb{Z}[x_1, \dots, x_n]$} \}.$$
Right away I noticed that $\mathbb{A}_n \neq \mathbb{A}^n$ for $n \neq 1$, as all pairs of the form $(z,z,0,\dots,0)$ (for complex $z$) are in $\mathbb{A}_n$ since $(z,z,0,\dots,0)$ is a root of the polynomial with integer coefficients $p(x_1,\dots,x_n) = x_1 - x_2.$ In particular when $n \neq 2$ we have $(\pi, \pi) \in \mathbb{A}_2$ but $(\pi, \pi) \not\in \mathbb{A}^2$.
Is this construction meaningful in any way? I know that $\mathbb{A}^n \subseteq \mathbb{A}_n$. Does it hold for $n > 1$ that $\mathbb{A}_n = \mathbb{C}^n$? My guess is no, but I'm not entirely sure how I'd go about proving this (I imagine that a counterexample would be nice, but proving that a set of $n$ numbers satisfies no polynomial with integer coefficients seems a lot harder than proving that any one number doesn't). What other information, useful or otherwise, can be gathered from the structure of $\mathbb{A}_n$ for $n > 1$?
Comment: Note that it is unknown whether there is a nonzero integer-coefficient polynomial $p(x,y)$ such that $p(\pi,e)=0$.
Comment: But it is known that the transcendence degree of the complex numbers over the rationals is infinite, so for any $n$ there exist complex numbers $\alpha_1,\dots,\alpha_n$ for which no nonzero integer-coefficient polynomial $p(x_1,\dots,x_n)$ exists satisfying $p(\alpha_1,\dots,\alpha_n)=0$.
Comment: Regarding whether $\mathbb A_n = \mathbb C^n$; note that if $(z,k_1,\ldots,k_{n-1}) \in \mathbb A^n$ and $k_1,\ldots, k_{n-1}\in \mathbb Z$ then $z \in \mathbb A$. Ineed, if $p \in \mathbb Z[X_1,\ldots,X_n]$ is such that $p(z,k_1,\ldots,k_{n-1}) = 0$, then $z$ vanishes at $p(-,k_1,\ldots,k_{n-1}) \in \mathbb Z[X]$.

In particular, $(\pi,0,\ldots,0) \not \in \mathbb A^n$.
Answer: (I assume you want to require $p\neq 0$ in your definition of $\mathbb{A}_n$ to avoid trivialities.)
This is kind of tautological, but perhaps a more enlightening way of describing your $\mathbb{A}_n$ is that it is the set of $n$-tuples of complex numbers that are not algebraically independent over $\mathbb{Q}$.  This makes it immediately clear that $\mathbb{A}_n$ is not all of $\mathbb{C}^n$.  Explicitly, you can choose the coordinates one at a time to get a point in the complement: first pick $x_1\in\mathbb{C}$ that is transcendental over $\mathbb{Q}$, then pick $x_2\in\mathbb{C}$ that is transcendental over $\mathbb{Q}(x_1)$, then pick $x_3\in\mathbb{C}$ that is transcendental over $\mathbb{Q}(x_1,x_2)$, and so on.  It is always possible to keep choosing more transcendental elements like this since the algebraic closure of $\mathbb{Q}(x_1,\dots,x_k)$ is always countable.  (This also illustrates that $\mathbb{A}_n$ is quite "small": for instance, it has Lebesgue measure $0$, since these countable sets on each coordinate have measure $0$.  See this answer of mine for some related ideas which also give an alternate way of proving $\mathbb{A}_n$ is not all of $\mathbb{C}^n$.)
Comment: $\mathbb{A}_n$ is uncountable for $n>1$ but always has measure $0$.  For instance, $(x,y)\in\mathbb{A}_2$ iff either $x$ is algebraic over $\mathbb{Q}$ or $y$ is algebraic over $\mathbb{Q}(x,y)$.  Each of these two cases has measure $0$ by Fubini's theorem (integrating the characteristic function of your set over $\mathbb{C}^2$): in the first case, there is a measure $0$ set of values of $x$ that are possible, and in the second case, for fixed $x$, there is a measure $0$ set of values of $y$ that are possible (so you get $0$ if you integrate with respect to $y$ first).
Comment: Thank you! I have a hard time understanding why the algebraic closure of $\mathbb{Q}(x_1, \dots, x_k)$ is countable for $k > 1.$ In particular, wouldn't the tuple $(z, z, 0, \dots, 0)$ (for $z \in \mathbb{C}$) always be in $\mathbb{A}_n?$ As a result, we would have a surjection $\phi: \mathbb{A}_n \to \mathbb{C}$ by $\phi(z,z,0,\dots,0) = z$ and $\phi(x_1,\dots,x_k) = 0$ otherwise, right? Would this then imply that $\mathbb{A}_n$ is uncountable? If $\mathbb{A}_n$ is uncountable, why does it have Lebesgue measure $0$? Or is it possible for a set to have measure zero while being uncountable?
Comment: The algebraic closure of any countable field $K$ is countable: there are only countably many nonzero single-variable polynomials over $K$, and each one has only finitely many roots.


How can I make my vertical line fit perfectly inside my div?

Question: I have a banner

I want to place a vertical line next to my first chapter section.
I've tried add the border-right on my first div.
I've also tried add the border-left on the div next to that, but either one no luck. I can still see the gap in the bottom.
I'm wondering - what is the best to make that line fit perfectly.
JSFiddle
I'm using Bootstrap. Here's the code:
HTML

Chapter

2

Practice

Test

Practice Test

Algebra 1

02/09/2015

75%

Score

Review

Report

CSS
.student-accordion {
    background-color: #000;
    color: white;
    min-height: 130px;
}

.student-accordion .left {
    text-align: center;
    text-transform: uppercase;
    padding-top: 15px;
    border-right: solid 2px white;
}

.student-accordion .mid {
    text-align: left;
    padding-top: 35px;

}

.student-accordion .right {
    text-align: center;
    text-transform: uppercase;
    padding-top: 35px;

}

.student-accordion .section-num {
    color: white;
    font-size: 39px;
    font-weight: bold;
    font-style: normal;
    font-family: "adelle-sans", sans-serif;
}

.student-accordion .score {
    color: white;
    font-size: 29px;
    font-weight: bold;
    font-style: normal;
    font-family: "adelle-sans", sans-serif;
}

Comment: Please [edit] your question to include a [mcve]. A link to an external resource does not count as an MCVE. Without this, your question is off-topic for Stack Overflow.
Answer: The problem is that .student-accordion has a min-height:130px; and .student-accordion .left has a calculated height of 126px giving you a gap on the bottom of 4px.
So the easiest solution is to either remove min-height: 130px; from .student-accordion or add it to .student-accordion .left.
Edit: Here is a fiddle.
Comment: @Michael_B - I did use the fiddle. I usually use the built in browser dev tools but on Firefox I also like to use the Firebug plugin. Chrome will list the height in the computed dev tool tab. For Firefox, you will need to to check the "Browser styles" box at the bottom of the computed tab to see all computed styles. Otherwise, you can look at the Box Model tab and add the values.
Comment: `.student-accordian .left` calculated height is actually a sub-pixel value between 125px and 126px. So it will be rendered with either a 4 or 5 pixel gap on the bottom depending on the browser used.
Comment: @Michael_B - I don't think you need to delete your comment as it is relevant to troubleshooting problems like this one. The OP and others may find these comments helpful.
Answer: Here's a simple fix that may work for you. It works in your fiddle demo.
In the following style rule...
.student-accordion .left {
    text-align: center;
    text-transform: uppercase;
    padding-top: 10px;
    border-right: solid 2px white;
}

... change padding-top: 10px to padding-top: 15px.
Answer: you could use

border-right
another div with 1px width
img that 1px wide
svg line element
pesudo element with #2 style
box-shadow (least preferable)
Comment: `1- border-right` is clearly doesn't work right now since I have some padding on my main div.
Comment: But thanks for other suggestions, I will try them now.


regex to turn URLs into links without messing with existing links in the text

Question: I am trying to convert URLs in a piece of text into hyperlinks - using regular expressions. I have managed to achieve this but the problem is when there are already existing links in the text
so
bla bla blah www.google.com bla blah www.google.com

should result in
bla bla blah www.google.com bla blah www.google.com

not
bla bla blah www.google.com bla blah <a href="www.google.com">www.google.com

Comment: Tomalak, read the question. This problem is more complicated than what you find with that google search
Comment: @amarillion: Bits and parts of the problem have been discussed here to no end. Even this exact question has been here. And every time it burns down to "don't do HTML with regex", and "matching URLs in a text is hard and impossible in the corner cases". This question will without a doubt burn down to that as well.
Comment: Have you even *tried* googling for this problem? This has been through here so many times that it's not even funny anymore (sorry if this sounds dismissive, it's just a fact). Look at: http://www.google.com/search?q=url+links+regex+replace+site%3Astackoverflow.com
Comment: @Ben: Don't take it personally, I did not intend to fend off a newbie. Now that I've head breakfast - welcome to Stack Overflow. ;-)
Answer: This is almost impossible to do with a single regular expression. I would instead recommend a state-machine based approach. Something like this (in pseudo-code)
state = OUTSIDE_LINK
for pos (0 .. length input)
   switch state
   case OUTSIDE_LINK
     if substring at pos matches /<a/
       state = INSIDE_LINK
     else if substring at pos matches /(www.\S+|\S+.com|\S+.org)/
       substitute link
   case INSIDE_LINK
     if substring at post matches /<\/a>/
       state = OUTSIDE_LINK

Comment: @Tomalak - apologies, I did try my best to search for similar questions before - and found similar posts, but none that answered my question

@amarillion Thanks very much, that works. I am sure there must be a way to do it using negative lookbacks? However this answer is perfect for what I was trying to do.
Answer: Finally finished it:
function add_url_links($data)
{
        $data = preg_replace_callback('/(<a href=.+?<\/a>)/','guard_url',$data);

        $data = preg_replace_callback('/(http:\/\/.+?)([ \\n\\r])/','link_url',$data);
        $data = preg_replace_callback('/^(http:\/\/.+?)/','link_url',$data);
        $data = preg_replace_callback('/(http:\/\/.+?)$/','link_url',$data);

        $data = preg_replace_callback('/{{([a-zA-Z0-9+=]+?)}}/','unguard_url',$data);

        return $data;
}

function guard_url($arr) { return '{{'.base64_encode($arr[1]).'}}'; }
function unguard_url($arr) { return base64_decode($arr[1]); }
function link_url($arr) { return guard_url(array('',''.$arr[1].'')).$arr[2]; }

Comment: Your solution is innovative but I feel that it could be much simpler and faster if your regex language has look-behinds - simply add `(?<!href=")` to the beginning of your conversion expression.
Answer: Another way of doing it  (in php)
    $strParts = preg_split( '/(<[^>]+>)/', $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
    foreach( $strParts as $key=>$part ) {

        /*check this part isn't a tag or inside a link*/
        if( !(preg_match( '@(<[^>]+>)@', $part ) || preg_match( '@(]+>)@', $strParts[$key - 1] )) ) {
            $strParts[$key] = preg_replace( '@((http(s)?://)?(\S+\.{1}[^\s\,\.\!]+))@', '$1', $strParts[$key] );
        }

    }
    $html = implode( $strParts );

Comment: Your code has an error `Undefined offset: -1`.  The fix is to change `preg_match( '@(]+>)@', $strParts[$key - 1] )` to `preg_match('@(]+>)@', $strParts[$key ? $key - 1 : 0])`
Answer: Another trick is to guard all the existing links by encoding the code, then replacing urls with links, and then un-encoding the guarded links.
$data = 'test http://foo LINK test';

$data = preg_replace_callback('/(<a href=".+?<\/a>)/','guard_url',$data);

$data = preg_replace_callback('/(http:\/\/.+?)([ .\\n\\r])/','link_url',$data);

$data = preg_replace_callback('/{{([a-zA-Z0-9+]+?)}}/','unguard_url',$data);

print $data;

function guard_url($arr) { return '{{'.base64_encode($arr[1]).'}}'; }
function unguard_url($arr) { return base64_decode($arr[1]); }
function link_url($arr) { return ''.$arr[1].''.$arr[2]; }

The code above is just a proof of concept, and doesn't handle all situations.  Still, you can see that the code is pretty straightforward.


How to calculate the impact on dependent variable with two independent variables with different sample sizes

Question: I am researching a framework using regression analysis. With the beta coefficients I now want to calculate the correlation between my variables with the influence of another.
So I have the beta of 0,465 of the independent on the dependent variable with a sample size of 176; additionally another independent variable has an impact on the relationship with beta 0,733 and the sample size 30. How do I calculate the final impact considering both different sample sizes?
Comment: It's not clear what you're looking for. Could you explain what you mean by "final impact"?
Answer: You don't.  You have to include both variable in the model in order to do this, and the model has to be on one set of data.


How to pass an array from Asp.net to JavaScript

Question: i wrote this code to pass array from asp.net code to javascript:
aspx File:

aspx.cs File:
StringBuilder sb = new StringBuilder();
sb.Append("var loc = [");
foreach (var str in lb1)   //lb1 is list
{
    sb.Append("['" + str.Value1 + "','" + str.Value2 + "','" + str.Value3 + "'],");
}
sb.Append("];");
StringBuilder sb2 = new StringBuilder();
sb2.Append("var own = [");
foreach (var str2 in lb2)   //lb2 is list
{
    sb2.Append("['" + str2.Value1 + "','" + str2.Value2 + "','" + str2.Value3 + "'],");
}
sb2.Append("];");

if (lb1.Count > 0 && lb2.Count > 0)
{
    string arrayStr1 = string.Format("[{0}]", sb.ToString().TrimEnd('{','}'));
    string arrayStr2 = string.Format("[{0}]", sb.ToString().TrimEnd('{', '}'));
    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "AssignValues(" + arrayStr1 + "," + arrayStr2 + ")", true);
}

The array that created is [var loc = [['New York','33.6306686','73.1175653'],];] - Now this array passed to the function of javascript. But nothing prints. Can anyone help me to solve this problem.
Comment: You should probably update your post; show the entire method (including it's name) of your .cs file. Then how you call this methods from your .js (probably your ajax call). Is AssignValues (your js) ever called?
Comment: @sander the AssignValues function is working fine without parameters. But on passing arrays as parameter to this function it shows nothing.
Comment: Plz try what I suggested before. You are also not passing any arrays, you are passing strings. What you probably want is JSON and you are in luck, .NET has ways of sending JSON to the frontend!
http://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html
Answer: why don't you use this form?
var yourjavascriptArray = <%=new JavaScriptSerializer().Serialize(cSharpArrayName);%>;


Are there general css paths for drupal

Question: Is there a specific drupal way to focus on one specific part of a nodes element in the css path? For example if I change the H2 element within my theme css it changes all H2... How can I change one specific one on the page. The object is to be able to focus on particular elements to make them unique... If this is possible how do I write the style declarations?
Comment: Your node should have a class on it.
Comment: my nodes have classes... What I am referring to is the css declaration path... it looks somewhat like this in drupal ---- html body.question-page div.container div#content div div#mainbar div#question.question table tbody tr td div#comments-48081.comments table tfoot tr td.comment-form form#add-comment-48081 table tbody tr td input -----
Comment: I am asking for general practice on focusing on one element to be able to change that one element in my css... hopefully that makes sense.
Answer: Drupal allows your site to have many Themes installed. Themes can define their own HTML structure to make your site look a certain way. Drupal has a few themes the ship out-of-the-box.
Depending on the theme you use it may or may not contain HTML classes or ids in the source to easily target specific items on the page. Typically, themes and Core html is fairly darn flexible.
Looking at the Zen Theme HTML and CSS markup you can see it has fairly specific rules to get at and theme alot of the content from Zen and also core drupal themes: Useful CSS selectors to add to your stylesheets

Are there general css paths for drupal


How to estimate memory need by XPathDocument for a specific xml file

Question: Is there any way to estimate the memory requirement for creating an XpathDocument instance based on the file size of the xml?
XpathDocument xdoc = new XpathDocument(xmlfile);
Is there any way to programmatically stop the process of creating the XpathDocument if memory drops to a very low level?
Since it loads the entire xml into memory, it would be nice to know ahead of time if the xml is too big. What I have found is that when I create a new XpathDocument with a big xml file, an outofmemory exception is never fired, but that the process slows to a crawl, only 5 Mb of memory remains a available and the Task Manager reports it is not responding. This happened with a 266 Mb xml file when there was 584 Mb of ram. I was able to load a 150 Mb file with no problems in 18.
After loading the xml, I want to do xpath queries using an XpathNavigator and an  XpathNodeIterator. I am using .net 2.0, xp sp3.
Answer: In short, no you cannot, except if you always have similar files to gather statictical data before starting the estimations.
Since tag, attribute, prefix and namespace strings are interned, it pretty much depends on the structure of the XML file how efficient the storage can be, and the ratio compared to the file on disk also depends on the encoding used.
In general, .NET stores any string as UTF16 in memory. Therefore, even if there was no significant structural overhead (imagine an XML file with only a single root tag and lots of plain text in it), the memory used would still double for a UTF8 source file (or also ASCII or any other 8-bit encoding) used. So string encoding is the first part in the equation.
The other thing is that a data structure is built in-memory to allow the efficient traversal of the document. Typically, nodes are constructed and linked together with references. Therefore each node uses up a certain amount of memory; since most non-value data are references, the memory used here also depends heavily on the architecture (64-bit uses twice as much memory for a single reference than a 32-bit system). So if you have a very complex document with little data (e.g. a whole bunch of few different tags with little text or attribute values) your memory usage will be much higher than the original document size, and at this will also depend a lot on the architecture your application runs on.
If you have a file with few very long tag and attribute names and maybe heavy default namespace useage, the memory used may also be much lower than the file on disk.
So assuming an arbitrary XML file with an unknown encoding, a reasonable amount of data and complexity it will be very difficult to get a reliable estimation. However, if your XML files are always similar in the points mentionned, you could create some statistics to get a factor which gets the ratio about right for your specific platform.
However, note that looking at "free memory" in the task manager or talking of a "very low memory level" are very vague quantifications. Virtual memory, caches, background applications and services etc. will influence the effective raw memory availability. The .NET Framework can therefore not reliably guess how much memory it should allow to be used to remain performant for a single process, or even before throwing an OutOfMemoryException safely. So if you get one of those exceptions, you are usually way beyond a possible recovery point for your application, and you should not try to catch and handle those exceptions.
Answer: You can simply check the file size and back out if it exceeds a certain upper bound.
var xmlFileInfo = new FileInfo(xmlfile);
var isTooBig = xmlFileInfo.Length > maximumSize

This will not be foolproof, because you cannot guess at what the correct maximum size will be.
Comment: My question turned around is basically what that maxium file size should be for the amount of memory that is available. I was hoping to do better than just guess.
Comment: @bill: it's not easy, if at possible, to find that magical value. Have you read Eric Lippert's fantastic [article about out-of-memory errors](http://blogs.msdn.com/b/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical-memory.aspx)? It shows how complex this matter can be. That coupled with you having no control whatsoever over the innards of XPathDocument, leaves you to guess...
Comment: I suspected it was not easy. what I can do is build a table of memory used by XPathDocument for files of increasing sizes and go with that.
Comment: @bill: read Lucero's answer's last paragraph, and the article I alluded to. Finding out when you have enough memory is the most difficult/impossible problem, not finding how much you need.
Answer: Yes sure you can do it with FileInfo class.
System.IO.FileInfo foo = new System.IO.FileInfo("<your file path as string>");
long Size = foo.Length;


Twig: Unexpected token "name" of value "as" ("end of statement block" expected)

Question: When i run a Twig Lint test localy using CLI on a file, i get no warning.
But, my Gitlab pipeline returns a KO for the same file at the Twig-Lint stage:

Unexpected token "name" of value "as" ("end of statement block" expected)

Here is my code:
<code>{% for subItem in item.subItems %}
    {% if subItem.subIndex is same as eaConst('SUBMENU_INDEX', ea.request)|int
       and subItem.linkUrl is not same as menuItemUrl
    %}
       {% set submenuItemLabel = subItem.label %}
       {% set submenuItemUrl = subItem.linkUrl %}
    {% endif %}
{% endfor %}
</code>
I have tried this on the 'if' statement, but the error is still here:
<code>{% if subItem.subIndex is same as(eaConst('SUBMENU_INDEX', ea.request)|int)
    and subItem.linkUrl is not same as(menuItemUrl)
%}
</code>
For me everything is correct, i can't figure out what's wrong.
Thank you for your help.
EDIT: Here is the pipeline test failure
https://gitlab.com/solo-projects3/ep-portfolio/-/jobs/2092671708
Comment: What is the reason of the filter `int` at the end of the statement?
Comment: It is a custom twig function i made in AppExtension class.
Comment: From the docs: the correct usage of [`same as(false)`](https://twig.symfony.com/doc/3.x/tests/sameas.html) is to have the right side of the comparison as a parameter of the word `as`. So: `if subItem.subIndex is same as(eaConst('SUBMENU_INDEX', ea.request)|int) and ...`
Comment: Isn't it what i've done on the correction i tried in my message?
Here is the pipeline failure test: https://gitlab.com/solo-projects3/ep-portfolio/-/jobs/2092671708
Answer: Well, as i didn't find any solution, i finally seperated the condition into 2 different 'if' statements:
<code>{% if subItem.subIndex is same as(eaConst('SUBMENU_INDEX', ea.request)|int) %}
    {% if subItem.linkUrl is not same as(menuItemUrl) %}
         ...
    {% endif %}
{% endif %}
</code>
It is verbose, but it works. If anyone have a better solution, i am still interested, as i am facing this issue quite often.


Slick carousel kenwheeler- making a div visible only for slide 2 and hide for others

Question: I am trying to make a div filled with other images which is place just under the carousel to only show for the slide 2 of the slick slide carousel from kenwheeler and hide for others, but i dont know how to target that in JS.
please can anyone help?

DAY 1

DAY 2

DAY 3

DAY 4

DAY 5

DAY 6

DAY 7

DAY 8

Comment: Is there a hook for which slide is active in the carousel? Does it place an active class on the item perhaps? You could use jquery to get that active class from the list, and when it exists on the item you want, then show your div.
Comment: basically when the slide is on center (which is when i want the other div to appear only) the class ''slick-slide' will have class added to it and it will have become 'slick-slide slick-current slick-center'. so i had this jquery created but it doesnt work, it shows it for all slides instead of just one. if($('#day2').hasClass('slick-slide slick-current slick-center')){
$('.product-container').css('display','block');
}
else {
 $('.product-container').css('display','none');

}
Comment: 1) Did you try a `console.log()` in the `hasClass` check? 2) You can simplify the classes you're looking up to something like `slick-current` only, probably. 3) Where did you put that check in your app? Specifically, is it in a document ready handler? Is it off on its own?
Comment: I tried both using the document ready and also not having anything and i have placed it on top of my page. i dont know how to use the console.log sorry, i basically want to do what this website has done, for each slide different products are showing but on mine some slides will not have the products. https://www.hobbs.co.uk/aw15-lookbook#slide-4
Comment: Post the code where your jquery exists please. Everything surrounding it, because placing it at the top of the page could be incorrect if you're not doing it correctly.
Comment: sure its the same code i have in the comments above and its places before my css on the same html page. the carousel jquery was on the bottom, i have brought it to the top below my jquery code and still doesn't work. i have also tried changing the id to class and then use this code: if($('.slick-slide').hasClass('day3')){
$('#product-container').show();
}
else {
 $('#product-container').hide();

}
Answer: You can add a function to the beforeChange event which is part of the slick slider API:
$('.your-sliders-class').on('beforeChange', function(event, slick, currentSlide, nextSlide){
  if (nextSlide == 1) {
    $('#product-container').show();
  } else {
    $('#product-container').hide();
  }
});

Slides index start from 0, so the second slide will be index 1.
Dont forget to replace the "your-sliders-class" with your slider's class...


Noise when attempting to bend the 8th hole on a harmonica

Question: I've noticed that when I bend on the 8th hole, weird things happen. If I blow normally, the sound is OK, but upon an attempt to bend (downwards, during the draw), the sounds stop to be melodic and all I can hear is a dull hissing sound, together with a hint of a very high-pitched whizz - as if the reed itself had actually stopped vibrating.
I have firstly observed it on a $10 North Star harmonica in D, so I just blamed this for the not-exactly-perfect quality of the instrument. But after some time I bought a Hohner Special 20 in C and I hear exactly the same thing! And again- it's only the 8th hole.
Is this a known problem? Am I doing the bend wrong? Or maybe is it possible that I have damaged the harmonica somehow during the cleaning or by blowing/drawing too hard?
Comment: I would assume you're just not creating enough energy to vibrate the reed.  Bending down should be harder than up, especially on the high notes.
Comment: The stronger I blow, the louder the whizz- and that's it. (BTW, errata- I've just checked; 8th hole, not 7th!)
Comment: Hmm OK. I'll let someone with more harmonica knowledge comment then :)
Answer: This must be because you are attempting an overdraw instead of an ordinary bend and are not there yet. You bend the 8th hole down by blowing, not drawing. I think you will experience the same problem if you attempt an overblow on the 4th hole.
Comment: Riiight... From the 8th hole the blow and draw reeds are the other way round, that's why it's different! So simple.. Thanks! :)
Comment: IOW you can only *bend* the highest note on the hole, highest note being the draw note on holes 1-6, and the blow note on holes 7-10.
Answer: Sometimes, the reeds can get slightly bent and catch against the sides of the slot, or little pieces of yuck (food items...) can get caught in there.
Most harps are amenable to "soaking"... Simply washing them out.  Most can be taken apart and you can see if the reed is physically hanging up on something.
Sometimes a tiny tweak is sufficient to put everything right.