Como enviar um vetor Javascript para o php e exibi-los?

Question: Eu consigo criar o meu array javascript e armazeno os valores dentro de um array chamado ArmazenaIds
ArmazenaIds = new Array();
    $('.checkboxs').each(function () {
        var estadoDoCheck = $(this).prop('checked');
        if(estadoDoCheck == true) {

            id = $(this).attr('iddoemail');
            ArmazenaIds.push(id);
            alert(ArmazenaIds);

        }

    });
    console.log(ArmazenaIds);
    $.ajax({
        url:'ajaxDoEnvioMensagem.php',
        type:'post',
        data:ArmazenaIds,
        beforeSend:function() {
            alert('carregando');

Queria saber como posso enviar esse array com todos os dados dentro para o ajaxDoEnvioMensagem.php e conseguir recebê-los no php;
Meu objetivo é pegar este dados , receber no enviomensagem.php e logo após chamar o método php do objetos.php;
Answer: Falta uma pequena alteração no campo data passado como parametro para a função $.ajax:

No campo data você pode passar um objeto com quantos atributos desejar. Tipo:
data: {campo1: [elemento1, elemento2], campo2: string}

Criei um novo vetor e a função success somente para testar. Um codigo php similar a esse é capaz de ler os dados enviados:
<?php
$ids = $_POST['ids'];

foreach($ids as $indice => $chave){
  echo $indice . ' => ' . $chave . '
';
}


Create Database Tables Windows 8 Metro

Question: If I am logged into Windows 8 as a non-admin, such as the guest account, will this database creation code fail? If so, how can I change it works with non-admin users:
<code>protected List<Order> orders;
    string dbName;
    #region Constructors

    public RestaurantRepository()
    {
        Initialize();
    }

    protected void Initialize()
    {

        dbName = "db_sqlite-net.db3";

        // check the database, if it doesn't exist, create it
        CheckAndCreateDatabase(dbName);
    }

    #endregion

    #region Database

    protected string GetDBPath()
    {
        string dbRootPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
        return Path.Combine(dbRootPath, "menufinderwin8.db");
    }

    // This method checks to see if the database exists, and if it doesn't, it creates
    // it and inserts some data
    protected void CheckAndCreateDatabase(string dbName)
    {
        // create a connection object. if the database doesn't exist, it will create
        // a blank database
        SQLiteAsyncConnection conn = new SQLiteAsyncConnection(GetDBPath());
        conn.CreateTableAsync<Order>();
        conn.CreateTableAsync<Order>();
        conn.CreateTableAsync<OrderDetail>();
        conn.CreateTableAsync<Product>();
        conn.CreateTableAsync<Restaurant>();

        //using (SQLiteConnection db = new SQLiteConnection(GetDBPath()))
        //{

            // create the tables
          //  db.CreateTable<Order>();
            //db.CreateTable<OrderDetail>();
            //db.CreateTable<Product>();
            //db.CreateTable<Restaurant>();
            // close the connection
            //db.Close();
        //}

    }
</code>
Answer: I think as long as the app is installed for all users, it should have access to its own local directory. I don't think you'd be able to share the database between the users, but I don't think it'd fail.
Let me know how it turns out, I'm curious :)

Create Database Tables Windows 8 Metro


Expressão lambda dá erro de conversão

Question: Essa é minha linq com lambda:
public JsonResult CarregaDescricaoRede(string _tipo_rede, string _uf, string _cidade)
        {
            var resultado_rede_descricao = (from _pdv in db.PDV
                                            .Where(r => r.Tipo_PDV == _tipo_rede)
                                            select new { _pdv.Descricao, _pdv.UF, _pdv.Cidade }).ToList().Distinct().OrderBy(o => o.Descricao);

            if(_uf != "Todos")
            {
                resultado_rede_descricao = resultado_rede_descricao.Where(c => c.UF == _uf); ***==> Aqui dá o erro***
            }

            return Json(new { resultado_rede_descricao }, JsonRequestBehavior.AllowGet);
        }

Esse é o erro:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IOrderedEnumerable<AnonymousType#1>'

Answer: Penso que o teu erro está em fazeres o OrderBy antes da condição.
Tenta:
var resultado_rede_descricao = (from _pdv in db.PDV
                                .Where(r => r.Tipo_PDV == _tipo_rede)
                                select new { _pdv.Descricao, _pdv.UF, _pdv.Cidade }).ToList().Distinct();

if(_uf != "Todos")
{
    resultado_rede_descricao = resultado_rede_descricao.Where(c => c.UF == _uf).OrderBy(o => o.Descricao); ***==> Aqui dá o erro***
}

Expressão lambda dá erro de conversão


What is the number of elements $x \in S_n$ such that the cycle containing $1$ in the cycle decomposition of $x$ has length $k$.

Question: Let $S_n$ denote the group of permutations of $\{1,2,3, . . . , n\}$ and let$ k$ be an integer between $1$ and $n$. I need to find the number of elements $x \in S_n$ such that the cycle containing $1$ in the cycle decomposition of $x$ has length $k$.
Thank you so much
Comment: Choose the other $k-1$ elements in the cycle, order them, then do whatever you want to the $n-k$ elements.
Comment: @SteveD:  Is it  $\frac{(n-1)!}{(k-1)(n-k)!} \times (n-k)!$?
Comment: Almost... you're missing the ordering of the other $k-1$ elements in the 1-cycle.
Comment: @SteveD: Should I divide the above number by k?
Comment: In what situations would you divide by a number in counting?  In what situations would you multiply a number in counting?  If we have picked what the $k-1$ extra elements in the cycle containing $1$ are, but do not yet know the order of said elements, and are currently counting all of these once, are we over counting or undercounting?  Should we then multiply or divide?  By how much?  Remember that the number of ways to arrange $k$ objects in a circle is $(k-1)!$.
Answer: As SteveD hinted at in the comments above: break apart via multiplication principle.

Pick the $k-1$ additional elements which appear in the cycle containing $1$

 $\binom{n-1}{k-1}$ choices

Fixing the position of $1$, pick how the $k-1$ other elements in its cycle are ordered in relation to $1$

 $(k-1)!$ choices

Pick how the remaining $n-k$ elements are permuted without regard to cyclic structure

 $(n-k)!$ choices

Convince yourself that every permutation such that $1$ is in a cycle of length $k$ is described and described uniquely via a sequence of answers to the above steps.  Via multiplication principle then, the total number of such permutations is the product of the number of options available at each step.

 $\binom{n-1}{k-1}(k-1)!(n-k)! = \frac{(n-1)!}{(k-1)!(n-k)!}(k-1)!(n-k)! = (n-1)!$

Check to make sure that this answer makes sense.  What values of $k$ are possible?  If we sum over all possible values of $k$, what is the total number of permutations?  Does this agree with what we expect?

$n$ possible values for $k$, and for each we have the same amount of $(n-1)!$.  Thus there are $n\cdot (n-1)! = n!$ total permutations, exactly what we expected would happen.
Answer: We can choose the cycle $(1,\ldots)$ of length $k\geq1$ in $(n-1)(n-2)\cdots\bigl(n-(k-1)\bigr)$ ways, selecting one number after the other in the desired order. We then can permute the remaining $n-k$ numbers among themselves in $(n-k)!$ ways. Therefore the total number of permutations with $1$ in a cycle of length $k$ is $(n-1)!$, independently of $k$. It would be nice to have a "direct combinatorial proof" of this fact.
Comment: Bittet, so wird euch gegeben! `:-)` See my answer.
Answer: Here's a combinatorial argument.
First observe that the number of permutations of $[n]$ in which $1$ is in a $k$-cycle is the same as the number of permutations in which $n$ is in a $k$-cycle. Let $\sigma\in S_n$, write $\sigma$ in canonical cycle notation, and erase the parentheses to get a string $p_1p_2\ldots p_n$; then $n$ is in a $k$-cycle if and only if $p_{n-k+1}=n$, so that $(np_{n-k+2}\ldots p_n)$ is a $k$-cycle of $\sigma$.
It is well known that the map that takes $\sigma\in S_n$ to a permutation $p_1p_2\ldots p_n$ by writing $\sigma$ in canonical cycle notation and erasing the parentheses is a bijection. Thus, the number of $\sigma\in S_n$ such that $n$ is in a $k$-cycle of $\sigma$ is the number of permutations of $[n]$ that have $n$ in position $n-k+1$, which is $(n-1)!$ independent of $k$.
Comment: Thank you. Altogether it is not as simple as I had hoped.


Truncated response received using HttpWebRequest

Question: I'm using the following code to make HttpWebRequests to a web site:
public static HttpWebResponse SendGETRequest(string url, string agent, CookieContainer cookieContainer)
{
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
   request.UserAgent = agent;
   request.Method = "GET";
   request.ContentType = "text/html";
   request.CookieContainer = cookieContainer;

   return (HttpWebResponse)request.GetResponse();
}

Everything worked fine with several web pages until I tried with a new one and only received the last part of the page. This is the received response:

    <spacer type="block" width="100%" height="5">

The header is correct and says that only the received data is sent. The following are the headers of the request and response:
Request:
GET /Broker/Ops/FichaContratoJS.asp?nc=815044&IP=5&YY=2012&M=6&St=0&CC=FESX201206 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19
Content-Type: text/html
Host: www.xxxx.com
Cookie: ASPSESSIONIDACBDCDBT=MGDNMNABOANDMILHBNCIDFCH;Autenticacion=Sid=230fae3d%2De0e2%2D4df1%2D8aa8%2D000fb352eaef&IdUsuarioWeb=xxxx; ASPSESSIONIDACBCCDAT=AFDJMNABAFJDDHABLOLAINDK; ASPSESSIONIDCADCBCAT=CEBJGNABLCALPJLDJFPBMLDE

Response:
HTTP/1.1 200 OK
Date: Wed, 09 May 2012 07:25:03 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Pragma: no-cache
**Content-Length: 155**
Content-Type: text/html
Expires: Wed, 09 May 2012 07:24:02 GMT
Set-Cookie: Autenticacion=Sid=230fae3d%2De0e2%2D4df1%2D8aa8%2D000fb352eaef&IdUsuarioWeb=xxxx; path=/
Cache-control: no-cache

Doing the same with a web browser works fine and returns a content length of about 4000 bytes.
Any ideas?
PD: Just in case it matters I'm doing several calls to the SendGETRequest from different threads to the same site but as there are no shared variables I think it shouldn't make a difference.
EDIT: This is the extension I use to extract the text from the Stream:
    public static string ReadTextResponse(this Stream stream)
    {
        int count;
        Encoding enconding = System.Text.Encoding.GetEncoding(1252);
        System.Text.StringBuilder stringBuilder = new StringBuilder();
        byte[] buffer = new byte[1023];

        do
        {
            count = stream.Read(buffer, 0, buffer.Length);

            if (count != 0)
            {
                string tempString = enconding.GetString(buffer, 0, count);
                stringBuilder.Append(tempString);
            }
        }
        while (count > 0);

        return stringBuilder.ToString();
    }

As far as I know it's correct. Also, note that the response header from the server contains the length of the truncated data
Comment: how do you call this method and use the returned HttpWebResponse?
Answer: I think that you are not using right the HttpWebResponse object.
Maybe you are not closing the request or reading all the response strem.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
Your method should be:
public static string SendGETRequest(string url, string agent, CookieContainer cookieContainer)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.UserAgent = agent;
        request.Method = "GET";
        request.ContentType = "text/html";
        request.CookieContainer = cookieContainer;

        string result;
        using (var myResponse = (HttpWebResponse) request.GetResponse())
        {
            using (var stream = myResponse.GetResponseStream())
            {
                result = null;
                if (stream != null)
                {
                    using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                        sr.Close();
                    }
                    stream.Close();
                }
            }
            myResponse.Close();
        }
        return result;
    }

Comment: I don't think this is the problem. The response header from the server contains the length of the truncated data
Comment: I'll try, but again, fiddler (an external web proxy debugger) is showing me the same data so looks like the web server is sending that data. Another thing, you don't need to call Close when using the using keyword.
Comment: Resharper refactoring leaves Close. i didn't notice. :p
Comment: if with fiddler you see the same response it probably means that you are requesting only a chunk of that page. http1.1 permits that kind of requests
Comment: Not intentionally. Do you know what kind of header would do that?
Comment: i'm asking you to use my code because I currently use it without problems in many project for doing the same thing you are trying to achieve. if it doesn't work maybe your problem is due to the useragent or cookiecontainer you are passing.
Comment: i don't remember the header but the value should be something like chunk or chunked
Comment: I cannot try until 21:00 GTM+1, but I will update the question for sure. Anyway I've been using my code also on a lot of projects ... I think that maybe is something related with the web server, the sessions or something like that.
Comment: Incredible ... I was sending the URL /Broker/Ops/FichaContratoJS.asp?nc=815044&IP=5&YY=2012&M=6 and the browser was sending /Broker/Ops/FichaContratoJS.asp?nc=815044&IP=5&YY=2012&M=06& (note the extra 0 on the M parameter (it's a month). Putting there that 0 returned the full page. Sounds like a defect to me.
Answer: Incredible ... I was sending the URL /Broker/Ops/FichaContratoJS.asp?nc=815044&IP=5&YY=2012&M=6 and the browser was sending /Broker/Ops/FichaContratoJS.asp?nc=815044&IP=5&YY=2012&M=06& (note the extra 0 on the M parameter (it's a month). Putting there that 0 returned the full page. Sounds like a defect to me
Answer: I have run into a similar situation and found that copying the response stream into a MemoryStream seemed to fix my problems.
public static string SendGETRequest(string url, string agent, CookieContainer cookieContainer)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.UserAgent = agent;
    request.Method = "GET";
    request.ContentType = "text/html";
    request.CookieContainer = cookieContainer;

    string result;
    using (var myResponse = (HttpWebResponse) request.GetResponse())
    {
        using (var stream = myResponse.GetResponseStream())
        {
            result = null;
            if (stream != null)
            {
                MemoryStream memStream = new MemoryStream();
                stream.CopyTo(memStream);
                memStream.Flush();
                stream.Close();

                using (var sr = new StreamReader(memStream, System.Text.Encoding.UTF8))
                {
                    result = sr.ReadToEnd();
                    sr.Close();
                }

            memStream.Close();
            }
        }
        myResponse.Close();
    }
    return result;
}


Use of regression equation when not all independent variables' values are known

Question: You are given a logistic regression equation that predicts the probability of having a disease dependent on whether or not three risk factors are present. For any given patient whose chance of disease you want to predict, you are able to find out whether or not they have the first two risk factors, but you have no information either way about the third. In a situation like this, is there any way the regression equation could reasonably be used?
Of course, you can't simply set the third term equal to zero, since that supposes the patient does not have the risk factor. Is there any other option? Say you know that the prevalence of the third risk factor in the patient's population is 25%. Could you set your third independent variable equal to 0.25 and then use the equation to estimate the patient's probability of disease?
Comment: To clarify my question, let me add that in the situation I'm describing, I have no information about the third risk factor for *any* patients in my population. It's not the case that I have the information for some patients but not others.
Answer: Solution 1: Missing value is set as a special category
This is especially adapted if the variable is already categorical: like "smokes", "doesn't smoke". You add the category "missing answer". This is when you consider a missing value is informative and you want to exploit this information: something you want to analyse.
Solution 2: simple imputation (not recommended)
The values are automatically filled. Practically they are replaced by:

the mean given the other known variables if continuous
the mode given the other known variables if categorical

This is known as "regression" in https://en.wikipedia.org/wiki/Imputation_(statistics)#Single_imputation. This may create a bias and is not recommended nowadays.
Solution 3: multiple imputation
The values are also automatically filled. The method considers the missing value has a distribution given the other variables and simulates several datasets according to this distribution. For example if the variable can have values A or B, and for a line in the dataset the probability of A/B (given the other variables) is say 30%/70%, datasets are generated by picking one of A and B with these probabilities. This require a special analysis that most stat software implement. You can read more here: https://en.wikipedia.org/wiki/Imputation_(statistics)#Multiple_imputation.
Answer: The answer above is already very good, but I just want to clarify something about your question. It's not clear from your question whether you have any information on the third risk factor. Benoit's answer works only if the data is available for some respondents and missing for others. If you don't have any information on the variable for any of your patients, it doesn't do any good to impute missing data. You probably know that, but I just want to make sure the bases are covered!
One other option for how to deal with the missing data if you have less than 5% missings and the missing data is missing at random, is to just perform the analysis on the cases without missing data, aka listwise deletion or complete case analysis.
Comment: Thanks for pointing that out. I meant that I don't have any data points at all on the third variable for my patients. I added a comment to my main question above to clarify.


Programatically updating node immediately after creation causes PDOException

Question: I'm working on a Drupal 7 site where nodes represent jobs in a queue. When a node is created, a custom module with hook_node_insert launches another program using exec. This program tells Drupal that the job has finished by requesting a page on the site at site.com/jobcomplete/NODE_ID/IS_ERROR. The callback for this page then does:
<code>$node = node_load((int)$node_id);
$node->field_completed[LANGUAGE_NONE][0]['value'] = ($error == 1) ? -1 : time();
node_save($node);
</code>
The problem with this is that sometimes the program errors out almost as soon as it's started. When this happens the callback is called before the request that created the node in the first place is completely finished, resulting in 'PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded' when node_save is called.
How can I get the callback to wait for the request that created the node to finish before trying to update it? sleep() doesn't seem to work.
Thanks.
Comment: you're running into a race condition essentially, the web is stateless. You need to setup some sort of job and worker queue. Maybe with a bit of code you can use the Progress module, http://drupal.org/project/progress
Comment: @tenken: Picking Drupal for the website wasn't my call. If I were to start this project again, I'd go with Django because the programs called are in Python and queuing is handled by Celery.
Answer: Drupal provides a Lock API for this purpose - to handle when multiple processes are competing for a resource.
In your case, you need to acquire a lock and release it when finished, checking if that lock is available prior to processing from the other component.
i.e:

lock_acquire
lock_release
lock_wait

Although not directly related, you may also be interested in the Queue API for other queue based processing tasks.
Comment: While looking into where I would put the lock I realized that [hook_node_insert](http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_insert/7) is called before the node is actually saved to the database, and that what I really needed was a hook after the database save, which doesn't exist. A workaround is described [here](http://drupal.stackexchange.com/questions/51056/is-there-a-node-hook-that-runs-after-a-node-is-fully-inserted-into-the-database).
Comment: +1 actually this looks like a solution for his problem easily. Simply acquire a lock before he exec's and then release it in his callback then node_save.


How would you implement an automatic way of the images loading in a pop-up (lightbox/colorbox) window by a click?

Question: What I mean is, can we achieve the blogspot.com/Blogger experience where we can add photos to the content (node in Drupal speak) and without any ado (adding class="colorbox", or enclosing the  element into an  ), clicking the photo in the post will make it enlarged in a pop-up window, similar to how colorbox functions.
I have visited this question Configuring Lightbox2 to Pop-Up Images embedded in nodes and it seems ambiguous to me.
I have a current Drupal 7 site and it's quite annoying that I have to manually enclose the images in a
 ...

every effing time.
Answer: You can. As always, there are several ways.
You can implement a Drupal behavior (jQuery script) that finds all images within the content and adds according classes / click callbacks.
Another way would be writing a little custom module implementing a content filter that does the same on your server.
I'm not at a PC right now. But I think you have two viable ideas now to search for. Let me know, if you need further help.


Upload Image with comments under forums

Question: In drupal 7 Forums under some topic I want to add a upload image field with the comment field. How can i achive this?
Answer: Install CKEditor

This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.

As mentioned by darol100, for Upload Install IMCE

IMCE is an image/file uploader and browser that supports personal
directories and quota.

Here is a nice video tutorial: Installing and Using CKEditor and IMCE
Comment: You need to install [IMCE](https://www.drupal.org/project/imce) too. So the user can upload the images to your server.
Comment: I have installed this module but it is allowing to upload image by a url, but I want to allow to upload image from local computer.
Comment: Then in CKEditor, you have to change its settings so it uses IMCE.
Answer: If you are looking for image captions, Here are couple of modules to do that..
Image Field Caption

Adds an extra text area for captions on image fields.
Similar to the alt and title text fields available with an image
  field, the caption text area can be used to enter text or html
  descriptions of an image.

Image Caption

This module uses JQuery to dynamically add captions to images. The
  image title attribute is used to create the caption. It basically
  wraps the image in an html container div, takes the image title text
  and appends that in a child div underneath the image. Technically, it
  works by implementing Drupal's hook_nodeapi to add one small snippet
  of captioner jquery to the head section of the page when a node of the
  configured type is viewed.

Upload Image with comments under forums


Activation mail and hash check processed from mysql_* into PDO

Question: Here is mysql_* code:
Activation mail and hash check
PDO:
Do anyone sees the solution ?
    if (isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
        // Verify data
        $search = $db->prepare("SELECT email, hash, active FROM users WHERE email=:email AND hash=:hash AND active=0");
        $search->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
        $search->bindParam(':hash', $_POST['hash'], PDO::PARAM_STR);
        $search->execute();
        //$match  = $search->fetch(PDO::FETCH_ASSOC);
        $match = $search->rowCount();

There is a problem in this part of condition
    if($match > 0){
                // We have a match, activate the account
                $db->prepare("UPDATE users SET active= 1 WHERE email=:email AND hash=:hash AND active=0");
                $db->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
                $db->bindParam(':hash', $_POST['hash'], PDO::PARAM_STR);
                $db->execute();

    echo '
Your account has been activated, you can now login
';
    }else{
                // No match -> invalid url or account has already been activated.
                echo '
The url is either invalid or you already have activated your account.
';
            }

    }else{
        // Invalid approach
        echo '
Invalid approach, please use the link that has been send to your email.
';
}

The condition finishes the code here:

The url is either invalid or you already have activated your account.

But it should finish the code here:

Your account has been activated, you can now login.
Comment: what is your question here
Comment: Code works perfectly here in mysql_* but don't work in PDO,
somewhere is error http://stackoverflow.com/questions/43986473/activation-mail-and-hash-check?noredirect=1#comment75002853_43986473
Comment: whats the problem u facing are u not getting the results u need?
Comment: How you are hashing?
Comment: Read the whole article and you will understand the question !
Answer: You check $_GET but later using $_POST.
Comment: @Grofman: Please don't edit others responses to your question only because your question is that much unclear you can't accept simple help comments (wrongly posted as an answer). Thanks.
Comment: I'm deleted answer, i really appreciate advice, sorry
Comment: @Grofman seems your database doesn't fill the rowCount at select.
http://php.net/manual/en/pdostatement.rowcount.php

> For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement

you have on this site an example how to solve this.
Answer: The problem in the flow is bound to this line of code:
$match = $search->rowCount();

You're executing a SELECT query and the rowCount is only available on INSERT, DELETE or UPDATE queries.
Instead, to find out if there is at leas match, you can use fetch() to get the "first" row, and if it exists, there was a match:
...
$match = $search->fetch();
if ($match) {
    ...

As another alternative approach to prevent that line of code you can in theory as well remove the first SELECT query in full and execute the second UPDATE query first and then check with the rowCount whether or not the user was updated.
There is more left open to comment with your code, like the logic you validate the hashes as they have no time-limit and the generation of the hash is even unknown but often critical.
Reference:

Row count with PDO
Answer: You have few mistakes in your code,
First the $_POST that you are using here does not exists.
$search->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$search->bindParam(':hash', $_POST['hash'], PDO::PARAM_STR);

You should be using $_GET
rowCount returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
Thefore rowcount, is not reliable on select,
below is working code that you can use to achieve what you looking for.

if (isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){

        $email = $_GET['email'];
        $hash = $_GET['hash'];

        $search = $db->prepare("SELECT email, hash, active FROM users WHERE email=:email AND hash=:hash AND active=0");
         $search->bindParam(':email', $email, PDO::PARAM_STR);
        $search->bindParam(':hash', $hash, PDO::PARAM_STR);
        $search->execute();

        $match = $search->fetchall(PDO::FETCH_ASSOC);

        if(count($match) > 0){
            //then match exists activate the profile

            $stmt = $db->prepare("UPDATE users SET active= 1 WHERE email= ?  AND hash= ? AND active=0")->execute(array($email,$hash));

            if(!$stmt){

                    print_r($db->errorInfo());

            }else{
                    //account activated
                 echo '
Your account has been activated, you can now login
';
            }

        }else{

             // No match -> invalid url or account has already been activated.
                echo '
The url is either invalid or you already have activated your account.
';
        }

    }else{

        // Invalid approach
        echo '
Invalid approach, please use the link that has been send to your email.
';
    }

Comment: Thank you so much !!!!!!!!!!!!!!!!!!! Thank you!!! Thank you!!! Thank you!!! Thank you !!!Thank you
Comment: Someone gave me a negative assessment and i don't have 15 points to give you ... Does not matter, surely thank you so much!
Comment: @Grofman: You give 15 Reps by accepting in any case. And another hint: If you look at the code, you can spare the first query in full. The update query would only run (and update) if that user/hash exists. Bonus is, you would get rowCount set then. The `fetchall` proposed here still does not always work with rowcount and in any case should not be done because it is not necessary. You only want to update. The database solves that for you already. Just check if updating worked and how many rows were affected.
Comment: @hakre if you are the downvoter please explain what is it for? as for as my code is concern there's no `rowCount` here
Comment: I did not downvote, but if you do a fetchAll operation only to count rows, this is wrong advice (as it should never be necessary), instead suggest a change that makes that query superfluous. I can imagine that triggerd the d/v by someone (but not me). I already have this reference in my answer which outlines this quite well: http://stackoverflow.com/a/16776839/367456


Render in CSV format in grails

Question: Grails provides Converter class to quickly transform any kind of Java/Groovy objects to either XML/JSON response.
Like,
render obj as XML

or
render obj as JSON

I am working on a grails app that requires me to render an object in csv format. Is there a way to do that?
I tried out few stuff and I have explained those below:
Snippet of my code
csv {
    def results = []
    for(d in Data.list()) {
        def r= [d.id, d.name]
        results << r
    }
    def result = ''
    results.each{ row ->
        row.each{
            col -> result += col + ','
        }
        result = result[0..-2]
        result += '\n'
    }
    println result

    render(contentType:'text/csv',text:result)
}

I stored my results in an ArrayList and then converted them to a comma separated string and then passed it to a render method. When I run the above code on the browser, it creates the desired file and the browser pops up a dialog box to "Save As" the file.
When I changed the contentType to text/html, the file contents are displayed on the browser with no newline chars.
Is there a better way to render the contents of the csv file on the browser the same way its on the file.
Thanks.
Answer: So I was just trying to solve the same problem -- responding to a Grails 3 request with a CSV download.
I got a tip from the Grails slack channel to use the Apache Commons CSV code which takes care of the details like handling commas, quotes and other special characters.
To use it, you'll need to add it to your project's dependencies. In build.gradle, under dependencies add:
compile "org.apache.commons:commons-csv:1.2"

Here's an example controller that puts everything together and responds to all requests with the CSV download for the domain object Item.
package name.of.package

import grails.rest.*
import grails.converters.*
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter

class ItemController extends RestfulController {

    static responseFormats = ['json', 'xml', 'csv']
    ItemController () {
        super(ApprovedHotel)
    }

    def export(Integer max) {

        def items = Item.list()
        withFormat {
            csv {
                def results = []
                for(d in items) {
                    def r= [d.column1, d.column2]
                    results << r
                }

                StringWriter stringWriter = new StringWriter();
                CSVPrinter printer = new CSVPrinter(stringWriter, CSVFormat.EXCEL);
                printer.printRecords( results )
                printer.flush()
                printer.close()
                result = stringWriter.toString()

                response.setHeader("Content-disposition", "attachment; filename=filename.csv")
                render(contentType:'text/csv',text:result)
            }
        }
    }
}

Comment: Thanks for the answer Sam. Just note the need to declare the variable result to avoid the error groovy.lang.MissingPropertyException No such property: result for class...
Answer: You can render the CSV as text/plain instead of text/html.   Browsers will render this as plain text, similar to what you'd see if you open the file in an editor.
Answer: If you want to display csv data in the browser you need to use

instead of \n for a new line if you want new lines to be displayed properly in HTML. Browsers generally ignore control characters and only base formatting on HTML tags.
If you want to allow the user to download a csv file code like the following will work.
response.setHeader("Content-disposition", "attachment; filename=Edata.csv")
render(contentType: "text/csv", text:varContainingData )

Render in CSV format in grails


highlight buildings based on value and show in browser

Question: I want to build a website with a map based on openstreetmap that colors buildings based on a  their potential average annual yield of solar power. I have the energy data for individual houses.
My question is now, can I assign each house (identified by street name and number) a value and the house can then be colored based on this value in the browser?
I have little to no experience with openstreetmap and would be happy about hints into the right direction.
Answer: So you need a OSM dataset and filter it for building=* ways to get the building outlines (e.g. with osmosis). Then you do create a second run to filter for addr:= tags of nodes and merge them with the building outlines from step 1. Be aware of conflicts and that one building can have multiple addresses. So now you have a dataset with normalized addresses and need to create a lookup structure like hashmap to get a mapping for your solar data: addr:street x addr:housenumber -> building id
(very raw idea on how to do it)
IMHO the mixing of external datasources to the copyleft open database license makes that you need to relicense your dataset also under ODbL.
Also keep in mind that not every address is currently at OSM and the existing ones can be wrong!
Comment: Not a problem, find the way that works best for you :)
There is also a guy who offers a [building extract for Germany](http://schwarzplan.osm4people.org/) as Shapefile, so you might can use it with QGIS.
Also some areas already contain (rough) building heights that might slightly improve your potential analyses. But full 3D processing can be a challenge on performance and datasources...
Comment: Thanks, @MaM. Your answer got me pointed in the right direction. I ended up using JOSM to extract the buildings (as a beginner I still needed the visual presentation of what I am doing). I haven't merged the data yet, but it does not seem too hard. Thanks for your information regarding licensing.


Origin of Counter-attacking style of play in football?

Question: Counter-attacking is one of the most used playing strategies in football. After searching for history of this style of play I came across Wikipedia and Independent articles which mention the first use of counter-attack in football may have come from England's Keith Newton in 1970 World Cup quarter-final match against Germany, where he has set up goals for Alan Mullery and Martin Peters. So, my question is:
Is the aforementioned match the first one to use the counter-attacking style of play? And if not, which one was it and when did it take place?
Answer: Herbert Chapman is believed to be the inventor of counter-attacking style of play. From his Wikipedia article, citing Studd, Stephen (1998) - Herbert Chapman, Football Emperor: A Study in the Origins of Modern Soccer:

Gradually, he created a style of highly-organised, counter-attacking
  football, which was at odds with the prevailing orthodoxy but
  nevertheless highly effective; Swindon Town's England international
  Harold Fleming, after losing 4–1 at home to Northampton, remarked to
  Chapman: "You have something more than a team: you have a machine."

Probably, Swindon Town's 1 - 4 defeat to Northampton Town during the period of 1907-1912, when Chapman was the manager of Northampton, was one of the earliest recorded matches that employed counter-attack.
This TheGuardian post also mentions Chapman being the one who practiced counterattacking style of play in the clubs he managed:

Early football very much focused on having the ball and trying to make
  use of it but, within 50 years, counterattacking had emerged, as
  practiced by Herbert Chapman, first at Northampton and then, more
  meaningfully, at Huddersfield and Arsenal.

Note that the counterattacking style of play was enhanced thanks to WM formation that was also created by Chapman:

The WM system, known for the shapes described by the positions of the
  players, was created in the mid-1920s by Herbert Chapman of Arsenal to
  counter a change in the offside law in 1925. The change had reduced
  the number of opposition players that attackers needed between
  themselves and the goal-line from three to two. This led to the
  introduction of a centre-back to stop the opposing centre-forward, and
  tried to balance defensive and offensive playing. The formation became
  so successful that by the late-1930s most English clubs had adopted
  the WM. [...] The gap in the centre of the formation between
  the two wing halves and the two inside forwards allowed Arsenal to
  counter-attack effectively. [...]

Here is the scheme of WM formation:
                                                (Source)


json jquery filter javascript array

Question: I have a json object array. I want to search the array and for each object, create a list of 'services' that is a comma-seperated list of all the keys which have a value of "yes".
The list of json objects with the services list is then displayed in html using jquery's each.
Its a large json file so I want to do it as efficiently as possible.
I already have the object's properties being accessed through jQuery's each (ie, obj.name)
-- so I think it should be possible to filter the services listed for each object using
jQuery's filter, and then display the key if the value is yes.
But it seems like a more efficient option would probably be to create a new javascript array, join the services with a value of yes and then add that variable to the html being
appended.
Im not sure which would be faster and so far havent been very successful at either... so any advice and examples would be very helpful.
Here's what the json array looks like:
[
 {"name":"name1",
  "service1":"y",
  "service2":"y",
  "service3":"n",
 },

 {"name":"name2",
  "service1":"n",
  "service2":"y",
  "service3":"n",
 },
];

Answer: If you just want to filter the array then use grep.
grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
http://api.jquery.com/jQuery.grep/
Answer: First off, delete trailing commas. Internet Explorer gets really, really confused by them. Anyway, I assume you don't want to "search" the array when you say "for each value"; you want to iterate through the array and parse it into a more usable list. The first method I'd suggest is just passing what you want as the array you desire, but if that's not an option, what you're looking for is some variant of this, which should be fairly efficient (jsFiddle example):
var json = [
  {"name":"name1", "service1":"y", "service2":"y", "service3":"n"},
  {"name":"name2", "service1":"n", "service2":"y", "service3":"n"}
];
var parsed = {};

for (var i = 0, iLen = json.length; i < iLen; i++) {
  // Assuming all we need are the name and a list
  var name;
  var list = [];

  for (var key in json[i]) {
    var value = json[i][key];

    // We need to hold on to the name or any services with value "y"
    if (key === "name") {
      name = value;
    } else if (value === "y") {
      list.push(key);
    }
  }

  // Add them to the parsed array however you'd like
  // I'm assuming you want to just list them in plain text
  parsed[name] = list.join(", ");
}

// List them on the web page
for (var key in parsed) {
  document.write(key + ": " + parsed[key] + "
");
}

That way you wind up with a display to the visitor of the services available and still keep an array around for further use if necessary.
Comment: perfect - thank u! yes, i meant iterate and parse as opposed to search... thanks so much!
Answer: jQuery.inArray()  Search for a specified value within an array and return its index (or -1 if not found).
http://api.jquery.com/jQuery.inArray/
Or
http://api.jquery.com/jQuery.each/

json jquery filter javascript array


Getting MIDI timecode/clock from MIXXX beat detection

Question: Does anyone on here know if mixxx can somehow generate MIDI timecode/clock information for jack from its detected beat of the current playback. As applications like ardour, qtraktor, seq24 and other sequencers can do?
Answer:
Mixxx includes a "MIDI for light" script that can send MIDI clock output for controlling lights or other MIDI synced hardware or software

See https://mixxx.org/wiki/doku.php/midi_clock_output


Is it possible to have more than one canvas on an HTML5 page?

Question: I was wondering if it is possible to have more than one canvas fully functioning on and HTML5 page. I have tried this a little while ago and it didn't work but I really didn't take time to think about how to do this and it ultimately failed. So is it possible to have more than one canvas fully functioning on an HTML5 page?
Comment: Yes, it possible to have more than one canvas fully functioning on an HTML5 page.
Comment: Why don't you try it by yourself and find the answer? It takes less than a minute to write a quick HTML test page, perhaps less than the time it took you to type your question here on SO.
Answer:

var cnv1 = document.getElementById("1");
var ctx1 = cnv1.getContext("2d");
var cnv2 = document.getElementById("2");
var ctx2 = cnv2.getContext("2d");

ctx1.fillStyle = "#FF0000";
ctx1.fillRect(0, 0, 50, 75);

ctx2.fillStyle = "#0000FF";
ctx2.fillRect(0, 0, 50, 75);
canvas {
  border: 2px solid black;
}
<canvas id="1" width="100px" height="100px">
Canvas doesn't work.
</canvas>
<canvas id="2" width="100px" height="100px">
Canvas doesn't work.
</canvas>
Comment: Would you mind rewording your answer as it comes across as a little ambiguous and a touch rude. We were all beginners at some point and have all asked naive questions.
Comment: Run the script in case you still don't believe
Comment: I see. Answer reworded


How to interpret scikit learn classification tree?

Question: I'm currently trying to work with scikit-learn classification tree.
I followed the example on iris dataset : http://scikit-learn.org/stable/modules/tree.html and everything is working fine.
I do not understand the final graph though. My problem is that values like [50, 0, 0] are not clear to me. Which values corresponds to which class ? I mean, if I shuffle the lines of the dataset, class 0,1,2 will not be in the same order so my tree values will change.
So does anybody knows how I could change the code in order to have the proper initials labels before the values (and if possible how to plot the proportions for each leaf ?)
Thanks,
PS : If you feel that this question is too scikit-learn based. Please edit it so it is sent to stack overflow instead.
Comment: This post might be relevant to your question:
http://stackoverflow.com/questions/23557545/how-to-explain-the-decision-tree-from-scikit-learn
Answer: The ordering of the classes in the value parameter should be deterministic and independent of the samples ordering in the training set.
Either the unique string name or integer identifier for each class is stored in the classes_ attribute of the DecisionTreeClassifier instance after a call to the fit method.
Comment: Ok, thanks. Still, do you know how i could access the tree structure so I can modify values to have proportions instead ? An other problem I have is that for a tree with of max_depth=5, values are plot only for the leafs at the bottom of the tree.
Comment: Then just have a look at the source code of the `export_graphviz` function and customize it to have it work the way you want.


How to route a reply packet to the device it coming from?

Question: I have an ipip tunnel, I want all the reply packets coming from ipip device also going through ipip. I have tried the following iptables rules
sysctl -w net.ipv4.ip_forward=1
ip rule add fwmark 1 lookup 100
ip route add default dev ipip0 table 100
iptables -t mangle -A PREROUTING -i ipip0 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -m mark --mark 0x1 -j CONNMARK --save-mark
iptables -t mangle -A OUTPUT -m connmark --mark 0x1 -j CONNMARK --restore-mark

I can see the prerouting rules working ok, but the output rule never triggered. I cannot figure out why.
Answer: Outbound packets are generated by host and has no packet mark but sure has connection's mark. So mark inbound packets, copy packet mark to connection mark, then mark new outbound packets back with connection's mark.
iptables -t mangle -A PREROUTING -i ipip0  -m conntrack --ctstate NEW -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -m mark --mark 0x1 -j CONNMARK --save-mark
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark

or shorter
iptables -t mangle -A PREROUTING -i ipip0  -m conntrack --ctstate NEW -j CONNMARK --set-mark 1
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark

and use fwmark selector in ip rule for policy based routing.
You should loose Strict Reverse Path checks for interfaces without default route
sysctl -w net.ipv4.conf.ipip0.rp_filter=2

RFC3704 Strict Reverse Path
For each inbound packet kernel checks "reverse path". Kernel  swapps inbound packet's source and destination and check via what interface it will be routed in reverse direction by consulting routing table. In this check kernel doesn't respect packet's mark (fwmark).
With rp_filter=1, if the return interface for a packet does not match the interface through which the packet entered, the packet will be dropped.
For example, a host has two interfaces:
eth0 with 192.168.37.3 and
eth1 with 192.168.39.5.
The default route is via eth0.
default via 192.168.37.1 dev eth0 onlink
192.168.37.0/24 dev eth0 proto kernel scope link src 192.168.37.3
192.168.39.0/24 dev eth1 proto kernel scope link src 192.168.39.5

According to the routing table, the return path for a packet with src ip 220.127.116.11 entering through eth1 will be through eth0.
eth0 and eth1 are different interfaces and  packet will be dropped at first routing decision, right after PREROUTING and before INPUT/FORWARD and never reach Local processes.
At the same time return path for a packet with src ip 192.168.39.45 entering through eth1 will be through eth1 so interfaces matched and packet's processing will continue.
Comment: If I remove ```-m connmark --mark 0x1``` filter, the output rule is triggered, but no effect at all, because it restores nothing, all triggered mark value is zero. If I use  ```iptables -t mangle -A OUTPUT -m connmark ! --mark 0x0 -j CONNMARK --restore-mark```,  ``` iptables -t mangle -L -v ```    still show nothing.
Comment: Is it a host or router? Why you enable net.ipv4.ip_forward?
Comment: Also `ip route add default dev ipip0 table 100` replace with `ip route add default via ip_of_tunnel_remout_end dev ipip0 table 100`
Comment: Try is it works with `sysctl -w net.ipv4.conf.ipip0.rp_filter=2`
Comment: Thanks for the replies  finally I use ```ip rule add from 10.10.11.3 lookup 100
ip route add table 100 to default dev ipip0 ``` to resolve the problem
Comment: I have tried to set rp_filter=0, It does not work.


Unity game view too dark on runtime

Question: I made a simple game menu in unity, but it's looking way too dark in the game view (and in runtime), I tried:
Window->Rendering->Lightning Settings and set the Environment Lightning's Source to color and Light Grey color, also checked the Auto Generate option in Lightmapping settings but nothing of the above worked, it still looks way too dark. Is there any fix for this?

Sorry for the small image in the first link but I think it's very noticeable the difference in the colors anyway.
Comment: I e seen similar in one of my projects. As an example on my pc and chrome my webgl game seems dark but dark like I meant it. If I load it on a Mac it's as dark as a badgers butt. Not all systems seem to work with the same lighting. It's therefore something we need to allow for
Comment: Is it a canvas image? What material is it using?
Comment: I can see that you are using only canvas nothing else, in this scene, This should not be the case where you need light for canvas. try using any directional light, that may solve your problem. ```Right-click on hierarchy->Light->Directional Light```
Comment: Is this by any chance occurring when you're switching between one scene and another?
Answer: In the scene tab, you have to check the little sun ☼ next to the "Shaded" drop down so as to see the real lightning of your scene.
Since you have no light in your scene (except the ambient one) your models look very dark. Add a directional light to your scene (GameObject > Light > Directional Light)
Comment: my environment lightning source is color, not skybox
Comment: does this help?
Comment: nope, looks exactly the same even with the directional light
Comment: also when i check that little sun the scene looks exactly the same as well
Comment: Gamma has a non-linear approach to light intensity and as such you may see inconsistent colors coming through. Some areas may be brighter, others darker. Linear, as the name implies does utilize a linear approach to light intensity and will result in more realistic looking lighting and colors. Some platforms are restricted to Gamma color space, while others can utilize Linear.  Below is an example of the same scene utilizing a different color space.
You can find this setting by going into  Edit > Project Settings > Player > Other Settings
Comment: did that help you?
Comment: yeah, it's fixed
Comment: what helped you or what have you done ?, and nice :)
Comment: my settings had the gamma color space, changing it to linear fixed it

Unity game view too dark on runtime


How to input values into database and collect the new id to store in php/html?

Question: I just can't figure out how to solve this problem using php to show on a web page.

When a user inputs values into "navn" and "kommentar" on my webpage. I will save these into two values. The "navn" value shall be saved into the database table "bruker" where "bruker_id" is auto increment. Then I want to get back which bruker_id the "navn" was saved under.

--> INSERT INTO bruker (navn) VALUES (inserted name from user);

Using the "bruker_id" and the "kommentar" I want to save into the table "kommentar" all the relevant information. Timestamp shall be current time and attraksjons_id is saved in a URL parameter called attraksjoner in Dreamweaver.

--> SELECT bruker.bruker_id FROM bruker WHERE bruker.navn = inserted name from user;
--> INSERT INTO attraksjon (bruker_id, attraksjons_id, kommentar, tidsstempel) VALUES (collected bruker_id from user, URL parameter attraksjoner from dreamweaver, comment collected from form, automated timestam);
Thank you in advance for your answer.
My database is as following:
Tablenavn: attraksjon
Primary key: attraksjons_id
attributes: attraksjons_navn, generell_info
---- Relation many-to-many table ----
Created many-to-many
table reisetips,
primary keys: bruker_id, attraksjons:id
attributes: kommentar, tidsstempel
--- Next tabel which is connected to attraksjon with many-to-many relation ----
Table name: kommentar
Primary keys: bruker_id
attributes: navn
My form consists of a text field for "navn" and one text area for "kommentar".
Comment: Assuming the MySQLi extension: http://www.php.net/manual/en/mysqli.insert-id.php
Answer: The Mysqli function "insert_id" can be helpfull in your case.
As described by the documentation : PHP Documentation
Another way to achieve this is by not using auto_increment and manage the ID yourself:
Before Inserting into the database your row, grab the last ID in the table and add one (For Exemple).
Pay attention that to avoid lock and other concurent write, you'll have to do this using  transaction and prepared statement.
Comment: Thank you for your comments, I will look into what you just wrote. The links are helpfull.
Answer: if you are using PDO then PDO::lastInsertId will do the work


What does it mean Offline support (7 day validity) in apple provision profile?

Question: When I tried to create iOS development provision profile I saw check box "Offline support (7 day validity)" Yes / No
What does it mean?
Comment: You "saw" it where?
Answer: This option means that you can build and run application at device with disabled internet.
If you switched this option off, you will see app verifictaion error, when you run app at real device.


Laravel whereIn return only item of each

Question: I have the following Eloquent query
Task::whereIn('user_id', [5,6,7,8])
            ->onlyActive()
            ->with('user')
            ->get();

which works perfect. The problem is that each user_id can have multiple Tasks, but i do only want to return one Task of each user_id.
Any ideas?
Answer: Easiest would be to define a new relationship on User model to get the latest Task - if that works for you
class User extends Model
{
    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    public function latestTask()
    {
        return $this->hasOne(Task::class)->latest();
    }
}

Then to query one active Task for each user
User::whereIn('id', [5,6,7,8])
    ->with(['latestTask' => function($query){
        $query->onlyActive();
    }])
    ->get();

Answer: why not use take()?
->with([
   'user' => function($user) {
       $user->tasks()->take(1);
    }
])


Angular 2 : Toggle Boolean based on a condition

Question: I have a search-bar and I want to show all the filtered names when the input value length is 2 or longer.
I managed to get the value.length out of the input field. Now I'm stuck.
At first I had done:
if (value.length >= 2){
  showNames: true;
}

Default showNames is false. And when the length was 2 or higher, it set to true. So, that's working. Only when the user erases the text, so the value.length is below 2 again, the boolean won't turn false again. I tried if else, but I know that's not correct in Angular 2.
<ion-searchbar (ionInput)="getNames($event)"></ion-searchbar>
<ion-list *ngIf="showNames">
   <ion-item *ngFor="let name of names">
     {{ name }}
   </ion-item>
</ion-list>

I know I can toggle a boolean from a button click, but I just want to toggle it from the length of a value.
*ngIf="value.length >= 2" doesn't work either, because I create the variable 'value' in my Typescript. So in my HTML it's not defined. And I don't want to use the big formula to calculate the length, that's why I created a variable.
How can I either

Pass the variable 'value' from my Typescript to my HTML so I can use the *ngIf="value.length > 2"?
OR do some kind of If / Else in my Typescript, so I can use a single boolean like *ngIf="showNames" in my HTML?
Answer: You can bind to the model of the searchbar like this:
<ion-searchbar [(ngModel)]="searchValue" (ionInput)="getNames($event)"></ion-searchbar>
<ion-list *ngIf="searchValue.length >= 2">
   <ion-item *ngFor="let name of names">
     {{ name }}
   </ion-item>
</ion-list>

And in your component define such a variable:
export class ComponentA {
    searchValue: string = "";

    // ...
}

Answer: You could make showNames a function and aim to do *ngIf="showNames()", or if it is that short perform the check right there: *ngIf="value.length >= 2"


Python cached decorator taking stale values from parameter

Question: I have a python function which is caching results based on the parameter passed. The issue is, fval() can return different values depending on other factors. But the test() is still sending me stale values. How do I ensure, the parameter v is getting the latest values from fval()
@cached(60*5)
def test(a,v=fval()):
  print "inside function"
  return a,v

r = test(2)
inside test function
print r
(2, 5)

print fval()
7

r = test(2) . #This time I am expecting v to be 7, but it isnt
print r
(2,5)

I am expecting r to print (2,7) instead. How do I ensure, latest values are being sent as a parameter to the cached function ?
Answer: Optional values are evaluated when the function itself is evaluated for all functions in Python. The usual solution is to provide a value that represents nothing, then check for it:
@cached(60*5)
def test(a, v=None):
    if v is None:
        v = fval()

    print "inside function"
    return a, v

If, after that, you also expect cached to act on the final value of fval() instead of the absence of a second argument, you'll need to do something like this:
@cached(60*5)
def _test(a, v):
    print "inside function"
    return a, v

def test(a, v=None):
    if v is None:
        v = fval()

    return _test(a, v)

Comment: Hey, I thought [your answer](https://stackoverflow.com/questions/195149/is-it-possible-to-sandbox-javascript-running-in-the-browser/24660713#24660713) was a useful, creative contribution that deserves to stay (it was a unique approach for a similar problem I had) - a bit odd, but a very interesting option to keep in mind, was it really unsalvageable for some reason?
Comment: @CertainPerformance: I no longer think it's a robust approach, now that I've seen some of the direction web workers are going, and haven't looked into whether it can still be a safe approach – so it's safer for me not to recommend it at all for now. Will try to find time to check it more thoroughly. (Even when I had the same problem at a job, my main choice of defense was a sandboxed iframe, not a web worker.)
Answer: It's because of this line:
def test(a,v=fval()):
In Python, default arguments are resolved once, at function definition.
You'll probably need to do something like this:
def test(a, v=None):
    if v is None:
        v = fval()

    # the rest here


RDBMS vs file system for file storage

Question: Are there any advantages of storing entire files in an RDBMS over storing the files in the file system with references to the file path in the RDBMS?
Which approach shall be faster? When do I choose one over the other? Does it matter which file system is in use? (say ext3)
I do not expect the files to change at all. The files may be json or xml or might be pdf (less likely). Also, there might be no need to refer to these files often. They are only meant for archival.
Thank you.
Comment: Thanks for the responses. I am convinced by arguments from both sides. Looks like this is going to be a tradeoff decision.
Answer: Given that the files are not expected to change, there is limited value in keeping the files in the DBMS.  The primary advantage of keeping files in the DBMS is that the DBMS knows how to manage transactions, but if the files won't change, then that advantage becomes minuscule.
Another advantage of storing files in the DBMS is that the database backup will contain the files; with the files stored separately, you have to backup the separate stash of files as well as the DBMS itself to keep all the data secure.
Another advantage of storing files in the DBMS is that the database can enforce more subtle controls on access to the files.
The primary advantage of storing the files in the file system is that it is easy (easier) to see what you've got.
A secondary advantage is that you can back up or manipulate the files outside the DBMS - though that is also a disadvantage from some points of view.
If the files are stored in blobs in the DBMS, then the normal SQL client software can retrieve the contents over a normal SQL connection.  If the SQL client software is not on the same machine as the DBMS and the files, then you have to worry about how clients do get hold of the file data.
Another advantage of separating the files from the DBMS is that the files could be stored off the DBMS machine.  On the other hand, that then complicates getting the files loaded 'into the DBMS'.

On the whole, given the issues outlined above, there seem to be some advantages with going with the 'files in DBMS' approach.  On the other hand, many people do go with 'files in file system' approach, and they survive.  It may be that their SQL clients are on the same machine as the DBMS, so the file transfer issues are not insurmountable, but that's the bit that has me most worried.
Answer: If file size is less than 1MB you may store them in the RDBMS, but otherwise consider storing them on the file system. See http://technet.microsoft.com/en-us/library/bb933993.aspx
Are there any advantages of storing entire files in an RDBMS over storing the files in the file system with references to the file path in the RDBMS?

if money etc. is no problem, then storing in RDBMS is advantageous, since you will get all the benefit of a RDBMS, plus no overhead of dereferencing the file from the reference stored in the db.

Which approach shall be faster?

RDBMS

When do I choose one over the other?

dictated by practical considerations. consider file system if file is > 1MB. Many shared-hosting providers do not enable FILESTREAM.

Does it matter which file system is in use?

I don't know about this.
Answer: To add to what Jonathan Leffler has written:
DBMS are not as efficient when dealing with BLOBs as when dealing with fixed-size objects, so we can say that DBMS don't "like" large objects. Also many DBMS store BLOBs outside of tables, in a separate storage.
If your goal is archiving purposes, it makes sense to store files separately for easier backup and retrieval. Also you can move files to some backend storage and make them "offline" to free space on the server (if needed).

RDBMS vs file system for file storage


Solaris crossover via fiber

Question: I have two Sun servers running Solaris 10.  Both have Emulex fiber channel cards.  I'd like to connect the two in a "crossover" fashion like you would copper ethernet & IPv4.  Point being I have a ZFS array attached to one that I'd like to share to the other via NFS over fiber channel.  These are for testing/development, so no budget for a switched fabric.
How would I go about setting this up?  I'd appreciate any experiences shared, doesn't have to be Solaris based.
Comment: My main concern is whether or not it'd actually work or if it'd damage the HBA's (kinda joking).  For example, old crossover between copper NIC's required a special CAT5 cable.  Any copper NIC in the last several years can do crossover automatically.  Never heard of doing this via fiber, which is why I'm asking if it'd actually work.
Comment: You'll need to get the Fibre Channel link layer up and running, and then configure IP on it.  I'm not sure that the latter is even possible on solaris; RFC 4338 is a PROPOSED standard for this, not sure it was ever ratified.  Alternately, you could use solaris's native fibre channel target provider, and export ZFS volumes as block devices.  That is not the same as doing NFS though; both hosts will not get access to filesystem-layer stuff, I don't believe.
Answer: Based on your comments your question is about how to go and connect the devices physically, and not about the config. In that case you just need to create a rollover cable from the normal fiber cable you probably have already. Most fiber cables have separate connectors (LC/SC) only held together by a small plastic clip or a small shell that you can take apart or bend enough to take the connectors out of it (this is perfectly safe, it's how they meant to work), reverse their order and reassemble the duplex connector. Now you have as crossover cable, tx goes to rx on the other side and vice versa.
This is common practice with patch panels.
There is at least 2 kinds of different adapter types.
FiberChannel and Ethernet. The main difference is encoding and protocols.
FC uses an 8/10 encoding, meaning that every 8 bits have a 2 bit parity attached, meaning that in case of a 10Gb HBA you get a 8GB FC link. It also uses FCP as the transport protocol (similar to TCP), it transports SCSI commands over Fibre Channel networks. And actually a whole different stack.
On the other hand, Ethernet NICs don't have this encoding, so a 10Gb NIC will bring up a 10Gbps link. You can't mix and match these adapters as they will not bring up a link.
FC over Ethernet does exist, it would use a mixed network which requires a type of hybrid adapter (called converged network adapters), which has both a NIC and a HBA, where the FC frames are encapsulated in Ethernet frames, on the end devices split and handled separately.
Comment: Cool thanks!  I'll try that.  Another question is, are all fiber cards made alike, or are some made for storage & others for network?
Comment: Added the explanation to the article as it doesn't fit here.

Solaris crossover via fiber


Como saber contar números repetidos em um vetor?

Question: Estou querendo saber se há quantos valores repetidos no vetor.
Aqui está o código que tentei, porém não tive sucesso.
#include <stdio.h>

int main(int argc, char** argv)
{
  int a, i, j, c = 0;
  scanf("%d", &a);
  int vetor[a];
  for(i = 0; i < a; i++)
  {
     scanf("%d", &vetor[i]);
  }
  for(i = 0; i < a; i++)
  {
     for(j = 0; j < a; j++)
     {
         if(vetor[i] == vetor[j])
         {
            c++;
         }
     }
 }
   printf("%d\n",c);
   return 0;
}

Comment: Recomendo que use nomes mais descritivos nas suas variáveis. `i` e `j` até que são auto-explicativos devido a convenções, mas `a` poderia se chamar `quantidadeDeEntradas` e `c` poderia se chamar `repeticoesEncontradas`, por exemplo. Fica mais fácil pra quem está lendo seu código conseguir te ajudar. Além disso, explique melhor o seu problema. Dê exemplos de entradas e saídas esperadas correspondentes.
Answer: Do jeito que você colocou, existirão a casos onde i e j são iguais e portanto vetor[i] e vetor[j] são iguais, afinal de contas comparar uma posição do vetor com ela mesma sempre vai resultar em elementos iguais sendo comparados. Esse caso não é interessante e não deveria ser contado.
Outra coisa, é que contando i e j, ambos de 0 até a - 1, se na posição 3 e na posição 5 houver uma repetição, ela será contada duas vezes, uma com i = 3 e j = 5 e outra com i = 5 e j = 3.
Logo, se existem x repetições, o seu programa está dando o valor de 2 * x + a.
A solução para ambos os problemas é simplesmente trocar o j = 0 do for interno por j = i + 1.
Veja o código corrigido:
#include <stdio.h>

int main(int argc, char** argv) {
    int a, i, j, c = 0;
    scanf("%d", &a);
    int vetor[a];
    for (i = 0; i < a; i++) {
        scanf("%d", &vetor[i]);
    }
    for (i = 0; i < a; i++) {
        for (j = i + 1; j < a; j++) {
            if (vetor[i] == vetor[j]) {
                c++;
            }
        }
    }
    printf("%d\n", c);
    return 0;
}

Veja aqui funcionando no ideone.


SPIAT package Error in define_celltypes(formatted_image, phenotypes = c("panCK+", "CD8+", : could not find function "define_celltypes"

Question: I use the SPIAT package (https://cancer-evolution.github.io/SPIAT/articles/introduction.html) to analyze the spatial distribution patterns of tumor and immune cells in human tissue samples. THe package is really useful, however in one of the functions the package provides I get an error message: "Error in define_celltypes(formatted_image, phenotypes = c("panCK+", "CD8+",  :
could not find function "define_celltypes".
I try to specifying each Phenotype using the so-called define_celltypes function which can be used to add a column indicating the cell type. By default the column is called Cell.Type. The difference between Phenotype and Cell.Type is that phenotype represents all the markers present on the cell but Cell.Type is the identity of the cell.
Here is the code and the R file with the txt.file.
https://drive.google.com/drive/folders/1lX9Sprd3IDxz08AcJnZ7WT4UE96MWZCC?usp=sharing
Your help would be much needed! Thank you.
> phenotypes = c("panCK+", "CD8+", "FoxP3+", "CD163+", "PD_L1+")
> names = c("Tumour", "TILs", "Tregs", "Macrophages", "PD-L1+ cells")
> #SPIAT define_celltypes can be used to add a column indicating the cell type.
> #By default the column is called Cell.Type. The difference between Phenotype and Cell.
> #Type is that phenotype represents all the markers present on the cell but Cell.Type is the identity of the cell.
> formatted_image <- define_celltypes(formatted_image,
+                                     phenotypes = c("panCK+", "CD8+", "FoxP3+", "CD163+", "PD_L1+"),
+                                     names = c("Tumour", "TILs", "Tregs", "Macrophages", "PD-L1+ cells"),
+                                     column.name = "Cell.Type")
Error in define_celltypes(formatted_image, phenotypes = c("panCK+", "CD8+",  :
  could not find function "define_celltypes"```

Answer: Thank you for raising the issue. It seems that the version of our vignette is ahead of the package itself, which means define_celltypes is not available yet.
However, we have submitted the new version (0.99.0) of SPIAT to Bioconductor. It will be included in the Bioconductor devel branch soon. We will update the answer when the new version and new functions are available.
Thank you!
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31450987)


How to interpret error measures?

Question: I am running the classify in Weka for a certain dataset and I've noticed that if I'm trying to predict a nominal value the output specifically shows the correctly and incorrectly predicted values. However, now I'm running it for a numerical attribute and the output is:
<code>Correlation coefficient                 0.3305
Mean absolute error                     11.6268
Root mean squared error                 46.8547
Relative absolute error                 89.2645 %
Root relative squared error             94.3886 %
Total Number of Instances               36441
</code>
How do I interpret this? I've tried googling each notion but I don't understand much since statistics is not at all in my field of expertise. I would greatly appreciate an ELI5 type of answer in terms of statistics.
Answer: Let's denote the true value of interest as $\theta$ and the value estimated using some algorithm as $\hat{\theta}$.
Correlation tells you how much $\theta$ and $\hat{\theta}$ are related. It gives values between $-1$ and $1$, where $0$ is no relation, $1$ is very strong, linear relation and $-1$ is an inverse linear relation (i.e. bigger values of $\theta$ indicate smaller values of $\hat{\theta}$, or vice versa). Below you'll find an illustrated example of correlation.

(source: http://www.mathsisfun.com/data/correlation.html)
Mean absolute error is:
$$\mathrm{MAE} = \frac{1}{N} \sum^N_{i=1} | \hat{\theta}_i - \theta_i | $$
Root mean square error is:
$$ \mathrm{RMSE} = \sqrt{ \frac{1}{N} \sum^N_{i=1} \left( \hat{\theta}_i - \theta_i \right)^2 } $$
Relative absolute error:
$$ \mathrm{ RAE} = \frac{ \sum^N_{i=1} | \hat{\theta}_i - \theta_i | } {  \sum^N_{i=1} | \overline{\theta} - \theta_i | } $$
where $\overline{\theta}$ is a mean value of $\theta$.
Root relative squared error:
$$ \mathrm{ RRSE }= \sqrt{ \frac{ \sum^N_{i=1} \left( \hat{\theta}_i - \theta_i \right)^2 } {  \sum^N_{i=1} \left( \overline{\theta} - \theta_i \right)^2 }} $$
As you see, all the statistics compare true values to their estimates, but do it in a slightly different way. They all tell you "how far away" are your estimated values from the true value of $\theta$. Sometimes square roots are used and sometimes absolute values - this is because when using square roots the extreme values have more influence on the result (see Why square the difference instead of taking the absolute value in standard deviation? or on Mathoverflow).
In $ \mathrm{ MAE}$ and $ \mathrm{ RMSE}$ you simply look at the "average difference" between those two values - so you interpret them comparing to the scale of your valiable, (i.e. $ \mathrm{ MSE}$ of 1 point is a difference of 1 point of $\theta$ between $\hat{\theta}$ and $\theta$).
In $ \mathrm{ RAE}$ and $ \mathrm{ RRSE}$ you divide those differences by the variation of $\theta$ so they have a scale from 0 to 1 and if you multiply this value by 100 you get similarity in 0-100 scale (i.e. percentage). The values of $\sum(\overline{\theta} - \theta_i)^2$ or $\sum|\overline{\theta} - \theta_i|$ tell you how much $\theta$ differs from it's mean value - so you could tell that it is about how much $\theta$ differs from itself (compare to variance). Because of that the measures are named "relative" - they give you result related to the scale of $\theta$.
Check also those slides.
Comment: You should choose the model with bigger correlation and smaller error estimates. As you see, there are multiple measures of model performance (and those are only few them) and sometimes they give different answers. It is almost never the "yes/no" kind of answer you get. The task of model selection would get easier if you catch up with theory, you can check for example [those lectures](http://www.r-bloggers.com/in-depth-introduction-to-machine-learning-in-15-hours-of-expert-videos/).
Comment: @Tim Mean absolute error should probably be abbreviated as MAE:)
Comment: @MewX What kind of references you are looking for? It is basically a rescaled RMSE. There is not much to say about it...
Comment: Thank you for your explanation!
I am trying to evaluate the performance of various algorithms. So for example, if I get this other output (Correlation: 0.3044, MAE: 10.832, MSE: 47.2971, RAE: 83.163%, RSE: 95.2797%) and I try to compare it to the first one, which one could I say performed better?
Comment: Thank you very much! I went ahead and marked your reply as the answer because you've helped me plenty!
Comment: @Antoine 23 upvotes and no-one noticed...
Comment: Could you please provide more information about RRSE? I would like to cite this formula but I was unable to find more information about it. Thanks!

How to interpret error measures?


Why would after a finite number of steps we will end up with disjoint sets?

Question: I know this question will get a lot of downvotes but pardon me because after thinking about it in many ways, I can't see why I would end up with disjoint sets after a finite number of steps. Now I state my problem.
Let $(\Omega,\Sigma,\mu)$ be a measured space. Let $A_1,A_2,A_3,...,A_n\in\Sigma$ and let $c_i,c_2,c_3,...,c_n\in(0,\infty)$. Define a quantity $h$ as
$$h=\sum_{i=1}^{n}c_i\mu(A_i).$$
$\textbf{Step 1}$
Let's find two sets $A_j,A_k\ (j\neq k)$ such that $A_j\cap A_k\neq\emptyset$. Then $A_j=A_j\setminus A_k\cup (A_j\cap A_k)$, $A_k=A_k\setminus A_j\cup (A_j\cap A_k)$. It is obvious that $A_j\setminus A_k,\ A_k\setminus A_j,\ A_j\cap A_k\in\Sigma$.
$\textbf{Step 2}$
Rewrite the quantity $h$ as
$$h=\sum_{i\in [n]\setminus\{j,k\}}c_i\mu(A_i)+ c_j\mu(A_j\setminus A_k)+ c_k\mu(A_k\setminus A_j)+ (c_j+c_k)\mu(A_j\cap A_k).$$
$\textbf{Repeat Step 1 and Step 2}$
Now, my question is, how can I prove that after a finite number of steps, we will end up $h$ in the form
$$h=\sum_{i=1}^{m}d_i\mu(B_i),$$
where $d_i\in(0,\infty)$ and $\forall p,q\in[m]\ (p\neq q)$ we have that $B_p\cap B_q=\emptyset.$
Can somebody prove it by contradiction or any other method?
Comment: There is only a finite number of patterns of the form "belong to the sets $A_{i_1},\ldots,A_{i_s}$ but not to the remaining ones".  So $m=2^n$ is sufficient.
Comment: @MichalAdamaszek Can you elaborate on your answer?
Comment: Look at all the regions in the Venn diagram of the $A_i$s.
Comment: @MichalAdamaszek ; I can't visualize the Venn diagram of more than three sets.
Comment: I can't either. Start with 2, 3 sets, understand what is going on, and generalize.
Answer: Here is my Venn diagram suggestion from the comments written out more formally
$$\sum_{i=1,\ldots,n}c_i \mu(A_i) = \sum_{I\subseteq\{1,\ldots,n\}}\left(\left(\sum_{i\in I}c_i\right) \cdot \mu\left(\bigcap_{i\in I}A_i\setminus\bigcup_{j\not\in I}A_j\right)\right). $$


For which set of values of predictors will my response variable be guaranteed to equal a certain level

Question: For which set of values of predictors (numerical) will my response variable (factor) be guaranteed to equal a certain level (using Random Forest)
I am going to explain it on base of the iris dataset:
Goal --> I need to get as many species of setosa as possible
The way --> i must find the best (representative) combination of: "Sepal.Length","Sepal.Width","Petal.Length","Petal.Width" values, which  identify only setosa and not any other species.
I would appreciate any help as i cannot find any hint or way how to handle this problem.
--> mean of the parameters set in the group of setosa is not sufficient! (as in my original dataset the difference between groups are not that clear!)
To get a bit background of my real problem is that i have different temperature sensors at different points in the production line, and i must identify which combination of those temperatures leads to good quality product, and which combination leads to bad quality product, i think it is very simple to understand. We must find best combination of temperatures and try to achieve it at the production.
[UPDATE]
I have found a similar question on cross validated (but my target value is a factor, not numeric as in this case, but the main princip is the same:
How would I be able to find for which values of inputs do i get the setosa target variable
), however it has not been answered.
Comment: What does it mean to "get" species of setosa? If you label all of your data "setosa," you're guaranteed to "get" all of the setosa in it (and a lot of non-setosa also). So it seems more sensible to "get" setosa *and only* setosa, which sounds like a classification problem, which is an enormous field. I recommend you start by reading *Elements of Statistical Learning*.
Comment: Exactly i wanna "get" setosa and "only" setosa. I have tried already classification using RF, but i have no idea how i can get the best representative combination of values and not only predicition. I got really stuck at this point
Comment: I think you are trying to get the ranges of values in the variables for which a typical outcome would be Species=setosa. Correct? In this case a descriptive statistics with confidence intervals would maybe suffice?
Comment: The classification model aside, unless you only have one predictor, there might be/are going to be multiple predictor value combinations which result in a certain classification. For example, a high value on predictor 1 on its own might result in (high probability of) class 1, while moderate to high values on predictors 2 and 4 might also result in class 1. My question/suggestion: do you want to find the single least 'errorprone' classification rule, or would you also want to combine such predictorpatterns into a classification rule?
Comment: Well i do have more then one predictor (my original dataset has at least 3 predictors), therefore i need combination of all of them together
Answer: It sounds like you're looking for the term classification. That entire field deals with models trying to predict a class (setosa or not) from some features.
Comment: Exactly i am looking for classification (i already did it with RF), however what i get from it is only predicition of the `Species` and i need to find the representative values set (the best combination) of parameters which lead to predicition of one of the Species, in my case it is setosa.As for example values of:   Sepal.Length **5.1**,  Sepal.Width **3.0**, Petal.Length **1.4**,  Petal.Width **0.2**  are most representative of Species Setosa.
Comment: Then you should search for answers (or post a new question) specifically about the method you used, because this process is very different for different approaches. Also, you will need to define your loss function - i.e. what do you mean by "most representative"? Identify only setosa? Identify as many setosa as possible within some predictor bin? Make least classification errors?..


Inverter Pilha Dinâmica

Question: alguém poderia me auxiliar com essa pilha?
O objetivo é criar uma função que inverta os valores da pilha, tentei fazer isso utilização a função Inverter() do código abaixo, porém ela não está funcionando, quando executo simplesmente encerra o código. Caso alguém tenha alguma ideia, posso estar fazendo a alocação errada...
#include <stdio.h>
#include <stdlib.h>

typedef struct elemento{
    int valor;
    struct Elemento *anterior;
} Elemento;

typedef struct pilha{
    struct Elemento *topo;
    int tam;
} Pilha;

Pilha *criaPilha(){
    Pilha *p = (Pilha*)malloc(sizeof(Pilha));
    p->topo = NULL;
    p->tam = 0;
    return p;
}
int vazia(Pilha *p){
    if(p->topo == NULL){
    return -1;
    } else {
    return 2;
    }
}
void empilha(Pilha * p, int v){
Elemento *e = (Elemento*)malloc(sizeof(Elemento));
e->valor = v;
    if(vazia(p) == 2){
        e->anterior = p->topo;
    }
    p->topo = e;
    p->tam++;
}
int desempilha(Pilha *p){
    int val;
    if(vazia(p) == 2){
        Elemento *aux;
        aux = p->topo; //Crio uma variável para ajudar a acessar o elemento anterior armazenado no topo;
        val = aux->valor;
        p->topo = aux->anterior; //Topo passa a ser o elemento anterior
        p->tam--;
        free(aux);
        return val;
    }
}

void maiorMenorMedia(Pilha *p, int *maior, int *media,int *menor){
int r = 0, cont = 0;
int soma = 0;
int menorc = 99999;
int maiorc = -99999;
while(p->topo != NULL){
    r = desempilha(p);
    if(r > maiorc){
        maiorc = r;
    }
    if(r < menorc){
        menorc = r;
    }
    cont++;
    soma += r;
}
*maior = maiorc;
*media = (soma/cont);
*menor = menorc;
}

int maisElementos(Pilha *a, Pilha *b){
if(a->tam > b->tam){
    return 1;
} else {
    return 0;
}
}
Pilha * inverter(Pilha *pilha){
    int value;
    Pilha * aux = criaPilha();
    while(pilha->topo != 0){
        value = desempilha(pilha);
        empilha(aux, value);
    }
    return aux;
}

int main(int argc, char** argv) {
    Pilha *pteste = criaPilha();
    empilha(pteste, 15);
    empilha(pteste, 16);
    empilha(pteste, 17);
    printf("%d\n", pteste->tam);

    int maior, media, menor;

    maiorMenorMedia(pteste, &maior, &media, &menor);
    printf("Maior: %d\n", maior);
    printf("menor: %d\n", menor);
    printf("media: %d\n", media);

Pilha *a = criaPilha();
Pilha *b = criaPilha();
empilha(a, 15);
empilha(a, 16);
empilha(b, 15);
empilha(b, 16);
empilha(b, 17);
empilha(b, 18);

if(maisElementos(a,b) == 1){
    printf("Pilha A tem mais elementos\n");
}else{
    printf("Pilha B tem mais elementos\n");
}

Pilha *z = criaPilha();
z = inverter(b);
int x = 0;
x = desempilha(z);
printf("%d", x);
}

Comment: O resto das funções estão bem? Testei e há um problema qualquer na função desempilha
Answer: Tem vários pormenores que não estão certos embora a lógica em si esteja certa. Aconselho sempre a olhar com muita atenção para os avisos do compilador pois quase sempre são erros e coisas que deve corrigir.

Na definição da estrutura elemento:
typedef struct elemento{
    int valor;
    struct Elemento *anterior;
    //     ^---
} Elemento;

O typedef só é finalizado no fim da instrução logo não pode usar o nome definido por ele no meio da estrutura. Para alem disso o typedef é feito para poder utilizar apenas Elemento e não struct Elemento. Por isso o correto é:
typedef struct elemento{
    int valor;
    struct elemento *anterior;
    //     ^---
} Elemento;

Logo na estrutura seguinte tem o mesmo problema:
typedef struct pilha {
    struct Elemento *topo;
//      ^-----^
    int tam;
} Pilha;

Em que struct Elemento deve ser apenas Elemento pois esse sim corresponde ao typedef que fez anteriormente.
O empilha não coloca o ultimo elemento a apontar para NULL e por isso o teste se a pilha está fazia na função vazia, o if(p->topo == NULL) { não funciona como esperado e começa a aceder a valores fora da memoria que declarou.
Para corrigir basta afetar o e->anterior = NULL quando é o primeiro elemento da Pilha:
void empilha(Pilha * p, int v) {
    Elemento *e = (Elemento*)malloc(sizeof(Elemento));
    e->valor = v;
    if(vazia(p) == 2) {
        e->anterior = p->topo;
    }
    else { //se está vazia porque é o primeiro
        e->anterior = NULL; //mete esse a apontar para NULL
    }
    p->topo = e;
    p->tam++;
}

Tem muitas outras coisas a melhorar mas deixo apenas as mais importantes:

Evite utilizar números soltos (mágicos) tal como if (vazia(p) == 2). Isto torna-se bem difícil de ler e fácil de errar. Pode utilizar #define para definir constantes que facilita.
Defina retornos das funções para todos os caminhos possíveis. Na sua função desempilha caso a pilha esteja vazia não tem nenhum retorno especificado.

Inverter Pilha Dinâmica


Keras: Combining data generators to handle image + text

Question: I am working on a multilabel classification model where I am trying to combine two models, a CNN and a text-classifier into one model using Keras and train them together, like so:
#cnn_model is a vgg16 model

#text_model looks as follows:
### takes the vectorized text as input
text_model = Sequential()
text_model .add(Dense(vec_size, input_shape=(vec_size,), name='aux_input'))

## merging both models
merged = Merge([cnn_model, text_model], mode='concat')

### final_model takes the combined models and adds a sofmax classifier to it
final_model = Sequential()
final_model.add(merged)
final_model.add(Dense(n_classes, activation='softmax'))

As such, I am working with an ImageDataGenerator to process the images and the respective labels.
For the images I am using a custom helper function that reads images into the model via paths provided by pandas dataframes - one for training (df_train) and one for validation (df_validation). The dataframes also provide the final labels for the model in the "label_vec" column:
# From https://github.com/keras-team/keras/issues/5152
def flow_from_dataframe(img_data_gen, in_df, path_col, y_col, **dflow_args):
    base_dir = os.path.dirname(in_df[path_col].values[0])
    print('## Ignore next message from keras, values are replaced anyways')
    df_gen = img_data_gen.flow_from_directory(base_dir, class_mode = 'sparse', **dflow_args)
    df_gen.filenames = in_df[path_col].values
    df_gen.classes = numpy.stack(in_df[y_col].values)
    df_gen.samples = in_df.shape[0]
    df_gen.n = in_df.shape[0]
    df_gen._set_index_array()
    df_gen.directory = '' # since we have the full path
    print('Reinserting dataframe: {} images'.format(in_df.shape[0]))
    return df_gen

from keras.applications.vgg16 import preprocess_input

train_datagen = keras.preprocessing.image.ImageDataGenerator(preprocessing_function=preprocess_input)                                                  horizontal_flip=True)
validation_datagen = keras.preprocessing.image.ImageDataGenerator(preprocessing_function=preprocess_input)#rescale=1./255)

train_generator = flow_from_dataframe(train_datagen, df_train,
                                                     path_col = 'filename',
                                                     y_col = 'label_vec',

                                                    target_size=(224, 224), batch_size=128, shuffle=False)
validation_generator = flow_from_dataframe(validation_datagen, df_validation,
                                                     path_col = 'filename',
                                                     y_col = 'label_vec',
                                                         target_size=(224, 224), batch_size=64, shuffle=False)

Now I am trying to provide my one-hot-encoded text vectors (i.e. [0,0,0,1,0,0]) to the model, which are also stored in a pandas dataframe.
Since my train_generator provides me with the image and label data, I am now looking for a solution to combine this generator with a generator which allows me to additionally feed the respective text-vector
Answer: You might want to consider writing your own generator (making use of Keras' Sequence object to allow for multiprocessing) instead of modifying the ImageDataGenerator code. From the Keras docs:
class CIFAR10Sequence(Sequence):

    def __init__(self, x_set, y_set, batch_size):
        self.x, self.y = x_set, y_set
        self.batch_size = batch_size

    def __len__(self):
        return int(np.ceil(len(self.x) / float(self.batch_size)))

    def __getitem__(self, idx):
        batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
        batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]

        return np.array([
            resize(imread(file_name), (200, 200))
               for file_name in batch_x]), np.array(batch_y)

You could have your labels, paths to the images, and paths to the text files in a single pandas dataframe and modify the __getitem__ method from above to have your generator yield all three of them simultaneously: one list of numpy arraysX which contains all the inputs, one numpy array Y which contains the outputs.
Comment: See [here](https://github.com/sdcubber/Keras-Sequence-boilerplate/blob/master/Keras-Sequence.ipynb) and [here](https://blog.ml6.eu/training-and-serving-ml-models-with-tf-keras-3d29b41e066c) for some boilerplate code.


Android studio : leave my one-line methods as i've typed them when reformating code

Question: Is there an option in android studio to leave one-line method when reformatting code ? For example, for a simple getter, i prefer this style of coding:
public int getPosition() {return mPosition;}

But, when i reformat the code, this method is changed like this:
public int getPosition() {
    return mPosition;
 }

Answer: Finally, I've found the solution.

Go to File > Settings > Editor > Code Style > Java
Click the Wrapping and Braces tab
Find the Keep when reformatting section
Turn on the Simple methods in one line checkbox

And it just go fine!
Comment: Kudos for giving the solution to your own problem. ("Nervermind I found a solution.")


ZFS SAS/SATA controller recommendations

Question: I've been working with OpenSolaris and ZFS for 6 months, primarily on a Sun Fire x4540 and standard Dell and HP hardware. One downside to standard Perc and HP Smart Array controllers is that they do not have a true "passthrough" JBOD mode to present individual disks to ZFS.
One can configure multiple RAID 0 arrays and get them working in ZFS, but it impacts hotswap capabilities (thus requiring a reboot upon disk failure/replacement). I'm curious as to what SAS/SATA controllers are recommended for home-brewed ZFS storage solutions. In addition, what effect does battery-backed write cache (BBWC) have in ZFS storage?
Comment: Battery-backed caches are tricky.  Sort of controller dependent since ZFS forces a sync() after every write last I looked to ensure consistency, which can badly slow down some controllers which don't ignore the command.  Of course, if you put your ZIL on a SSD or spare drive, this is not a problem.
Comment: HP SmartArray controllers can quite easily work in 'pass-through' mode, in fact that's their default - just don't create any array sets.
Comment: Really? So the drives would still be visible in Solaris if I don't configure any arrays/logical drives?
Comment: To clarify, HP controllers are not capable of the SCSI passthrough needed for proper ZFS operation.
Answer: I recommend a (almost) any SAS/RAID controller that uses the LSI 1068E SAS chip (PCI-E) and supports Initiator-Target mode (JBOD mode).  This does not include MegaRAID controllers.
I use the a 3442E and Dell 6/iR.

LSI SAS 3442E (4 internal - SFF-8484, 4 external - SFF-8470)
LSI SAS 3081E (8 internal - SFF-8087)
LSI SAS 3041E (4 internal - SATA)
LSI SAS 3801E (8 external )
LSI SAS 9212-4i4e (4 internal - SATA, 4 external SFF-8088)
LSI SAS 9211-8i (8 internal - SFF-8087)

You get the idea.
Also I recommend Dell SAS Controllers which are cheap on ebay.

Dell SAS 5/iR - (4 internal ports)
Dell SAS 6/iR - (8 internal ports)
Dell H200

Not
- Dell PERC 5/E
- Dell PERC 5/I
- Dell PERC 6/E
- Dell PERC 6/I
Why not MegaRAID?
These controllers do not support a non-RAID, JBOD mode.  They cannot present disks to the host directly.  Each disk must first be included in a Logical disk.  You can create a single logical volume for each disk you have and give this to ZFS. Performance should be equivalent.  However, it means putting header information onto the physical disk.  If your controller fails, you must use another MegaRAID, configured exactly the same.  And there is not guarantee that another SAS or SATA controller will see the data correctly and present the volumes in a way that the zpool can be correctly constructed.
Comment: I just converted to the LSI SAS 9211-4i and 8i to replace the P410 controllers in the HP ProLiant DL180 G6. It works wonderfully.
Comment: nicholasv, did you flash the Dell 6/iR with LSI firmware so you can present the disks as jbod to zfs? I am looking at buying a couple of these, but it seems the Dell 6/iR doesn't support jbod mode with the normal firmware.
Comment: @PeterValadez You don't actually have enough Rep on [SF] to post comments on just any Question. You need 50 Rep for that. Regardless, [SF] **is not** a forum; unless your directly answering the Question it's Off-Topic; and specific product recommendations are OT as well.
Answer: The recommened controller is anything using the LSI SAS 1068E chipset. It's what Sun uses, so has the best support. As phresus mentions, the ASOC-USAS-L8i is a good cheap card that uses it. Battery-backed write cache helps performance, particularly for NFS. Another alternative is to use an SSD for the ZFS Intent Log, but only some have capacitors to ensure data is written after power-loss. For large read workloads, a MLC SSD can be used as L2ARC to supplement RAM caching.
Comment: In Europe the easiest to get card is propably Intel sasuc8i, which is ~130€ in most German web stores.
Answer: I would highly recommend you check out the Guide to Building a Media Storage Server thread at AVS Forum here. There is a wealth of knowledge in there comparing/contrasting various storage methods including ZFS. From the thread it seems like the Supermicro aoc-sat2-mv8 or newer aoc-saslp-mv8 are currently the most economical solutions for JBOD.
Comment: I'm fairly sure the AOC-SASLP-MV8 isn't supported in Solaris.  The AOC-USAS-L8i is recommended instead (albeit you don't get a mounting bracket, and it blocks the slot above it -- thanks, SuperMicro).
Answer: For 6Gb/s I have been testing the LSI 9211-4i and it works flawlessly.
If you need more ports or external JBOD connectivity, see the other 9xxx models.
Do not use a RAID controller for ZFS.
Answer: Note that answer to this question changes with time (with new hardware and/or driver etc) - read the date of any post before making your order! :)
This blog post (Written in May 2010) is one of the most comprehensive listing I have seen which listed what works under Solaris, Linux and FreeBSD.
Answer: You can use this Supermicro SATA JBOD card AOC-SAT2-MV8 to use ZFS on Solaris.

ZFS SAS/SATA controller recommendations


I have a column CHANGE_DATE in my table which is a date with timestamp, how can I fetch rows where CHANGE_DATE is equal to yesterdays date

Question: I have a CHANGE_DATE column ( 2019-06-06T18:30:00.000+00:00") in a table USER_DETAILS, I have to fetch rows where CHANGE_DATE is yesterdays date. Can you please help me with the SQL query
Comment: Does this column datatype is VARCHAR?
Comment: Its datatype is DATE
Comment: Its oracle database not MySQL
Answer: Try this:
<code>select * from USER_DETAILS where date(CHANGE_DATE)=date_add(current_date,interval -1 day);
</code>