UPDADE de informações do BD

Question: Olá Meu projeto tem um form que trás as informações do BD caso o usuário queira editar, ele não está alterando os dados, nem a imagem..
form:
  <?php
  $id = $_GET["id"];
  //Executar consulta
  $result = mysqli_query($conectar, "SELECT * FROM videos WHERE id = '$id' LIMIT 1");
 $resultado = mysqli_fetch_assoc($result);
 ?>

Editar de Vídeo

<form class="form-horizontal" method="post" action="processa/proc_edit_vid.php"  >

    Título

            <input type="texto" class="form-control" name="nome" placeholder="Título do Vídeo" value="<?php echo $resultado['nome'] ?>">

    Descrição

        <textarea class="form-control" rows="3" name="desc_vid" placeholder="Descrição do Vídeo"><?php echo $resultado['desc_vid'] ?></textarea>

    Tempo

            <input type="texto" class="form-control" name="tempo" placeholder="Tempo de Vídeo" value="<?php echo $resultado['tempo'] ?>">

    Star 1

            <input type="texto" class="form-control" name="star_1" placeholder="PornStar 1" value="<?php echo $resultado['star_1'] ?>">

    Star 2

            <input type="texto" class="form-control" name="star_2" placeholder="PornStar 2" value="<?php echo $resultado['star_2'] ?>">

    Imagem

<input type="file" name="imagem">

<?php
$foto = $resultado['imagem'];
    if($foto == ""){?>

            Imagem  BD

                O Vídeo não possui Imagem

<?php
}
    if($foto != ""){?>

            Imagem do BD

                <img src="<?php echo "video/thumb/$foto"; ?>" width="100" height="100">
                <input type="hidden" name="img_antiga" value='<?php echo $foto ?>'>

<?php } ?>

    Tags

            <input type="texto" class="form-control" name="tags" placeholder="Tags" value="<?php echo $resultado['tags'] ?>">

    Description

            <textarea class="form-control" rows="3" name="description" placeholder="Descrição que o Google Recebe"><?php echo $resultado['description'] ?></textarea>

<?php $categoria_id = $resultado['categoria_id']; ?>

    Categoria

            <select class="form-control" name="categoria_id">
                <option>Selecione</option>
                <?php
                    $result_cat = mysqli_query($conectar, "SELECT * FROM categorias");
                while ($dados = mysqli_fetch_assoc($result_cat)){
                    $id_categoria = $dados['id'];
                ?>
                <option value="<?php echo $dados["id"];?>"<?php if($id_categoria == $categoria_id){echo 'Selected';} ?>
                ><?php echo $dados["nome"];?></option>
                <?php } ?>
            </select>

<input type="hidden" name="id" value="<?php echo $resultado['id']; ?>">

  <button type="submit" class="btn btn-success">Editar</button>

</form>

Como Foram salvos
    $nome = $conectar->real_escape_string($nome);
    $desc_vid = $conectar->real_escape_string($desc_vid);
    $tempo = $conectar->real_escape_string($tempo);
    $star_1 = $conectar->real_escape_string($star_1);
    $star_2 = $conectar->real_escape_string($star_2);
    $nome_final = $conectar->real_escape_string($nome_final);
    $categoria_id = $conectar->real_escape_string($categoria_id);
    $tags = $conectar->real_escape_string($tags);
    $description = $conectar->real_escape_string($description);

    $query = mysqli_query($conectar, "INSERT INTO videos (nome, desc_vid, tempo, star_1, star_2, imagem, categoria_id, tags, description, created) VALUES ('".$nome."', '".$desc_vid."', '".$tempo."', '".$star_1."', '".$star_2."', '".$nome_final."', '".$categoria_id."', '".$tags."', '".$description."', NOW())") or die(mysqli_error($conectar));

PHP de Edição
    <?php   session_start();
    include_once("../seguranca.php");
    include_once("../conexao.php");

    $id = $_POST["id"];
    $nome = $_POST["nome"];
    $desc_vid = $_POST["desc_vid"];
    $tempo = $_POST["tempo"];
    $star_1 = $_POST["star_1"];
    $star_2 = $_POST["star_2"];
    $imagem = $_FILES['imagem']['name'];
    $categoria_id = $_POST["categoria_id"];
    $tags = $_POST["tags"];
    $description = $_POST["description"];
    $img_antiga = $_POST["img_antiga"];

    if($imagem == ""){
    $nome = $conectar->real_escape_string($nome);
    $desc_vid = $conectar->real_escape_string($desc_vid);
    $tempo = $conectar->real_escape_string($tempo);
    $star_1 = $conectar->real_escape_string($star_1);
    $star_2 = $conectar->real_escape_string($star_2);
    $nome_final = $conectar->real_escape_string($nome_final);
    $categoria_id = $conectar->real_escape_string($categoria_id);
    $tags = $conectar->real_escape_string($tags);
    $description = $conectar->real_escape_string($description);
    $img_antiga = $conectar->real_escape_string($img_antiga);

    $query = mysqli_query($conectar, "UPDADE videos set nome='$nome', desc_vid='$desc_vid', tempo='$tempo', star_1='$star_1', star_2='$star_2', categoria_id='$categoria_id', tags='$tags', description='$description', modified = NOW() WHERE id='$id'");
        if (mysqli_affected_rows($conectar) != 0){

    ";
    }else {
        echo "

        ";
    }
    } /* Comentado até o fim, pra testar o UPDADE
    else{
    // Local onde imagem vai ser salva
    $_UP['pasta'] = 'video/thumb/';
    // Tamanho da imagem
    $_UP['tamanho'] = 1024*1024*100; //5Mb
    // Exrensões permitidas
    $_UP['extensoes'] = array('png', 'jpg', 'jpeg', 'gif');
    // Renomear a imagem
    $_UP['renomear'] = false;

    // Tipos de erro de UpLoad do PHP
    $_UP['erros'][0] = 'Não houve erro';
    $_UP['erros'][1] = 'Imagem maior que o limite do php';
    $_UP['erros'][2] = 'Imagem muito grande';
    $_UP['erros'][3] = 'UpLoad da imagem feita parcialmente';
    $_UP['erros'][4] = 'Erro no UpLoad da imagem';

    // Verifica se houve algum erro
    if($_FILES['imagem']['erros'] != 0){
        die("Não foi possivel fazer UpLoad, Erro:
". $_UP['erros']        [$_FILES['imagem']['erros']]);
        exit;
    }

    // Verifica qual a extensão
    $img_nome = $_FILES['imagem']['name'];
    $img_separador = explode('.', $img_nome);
    $extensao = strtolower(end($img_separador));
    //$extensao = strtolower(end(explode('.', $_FILES['imagem']['name'])));
    if(array_search($extensao, $_UP['extensoes'])=== false){
echo "

";
    }
    // Verifica o tamanho
    else if ($_UP['tamanho'] < $_FILES['imagem']['size']){
echo "Imagem muito grande, limite de 5Mb";
    }
    // Salva nos arquivos do site
    else{
//Verifica se deve trocar o nome da imagem
if($_UP['renomear'] == true){
    // Cria nome Baseado no UNIX TIMESTAMP atual e com extensão
    $nome_final = time().'.jpg';
}else{
    // Mantem o nome da imagem
    $nome_final = $_FILES['imagem']['name'];
}
// Verifica se é possivel mover a imagem para a pasta escolhida
if(move_uploaded_file($_FILES['imagem']['tmp_name'], $_UP['pasta'].$nome_final)){
    // Upload efetuado com sucesso

    echo "

";
}else{
    // Falha no UpLoad

    echo "

";
    }
}
    }*/
?>

Comment: Nos dois últimos `UPDATE` você tá colocando pontos tentando concatenar, mas não está fechando as aspas duplas antes e reabrindo-as depois das variáveis.
Comment: esse é o problema, estou tentando editar um produto que já tem imagem, então como if($imagem == "") ele só executa o primeiro UPDATE, (já comentei o código apos o else) ele apresenta o alerta que foi editado(adicionei o mesmo alerta do else), porém não alterou nenhum campo no BD
Answer: Os updates conforme KillerJack destacou envolvendo variáveis com aspas duplas.
"UPDADE videos SET nome='".$nome."', desc_vid='".$desc_vid."', -----

Mas também pode-se omiti-las retirando os pontos de concatenação.
"UPDADE videos SET nome='$nome', desc_vid='$desc_vid', -----
$query = mysqli_query($conectar, "UPDADE videos SET nome='$nome', desc_vid='$desc_vid', tempo='$tempo', star_1='$star_1', star_2='$star_2', imagem='$nome_final', categoria_id='$categoria_id', tags='$tags', description='$description', modified = NOW() WHERE id='$id'");

$query = mysqli_query($conectar, "UPDADE videos SET nome='$nome', desc_vid='$desc_vid', tempo='$tempo', star_1='$star_1', star_2='$star_2', categoria_id='$categoria_id', tags='$tags', description='$description', modified = NOW() WHERE id='$id'");

Comment: esse é o problema, estou tentando editar um produto que já tem imagem, então como if($imagem == "") ele só executa o primeiro UPDATE, (já comentei o código apos o else) ele apresenta o alerta que foi editado(adicionei o mesmo alerta do else), porém não alterou nenhum campo no BD.

UPDADE de informações do BD


Python class instances deleting themselves

Question: I am working on a text adventure game written in Python just for fun (to see if I could do it).  I am working on the module for the entities, and am working on a method for them being killed.  When an entity is killed, instead of just displaying a kill message and rendering the entity unable to act, I also want its instance to be deleted to conserve memory.
How can I make an instance of the entity class delete itself?
For example (partly pseudocode):
class Entity(object):
    #other methods here

    def kill(self):
       if self.health <= 0:
           self.deleteinstance
           or
           deleteinstance(self)

Thank you in advance for your help.
EDIT: I understand that this is a duplicate, but the answers in all the others reference that objects are deleted when nothing refers to them.  My question here is how to make nothing refer to the instance of this class, because without a kill method, presumably the instance will still be in memory with negative health.
Comment: Python objects are garbage collected. You only need to remove any reference to them and they will be deleted automatically. Google Python Object Lifetime including [this SO post](http://stackoverflow.com/questions/11894045/python-object-lifetime-characteristics) for more.
Answer: Now, why would you do that?
Objects in Python will be garbage collected once nothing points to them, so you need not worry. Otherwise, you should checkout some of the answers in this other SO question: Python object deleting itself.
You could try:
def kill():
    if self.health < 0:
        del self

Comment: `del self` won't do anything that Python isn't already going to do once the method ends.
Comment: Thank you, I will try this.  I didn't realize it was a duplicate.
Comment: Check out the answers in the other questions, they have much more content that could be useful.


Ubercart shipping API, get the package object with php to send the tracking number to the client as email

Question: I have an online shop implemented in Ubercart 6.x-2.4 and Drupal 6.19
All cool everything works but I'm struggling to do custom things
What I want to do is after saving the shipment data (i'm insterested in sending the Client that the package has been sent and he has to receive by email the tracking number)
So I added a predicate that does just that, but I don't know how to get the shipment object associated with the order and get that tracking number. I just know that there is an API somewhere...
Answer: Are you managing to save the tracking number to the order? With a bit of preprocess magic you could probably get the number as a variable to the invoice template that already gets sent out.
EDIT:
Something like the below would work, that I did to get extra data displayed in an invoice. I did this in my theme, so replace that with your own theme name (and the other capitalised bits).
    function [THEMENAME]_preprocess_uc_order(&$variables) {
        $variables['tracking_number'] =
           db_fetch_object(db_query("QUERY TO GET TRACKING NUMBER"))->COLUMNNAME;
    }

Then if you put uc_order.tpl.php (needed as a dummy file so your theme can override other templates) and your own custom template into your theme directory then you are able to reference it in the template with a simple call like print $tracking_number;
Comment: I could do it with a predicate on the event when creating a new package with an action of executing a PHP code and it gives you 2 objects: order and shipping so I could get all that Info
Comment: @PartySoft, did the edit solve your problem?
Comment: Yes, it did, I guess It can be done both ways
Answer: This question needs an update for Drupal 7. I created a module for drupal 7 and a patch for UberCart that accomplish adding Tokens for shipment tracking that can easily be used in email.


How to calculate covariance of X and Y given joint probability

Question: $X$ and $Y$ are dependent variables both normally distributed as $N(\mu-const, \sigma^2)$. I don't know what the joint distribution is.
I know that when $const = 0$, then the joint probability yields:
$P(X < 0, Y < 0) = 1/6$
Now I want to calculate $P(X < 0, Y < 0)$ for different values of $const<0$. For this I attempted to compute the multivariate normal distribution but:

I don't know the value of $cov(X,Y)$.
I don't know the value of $V(X+Y)$.

So I was wondering if, knowing the value of $P(X < 0, Y < 0)$ for $const=0$, I could derive the value of $cov(X,Y)$ so I could finally compute $P(X < 0, Y < 0)$ for other values of $const<0$.
Any tips?
Answer: It is immediately obvious that there is insufficient information to obtain the desired probability:  you have, for a given constant, three parameters that may vary:  the common marginal mean $\mu$, the common marginal variance $\sigma^2$, and the correlation $\rho$; yet you have only one condition which is that when the constant is zero, $$\Pr[X < 0 \cap Y < 0] = 1/6.$$  You can create an infinite subfamily of normal distributions with a variety of such parameters that satisfies the probability constraint.
Comment: I'm sorry but the parameters $\mu$ and $\sigma^2$ are known.


Nominating Possible New Moderators

Question: So for those of you in the loop, we have two active moderators pro tempore from the original three that were instated manually by the Stack Exchange staff. After 1001 days in the Beta game, it's not too surprising that at least one of them is occupied with other things for the time being, whatever they are.
Since luchonacho has gone out on a limb and suggested calling for a new moderator, and there seems to be no push back against the idea, we may as well give it a shot.

I'd like to hereby leave this thread open for nominating anyone who you think would make a robust and helpful moderator for representing our humble Stack at large. You may nominate yourself and it is even encouraged, if you feel like you are qualified. A few things to keep in mind:

This isn't a formal election. The moderator will as far as I know will be placed in by fiat. Think of it as a referendum. I ain't a representative of StackExchange, but this thread is now Community Manager approved. Presumably, if every candidate gets zero or one votes, it may mean there is no one suitable to become moderator either.(Although we have some good users who I think the community trusts, so I don't think low voting will be a problem.)
One nomination per answer below.
Vote up if you approve of a nominated candidate and down if you don't. Vote on as many candidates as you have an opinion on.
Please discuss any reservations or endorsements you have of someone in the comments. More feedback can help newer users figure out what's what. But of course, you are free to just vote quietly and not rock any boats.
If someone nominates you just accept or decline in that nomination's comments. Feel free to add an edit saying a little about yourself if you accept.

You can read the roles of moderators from the help section on them and the theory of moderation post.
Comment: Hear, hear @Kitsune and @luchonacho! Truth is, we (the Community Team) were working in the background to find some fresh blood and getting a public meta question up like this one was our next move. Great to see the initiative come up through the community instead! __So, who else wants to throw their hat in the ring?__
Comment: @Ana Thank you for your information about the behind the scenes. I didn't know this already being discussed by the SE team, but while you are here, do you want to clarify/elaborate on the process of choosing a new moderator that I may not have covered? Or is the process covered in a post somewhere else?
Comment: Looks like y'all have all the right info at this point. I'll be checking back come Monday to review the folks who've volunteered. The CM team will get someone appointed soon after that, with heavy weight given to endorsements expressed by the community here. Oh, and I featured this post so that it's showing up in the sidebar across the main site, not just on meta.
Comment: I got a day or so behind being out sick, but a heads up to everyone that this hasn't been dropped.
Comment: Oh wow, good to see this picked up! For completion, could you add some information about **what is the role of a moderator**? I don't think I have a clear idea about it, and it might benefit those wanting to nominate themselves. Also, I am a bit confused about the "this is not a formal election but its result will hold through" bit. Finally, is there any sort of deadline for this?
Comment: This is mostly just a referendum lucho. It does not necessarily bind. Strict deadlines are not really the name of the game here I think, but earlier nominations are clearly better.
Comment: Oh and forgot to mention also, I added two posts of interest about moderation at the bottom.
Comment: Sounds good. Hopefully we'll get some more turnout and we'll be able to move from there.
Answer: I would like to offer up myself, Kitsune Cavalry, for nomination.
Now I know what some of you veterans are probably thinking. Kitsune is nothing but a rabble-rousing charlatan, who has built a reputation on answering dumb homework questions, maybe being still kinda wrong after many corrections, and indulging whacky theoretical musings of less interest to the more sophisticated and dignified users of our academic ivory tower.
I am also not terrifically active on meta. I lurk and read, and don't post too much. But I did run that one regression for us, which maybe someone thought was cool. With ye countrymen and women I stood fast against Banned Boy™ and I'm still actively voting, shaking a stick at some of these rapscallions that pass through. And every now and then, I have a few knowledge-y tricks up my sleeve. (Yes, those are multiple links and I do think I'm funny.)

Alright, I've had my fun.
I think a lot of active people have seen me around enough to know what kind of user I am here, so ask me whatever and feel free to snoop around my profile. Beyond my goofiness, I've made my fair share of serious academic contributions to this site, and have brought my peers in here where I could. It was a boon to me while I got my Masters, and I've expressed before that ideally, the site would have more reference request and research level questions. Getting more professional economists here is difficult, but until then, I've always had a heart for helping the undergrads and other various fledglings who come here. I do hope to become a better professional economist myself, so that I can more broadly contribute to this site for a long time to come.
Comment: Please comment on the following proposal, https://economics.meta.stackexchange.com/a/1647/61
Comment: Last time I heard, voters partly decide who to vote depending on what they are promised in return.
Comment: @AlecosPapadopoulos Looks fine, although I would add the [Oxford comma](https://en.wikipedia.org/wiki/Serial_comma) :/
Comment: @AlecosPapadopoulos It is done. Any particular reason you wish to hear our thoughts on that proposal?
Comment: Moving my comment over here: @AlecosPapadopoulos My upvote for your proposal is still sitting there nice and neat. I think my ideal Econ.SE would be everyone from the undergrad level to the professional research level coming in to answer questions. A cursory look at the top unanswered questions however reiterates how hard it is to agglomerate those professional economists, as was touched on above in that thread and throughout our history here. I think your subtitle is still a good umbrella and I still support it.
Comment: Maybe instead of "those", I would add in, "students and professionals", to more explicitly state the scope of people welcome onto the site. So it would read something like, "For students and professionals who study, teach, research, and apply economics and econometrics." Just my two cents.
Answer: I am abstaining from making a nomination (but the nominations made so far are great and the extra pair of hands would be very welcome as I have said elsewhere).
As Kitsune said, the best place to look for information about what moderators do is the "A Theory of Moderation" blog post.
I thought would add, more informally (and somewhat belatedly), some notes about what moderating this site is like.
We come to the site regularly to check if there is any tidying up to be done. Mostly, that means that a lot of the times that I come here I will just be busy with the invisible work of addressing flags (deleting bad posts, converting answers to comments, deleting yet another account from everyone's favorite resident troll). From the mod control panel it looks like jmbejara and I have made about 500 interventions in the last quarter, most of them extremely minor. I try to exercise a light-touch approach and let the community deal with as much as possible (e.g., though voting).
This work naturally takes away some time that might otherwise be available for writing answers on the site. But I try to keep an eye out, in particular, for questions where it looks like I might be well-placed to make a pivotal intervention.
It's useful to keep an eye on what the other moderators are up to. Sometimes, a moderator will be away and it is then necessary to increase the frequency of your own contributions to prevent flags from piling up. But even then, the site never demands more than about an hour a day.
Sometimes, moderation requires coordination with other sites (e.g, because we need to check whether they are happy to receive a migration, or because we need to check whether a suspicious econ user also looks dodgy on other parts of the network). For that purpose we have a special moderator chat room (called "Teacher's Lounge"), which is also a good place to talk to more experienced mods about any questions we might have.
It's useful to also spend time reading about how the SE network works more generally (e.g., by browsing the help documentation, blog posts, and meta.stackexchange.com) because people often have requests/questions that boil-down to network-level rather than site-level policy, and because this knowledge is helpful when dealing with new situations for the first time.
I try to contribute to any issues that show-up here in meta. I think that being singled-out as a moderator inevitably lends a bit of extra gravity to interventions on topics like site policy. So I consider it important to reflect on the evolving nature of the community and the ways in which it might be prodded in the right direction.
If anyone has any specific questions, I'd be more than happy to offer my perspective.

Kitsune Cavalry asks: "how much communication [do] you have with the community staff and what [do] the discussions entail"?
The answer is, very little. In fact, in the three years that the site has been up and running I can only remember two occasions on which it was necessary to communicate with the team. The first was for some guidance on how to deal with a particularly problematic user; the second was recently to discuss the need for extra moderation help on this site. In both cases, the team was very responsive and supportive, and one has the real sense that they are there to help whenever needed. But at the same time, the network gives moderators a pretty comprehensive set of tools, which allows the site to be fairly autonomous.
Comment: First off, thanks for taking some time to offer your thoughts. The only question I have is how much communication you have with the community staff and what the discussions entail.
Answer: Well I might as well nominate myself, the man, the myth, the legend, EconJohn.
I check the site on a regular basis am actively involved in asking questions that both benefit myself and others.
I am constantly developing my skills and have even answered my own questions keeping the question answer up.
I have very much benefited from this site and I want to help other benefit from it as well.
Comment: Please comment on the following proposal, https://economics.meta.stackexchange.com/a/1647/61
Comment: Best to you, I've seen you 'round these parts and you have some interesting questions.
Answer: Finally, I would like to nominate @denesp. Using business-world lingo, he is a "company man". And very sensitive regarding the rules of engagement here.
Comment: Thank you Alecos, but as Kitsune said I do not want to be a moderator.
Comment: He always has such a wit about his rules though, don't think he is a boring man! Unfortunately, denesp has stated he does not want to be moderator in lucho's thread.
Comment: ... +1 to him anyway hear ye hear ye
Answer: I would like to nominate @EnergyNumbers. He was present in the first failed attempt, and this goes a long way in terms of not-so-easy-to-quantify experience and familiarity with the culture and the atmosphere ... let alone poignant no-BS comments.

Edit by EnergyNumbers:
I regret that I have to decline this nomination
I don't have as much time as I used to have, and I really couldn't give this site an average of 30-60 minutes each day to do the janitorial work needed.
I am touched that I was nominated, and by the kind words from my fellow posters: thank you!
Comment: @luchonacho he is now!
Comment: I was going to propose him if no one else offered. A solid pick. :^)
Comment: Notice that this user **is not aware of this nomination** (he last visited meta on July 22nd).
Comment: @luchonacho The inclusion of his username in the post has sent him an alert. He will eventually see it. In any case, here we won't be entering an official voting phase. It will be up to the SE management team to assess the candidates, look at upvotes for each etc, and contact directly the nominated.
Comment: Are you sure about it? I don't remember receiving one (but could be wrong). In any case, I gave him a ping in the chat (which in my experience does give you a notification).
Answer: Update: Thanks for the proposition Alecos but I do not want to stand in the election. (luchonacho)
I would like to also nominate @luchonacho. Recently, he has been bulldozing the site the way I did in the past (this is the "young-guns-a-blaze" nomination) and he has cast a tremendous amount of votes in a very short time, something that I consider one of the important contributions in order to energize participation in the main.
Comment: He got the gold votes badge before I did. I have to give him kudos.
Comment: I'm humbled by the nomination, thanks! (Didn't know my voting behaviour was odd!) I do want to know precisely what moderation means/entails, and will provide my decision after that (too many commitments starting next academic year).
Comment: I updated the post with my choice. I prefer not to stand for the election.

Nominating Possible New Moderators


JavaScript & jQuery not working after fiddle update

Question: I found this jsfiddle link http://jsfiddle.net/wQ8YA/19/ on the internet.I'm trying to modify the code according to suit my needs.The problem is that the moment I make some changes like
//create a group
var group = new Kinetic.Group({
draggable: true //make group draggable
});
var rec = new Kinetic.Rect({
    x: 10,
    y: 330,
    width: 600,
    height: 600

  });
 group.add(rec);

// use of
var myRoom = createGroup(100, 200);
myRoom.add(new Kinetic.Circle({config}));

In the code and click the UPDATE button all the jQuery UI effects disappear. I don't know why this is happening.Is it because of my code or something else??
The fidddle containing the above changes is http://jsfiddle.net/wQ8YA/25/
Comment: Did you check the Javascript console? It's complaining of a syntax error.
Answer: Below statement is incorrect
myRoom.add(new Kinetic.Circle({config}));

instead it should be
myRoom.add(new Kinetic.Circle(config));

I assume config itself is JSON object so you need not to enclose it in braces ( { } )
Comment: Hmm, I don't see a declaration of the `config` variable anywhere in the code. That gets rid of the error, but it's probably not doing anything useful.
Comment: +1: Yep, works fine after that change: http://jsfiddle.net/TrueBlueAussie/wQ8YA/26/
Comment: OP might have added them in his fiddle and/or he might have playfully deleted it from fiddle as now I also can not see it.


Ideal of $\mathbb{Z}[\sqrt{10}]$: principal, prime or maximal?

Question: my task is following

Let $I=\{a+b\sqrt{10}:13\mid2a-b\}$ be a subset of the ring $\mathbb{Z}[\sqrt{10}]$. Decide if $I$ is an ideal of $\mathbb{Z}[\sqrt{10}]$ and if so, decide if it is principal, prime or maximal.

I've proved that $I$ is ideal indeed (addition is trivial and it is closed under multiplication because $13\mid2a-b\ \Leftrightarrow\ 13\mid a-20b$).
But I have problem with the properties of $I$. I know that $I$ is prime/maximal iff $\mathbb{Z}[\sqrt{10}]/I$ is an integral domain / a field. I don't know, how to continue -- $I$ is kernel of some ring homomorphism, but I have no idea how to use it. I suppose we would like to use something like $f:\mathbb{Z}[\sqrt{10}]\to\mathbb{Z}_{13},a+b\sqrt{10}\mapsto[2a-b]_{13}$ but is this even a map?... Edit: oh, of course $f$ is a map, since the element $a+b\sqrt{10}$ represents only itself...
Comment: **Hint** $\ 10\equiv 6^2\pmod{13}.\, $  See my answer if it is not clear where that leads.
Comment: What's going on with "decide if $I$ is principal" ?
Comment: @user26857 I have a hint, that I should use map $F:a+b\sqrt{10}\mapsto a^2-10b^2$. Suppose $I=(a+b\sqrt{10})$. If $c+d\sqrt{10}\in I$, then there is $x+y\sqrt{10}\in\mathbb{Z}[\sqrt{10}]$ such, that $c+d\sqrt{10}=(x+y\sqrt{10})(a+b\sqrt{10})$ and applying $F$ I should have $a^2-10b^2\mid c^2-10d^2$, right?
Comment: @user26857 I don't know wheter $I$ is principle or not. So I suppose it is. (if it is principle indeed i want to find generator, if not I should obtain contradiction). Let be $I=(a+b\sqrt{10})$. If $c+d\sqrt{10}\in I$ then there are $x,y\in\mathbb{Z}$ such, that $c+d\sqrt{10}=(x+y\sqrt{10})(a+b\sqrt{10})$. Now I would like use $F:a+b\sqrt{10}\mapsto a^2-10b^2$ somehow. $F$ should be an analogy to similar situation, when we researched subsets of rings $\mathbb{Z}[i]$ and $\mathbb{Z}[i\sqrt{5}]$. We used there a map $g:\mathbb{C}\to[0,\infty),z\mapsto|z|^2$, so we obtained divisibility condition
Comment: @user26857 Ok, so $I=\left(13,\sqrt{10}-6\right)=\left\{(13x-6y)+y\sqrt{10}\ |\ x,y\in\mathbb{Z}\right\}$. If $I=\left(a+b\sqrt{10}\right)$, then $a^2+10b^2\mid(13x-6y)^2+10y^2,\forall x,y\in\mathbb{Z}$? If so, could you explain me this a little bit more, please? It's not clear to me...
Comment: @user26857 Yea, a typo. :) I came back to $x,y$ because then $\left|a^2-10b^2\right|\mid\left|(13x-6y)^2-10y^2\right|$, so I can generate candidates for the right side easily. E.g. for $x=0,y=1$ I have $\left|a^2-10b^2\right|\mid26$, for $x=1,y=0$ I have $\left|a^2-10b^2\right|\mid169$, hence $\left|a^2-10b^2\right|\mid13$. Or not?
Comment: @user26857 So please, what am I supposed to do?
Answer: If you have proved that $I$ is an ideal, then you have proved that the map
$$f:\mathbb{Z}[\sqrt{10}]\to\mathbb{Z}_{13}
\mbox{ given by }
a+b\sqrt{10}\mapsto[2a-b]_{13}
$$
is a ring homomorphism with kernel $I$.
By considering the elements with $a=0$, it is clear that $f$ is surjective.
What does this tell you about $f$ ?
Comment: @byk7: The isomorphism part. What does that tell you about $I$, since $\Bbb Z_{13}$ is a field?
Comment: @CameronBuie yea, just got it... since $\mathbb{Z}[\sqrt{10}]/I\cong\mathbb{Z}_{13}$ and $\mathbb{Z}_{13}$ is a field, then $I$ is prime as well as maximal...
Comment: @byk7: You're overthinking it a bit. What does the First Isomorphism Theorem let you conclude about $I,$ given that it is the kernel of the ring homomorphism $f$ mapping onto the field $\Bbb Z_{13}$?
Comment: @CameronBuie oh, you mean, that $\mathbb{Z}[\sqrt{10}] / I$ is isomorphic to $\mathbb{Z}_{13}$? Or that $I=\ker f$?
Comment: Something like there is a homomorphism g: Z[sqrt(10)] / I → Z/13Z, such that g∘p=f, where p is projection Z[sqrt(10)] → Z[sqrt(10)] / I, and g is surjection as well?
Answer: Hint $\,\ 13\mid 2a\!-\!b\iff 13\mid 2(a\!+\!6b)\iff 13\mid a\!+\!6b\iff a+b\sqrt{10}\in (\sqrt{10}\!-\!6,\,13)$
Comment: @byk7 Let $\,w = 6\!-\!\sqrt{10}.\,$ If $\,(w,13)=(v)\,$ then $\,v\mid w\,$ so $\,v'\mid w'\,$ so $\,vv'\mid ww'=26.\,$ Also $\,v\mid 13\,$ so $\,v'\mid 13'=13\,$ so $\,vv'\mid 13^2,\,$ so $\,vv'\mid (26,13^2)=13(2,13)=13.\, $ Thus if $\,v = a+b\sqrt{10}\,$ then $\,vv'=a^2\!-10b^2 = \pm 13.\,$ But that has no integer solutions, being unsolvable mod $10.\ \ $
Comment: @byk7 Btw, proving the nontrivial direction $(\Leftarrow)$ of the final arrow in the answer is very simple [via this criterion.](http://math.stackexchange.com/a/608414/242)
Comment: @byk7 $\, w = vu\,\Rightarrow\,w' = (vu)' = v'u'\,$ since conjugation is a ring hom.
Comment: ok, so there are at most two generators of $I$, but what to do now, please?
Comment: @byk7 What part(s) are you stuck on?
Comment: well, I have two generators of $I$, but this doesn't say, that $I$is not principal. I should use a norm $a+b\sqrt{10}\mapsto\left|a^2-10b^2\right|$, but dunno how.
Comment: Last thing -- why $v\mid w\Rightarrow v'\mid w'$ ?
Comment: @byk7 See also [this answer](http://math.stackexchange.com/a/2054160/242) where I show how to use the above mentioned criterion.


Beginner's question about compound time signatures

Question: Hello I am learning musical theory, I have a question about compound time signatures :
I read that for a compound time signature, like 6/8,

"the upper number is the number of divisions thus you have to divide
  it by three to get the number of beats".

This is true if for example each beat is made of 3 divisions, what if each beats is say made of 5 divisions, like a dotted full do + full re beamed together ? In this case you have to divide it by 5, and if each beat is of variable number of divisions, the upper number can't get you immediately the number of beats.
Answer: Let's consider a complex time signature like 7/8. There are 3 different beat divisions we could use: 2,2,3; 2,3,2 and 3,2,2. In practice there are two ways to distinguish between these different possibilities - either study the grouping of notes or see if the composer left a note on the score.
The latter's very straight forward. Often modern composers will write above the stave "(2+2+3)", for example.
The former requires looking at barred notes and ties and seeing where they split.
In general, the time signature itself only really tells us the number (6) and the length (8) of beats. 6/8 is assumed to mean 3+3 because we've decided it does.
Comment: I mean the information isn't directly in the signature. It has been defined that way. And yeah that was a little slip.
Comment: I wrote this on mobile. I'll add some score extracts when I have a chance.
Comment: Note also that the beat divisions can vary from bar to bar;  for example, the finale of Stravinsky's "Firebird" changes back & forth between 3+2+2 and 2+2+3.
Answer: Compound time is essentially made up of dotted beats. so the compound version of say 2/4 is 6/8, 1/4 is 3/8, 3/4 is 9/8 and so on...  (for 2/2 it's 6/4) meaning there are n dotted beats in a bar (where n=1,2,3 and the beats are as specified by the bottom number)
in other words the compound time signature will always be divisible by 3 as a dotted note contains three subnotes (i.e. a dotted crotchet will have three quavers)
So 5/8 is not a compound time as far as I'm concerned.
I am also an amateur, so I hope a more experienced musician will correct me if there's any mistake.
Answer: 6/8 is compound, in that it can be counted in two different ways. It contains 6 quavers (1/8 notes) - just as could be found in 3/4 time, BUT the emphasis is not the same. In 3/4, the count is 1and 2and 3and, but in 6/8 it's ONE,two, three,FOUR, five, six. Could be exactly the same tempo, but on 6/8 the 'feel' is different as in there are two emphasised parts - ONE and FOUR. This effectively gives it a 'two' feel, as it can be counted as ONE, TWO, slower than the quick six count. Thus your idea of divide by 3. Exactly the same thing happens with 3/8, 9/8 and 12/8. 12/8 will be countable as ONE-- TWO--THREE--FOUR--.So, yes, each beat has 3 divisions, in a way.
5/8, 5/4, 7/8 and 7/4 are not compound, as they cant be 'split' in the same way. Yes, 5/4 is often split into ONE, two, three, FOUR,five, but the parts aren't equal. It gets split into ONE, two, THREE, four, five as well, which gives a different feel.Each beat has not five divisions, each BAR has five !
Answer: We have notes available that split readily into two - quarter notes, half notes...    We have notes that split readily into three - dotted quarters, dotted halves...    There isn't a stock five-divisible note.  If that's what you want, use tuplet notation.
In traditional theory there are two types of time - Simple and Compound.  Simple has beats that divide into 2, Compound has beats that divide into three.
Why don't we have a type that divides into 5?  Well, we could.  Notational possibilities are wide open these days, and some composers delight in unusual time signatures like 7/13 and 9/6.   (They usually use them to indicate tempo relationships between different sections of music, rather than any particularly complex rhythm within the bar though.  Don't worry about it for now!)
But you'll find that music tends to fall into groups of 2 or 3.  5/8 is not a pure Simple or Compound time, it's either 3+2, a compound beat followed by a simple one, or 2+3, a simple beat followed by a compound one.
Answer: You're right. It would be possible to divide the beat into 5. One example is C-V Alkan's Etude in E op 35 no 12. This is notated in 10/16. Its tempo is given as "Andante. MM 88=crotchet [quarter] tied to semiquaver [16th]". But compound time-signatures with each beat divided into 5 or any higher prime are IME extremely rare, so mentioning only the case of division into 3 makes a reasonable simplification which covers all the music that the learner is likely to come across.
Answer: Throughout this explanation these terms will be used:
Minim: Half note
Dotted Minim: Dotted half note
Crotchet: Quarter Note
Dotted Crotchet: Dotted Quarter note
Quaver: Eighth Note
Dotted Quaver: Dotted Eighth Note
Semiquaver: Sixteenth Note
In a time signature, the numerator denotes the number of beats and the denominator denotes the type of beats.
In a simple time signature like 3/8, 3 says that the number of beats is three and 8 says that the type of beats is Quavers; meaning 3 Quaver beats in a bar
Similarly 4/4 :
4 Crotchet beats in a bar
But, this is slightly different for compound time signatures when it comes to grouping.
First of all, let us take a look at some compound time signatures and what they mean:
6/8 :Literally this means 6 quaver beats. These 6 quavers can be grouped into 2 dotted crotchet beats in a bar.
Similarly,
9/8: 9 Quaver beats=3 dotted crotchets
12/8: 12 Quaver beats= 4 dotted crotchets
6/4: 6 Crotchet beats= 2 dotted Minims
9/4: 9 Crotchet beats = 3 dotted Minims
12/4: 12 Crotchet beats= 4 dotted Minims
6/16: 6 Semiquaver beats= 2 dotted Quavers
9/16: 9 Semiquaver beats= 3 dotted Quavers
12/16: 12 Semiquaver beats =4 dotted Quavers
In all of the above compound time signatures, the numerator could be divided into equal sub groups.
However, there are situations when this is not possible. Such time signatures are known as Irregular time signatures.
Some examples are:
5/8: 5 Quaver beats in a bar
7/8: 7 Quaver beats in a bar
5/4 : 5 Crotchet beats in a bar
7/4: 7 Crotchet beats in a bar
In these time signatures, as the top figure cannot be divided into equal subgroups, they must be divided unequally.
For example;
5/8 could be divided into a Crotchet and a dotted Crotchet
5/4 could be divided into a Minim and a dotted Minim
Therefore Irregular time signatures are a different concept than compound time signatures.


Can IBM Cloud Free Tier run Wordpress?

Question: Is it possible to run Wordpress site using IBM Cloud Free Tier account? If so what is overall technical plan i should follow?
Comment: General networking and server admin questions are off-topic for Stack Overflow, unless they directly involve programming or tools used for programming. You may be able to get some help on [Server Fault](https://serverfault.com), but please keep in mind [what topics you can post about there](https://serverfault.com/help/on-topic).
Comment: The question is too broad. What does mean "run", just start and not crash or serve thousands of users?
Answer: Yes you can but you will be limited in the architecture you can use. Here is an example of running wordpress on an IBM Cloud Kubernetes Service cluster: https://github.com/IBM/Scalable-WordPress-deployment-on-Kubernetes. This should be able to be deployed on a free tier cluster.

Can IBM Cloud Free Tier run Wordpress?


Using StreamBuilder to build widget from a Future in Flutter

Question: I am trying to build a widget with a list of values returned by an api call using StreamBuilder.  The stream is created from a Future using the fromFuture method.  I can see the api call being made and a value being placed into the Future variable but the creation of the stream never triggers the StreamBuilder.
Clearly I am missing something with my understanding of streams and how they work in Dart.  If anyone could clarify it would be greatly appreciated.
Stateless widget:
return StreamBuilder<List<Category>>(
  stream: api.getCategories(),
  builder: (context, snapshot) {
    if ( snapshot.hasData ) {
      final children = snapshot.data!.map((category) => Text(category.name)).toList();
      return ListView(children: children);
    }
    return Center(child: CircularProgressIndicator());
  },
);

API class:
  Stream<List<Category>> getCategories() {
    return Stream.fromFuture(this.apiCategories());
  }

  Future<List<Category>> apiCategories() async {
      // api call made here
  }

Answer: Assuming that you've used await in your future and everything, you could first check if your connection is done or awaiting.
return StreamBuilder<List<Category>>(
  stream: api.getCategories(),
  builder: (context, snapshot) {
    if(snapshot.connectionState == ConnectionState.done){
      if ( snapshot.hasData ) {
        final children = snapshot.data!.map((category) => Text(category.name)).toList();
        return ListView(children: children);
      }
      else{
        return Center(child: Text("No data returned from the API"));
      }
    }
    return Center(child: CircularProgressIndicator());
  },
);


How to create a new table that summarises data from another data frame?

Question: I have a data frame df whose data looks like,

dataset <- data.frame(customer_id = c(12,12,234,234,781,456),
                  Sales_id = c(20013211129, 20013217122, 20013149844, 20013273151, 20013222724, 20013171637),
                  Rev = c(1000,1000,1000,1000,1000,1000),
                  Source = c('App', 'Non-App', 'App', 'Non-App', 'Non-App', 'Non-App'))

customer_id |   Sales_id  | Rev | Source
       12     20013211129   1000  App
       12     20013217122   1000  Non-App
       234    20013149844   1000  App
       234    20013273151   1000  Non-App
       781    20013222724   1000  Non-App
       456    20013171637   1000  Non-App

I want a table to be created using data of this data frame that shows result as,

........No_of_customers | no_of_orders | total_revenue
App         2                 2               2000
Non-App     4                 4               4000
Total       6                 6               6000
App%        33%               33%              33%

Here, the number of customers is on the basis of count of distinct customer_id, number of orders is on the count of distinct sales_id and total is directly the sum total of the preceding two rows.
I'm new to R, so I need some help regarding what functions should I use for this job
Comment: For this kind of stuff you should definitly look into the packages "tidyr" and "dplyr". Be warned, it will take you many hours (weeks really) to learn and get to a point where you can make a table like that. But there is probably no alternative.
Comment: the `ddply` function is good (from the `plyr` package) for data summaries. You can do more than one at once and name them, and group by various other variables
Answer: Here a solution, probably not the best one but it works...
## Load Data
customer_id <- c(12,12,34,234,781,456)
Sales_id <- c(20013211129,
              20013217122,
              20013149844,
              20013273151,
              20013222724,
              20013171637)
Rev <- rep(1000, 6)
Source <- c("App", "Non-App", "App", "Non-App", "Non-App", "Non-App")
data <- data.frame(customer_id, Sales_id, Rev, Source, stringsAsFactors = FALSE)

## Create Overview table
library(dplyr)
result <- data %>%
  group_by(Source) %>%
  summarise(No_of_customers = length(unique(customer_id)),
            no_of_orders = length(unique(Sales_id)),
            total_revenue = sum(Rev))
temp_res <- result[,-1]
temp_res <- rbind(temp_res, apply(temp_res, 2, sum))
temp_res <- rbind(temp_res, temp_res[1,]/temp_res[3,]*100)
cbind(Cat = c("App", "Non-App", "Total", "App%"), temp_res)

However, I do not recomend to put totals and shares as additional row into a data.frame.
Instead I would do something like that...
library(tidyr)
result <- result %>%
  pivot_longer(cols = -Source, names_to = "Cat")

## get Total
result %>%
  group_by(Cat) %>%
  summarise(Sum = sum(value))

## get Share
result %>%
  group_by(Cat) %>%
  summarise(App_share = value[Source == "App"] / sum(value))


Python Flask returning with backslashes to JSON curl request

Question: I am getting the results from my mongoDB database and trying to send them as a JSON object through curl:
custos = customerDB.CustomerModel.find()

jsonCusto = []
for doc in custos:
temp = json.dumps(doc, default=json_util.default)
jsonCusto.append(temp)

I print this before send and get:
'{"firstName": "Joshu", "lastName": "Wak", "creation": {"$date": 1414531609314}, "Cust_ID": 101, "streetNo": "3231", "_id": {"$oid": "54500a19d0f6120a0021c879"}, "email": "email@example.com", "streetName": "washingoton"}'

but on the curl screen I get:
"{\"firstName\": \"Joshu\", \"lastName\": \"Wak\", \"creation\": {\"$date\": 1414531609314}, \"Cust_ID\": 101, \"streetNo\": \"3231\", \"_id\": {\"$oid\": \"54500a19d0f6120a0021c879\"}, \"email\": \"email@example.com\", \"streetName\": \"washingoton\"}

I tried about 10 combinations and cannot get it right. I would appreciate any help.
Thanks!
Comment: I read on Google that these are only 'visual', and do not actually exist in the variable value itself. Is this right? It doesnot happen to other websites though?
Comment: How are you *sending* `jsonCusto` to the client?  `jsonify(someKey=jsonCusto)` or something else?
Comment: I tried both jsonify(someKey=jsonCusto) and someKey=jsonCusto
Comment: `return someKey=jsonCusto` isn't valid Python - can you show us the part where you actually return the `jsonCusto` to the client?
Comment: I just return it with 'return Custo', is that wrong?
Comment: Is `Custo` the same as `jsonCusto` in your code snippet or is it something else?  If it is the same as `jsonCusto` what customizations have you made to Flask so it understands a list of strings is a single `application/json` response?
Comment: My *suspicion* is that you are double-encoding your JSON data (first with `json.dumps` in your code snippet here and then again before you return it to the client).
Comment: "[{\"firstName\": \"Alex\", \"middleName\": \"X\", \"lastName\": \"bunyc\", \"creation\": {\"$date\": 1414628193009}, \"streetNo\": \"323\", \"_id\": {\"$oid\": \"5451836114b6e46b4b4a3b98\"}, \"email\": \"DD@D\", \"streetName\": \"chicago\"}]"
Comment: The double quotes int he outermost layer are the problem. So how do I get rid of them?

PS. you think the looping might be the issue?
Answer: You almost certainly are double-encoding your JSON.  Simply remove the json.dumps in your loop and only use it at the end:
custos = customerDB.CustomerModel.find()
jsonCusto = list(custos)
jsonText = json.dumps(jsonCusto, default=json_util.default)

Answer: I had same challenge. In my case I wrote some_schema.dumps() instead of some_schema.dump()
Below is the output of author_schema.dumps():
@app.route('/authors', methods = ['GET'])
def index():
    get_authors = Authors.query.all()
    author_schema = AuthorsSchema(many=True)
    authors= author_schema.dump(get_authors)
    return make_response(jsonify({"authors": authors}))

Output:
{
  "authors": "[{\"specialisation\": \"Joke Developer\", \"name\": \"Kaunda Ibn Ahmed\", \"id\": 1.0}, {\"specialisation\": \"History\", \"name\": \"Akademic Vuvuzela\", \"id\": 2.0}]"
}

Below is the output of author_schema.dump():
@app.route('/authors', methods = ['GET'])
def index():
    .....
    .....
    authors= author_schema.dump(get_authors)
    return make_response(jsonify({"authors": authors}))

Output:
{
  "authors": [
    {
      "id": 1.0,
      "name": "Kaunda Ibn Ahmed",
      "specialisation": "Joke Developer"
    },
    {
      "id": 2.0,
      "name": "Akademic Vuvuzela",
      "specialisation": "History"
    }
  ]
}


R Frequency table of multiple columns, grouped by third variable

Question: I have a data table that looks like this with "groups" of columns that belong together:

Group 1: Q1_1, Q1_2, Q1_3
Group 2: Q2_1, Q2_2

 ID Sex  Q1_1 Q1_2 Q1_3 Q2_1 Q2_2
 1   m    2     5    2    4    4
 2   f    4     5    1    3    1
 3   m    5     4    4    5    5
 4   f    2     4    3    5    4

First, I would like to count all values that appear across all rows in that group of columns and create a new data table out of it that should look like this:
 answer  freq_Q1_all  freq_Q2_all
    1         1            1
    2         3            0
    3         1            1
    4         4            3
    5         3            3

And last, I would like to create a similar data table but separated by variables of column Sex.
 answer  freq_Q1_all_f  freq_Q1_all_m  freq_Q2_all_f  freq_Q2_all_m
    1         1              0               1               0
    2         1              2               0               0
    3         1              0               1               0
    4         2              2               1               2
    5         2              1               1               2

Any help is much appreciated. Thanks!
Answer: Using the tidyverse:
First question:
library(tidyverse)

dat %>%
    pivot_longer(cols = starts_with("Q"), values_to = "answer") %>%
    separate(name, into = c("question", "question2")) %>%
    count(question, answer) %>%
    pivot_wider(names_from = question, values_from = n) %>%
    mutate_if(is.numeric, replace_na, 0)

  answer    Q1    Q2
   <dbl> <dbl> <dbl>
1      1     1     1
2      2     3     0
3      3     1     1
4      4     4     3
5      5     3     3

Second question:
dat %>%
    pivot_longer(cols = starts_with("Q"), values_to = 'answer') %>%
    separate(name, into = c("question", "question2")) %>%
    count(Sex, question, answer)  %>%
    unite(question, question, Sex, sep = "_") %>%
    pivot_wider(names_from = question, values_from = n) %>%
    mutate_if(is.numeric, replace_na, 0)

  answer  Q1_f  Q2_f  Q1_m  Q2_m
   <dbl> <dbl> <dbl> <dbl> <dbl>
1      1     1     1     0     0
2      2     1     0     2     0
3      3     1     1     0     0
4      4     2     1     2     2
5      5     1     1     2     2

The major work you need to do for this is just reshaping the data, which is where we use pivot_longer (could also use gather) and pivot_wider (could also use spread). separate and unite help us to clean up columns that need to be separated (Q1_1 -> Q1, 1) and united (Q1, f -> Q1_f). From there it is just a little data cleanup.
If you are unfamiliar with these functions, it might be helpful to step through the operations, executing the code line-by-line.
data
dat <- structure(list(ID = 1:4,
                      Sex = c("m", "f", "m", "f"),
                      Q1_1 = c(2L, 4L, 5L, 2L),
                      Q1_2 = c(5L, 5L, 4L, 4L),
                      Q1_3 = c(2L, 1L, 4L, 3L),
                      Q2_1 = c(4L, 3L, 5L, 5L),
                      Q2_2 = c(4L, 1L, 5L, 4L)),
                 class = "data.frame",
                 row.names = c(NA, -4L))

Comment: Thanks! It works.
Just for my understanding: How exactly does `separate` work? Where do you define the object `name` and where do the names "question" and "question2" appear?
Comment: `name` comes from the result of  `pivot_longer`. `question` and `question2` will be in the data.frame after executing `separate`. you might want to look at executing the statements one-by-one to see the "internal" operations


How to calculate total no. of Q_id remains

Question: I have two tables

STUDENT_RESPONS(Q-NO, STD_ID,RESPONSE)
QUESTION(Q_NO, QUESTION,A,B,C,D)

how to calculate total Q_NO which is not attp by student
SELECT COUNT(Q_NO) FROM QUESTION MINUS SELECT COUNT(Q_NO) FROM STUDENT_RESPONS

I want to subtract Q_no from from table question and Q_no from table Student_response
Comment: Can you show us some sample data along with expected result?
Comment: First normalise your schema
Answer: You can specify the not in
SELECT count(*)
FROM Question q
WHERE q.Q_NO NOT IN (
      SELECT Q_NO
      FROM STUDENT_RESPONS)

or else the left join
SELECT count(*)
FROM Question q
LEFT JOIN STUDENT_RESPONS s ON t.Q_NO=s.Q_NO
WHERE s.Q_NO is NULL

These 2 queries will return all questions that have not been answered by students


Exclude file storage from VMWare snapshots?

Question: Say we have a Windows Server 2008 with the role of a file server, and 500GB of files on the D drive. Files are backup up to tape.  How is it possible to take a snapshot of the OS without the file on the D drive (or delta) being included in the VM?
Answer: Configure the virtual hard disk as 'Independent', in 'Persistent' mode.
This will prevent the disk from being affected in any way when a snapshot is taken or reverted; if you revert a snapshot, you will not revert the Independent disk.
Comment: Thanks, first time user here.  You saved us a lot of time.
Answer: You can set your disk to be 'independent'. When the disk is added, or when the VM is down, right click the VM - > Edit settings. Select the disk and the option to make it independent and persistant is there on the right. Any independent disk wont be snapshotted.


fckeditor's filemanager in codeigniter question

Question: I will be short in my question.
In my codeigniter setup I use database session. in this session I have a variable admin_site_id  which i get via
<code>$this->session->userdata('admin_site_id');
</code>
What would be the best way to get the same thing in non CI php script?
I have a file manager of fckeditor, which I want to integrate but the pics should be uploaded in different folders , depending on the website administrator is editing right now...
Answer: By default, CI stores session data in a cookie called ci_sessions, you can access it through: <code>$_COOKIE['ci_session'];</code>
Depending on if you magic_quotes turned on, encryption, or storing session data in the database you may have to remove slashes, unserialize the data, and run a SQL query to grab the data using the cookie hash.
You can read more on how to this here:  http://renownedmedia.com/blog/accessing-codeigniter-session-data-using-external-scripts
Comment: But I don't like the matter that I need to connect to DB again and from extra place....
Comment: True, although session->userdata() would be making a call back to the database anyway, I agree it sucks to have db settings in multiple places. You could require_once APPPATH.'/config/database.php'; in the script and access the CI db config from the script. Another option would be to turn off database session storage, or like @someoneinomaha suggested start using native php sessions.
Answer: I did something similar on a CI project recently. I ended up using the Native Session Library (http://codeigniter.com/wiki/Native_session/) that uses native PHP sessions.
So I was able to set a session variable that was accessible in CI - using the typical CI session syntax, but was then able to access that same session using a non-CI php script.
My project for this isn't live yet, so I can't speak to any potential production issues that might come up, but others seem to be using it without problems.


Represent data across multiple categories and sub categories

Question: The data contain category and sub-category distributions.
The categories are topics in a quiz such as: Music, Sports, Business.
Each category has three levels to choose from: Basic, Standard and Advanced.
For example: A user might take a quiz on Music across different levels. Say the number of questions attempted is 100. The user would have answered them across levels. 40 for basic, 40 for standard and 20 for advanced. The data consist of counts of the questions attempted within each category for each user.
What is the best way to represent these data on a graph? Each graph would contain up to 5 main categories.
Comment: It is difficult to understand this description.  Could you perhaps post a simple example of your dataset?  And please clarify what you mean by "represent": does that mean a logical file format, a graphical visualization, a statistical summary, or perhaps something else?  What is the intended purpose of this representation?
Comment: Thanks.  But what are the data?  The quiz answers?  Scores and subscores?  Counts of questions attempted?  I notice your edit does not address the last two questions I asked in my previous comment--please clarify those points, too.
Comment: Hey, updated the question
Comment: Count of questions attempted.
Comment: Are you thinking about a graph like a report card for each student? Or are you thinking of visualizing a lot of students on a graph? If it's the latter, how many?
Comment: Kind of. However the graph will only be there for one 'student' or 'user'. It will go up on their profile page, each user has their own set of analytics.
Answer: If the domain all have a base of 100, a stacked bar chart may be suitable.


Can not change nginx 1.2.5 default website

Question: I just installed nginx version 1.2.5 on a new server and discovered that I can not change the default file for default website.
In /etc/nginx/sites-available/default file I have the following lines:
server {
listen 80 default_server;
    server_name myserver;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    root /var/www/default;
error_page 404 /4044.html;
    location / {
        index index.html index.htm;
    }

}

server {
... server2...
}
server {
... server3...
}

Unfortunately, when I open a page by using server's IP address http://ip_address, instead of file /var/www/default/index.html nginx displays it's default file "Welcome to nginx". In case of 404 error it doesn't display the file /var/www/default/4044.html but it's default "not found"page.
I tried to change:
listen 80 default_server; to listen 80 default;
and
server_name myserver; to server_name servers_ip_address
restarted nginx, but no success. Checked error.log file but nothing wrong. I have nginx installed on 2 more servers but olders versions of nginx. There are no problems like this.
Any ideas? If I cannot change its, does anyone knows wher default pages are located so that I can edit them? Thanks.
Comment: Are you sure, that you have symlink to this file in `/etc/nginx/sites-enabled`?
Answer: For some reason new Nginx's configuration file doesn't include file /etc/nginx/sites-available/default. That was my problem.
Comment: well thats a debian specific behaviour. sites-available holds all your configuration files and sites-enabled holds all **active** configuration files. So to enable a site just use:
`sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/`
Answer: This is old but if you can't figure out the answer take a look at Config Changes Not Reflected on the nginx wiki.
Try to clear your browser cache and see if the changes are reflected. As soon as I cleared my browser cache the "Welcome to Nginx" page never loaded again.
Answer: The is the correct behaviour based on your configuration. Then you load the IP address of the server, you will always get the first virtual server definition for that IP address, since nginx cannot determine the server name from the HTTP header.
If you want another server block to respond, simply move it to the first position for that IP address.
The HTML files fo the default server are located in /var/www/default, which is defined by the "root" directive (root /var/www/default;)
Having a default configuration for an IP is actually quite useful. I use it to automatically redirect from non www. address to www.somedomain.com like this:
server {
listen 192.168.1.1 default;
server_name "_";
root /usr/local/nginx/html/whaever;
if ($host ~* ^[^.]+\.[^.]+$) { rewrite ^(.*)$ http://www.$host$1 permanent; }
}

Comment: gmck, that's the problem. If I load the IP I don't get the first virtual server definition. As I wrote, the document root for first virtual server is /var/www/default but nginx shows it's own default file "welcome to nginx". It's not the file that I have in /var/www/default. I want to know how to get rid of "welcome to nginx" file when I load server's IP.
Comment: @gmck, you're doing it wrong: http://nginx.org/en/docs/http/converting_rewrite_rules.html and http://wiki.nginx.org/Pitfalls


C "void value not ignored as it ought to be" error on a function that returns an int

Question: I have the following code and am getting
"error: void value not ignored as it ought to be
int ab = findActiveBlock();"
I would understand this error if findActiveBlock was set to void but it is returning an int? Please help
void updateActiveBlock() {

    int ab = findActiveBlock();
    //code using ab//
}

int findActiveBlock() {
    for (int i = 0; i < BLOCKCOUNT; i++) {
        if(blocks[i].active) {
            return i;
        }
    }
    return 1;
}

additional info: this is C, "blocks[]" is an array of structs.
Comment: @pm100: Unlikely. Those compilers that woudn't reject the code outright, would normally assume that an undeclared function returns `int`, not `void`.
Comment: thats because you need to declare findActiveBlock before you call it.
Answer: I would make a wild guess that your findActiveBlock is actually pre-declared somewhere above as a void-returning function. You simply forgot to update that declaration to make it match the definition.
P.S. As an additional side note: () parameter lists is an obsolescent feature in C. For functions that have no parameters, prefer to use (void) in their declarations.
Comment: that was it! thank you! I'm still getting used to header files and I always forget to update them.. thanks !!
Answer: Just a stab in the dark, but is *.active a function? If so it would need parentheses.
 int findActiveBlock() {
    for (int i = 0; i < BLOCKCOUNT; i++) {
        if(blocks[i].active()) {   //added parentheses to active
            return i;
        }
    }
    return 1;
}

Comment: There are no member functions in C. Yes, it could be a function pointer, but that wouldn't make any sense in the context.
Comment: And if it were a function pointer, it would not be a void value that should be ignored. It would be a pointer-to-function value.


How to manage production of box plots if you have a massive number of data points?

Question: Consider the following snippet:
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(1, 5760000)
plt.boxplot(data)

It takes a long time, and a lot of memory, for matplotlib to plot this.
What can I do better?
One idea I had is to calculate the min, max, median, first quartile, and third quartile using numpy. Then, I can give these values directly to boxplot, so that it doesn't have to do the calculations.
This snippet of code runs very fast:
import numpy as np

data = np.random.rand(1, 5760000)
fq, median, tq = np.quantile(data, [0.25, 0.5, 0.75])
dmin, dmax = np.min(data), np.max(data)

However, there is no such option (that I can see).
The second idea I had is to manually draw the box plot given the above statistics, but that requires me to deal with the details of matplotlib artists, and I'd like to avoid that if possible.
The third idea I had is to just use a simpler style to plot the relevant box plot quantities. It won't look like a box plot, but it conveys the same information.
I am going to run with the third idea for now, but I hope there is a way for me to just use boxplot directly.
Answer: First: boxplot interprets data = np.random.rand(1, 10) differently from data = np.random.rand(10, 1). The first is interpreted as a list of 10 box plots, each created from 1 data point, while the second is interpreted as a list of 1 box plot, each with 10 data points.
Therefore, passing np.rand.rand(1, 5760000) plots 5760000 individual box plots in a single graph. This is what is time and memory consuming. You actually want to pass np.rand.rand(5760000, 1), since you want to plot one box plot with statistics from a data set containing ~6 million data points.
Second: the following page answers how to manually pass data to the box plot drawer function: https://matplotlib.org/3.1.0/gallery/statistics/bxp.html
Answer: import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(5760000,1)
plt.boxplot(data)

Comment: Alright, I'm stumped. Did something massive change in `numpy` or `matplotlib` between 2019 and 2022? This answer appears to be what the author intended, whereas `plt.boxplot(np.random.rand(1,10))` just shows bars for 10 points.
Comment: Nevertheless, code-only answers are usually discouraged. Can you edit this answer to help explain the difference? Also see: [How to answer](https://stackoverflow.com/help/how-to-answer).


Finite closed covering of a bounded set in $\mathbb{R}^n$

Question:

My Attempt:

I think here I can define the diameter of $A$ as follows since it is bounded.
diam $A=\sup \{|x-y|: x, y \in \mathbb{R}^n\}$
So, I can take each $r_k$ as diam $A$.
Am I on the right track? Or is there something else I have to consider? I appreciate your opinion. Thanks.
Answer: Hint: Let $S = \{\sum r_k^2 : A \text{ can be covered by } (\bar B(a_k,r_k))_{k=1}^n\}$.  You have shown that $S$ is non-empty.  Note also that all elements of $S$ are non-negative.  It now suffices to show that $S$ is closed.


Do 3 Dimensional Fractals exist?

Question: I understand that certain mathematical sets produce fractals. Are there fractals defined by sets with more than 2 variables? Is that possible?
Comment: Sure, why not?${}$
Answer: Yes, they do.  Most fractal constructions can be taken into three dimensions.  One of the easiest to visualize is to make a 3D version of the Sierpinski carpet.
Take a cube, cut it into $3 \times 3 \times 3$ subcubes, checkerboard color them with the corners black, and remove all the white ones.  Now partition the subcubes you kept and keep going.  The result is
Comment: Also http://upload.wikimedia.org/wikipedia/commons/b/b4/Sierpinski_pyramid.png.

Do 3 Dimensional Fractals exist?


md contact chips css not working

Question: I am using md contact chips and my template looks like this
 <md-chips ng-model="ser" md-autocomplete-snap
              md-require-match="true">
      <md-autocomplete
        ng-disabled="autoCompleteOptions.isDisabled"
        md-no-cache="autoCompleteOptions.noCache"
        md-selected-item="si"
        md-search-text="searchText"
        md-items="sellable in getSellableByFilter(searchText)"
        md-min-length="1"
        md-item-text="sellable.name"
        placeholder="Search for a Service/Package here"
        md-select-on-match="true",
        >
      </md-autocomplete>
      <md-chip-template>

          {{$chip.name}}

      </md-chip-template>
    </md-chips>

Searching works fine but when I select an item, it looks like input field only and there is no chip like css attached.
How do I fix this?
I tried using md contact chips as well but still same issue.
error message I see in console
angular.js:14800 TypeError: Cannot read property 'some' of undefined
    at MdChipsCtrl.appendChip (angular-material.js:27822)
    at MdChipsCtrl.<anonymous> (angular-material.js:28128)
    at angular.js:1383
    at angular-material.js:25732
    at Array.forEach (<anonymous>)
    at handleSelectedItemChange (angular-material.js:25732)
    at angular-material.js:25694
    at processQueue (angular.js:17169)
    at angular.js:17217
    at Scope.$digest (angular.js:18352) "Possibly unhandled rejection: {}"
(anonymous) @ angular.js:14800
(anonymous) @ angular.js:11218
processChecks @ angular.js:17199
$digest @ angular.js:18352
(anonymous) @ angular.js:18581
completeOutstandingRequest @ angular.js:6428
(anonymous) @ angular.js:6707
setTimeout (async)
Browser.self.defer @ angular.js:6705
$evalAsync @ angular.js:18579
(anonymous) @ angular.js:17041
scheduleProcessQueue @ angular.js:17217
then @ angular.js:17138
getDisplayValue @ angular-material.js:25907
(anonymous) @ angular-material.js:26070
(anonymous) @ angular-material.js:1730
processQueue @ angular-material.js:1727
(anonymous) @ angular.js:20566
completeOutstandingRequest @ angular.js:6428
(anonymous) @ angular.js:6707
setTimeout (async)
Browser.self.defer @ angular.js:6705
timeout @ angular.js:20564
nextTick @ angular-material.js:1711
positionDropdown @ angular-material.js:25453
handleResults @ angular-material.js:26273
handleQuery @ angular-material.js:26251
focus @ angular-material.js:25824
fn @ VM61232:4
callback @ angular.js:27475
$digest @ angular.js:18352
$apply @ angular.js:18649
(anonymous) @ angular.js:27480
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014

Answer: Your model has to be of type Array, and perhaps in your controller you're not initializing it to anything (it's undefined).
ser = []

md contact chips css not working


how to add a "add user" tab to admin/people

Question: Currently on the user administration page admin/people there is a link below the tab row that lets admins add users (links to admin/people/create). Instead I would like to place that link in an additional tab next to the tabs "list" and "permissions". Has anybody experience in this? Or is there even a module for this?
I currently have difficulties finding anything because "add user tab" are quite generic search terms and there is a lot to find – but not meeting my problem.
thank you!
Answer: I think what you're asking is the same as this.  Apologies if not.
Here I've added a menu item that links out to another page.  So you should be able to change the links to your needs.  For this I created a module 'taskmenuextras'
<code>    **
* Implementation of hook_menu_alter
*/
function taskmenuextras_menu_alter(&$items) {
    $items['user/%user/featuredjobs'] = array(
        'title' => t('Featured Jobs'),
        'page callback' => 'taskmenuextras_redirect_nodequeue',
        'access callback' => 'taskmenuextras_user_has_role',
        'access arguments' => array(1, array('admin')),
        'type' => MENU_LOCAL_TASK,
        'weight'  => 0,
        );

    return $items;
}

function taskmenuextras_redirect_nodequeue() {
  drupal_goto('admin/structure/nodequeue/featured_jobs/view/1');
}

function taskmenuextras_user_has_role($user, $roles = array()) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}
</code>


Override login form submisssion

Question: I try to call a SOAP web service before an users authentication. I've try this
function beneficiaire_user_login(&$edit, $account){
    die('hello from login override'); }

Unfortunately, if my SOAP request is bad I cannot prevent the authentication.
What I want to do is:
click the login > check via a WS is the user exists > if yes create the user on Drupal, else show an error message.
Can I perform this action before the session opening ?
With a form_alter hook, it doesn't works, I do not see the "form alter" text
function beneficiaire_form_alter(&$form, $form_state, $form_id){
    exit('form alter');
}

Thanks
Comment: YOU HAVE TO VALIDATE THE LOGIN FORM AS CUSTOM VALIDATION
Comment: Clear the cache
Answer: I'm working on something similar. I think you can do this using a validation rule.
/**
 * Implements hook_form_alter().
 * We replace the local login validation handler with our own.
 */
 function beneficiaire_form_alter(&$form, &$form_state, $form_id) {
    // In this simple example we authenticate on username to see whether starts with dave
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'beneficiaire_user_form_validate';
    }
 }

/**
 * Perform validation rules and set error states
 */
function beneficiaire_user_form_validate($form, &$form_state) {
    if (!beneficiaire_authenticate($form_state)) {
        form_set_error('name', t('You are not on our super-secret list.'));
    }
}

/**
 * Custom user authentication function
 */
 function beneficiaire_authenticate(&$form_state) {
     // Check the webservice here and return false if user not found.
 }

Comment: Oops! Didn't realize I was responding to an old question.

Override login form submisssion


Why do I have different confident level when using TukeyHSD, t.test and formula in R

Question: I have a data, including two groups. I need to calculate the difference of these two groups, then calculate the confident level of 0.9. Also, I need to identify if these two groups are significantly different using ANOVA. However, I find something weird when calculating confident level. Here is my data
Sample <- data.frame(a=runif(100,0,1000),b=runif(100,0,1000))

The real data is too many, so I generate some random data.
First of all, I use the definition of confident level to calculate:
Diff <- (Sample$b-Sample$a)
Sd <- sd(Diff)
Mean <- mean(Diff)
Me <- qnorm(.9)*Sd/sqrt(length(Diff))
Lower <- Mean-Me
Upper <- Mean+Me

The result is:
> Lower
[1] -61.48252
> Upper
[1] 54.21919

Second of all, I use aov to do ANOVA analysis, then TukeyHSD is used to show the confident level:
Sample1 <- Sample %>%
  gather(Group,Score)
Aov <- aov(Score~Group,Sample1)
TukeyHSD(Aov,conf.level = .9)
> TukeyHSD(Aov,conf.level = .9)
  Tukey multiple comparisons of means
    90% family-wise confidence level
Fit: aov(formula = Score ~ Group, data = Sample1)
$Group
        diff       lwr     upr    p adj
b-a -3.631661 -76.10958 68.84626 0.9340892

Third of all, I use t.test to calculate the confident level of the difference of two groups:
> t.test(Diff,conf.level = .9)
    One Sample t-test
data:  Diff
t = -0.080451, df = 99, p-value = 0.936
alternative hypothesis: true mean is not equal to 0
90 percent confidence interval:
 -78.58381  71.32049
sample estimates:
mean of x
-3.631661

Because of randomly generating data, you probably have the different sample. But anyway, the confident level from three methods are different. S, am I doing wrong? And what is the right way?
Comment: your first confidence interval 'Me <- qnorm(.9)*Sd/sqrt(length(Diff)' is too narrow. When creating a two-sided confidence interval of alpha=0.9, you need to 'divide' the uncertainty onto both the lower and the upper side. So the .9 or 90% confidence interval would be 'Me <- qnorm(.95)*Sd/sqrt(length(Diff)'
Comment: Could you also explain why these results are different? Thanks
Answer: When you create the variable Diff, you are creating a single vector of numbers.
a = c(1,2,3,4,5,6,7,8,9,10)

b = c(2,4,6,8,10,12,14,16,18,20)

Diff = b - a

Diff

### [1]  1  2  3  4  5  6  7  8  9 10

The t.test function will return the confidence interval for this single vector.
t.test(Diff)

### 95 percent confidence interval:
### 3.334149 7.665851

This is the same as doing a paired t-test on the two groups, a and b.
t.test(b, a, paired=TRUE)

### 95 percent confidence interval:
### 3.334149 7.665851

To replicate this by hand, you need to 1) use the t-distribution, and 2) use 1/2 of alpha. 9 is the degrees of freedom for this example.
Sd    <- sd(Diff)
Mean  <- mean(Diff)
Me    <- qt(.025, 9, lower.tail=FALSE)*Sd/sqrt(length(Diff))
Lower <- Mean - Me
Upper <- Mean + Me

Lower

Upper

### Lower
### [1] 3.334149

### Upper
### [1] 7.665851

TukeyHSD is treating the Groups as two independent samples, not as a single vector of numbers, or as the difference in paired samples.  So it is different conceptually to the previous calculations.


Hibernate Unable to find a default provider

Question: Getting error :
org.hibernate.HibernateException: Error applying BeanValidation relational constraints
at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:219)
at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:126)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)

Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.applyRelationalConstraints(BeanValidationIntegrator.java:208)
... 207 more
Caused by: org.hibernate.HibernateException: Unable to build the default ValidatorFactory
at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:524)
at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:119)
    ... 212 more
Caused by: javax.validation.ValidationException: Unable to find a default provider
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:264)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:521)

Hibernate related maven conf:
<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.1.5.SP1</version>
        <scope>compile</scope>
        <exclusions>
            <exclusion>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>1.2.4</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.2.0.Final</version>
        <scope>compile</scope>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
        <version>4.3.1.Final</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
        <version>1.3.9</version>
        <scope>compile</scope>
    </dependency>

Suggestions that I found were:

Use hibernate 4+
User hibernate validation 4+
Add hibernate validation libraries
Add jsr305 (imo doesnt really matter)
Add javax validation libraries
Add hibernate-validator-annotation-processor

I have those all, but still getting error.
EDIT:
Showing how I am using my hibernate.
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.pool_size">5</property>
        <property name="show_sql">false</property>
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="com.foo.bar.MyClass />
    </session-factory>
</hibernate-configuration>

Building:
private static SessionFactory buildSessionFactory() {

    try {
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();

        configuration.setNamingStrategy(ImprovedNamingStrategy.INSTANCE); // also other configuration changes made here

        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();

        return configuration.buildSessionFactory(serviceRegistry); // this line gives the error

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        log.error("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

Comment: do you have validation-api-1.0.0.GA.jar as well?... if yes then remove it.
Comment: I removed that library, which was in my POM, still same issue though...
Comment: K just a thought try changing hibernate-validator to 4.1.0 ?
Comment: @DanglingPiyush same problem, but weird is that, when maven is building, it is doing this: `[INFO] Copying validation-api-1.0.0.GA.jar to \target\classes\META-INF\lib\validation-api-1.0.0.GA.jar` . I am not sure why, though.
Answer: Regarding your 6 points:

Use hibernate 4+
User hibernate validation 4+

Hibernate Validator 4.x is reference implementation of Bean Validation. And that's the right version to use. It is integrated in Hibernate 4. So versions seem right

Add hibernate validation libraries

Yes, that's required and you do that by adding the hibernate-validator dependency.

Add jsr305 (imo doesnt really matter)

Not related. Not even sure what JSR that is.

Add javax validation libraries

You do that explicitly, but they are also a transitive dependency to hibernate-validator so you would get them either way.

Add hibernate-validator-annotation-processor

No, that not required/related
So why does it not work? I think to answer this question we need more information. The exception suggests that javax.validation.Validation cannot see/load the Hibernate Validator Bean Validation provider. Do you work in a constrained class laoding environment? How do you use all these dependencies?
Comment: I made edit to my first post, where it shows how I am initializing hibernate(using dependencies).
Comment: But where do you run the code? In a Java SE application? Web application? EAR? Which container are you using?
Comment: Visibility should not be an issue in this case. Can you outline the content of the webapp as it is deployed? Which jars are in the lib directory etc


Got error from Text recognition using Tesseract in pycharm(Windows)

Question: I tried to read text inside the image using pytesseract and openCV in pycharm editor(windows). It display image but when read the text it show error.
Here is my code.
import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'
image = cv2.imread('test2.png')

image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
height,width,_ =image.shape
print(height,width)
print(pytesseract.image_to_string(image)) # ****

cv2.imshow('Output', image)
cv2.waitKey(0)

According to this code when I type and run
 print (pytesseract.image_to_string(image))

It showed error like follow.
Traceback (most recent call last):
  File "D:\Last Update\Uni of Mora\L4S1\FYP\new python project\HTMLCodeGenerator1\test detection.py", line 10, in <module>
    print(pytesseract.image_to_string(image))
  File "D:\Last Update\Uni of Mora\L4S1\FYP\new python project\HTMLCodeGenerator1\venv\lib\site-packages\pytesseract\pytesseract.py", line 409, in image_to_string
    return {
  File "D:\Last Update\Uni of Mora\L4S1\FYP\new python project\HTMLCodeGenerator1\venv\lib\site-packages\pytesseract\pytesseract.py", line 412, in <lambda>
    Output.STRING: lambda: run_and_get_output(*args),
  File "D:\Last Update\Uni of Mora\L4S1\FYP\new python project\HTMLCodeGenerator1\venv\lib\site-packages\pytesseract\pytesseract.py", line 287, in run_and_get_output
    run_tesseract(**kwargs)
  File "D:\Last Update\Uni of Mora\L4S1\FYP\new python project\HTMLCodeGenerator1\venv\lib\site-packages\pytesseract\pytesseract.py", line 263, in run_tesseract
    raise TesseractError(proc.returncode, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (1, 'Error opening data file C:\\Program Files (x86)\\Tesseract-OCR/eng.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory. Failed loading language \'eng\' Tesseract couldn\'t load any languages! Could not initialize tesseract.')

I tried various ways. But it doesn't work. I changed the environment variable, download test data again but it doesn't work. How I solve this.
Comment: try to uninstall pytesseract and reinstall through pycharm terminal with '''pip install pytesseract'''
Comment: I added language type. It's work
Answer: I think your main problem is with TESSDATA_PREFIX not being in Env Variables
See this answer
Pytesseract: Error opening data file \\Program Files (x86)\\Tesseract-OCR\\en.traineddata
Comment: I thinl I forgot to add language type.After that it's work now/ Thank you...
Comment: Please don't post links to other answers as answers. Just leave a comment to nominateethis question as a duplicate of the older question.
Comment: Okay Will Keep Sure Next Time


Can regression estimate the POSITION of the maximum value of a curve?

Question: Given a lot of training data, x and y, where y is the position of the maximum value of x. Can I train a regression model (e.g., logistic, linear) to approximate the POSITION of the maximum value of x?
For example,
If x = [1 3 4 10 2 -1 -2], then y will be 4 (because the 4th position has a value of 10, which is the maximum value).
If we do max(x), then get 10.
If we do maxpos(x), then get 4. <-- I want to use regression model to approximate the function maxpos.
Comment: Any assumptions about the form of the curve? Theoretically, you could fit the derivative of the curve and find where it equals zero (assuming unimodal curve)
Comment: No. This is not how regression works.  In regression, every value of X has an associated value of Y.  Height and weight; IQ and age; whatever.

So, please post some sample data and tell us what you want to find out... OK, now I see one data point. But I am still not at all clear what you want.
Comment: i don't think that makes any sense.  It's not regression.
Comment: Your title asks for the maximum of a curve but your example judges it by the largest observation. Unless you have essentially no noise (in which case, you're probably in the wrong place here), the two are [*not* the same thing](http://i.imgur.com/NvJ0ags.png).
Comment: I describe a profile likelihood method to obtain a confidence interval for such an estimate in an answer at http://stats.stackexchange.com/a/40609/919 .
Comment: @bey Hmm...I never thought about derivative, but can a regression model approximate derivative of a function?
Comment: @PeterFlom what I want is the POSITION of the maximum value of an array, x. in my example, I have an array of x with 7 points. max(x) will give me 10, but the position of 10 is 4. I want to make a regression model to get me the 4, i.e. maxpos(x)=4.
Comment: @whuber Thanks. Can you elaborate on it?
Comment: @RockTheStar depends on the family of models you are considering (hence my first comment). If its reasonably smooth, you could use something like LOWESS to get derivatives from your (x,y) data, then take the theoretical derivative of your family of models, and then find the closest fit from that family of derivatives to the derivative of the LOWESS curve. However, I'd take a look at whuber's response...it appears more statistically motivated.
Comment: As others have pointed out, you are not really describing a regression problem...not even sure if its a statistical problem. However, a valid statistical problem would be to view your data as a time series and then train a logistic regression (for example) to tell you the probability that the next point will be the maximum point. That is a clearly defined problem that could be tackled.
Comment: OK, then do you know how to do logistic regression? If not, there are a ton of resources out there. Also, you should ask a new question with a more focused title and problem statement.
Answer: Mode estimation is a big fat unknown in the statistical world. It is an unsupervised process, so regression would have to be framed carefully. Obviously, with discrete $X$ you can take your $Y$ to be counts and fit a loglinear model to those data. But your example, where $Y$ is magically taken to be $4$ which is the mode of the $X$ sample ... that makes no sense.
The best nonparametric way that I'm aware of estimating the mode from a sample is using a density smoother with kernel Boxcar, Gaussian, or Epanechnikov. I think it's $n^{1/5}$ efficient, which is to say incredibly slow.
Otherwise, maximum likelihood is a fully parametric way. If you assume a certain density, like normal, gamma, double exponential, or even Cauchy, you need only maximize a likelihood for the parametric density, and calculate the mode based on your distributional assumptions.
EDIT
One can use nonparametric methods with splines to fit a general non-linear trend, calculate the maximum from the fitted mean, and invert the maximum to obtain the $X$ value. For a small dataset, this doesn't make sense, but with hundreds of observations, continuously valued, it makes sense.
Example:
set.seed(1)
x <- seq(-3, 3, by=0.1)
f <- function(x) .3*x^3 - 4*log(abs(x))
curve(f, from=-3, to=3)
y <- rnorm(length(x), f(x), 2)
points(x, y)
l <- loess(y ~ x, subset = is.finite(y))
abline(v=x[which.max(predict(l))], col='red')
legend('bottomright', lty=1, col='red', 'Predicted max', bty='n', cex=0.5)

Comment: I suspect your interpretation of the question might not be the one intended. *Position* 4 was selected because the *value* there, equal to 10, is the largest of the group, *not* because the value 4 appeared twice. In other words, given a set of $(y,x)$ data (I adopt the reversed coordinates named in the question), the OP appears to wish to fit a model $E(x)=f(y)$ and identify the $y^{*}$ for which $\hat f(y^{*})$ is greatest. It is also important to obtain a standard error or confidence interval for $y^{*}$. I don't think distribution fitting or finding modes are involved here.
Comment: @whuber you're right.
Answer: Disclaimer: I never thought of this problem previously. Just did now, and after ~30 minutes of thinking, my brain managed to spit an answer. Scrutinize please.
TL;DR
Depends on the process that generates those numbers. For some processes, it could be possible that (say) when the 2nd component has value between 1 and 2, then the component of the largest value is always the 7th. In those cases, it would be possible to find useful regression models up to some degree that is dependent on the process.
But on the other hand, if the process is totally random, then in my view we a regression can never do do anything better than this trivial function:
if input vector seen identically in the learning set:
    return that vector
else:
    return a random number from {1,2,...,d}

There are many problems that can be made that share this unfriendly property. For example, can a regression function figure out $a+b$ if given many values of $a$, $b$ and their answers? Your question is essentially similar: can we use regression to learn about an operator?
I cannot think of a way of solving those problems by regression without cheating (e.g. by adding fancy new components in the samples).

Let's say that here is your training samples:
\begin{equation}
\mathbf{X} = \begin{pmatrix}
1& 3 &4 &10& 2 &-1 &-2\\
2& 66 &3 &3& 3 &3 &3\\
\vdots&\vdots&\vdots&\vdots&\vdots&\vdots&\vdots\\
5& 4 &0 &0& 9 &7 &2\\
\end{pmatrix}
\end{equation}
with the following target variables that correspond to the training samples (which specify the position of the component/dimension that has the highest value):
\begin{equation}
\mathbf{Y} = \begin{pmatrix}
4\\
2\\
\vdots\\
6\\
\end{pmatrix}
\end{equation}
So $x_i = (x_{i,1},x_{i,2}, \ldots, x_{i,d})$ is some training sample of yours (a $d$ dimensional vector). And since you have $n$ many samples, then if you stack those vectors atop each other you get an $n \times d$ matrix.
An optimistic estimator of the position:
Let's say that, by analysing your learning samples and their target variables (which is only $n$ samples), you managed to obtain the following estimated PDFs:

$\hat f_{X}$ PDF of random variable $X$; $X$ takes values in set of vectors $\{(\mathbf{x}_{i,1},\mathbf{x}_{i,2},\ldots,\mathbf{x}_{i,d}):1 \le i \le n\}$, where $\mathbf{x}_{i,j}$ is some number in matrix $\mathbf{X}$.
$\hat f_{X,Y}$ joint PDF of random variables $X$ and $Y$; $Y$ takes values in set of target values $\{1,2,\ldots,d\}$.

Then you get the expected value of the position of the component of the largest value is by:
\begin{equation}
\sum_{y=1}^d y\frac{\hat f_{X,Y}(\mathbf{x},y)}{\hat f_{X}(\mathbf{x})}
\end{equation}
The accuracy depends on how lucky we are in finding good estimations of the PDFs. The question is: how lucky can we be when we only have $n$ samples?
In my view, the answer is: it also depends on the process that generates those vectors. If we are lucky and the process is one that leaves a lot of correlation between the vector component values and the target variable, then this naive estimator could achieve 100% accuracy.
Another estimator of the position under more pessimistic assumptions
Let's go almost extreme:

The process that generates those vectors is random.
But component values can only be in $\{-10,-9,\ldots,-1,0,1,\ldots,9,10\}$. I.e. we are dealing with PMFs instead of PDFs (cause it's all discrete now).

I can't think if a proof now (sleep time here; or maybe I am wrong), but I strongly feel at the moment is that perfectly accurate estimations of PMFs of such random process can only exist when learning samples (i.e. those $n$ vectors) cover all possible sample vector values.
The smallest possible value for $n$ can be achieved only if learning samples are chosen at perfect randomness (uniform distribution) from the population. When this perfect random sampling happens, then smallest value for $n$ is $21^d$.
So if learning samples are perfectly uniform, then $n=21^d$ must be true in order to allow for finding perfect PMFs that can perfectly find the position of the component of the largest value.
In other words, while this is computationally feasible, it is far more computationally efficient to just a linked list of unique vectors instead! Which defeats the point using statistical methods to predict.
Yet another estimator under even more pessimistic assumptions
Let's go more extreme:

The process that generates those vectors is random.
Component values can take any value in $\mathbb{R}$!

Then if sampling is perfectly random, $n$ must be a number that is uncountable infinite in order to perfectly predict the function.
This is even worse than the previous case: it's computationally infeasible.
Comment: You might want to get some background in this question by reading about [response surface methodology](https://en.wikipedia.org/wiki/Response_surface_methodology).
Comment: @caveman. Thanks for the details explanation. I am a bit confused about the "An optimistic estimator of the position", can you elaborate on that?
Comment: @RockTheStar sure which part is the unclear one? (@whuber thank you dude I am reading about that)
Comment: @caveman the "An optimistic estimator of the position"
Comment: @RockTheStar it's optimistic cause it assumes that the process that generates the component values of the $d$ dimensional vector is not random. For example, every time the $i^{th}$ component has the highest value the $j^{th} = c_i$ where $c_i$ is some constant. In other words, we are assuming that the process that generates those vectors and their labels is also trying to ensure that when component $i$ is the largest component, then there is some other component $j$ that has some specific value.