Aplicação apresentando este erro: Error parsing data org.json.JSONException

Question: Estava tentando fazer um aplicação para android com conexao ao MySQL através de webservice e andou dando uns problemas, so que consegui resolver, mas apareceu esse, quando tento ver os produtos cadastrado no meu app minha LogCat aparece isso:

02-19 17:50:32.458: I/Choreographer(1033): Skipped 52 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:34.225: I/Choreographer(1033): Skipped 160 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:36.091: I/Choreographer(1033): Skipped 201 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:38.033: I/Choreographer(1033): Skipped 210 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:38.525: I/Choreographer(1033): Skipped 52 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:38.961: I/Choreographer(1033): Skipped 45 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:40.260: E/JSON Parser(1033): Error parsing data org.json.JSONException: Value (ViewRootImpl.java:363)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.Dialog.show(Dialog.java:298)
  02-19 17:50:52.076: E/WindowManager(1033):  at br.com.products.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.os.AsyncTask.execute(AsyncTask.java:535)
  02-19 17:50:52.076: E/WindowManager(1033):  at br.com.products.AllProductsActivity.onCreate(AllProductsActivity.java:57)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.Activity.performCreate(Activity.java:5933)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.ActivityThread.access$800(ActivityThread.java:144)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.os.Handler.dispatchMessage(Handler.java:102)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.os.Looper.loop(Looper.java:135)
  02-19 17:50:52.076: E/WindowManager(1033):  at android.app.ActivityThread.main(ActivityThread.java:5221)
  02-19 17:50:52.076: E/WindowManager(1033):  at java.lang.reflect.Method.invoke(Native Method)
  02-19 17:50:52.076: E/WindowManager(1033):  at java.lang.reflect.Method.invoke(Method.java:372)
  02-19 17:50:52.076: E/WindowManager(1033):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
  02-19 17:50:52.076: E/WindowManager(1033):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
  02-19 17:50:52.088: I/Choreographer(1033): Skipped 91 frames!  The application may be doing too much work on its main thread.
  02-19 17:50:52.417: I/Choreographer(1033): Skipped 33 frames!  The application may be doing too much work on its main thread.

OBS: Desculpe minha LogCat estar desajeitada, se alguem puder editar agradeço...
Minha Classe que gerencia a busca:
AllProductsActivity.java
package br.com.products;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://XXX.XXX.X.X/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_products);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

A Classe responsavel por tratar do JSON é essa:
JSONParser.java
package br.com.products;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Meu Arquivo PHP:
get_all_products.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

Alguem poderia me ajudar?
Answer: Você tem que especificar mais os seus erros sobre o que se fala em try/catch:
...
// try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
...

O seu erro está na obtenção do Json através da url_all_products. Tudo está ok no seu código java. Verifique seu .php. ao que parece o erro está no echo do Json encode. O erro pode está:

Na obtenção do GET.

O CORRETO ERA VOCÊ TER ESTE TIPO DE OBTENÇÃO:

Implementar Requisições HTTP POST e GET no Android
Comment: Tem certeza que esse é o problema, pq no erro diz que nao esta retornando um valor valido JSON...
Comment: Este é um dos erros, dos diversos. Em nenhuma parte do seu código contém erros  sobre sua pergunta, mas sim erros sobre o seu LOG. Caso você coloque o código que trate do Json, aí sim eu poderia entender melhor E EDITAR A RESPOSTA.
Comment: fiz as aletrações e nao ouve nenhuma mudança... editei a pergunta e coloquei a classe que trata do json
Comment: adicionei meu arquivo php... consegue ver onde esta o erro?
Comment: Edite a resposta.
Comment: Consegue me ajudar @Lollipop?
Comment: Mano você está enviando os dados via GET, mas no seu .php, NÃO HÁ NADA QUE O RECEBA.
Comment: Pode me ajudar a resolver, não sei mecher com php, este código peguei seguindo um tutorial
Comment: Complicado lhe ajudar se você não sabe o que ta fazendo no PHP, pois nem eu sei o que você quer  '-'
Comment: A unica coisa que eu quero é aprender a mecher com android-mysql... ai estava seguindo este tutorial => http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
Comment: o engraçado que mesmo a aplicação no android estar parando de funcionar depois de voce tentar criar o produto, no meu mysql ele cria... entao eu acho que o problema é na hora de retornar o valor, ele nao esta vindo como um valor valido JSON, saberia como converter ou algo do tipo? eu estava lendo mais e vi que preciso retirar os colchetes da resposta ("[]"), como eu faria isso? isto provavelmente é a causa..
Comment: se possivel de uma olhada neste topico => http://stackoverflow.com/questions/18147667/i-am-getting-error-parsing-data-org-json-jsonexception
Comment: Exatamente o quis dizer, mano. O problema está no retorno. Você está quase lá.
Comment: E.e, eu preciso descobrir uma forma de coloca os conchetes depois dos {} dessa resposta: {"products":[{"pid":"1","name":"iPhone","price":"4500.00","created_at":"2015-02-18 20:02:20","updated_at":null},{"pid":"2","name":"Motorola Moto G 2014","price":"800.00","created_at":"2015-02-19 18:56:46","updated_at":null}],"success":1}
Comment: alguem pode me ajudar?


What is the bait and switch method in Classical Western Music?

Question: I am stuck in a melody because i am using in-harmonic A minor and i need a function between its fifth and itself. So, if you people have any ideas, please do solve my problem? I will be obliged for that.
Thank you
Comment: I don't think this needs to be closed, but it's very unclear what you're trying to accomplish here. Can you edit the question to include the context of "bait and switch"?
Comment: Please also clarify what you mean by "I need a function between its fifth and itself". I am assuming it refers to A minor, but then I'm wondering do you mean the key or the chord?
Answer: I'm not quite sure what you're asking here. To me, "bait and switch" implies a deceptive cadence, in which V (the dominant chord) resolves to VI (in a major key it would be vi) instead of the regular i chord. So in the key of A Minor, instead of resolving E to Am, you'd play E to F.
More generally, you might try looking at some other irregular resolutions.
Comment: well, it is quite descriptive, it will take some time to read. i will get back to you in few hours. thanks for the idea.


Ir para o próximo elemento com next e adicionar uma classe ao anterior

Question: Estou tentando fazer com que ao clicar no link "próximo", uma das minhas listas seja revelada e a anterior seja ocultada, usando uma classe que possui display: none;, tentei com .next() do jQuery mas ocorreram alguns problemas, como, por exemplo, numa div com 3 ULs ele pular do primeiro para o último.
http://jsfiddle.net/5kkxy/

anterior

foo LTDA

End: Alameda dos Anjos 233, São Caetano do Sul - SP

Cep: 1234-000

Fone: (11) 1234-0000

Site: www.foo.com.br

E-mail: email@example.com

FOO LTDA

End: Rua do Bosque, 222, São Paulo - SP

Cep: 1234-000

Fone: (19) 8845-9897

Site: www.foo.com.br

E-mail: firstname.lastname@example.com

Jhon Doe

Rua Plesk, 400 São paulo - SP

Cep: 1234-000

     proximo

CSS:
.content {
    width: auto;
    height: 750px;
    margin: 0 auto;
}
.content a.prev, a.next {
    float: left;
    display: block;
    width: 31px;
    height: 27px;
    color: #f26;
    position: relative;
}
.content a.prev {
    background-image: url(../assets/img/setas.png);
    background-repeat: no-repeat;
    background-position: 0 0;
    top: 50px;
    margin: 0 10px 0 0;
}
.content a.next {
    background-image: url(../assets/img/setas.png);
    background-repeat: no-repeat;
    background-position: 0 -27px;
    top: 50px;
    margin: 0 0 0 10px;
}
.content .representante-mapa {
    width: 850px;
    height: 560px;
}
.content .representante-info {
    width: 650px;
    height: 134px;
    background-color: #df6225;
    background-image: url(../assets/img/rep-map-info.png);
    background-position: -1% 50%;
    background-repeat: no-repeat;
    margin: 0 auto;
    float: left;
}
.content .representante-info .texto {
    width: 328px;
    height: 100%;
    margin: 0 0 0 60px;
}
.content .representante-info .texto ul {
    list-style-type: none;
    margin: 0;
    padding: 0 0 0 20px;
}
.content .representante-info .texto ul.hidden {
    display: none;
}
.content .representante-info .texto ul li {
    font-family:'helvetica neue', arial, sans-serif;
    font-size: 14px;
    color: #fff;
}
.content .representante-info .texto ul li h2 {
    font-family: arial, serif;
    text-transform: uppercase;
    font-size: 16px;
    color: #fff;
    padding: 0;
    margin: 0;
}

Answer: Se o teu problema está no código em jQuery, devias ter o mesmo na pergunta!
Problema no HTML
Tens um problema no HTML, o id do teu elemento que envolve as diversas listas contém o caracter # a mais:

Deveria ser:

Navegação em ciclo com jQuery
Para que possas navegar "em circulo" pelas diversas listas, tens que ir andando para o elemento seguinte, mas verificar se o elemento atual é ou não o último, para que possas voltar para o primeiro elemento, criando assim o loop desejado. O mesmo se aplica se estiveres a usar a navegação ao contrário.
Exemplo a funcionar no JSFiddle
var $list = $('#rep-info'); // elemento que contém as ULs

$('.prev, .next').on("click", function(e) {
    e.preventDefault();

    var $item = $list.find('ul:not(.hidden)'); // apanha quem está visivel

    $item.addClass('hidden'); // esconde todos

    if ($(this).hasClass('next')) { // andar para o próximo
        if ($item.is(':last-child')) { // se for a última UL
            $list.find('ul:first-child').removeClass('hidden');
        } else {
            $item.next().removeClass('hidden');
        }
    } else { // andar para o anterior
        if ($item.is(':first-child')) { // se for a primeira UL
            $list.find('ul:last-child').removeClass('hidden');
        } else {
            $item.prev().removeClass('hidden');
        }
    }
});

Comment: +1 por boa solução e pelo erro da ID :)
Comment: @Zuul muito obrigado por sua resposta, você pensou em todos os detalhes. inclusive me pontuou sobre meu erro na ID do elemento!
Comment: deve ser a melhor solução porém eu te juro que eu não entendi nada, kkkkk :/
Comment: é porque cada um tem um jeito diferente de chegar a uma solução, na lógica dele tá bem perto do que eu já estava tentando antes, mas a sua também funciona. aqui o projeto como está ficando http://bit.ly/1gXSuO8
Answer: Aqui vai uma outra alternativa, usando só a classe hidden como sugeriu:
$('.next, .prev').on('click', function (event) {
    event.preventDefault();
    trocar($(this).hasClass('next')); // chama a função passando true ou false consoante seja o botao next ou prev
});

function trocar(index) {
    var ul = $('ul');   // por em cache todos os ul
    var visivel;        // iniciar a variavel que vou usar para saber qual está visivel, ie: não hidden
    ul.each(function (i) { // um ciclo para verificar todos os ul
        if (!$(this).hasClass('hidden')) {  // no caso de não ter a classe
            if (!index && i == 0) {         // no caso de prev e ser o primeiro elemento
                visivel = ul.length - 1;    // dar o index do ultimo elemento à variavel "visivel"
            } else if (index && i == ul.length - 1) { // no caso de proximo e de ser o ultimo elemento
                visivel = 0;  // voltar ao principio
            } else {
                visivel = i + (index ? 1 : -1); // casos intermédios
            }
        }
    })
    ul.addClass('hidden'); // esconder todos
    ul.eq(visivel).removeClass('hidden'); // não esconder o escolhido como visivel
};

Exemplo
No exemplo está uma versão melhorada do código. Comprimido pelo Zuul™
Comment: Não consigo fazer clique com o meu rato para votar na tua resposta... acho que está relacionado com a ausência de uma explicação superficial do código! ;)
Comment: Os ratos suecos são muito melhores :) Mas vou acrescentar uns comentários agora que consegui comprimir o código mais um bocadinho :)
Comment: @Zuul, já editei. Dá uma olhada e edita o que achares :))
Comment: Eu só "comprimia" os dois eventos de `click` para um só de forma a reduzir mais o código, algo tipo: `$(this).hasClass("next") ? troca(1) : troca(0)`, mas +1
Comment: @Zuul, boa ideia. Só tenho medo de haver outros ``.
Comment: sua resposta também está correta!
Answer: Você pode sim, fazer utilizando o .next() do jquery e também o .prev() porém terá de verificar se há um próximo/anterior elemento antes de sair fazendo o que tem de fazer, e também mudei algumas coisas no HTML, no caso o código seria este:
$('.next').click(function(){
    var el = $('.active');
    if (el.next().length > 0){
        el.addClass('hidden');
        el.next().removeClass('hidden');
        el.next().addClass('active');
        el.removeClass('active');
    }
});

$('.prev').click(function(){
    var el = $('.active');
    if (el.prev().length > 0){
        el.addClass('hidden');
        el.prev().removeClass('hidden');
        el.prev().addClass('active');
        el.removeClass('active');
    }
});

E sobre o HTML, você tem que colocar um
 por padrão, ou seja, tens que deixar um dos
 com a classe "active" ao carregar a página.
Exemplo funcionando no JSFiddle
Comment: obrigado pelo esforço :)


Domain Pointing

Question: I bought a domain through a (cheap!) domain company and I want this domain to point to a folder on the server.
The story
I originally bought www.domain.com along with hosting
A few months down the line I bought www.domain2.com
I want www.domain2.com to point ------> to www.domain.com/folder
How do I do this? can it be done through DNS, Im quite new to this!
Help!
Can you please explain exactly the dns commands, or records i need to add, cause I really dont get DNS at all!
Thanks
Answer: You'd set up an 'a' record which points to the ip address of the server, and then configure the server to direct requests for the name of the new domain to point to the folder you want it to serve.
The actual procedure to achieve this varies depending on the web server your running. If your using apache 1.3 take a look at virtual hosts. And this is the doc for apache 2
Answer: You don't do this through DNS.  DNS only associates a name to an IP address -- what happens at that IP address is up to the service you are connecting on.
Your DNS options are:

set up an A record for www.domain2.com to be the same IP address as www.domain.com
set up a CNAME record for www.domain2.com to be "www.domain.com".  CNAME is a DNS shortcut that says "look up this name instead and use that for an answer."  This means if you ever move www.domain.com somewhere else, www.domain2.com will follow along without you having to do anything.

You then configure your web server to have a virtual host on the same IP address, bound to the name www.domain2.com, which emits a http-redirect to http://www.domain.com/folder -- this may or may not be possible depending on what kind of hosting you have for www.domain.com.  If you are self-hosted, then you can set up the virtual host yourself.  However, if you are not self-hosted, you will probably have to contact your hosting's help desk department to ask if, and how, this is possible.

Domain Pointing


Hypothesis Testing question

Question: In a training center, a new strategy was implemented. After the implementation of this new strategy the training center claimed that on an average $80\%$ of the students passed. In order to find out whether this claim can be justified, we take a random sample of $30$ students and see that $60\%$ of the students passed. Do we have sufficient evidence to accept the $80\%$ claim?
Comment: Please see http://stats.stackexchange.com/questions/71127/one-sample-case-test-on-means/ The concept is the same. I suppose this could even be marked as a duplicate.
Comment: @Merovingian Not quite. That Q. is for continuous variables with a specified standard deviation, this is for a count (i.e. binomial) proportion.
Answer: It is generally easier to reject a claim than to "accept" it and if you consider failing to reject a claim to be the same as accepting it then that leads to poor science based on too small of sample sizes (http://dilbert.com/strips/comic/2004-04-13/).
Traditional hypothesis testing could look at testing "At least 80%" or "At Most 80%".  There are also tests of equivalence, but you need to determine what you mean by "equivalent", e.g. you could establish equivalence if you were 95% confident that the true percentage was between 75% and 85% (or another meaningful region), but the given data will not support that.
If you really need proof that the value is exactly 80% then you will need an infinite amount of data (or at least the entire population).
Answer: Probably not. A 95% confidence interval for a binomial distribution with 18 out of 30 students passing is 0.4 to 0.77.
It's not an outlandish claim, but it also doesnt seem very likely. What I don't understand is why you don't have access to everyone's results...but that probably falls well outside the realm of statistics.
Comment: (1) One crucial issue in any good analysis of this question is whether to use a two-sided or one-sided interval (or test).  What justifies your two-sided approach? (2) By not exploiting the asserted $80\%$ rate, your solution lacks power.

Hypothesis Testing question


Price Field Not Saving Programatically

Question: Price Field Type from the Commerce module package is not exportable for Feeds. So as a work-around, I saved my prices ('min price', 'hot price' and "deposit price') into  normal Float fields and just move the values to the Price Field Types  on-the-fly. And so here it is (set using Rules: After an item is saved of content type 'Property'):
$node->field_price_amount['und'][0]['value'] = [node:field-current-price-temp];
$node->field_hot_price_amount['und'][0]['value'] = [node-field-hot-price-temp];

etc.
and then applying the node_save($node) with $node->is_new set to FALSE.
All the other values are saving properly except for the field type defined by the Commerce module. No actual data saved to tables at all.
"$node->field_price" should be the right machine name I have defined for this field. But for some reason importing leads to error field_price_amount cannot be NULL. This is also weird. So I changed it to field_price_amount so it won't complain but still not saving despite no more errors in importing. (The db table is still named field_data_field_price but for some reason it is complaining as 'field_price_amount should not be null ).
Anyone have ideas?
Comment: Seems like there is a column amount not value for a price field $node->field_price_amount['und'][0]['amount'] = [node:field-current-price-temp];
Answer: Commerce price fields have a different data structure from standard fields.
i.e not:
$product->commerce_price[LANGUAGE_NONE][0]['value'] = 500;

but instead
$product->commerce_price[LANGUAGE_NONE][0]['amount'] = 500;
$product->commerce_price[LANGUAGE_NONE][0]['currency_code'] = 'USD';

or just:
$product->commerce_price[LANGUAGE_NONE][0] = array('amount' => 500, 'currency_code' => 'USD');

They also have a 'data' property for additional price component information.
More info: commerce_price_field_data_property_info
Comment: Glad to hear it :)

Price Field Not Saving Programatically


Formulário submetido, retorna Class not found autoload Composer

Question: Procurei ver se alguém passou por esse problema mas até agora não encontrei nada na internet. Estou tentando resolver a 2 dias e estou quase desistindo.
Diretório
index.php
src/
   |__Route/
   |       |__login.php
   |__Dao/
         |__UserDao.php
vendor/

Composer.json
"autoload": {
     "psr-4": {
         "Src\\": "src/"
     }
}

UserDao.php
<?php
namespace Src\Dao;

class UserDao {}

Index.php
<?php
require_once 'vendor/autoload.php';

login.php
<?php
use Src\Dao\UserDao;

No meu index.php funciona normalmente, tudo é carregado. O problema surge quando o formulário é submetido, chega no login.php e lança o Fatal error: Uncaught Error: Class ARQUIVO not found.
Agradeço desde já, caso alguém souber onde estou errando.
Comment: Você adicionou o require do autoload no arqivo login.php também?
Comment: Se adicionar, vai funcionar. Mas achei que era feito apenas um require do autoload. Não é possível fazer com um único require no arquivo que ira iniciar o sistema?
Comment: Isso seria possível se todas as requisições passassem pelo index.php. Como seu formulario redireciona diretamente ao arquivo login.php, é necessário incluir o autoload nele também
Comment: Seria o conceito de FrontController
Comment: Entendi, obrigado pelo feedback Everton.
Answer: Seu problema está relacionado ao carregamento do 'vendor/autoload.php';, é necessário carrega-lo, como você está trabalhando com arquivos php distintos ele é necessário, e no seu caso bastaria adiciona-lo no login.php:
<?php
require_once 'vendor/autoload.php';
use Src\Dao\UserDao;

Composer autoloading


How can you find the zeroes of a function with 1 point of the function and 2 points of the derivative of that function?

Question: I'm trying to figure out this question, that states $3$ points, and then to find the zeroes of a quadratic function. However, the function itself is not stated. Basically this is how it goes $f(0) = x$. Then I am given $2$ points of the derivative of the function, $f'(x_1) = y_1, f'(x_2) = y_2$.
I'm not sure if I'm doing this right, but I'm basically first finding the gradient of the derivative function, since if the function is quadratic, then it's derivative should be linear. I take $\frac{y_2 - y_1 }{ x_2 - x_1}$. Then solve for the $y$ intercept. Then I just reverse the derivation to get the final function, and solve for the zeroes. Is this the correct way of doing it? Or is there some other methodology?
Comment: Just edited your post to add some MathJax : you can take a look by attempting to edit this question . Drop by the [Beginner's tutorial for MathJax](https://math.meta.stackexchange.com/questions/33179/short-and-helpful-advice-on-using-mathjax-on-the-site) for drafting your questions in the future.
Answer: Your method will work. Knowing the equation of the (linear) derivative means you know everything about the quadratic except the constant term.
Alternatively, write the quadratic as $ax^2 + bx + c$ and use the data in the question to write three equations in the three unknown coefficients.
The methods are essentially equivalent. The second is somewhat more general, and does not require the nice geometric insight of the first.
Comment: I did forget to mention specifically that I am give f(0), which means that I am given the constant*. So I think it works. Thanks for the insight!


(NODE) Para que serve um processador com multiplos nucleos, se o NodeJS roda somente em uma thread?

Question: Exemplo:
Se eu quero montar um servidor, então, tenho que me "preocupar" com o clock e não com a quantidades de nucleos ?
Tipo, se eu tenho dois processadores para comprar
Processador X -> 8 Nucleos de 2.0GHz &&
Processador Y -> 4 Nucleos de 3.0GHz
Seria mais vantajoso comprar o processador Y para meu servidor ? Pois ja que o NodeJS só roda em uma thread/Nucleo , então, comprar o processador X seria "desperdicio" de 7 nucleos e no processador Y um "desperdicio" de 3 nucleos, e ainda com a vantagem de ter um clock maior !
Não sei se estou errado, mas, eu entendi por isso.
Se essa minha "teoria" estiver certa, o que devo fazer ? Mudar de linguagem ou aplicar Threads no meu APP ?
Comment: Para outras tecnologias usarem? O fato do Node ser limitado é um problema só dele. Claro que dá para usar outras coisas junto na máquina, dá para usar processos diferentes, embora tem cenário simples e tem cenário complicado porque seria forçado para resolver uma deficiência do Node. Não quer dizer que haverá desperdício, depende de como usa. Eu não vou falar para mudar de linguagem, mas é o que eu faria :) São duas coisas diferentes. Claro que depende um pouco do caso, pode ser que não precise disso tudo. Não existe resposta absoluta para essas coisas. Por isso não é simples responder isso.
Comment: Não, computadores só fazem o que softwares mandam fazer.
Comment: Não é o seu programa que vai gerenciar diretamente o uso dos nucleos, geralmente quem gerencia isso é o proprio sistema operacional, conforme necessário, fora que em um servidor não terá só um programa rodando, um sistema operacional é um composto de diversos programas, muitos já rodando, o processador não vai só servir a você, vai servir a tudo que estiver rodando.
Comment: E no caso de o seguinte: Digamos que eu quero criar um servidor de um jogo tal q eu comprei (exemplo: CS 1.6), ai eu vou no site e tal e baixo o servidor pra eu mesmo proprio hospedar... digamos que eu vá hospedar 3 servidores (3 portas diferentes) tudo no mesmo PC (pelo motivo de cada servidor rodar um mapa diferente). Entao, ao rodar esses 3 servidores ao mesmo tempo, será q o PC faz o parelismo automatico com outras Threads ? ou vai rodar tudo na mesma thread ?
Comment: Tlgd, eu pensei que o Sistema Operacional tivesse alguma funcao "inteligente" de jogar um processo para outra Thread no caso de q a Thread principal estivesse "lotada"
Answer: O Node.js tem o módulo cluster, que permite que você inicie processos Worker que dividem as requisições na mesma porta.
Na prática, você inicia um número de processos igual ao número de cores do seu processador e aproveita ao máximo cada um.
Fonte: https://nodejs.org/docs/latest/api/cluster.html
Comment: pô cara, era tipo isso mesmo ! Vlw


jquery selector to filter out th elements

Question: I have:
var rows = $table.find('tbody > tr').get();

This selects all rows.  However, not all tables have thead and tbody explicitly defined, so I need to filter out any rows that have .children('th')
Answer: EDIT: I'm assuming you wanted to filter out the rows that have  elements. If you wanted to end up with only those rows, then just get rid of the :not() part.

This will give you
 elements in the table that do not have a descendant .
var rows = $table.find('tr:not(:has(th))').get();

http://api.jquery.com/not-selector/
http://api.jquery.com/has-selector/

Note that this will also give consideration to nested tables. If there will be nested tables with  tags, try this:
var rows = $table.find('tr:not(:has( > th))').get();

...which should limit the consideration of the  tags to immediate children.
Answer: Why not change that to:
var rows = $table.find('tr > th').get();

EDIT:
var rows = $table.find("tr:has(th)").get();

Comment: spinon - This would actually select the `` elements. I think OP wants to select the `` elements.


Integrating Help in Qt5 C++ GUI Application

Question: I want to add the user manual for my Qt5 application as help but i am unable to find any built in tool for that.
I want to make it like Qt5 default help (without navigating user to external file or link). Help window should open right in application. I have tried QtDesktopServices and QTextBrowser. But none of them is providing the functionality as mentioned above.
Answer: I just changed the project's user manual to html files & it worked. Also, I've set the html files as the source for my textBrowser as below.
ui->textBrowser->setSource("help.html");


Android - Create and start Activities based on server response (JSON)

Question: I have a JSON response from the server, like this:
<code>{
    "types": [
                {
                    "type_name": "ACTIVITY_TITLE_1",
                    //  ... other Activity realted data
                },
                {
                    "type_name": "ACTIVITY_TITLE_2",
                    //  ... other Activity realted data
                }
                // ... and who knows how many more other type object...
             ]
}
</code>
I get this JSON from a background service, and after I saved that to a DB, my SplashScreen should generate activities from this JSON.
So I need to create a new Activity for every 'type' what I get from the server, and automatically start them one after the other.
Every Activity is exacty the same (so I instantiate the same class), just the content differs (what I get from the JSON).
The only problem is, that I don't know how many 'types' I'm gonna get, so how many Activity I need to create, and I can't use Fragments (what would be an easy solution), beacause I have to use Fragments in these Activites.
What is the best design approach for this?
From the first activity (kind of a long 'splash screen') I should start the ACTIVITY_TITLE_1 activity with startActivityForResult(), and when I'm done I start the ACTIVITY_TITLE_2 from that 'splash screen'?
Or I should start the ACTIVITY_TITLE_2 activity from the ACTIVITY_TITLE_1, and inside that ACTIVITY_TITLE_1 get the information somehow from the DB, that there are more activities based on the JSON array waiting for the start, and start the next one from there?
Neither looks too 'professional' solution for me...  :D
EDIT:
I'm developing kind of a simple "dashboard", and I have new data from the server in every 10 minutes in a JSON form like above. So I only need to display the latest JSON response, which is a "blueprint" for activities, and show them automatically one after the other... In the example above, there will be 2 activities automatically alternating in a few seconds... But if I get a server response 30 minutes later, which contains 3 activites (types), than I need to generate and show 3 one after the other. Always based on the last JSON response.
So, I'm gonna save immediately to DB my JSON response, but in the next automatic "round", I'll have to show 3 activities now. So I need to generate and start activites what I create on the fly... :D
Comment: " I can't use Fragments (what would be an easy solution), beacause I have to use Fragments in these Activites."

There exists a thing called child fragments ( fragment inside a fragment )
Answer: Ok . You don't need to create new activity foreach json response . Just hold one activity and than load the content depending on the response you get. Just from your splash screen which is an Activity/Fragment for itself send data to a new Activity you will generate . If you need to save all your responses hold a local database (Sqlite, Realm or whatever) and just change the content depending on the value that you need .
Comment: Probably I was not detailed enough.
I'm developing kind of a simple "dashboard", and I have new data from the server in every 10 minutes in a JSON form like above.

So I only need to display the latest JSON response, which is a "blueprint" for activities, and show them automatically one after the other...
In the example above, there will be 2 activities automatically alternating in a few seconds...
But if I get a server response 30 minutes later, which contains 3 activites (types), than I need to generate and show 3 one after the other. Always based on the last JSON response.
Comment: So, I'm gonna save immediately to DB my JSON response, but in the next automatic "round", I'll have to show 3 activities now. So I need to generate and start activites what I create on the fly...  :D
Comment: The problem is more complicated, but I tried to simplify the basis of the problem. I need to instantiate and alternate automatically the same activity based on external input.
I'm only interested about the "architecture design" what I should use.
My problem isn't just that to change the title and the list inside the activity. I have the reason why I need to create new Activity one after the other.

But the question is: what is the optimal/ideal solution?  :)


How to ensure CiviCRM checksum / cid are valid in custom Drupal module

Question: Follow up to an earlier question:
I am writing a simple custom Drupal module to display information about a contact's related organizations (see above for more background if interested).
One use case is that a logged in user sees this info, in which case determining whether to show the info is easy (I just use the Drupal contact ID to pull information from CiviCRM).
However, if someone visits the page from a checksum link sent via CiviMail, Drupal considers the user to be anonymous. I can pull the cid (CiviCRM contact ID) from the URL easily enough, but I need to be able to also verify the checksum in order to display information without a possibility of an information leak. How do I do that?
I found this function:
CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId) but this generates the checksum. I just need to verify an existing checksum (from the URL), not create a new one.
Answer: A little grepping around and I found this:
CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])
which takes a CiviCRM contact id ($cid) and compares it to the checksum in the URL and did the trick for me as follows:
  $cid = check_plain($_GET['cid']);
  if ($cid != "" && CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])) {
        //Contact ID and Checksum match up, embed a view
        //with $cid as an argument (or other custom functionality)
  } else {
        //Not a match, decide what you want to do in this case
        //(e.g. check if user is logged in, or display error...)
  }

UPDATE:
It looks like the usage has changed slightly in core since I pulled the above out of there (although the above was still working for me). Try this (taken from here):
    //check if this is a checksum authentication
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
if ($userChecksum) {
  //check for anonymous user.
  $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
  if ($validUser) {
    return $tempID;
  }
}

Comment: We still need a few more experts like yourself to commit to http://area51.stackexchange.com/proposals/77367/civicrm?referrer=c680l-NqIanXeNHrjdyxXQ2 so the CiviCRM community can get their own StackExchange vs. adding questions and answers to the Drupal, WordPress, and Joomla exchanges. If you haven't committed already, please do and help spread the word.
Comment: @kreynen thanks -- I'm already committed there and looking forward to the CiviCRM-specific exchange.
Comment: laryn - care to clarify a bit more about what you then did with CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])
Comment: @petednz I added a small bit of code in the answer to flesh out the textual description in the question.
Comment: In your code, $c has a value. Any idea what it is ?
Comment: @commonpike To be honest, I'm not 100% sure what that does, but it works if you use it as is rather than pulling the checksum out on your own. In any event, I've updated the code with more current code from core.
Comment: @laryn - and put this in a module? (feels like a stupid question but ...)
Comment: Yes, this is in a custom module. In my case it creates a custom block which checks the checksum/user ID and if valid, pulls in some private information (otherwise it displays nothing).


Matriz com strings no Visualg

Question: Estou tendo dificuldade com a seguinte questão:

Crie uma matriz M[21,10]. Faça a leitura de 10 nomes (com no máximo 20 caracteres) e armazene na primeira linha da matriz. Após a leitura, decomponha os nomes letra por letra e as armazene nas demais linhas da matriz a partir da segunda. Ao final, escreva a matriz.

O meu código ficou da seguinte maneira:
algoritmo "Exercício 4"
var
   m : vetor[1..21, 1..10] de caractere
   nome : caractere
   i, j : inteiro
inicio
   i := 1
   para j de 1 ate 10 faca
      repita
         escreva("Informe o nome: ")
         leia(m[i, j])
         se compr(m[i, j]) > 20 entao
            escreval("Informe um nome com no máx. 20 caracteres.")
         fimse
      ate compr(m[i, j]) <= 20
      fimrepita
   fimpara
   para i de 2 ate 21 faca
      para j de 1 ate compr(m[1, j]) faca
         escreval(copia(m[1, j], j, 1))
      fimpara
   fimpara
fimalgoritmo

Não estou conseguindo distribuir as letras na matriz, e o erro do meu código diz que está faltando um faça na 5ª linha de baixo para cima, mas o faça está ali.
Comment: Você já não fez essa pergunta? (Eu estava agora mesmo lendo ela)
Comment: Ok, não é assim que deve ser feito. Todas as publicações podem ser editadas quando você bem entender. Como a publicação atual está melhor que a outra, mantenha esta como está. A outra será fechada.
Comment: Relacionadas:
https://pt.stackoverflow.com/questions/206191/algoritmo-para-leitura-escrita-de-matrizes
https://pt.stackoverflow.com/questions/206782/strings-em-matriz
Comment: Na verdade fiz hoje de manhã também, agora só corrigi de "Vetor" para "Matriz" no título.
Mas perguntei novamente hoje à tarde mostrando o algoritmo, não somente pedindo a explicação.
Comment: Ah, foi mal. Jurava que tinha deletado a outra.
Comment: Relax, estou baixando o VisualG pra testar o código.
Comment: Beleza, valeu :)
Answer: Tem vários erros no seu algoritmo. Eu refiz todo ele conforme o enunciado do exercício.
Tente usar nomes descritivos para suas variáveis. O segundo loop estava ao contrário e eu acho que a confusão foi justamente por causa dos nomes das variáveis. Mesmo que você esteja acostumado com a matemática e tenha fixo na mente que i e j são, respectivamente, referentes às linhas e colunas é melhor usar nomes mais descritivos.
No primeiro loop é possível deixar fixo (hardcoded) o índice da linha da matriz como 1, afinal, os nomes só serão colocados na primeira linha, como diz o enunciado.
Ao invés de colocar o nome digitado na matriz, mesmo que inválido, eu criei uma variável chamada nome para validar antes se o nome estava dentro das regras, se sim, ele vai pra matriz, caso contrário, o repita continuará executando.
Até aí você estava indo bem, mas não consigo entender qual era o objetivo do bloco de código final.
O que eu fiz foi percorrer todas as colunas da matriz e, para cada coluna, percorrer todas as linhas disponíveis (2 - 21) fazendo com que a coluna receba 1 carácter da string que fica na primeira linha desta coluna.

algoritmo "Exercício 4"
var
   matriz: vetor[1..21, 1..10] de caractere
   nome: caractere
   linha, coluna, i : inteiro

inicio
   para coluna de 1 ate 10 faca
      repita
         escreva("Informe o nome: ")
         leia(nome)
         se compr(nome) > 20 entao
            escreval("Informe um nome com no máx. 20 caracteres.")
         fimse
      ate compr(nome) <= 20
      matriz[1, coluna] := nome
   fimpara

   para coluna de 1 ate 10 faca
      i := 1
      para linha de 2 ate 21 faca
         matriz[linha, coluna] := copia(matriz[1, coluna], i, 1)
         i := i + 1
      fimpara
   fimpara

fimalgoritmo

Comment: Obrigado pelas correções e dicas. Na hora da execução está dando o mesmo erro que no meu algoritmo. Diz que está faltando um faca, mas não está não. (faca da 5ª linha de baixo pra cima)
Comment: @Jow Eu editei a resposta, tinha um problema naquela linha mesmo.
Answer: Melhorei um pouco o código. Agora ele exibe o resultado.

Matriz com strings no Visualg


Switching active states of two GameObjects in Unity3D

Question: With Unity3D I am trying to create a scene with an alpha texture as a silhouette, which upon looking up is added, then looking down removes.
Currently I have the exposure of an equirectangular image changing on look up, but my silhouette object says I have not assigned it to an instance:

As you can see from the console, it is eventualy recognised, but I cannot set the active state. This is the current state of my code being applied to the scene:
using UnityEngine;
using System.Collections;

public class switchScript : MonoBehaviour {

    public Cardboard cb;

    public Renderer leftEyeDay;

    public Renderer rightEyeDay;

    private GameObject[] dayObjects;

    public GameObject nightObject;

    void Start () {
        MeshFilter filter = GetComponent(typeof (MeshFilter)) as MeshFilter;

        if (filter != null) {
            Mesh mesh = filter.mesh;

            Vector3[] normals = mesh.normals;
            for (int i=0;i<normals.Length;i++)
                normals[i] = -normals[i];
            mesh.normals = normals;

            for (int m=0;m<mesh.subMeshCount;m++)
            {
                int[] triangles = mesh.GetTriangles(m);
                for (int i=0;i<triangles.Length;i+=3)
                {
                    int temp = triangles[i + 0];
                    triangles[i + 0] = triangles[i + 1];
                    triangles[i + 1] = temp;
                }
                mesh.SetTriangles(triangles, m);
            }
        }
    }

    // Update is called once per frame
    void Update () {
        float xAngle = cb.HeadPose.Orientation.eulerAngles.x;

        if (isLookingUp (xAngle)) {
            var exposureValue = getExposureValue (xAngle);
            leftEyeDay.material.SetFloat ("_Exposure", exposureValue);
            rightEyeDay.material.SetFloat ("_Exposure", exposureValue);
            toggleNight ();
        } else {
            leftEyeDay.material.SetFloat ("_Exposure", 1F);
            rightEyeDay.material.SetFloat ("_Exposure", 1F);
            toggleNight ();
        }
    }

    public bool isLookingUp (float xAngle) {
        return xAngle > 270 && xAngle < 340;
    }

    public float getExposureValue (float xAngle) {
        var _xAngle = Mathf.Clamp (xAngle, 320, 340);
        return ScaleValue (320.0F, 340.0F, 0.3F, 1.0F, _xAngle);
    }

    public float ScaleValue (float from1, float to1, float from2, float to2, float v) {
        return from2 + (v - from1) * (to2 - from2) / (to1 - from1);
    }

    void toggleDay() {

        print (nightObject);

        nightObject = GameObject.FindGameObjectWithTag ("Night");

        nightObject.SetActive (false);

    }

    void toggleNight() {

        print (nightObject);

        nightObject = GameObject.FindGameObjectWithTag ("Night");

        nightObject.SetActive (true);

    }

}

Comment: you toggle ***components*** using .enabled.  you toggle ***whole game objects*** using SetActive.  it's a real "gotchya" in unity, very annoying!
Answer: GameObject.FindGameObjectWithTag ("Night") returns null when the whole object is set to !active. Just toggle the scripts on that object instead of the whole GO.
Answer: Ok, if anyone needs this, this is an easy way to create scene switch:
void Awake() {

        silhouetteObject = GameObject.FindGameObjectWithTag ("Night");

        silhouetteObject.GetComponent<Renderer>().enabled = false;
    }


Prove general Euclid's Lemma in a UFD using prime factorization

Question: I have seen plenty of proofs for this theorem:
In a UFD if $(a,b)=1$ and $a|bc$ then $a|c$.
They mostly use the gcd distributive law e.g. here.
Well I wanted to prove this just by relying on the properties that the UFD had.
My attempt:
Since $a|bc$ then for some $r$ we have $ar=bc$.
Now by the existence, since we know that any non unit element like $a$ can be rewritten as $t_1×....t_n$ where $t_i$ are irreducible, we can do this:
$$p_1^{α_1}...p_n^{α_n} g_1^{ε_1}...g_m^{ε_m} =q_1^{β_1}...q_k^{β_k}h_1^{ψ_1}...h_i^{ψ_i}$$
(Where $p_i$, $g_i$, $q_i$ and $h_i$ are primes.)
By uniqueness the set that is on right should be on left too, Am I right?
But since $(a,b)=1$ then $a$ and $b$ shouldn't share prime elements. Somehow it's like $A$ is a subset of $C$. I can't really manage this but it's becoming like a problem in set theory.
Can you please help me with my own approach??
Comment: @Hassuni I happen to have an answer previously written on precisely this topic, do take a look if you are interested in seeing a very general approach (arguably *the most* general): https://math.stackexchange.com/questions/3841783/writing-and-improving-basic-divisibility-proofs-in-ufd-some-examples/3841976#3841976
Comment: @David Kipper we are in a UFD. Irreducible implies primes. $p_i$'s are primes and so are the other ones. :/
Comment: Yes, of course, and in fact prime implies irreducible over a UFD, and we can likewise say that over a UFD every nonzero,nonunit can be written as a product of irreducible uniquely.
Comment: Yes, but I need that equation to be written in the form of factorization to prime elements!
Comment: I added a rigorous inductive proof.
Answer: You're very close. Let's look back at this equation you stated:'
$$
p_1^{α_1}...p_n^{α_n} g_1^{ε_1}...g_m^{ε_m} =q_1^{β_1}...q_k^{β_k}h_1^{ψ_1}...h_i^{ψ_i}
$$
corresponding to $ar=bc$. As you said, because we are in a UFD the set of primes, counted with multiplicity, is the same on both sides (up to units). Furthermore, as $(a,b)=1$ then no $p_i$ can divide $b$. Once again by uniqueness, that means that no $p_i$ can divide $q_j$. In fact, we can go farther and say that no $p_i^{\alpha_i}$ can divide $q_j$. Putting this together, all the $p_i^{\alpha_i}$ must appear in the factorization on the right hand side (up to units). Furthermore, the $p_i^{\alpha_i}$ cannot divide the $q_j$. Thus, up to units, the $p_i^{\alpha_i}$ must each divide some $h_j^{\psi_j}$. Hence, all the prime factors of $a$ counted with multiplicity divide $c$. Hence, $a \mid c$.
Comment: Te be *rigorous* we should use induction, and doing that yields something like the proof in my answer.
Comment: Yeah good point, it absolutely could be made more rigorous with that addition.
Answer: It has a natural proof by induction on the number $\:\!k\:\!$ of prime factors of $\,a,\,$ using as inductive step Euclid's Lemma (if a prime divides a product then it divides some factor). If $\,k=0\,$ then $\,a\,$ is a unit so $\,a\mid c.\,$ Else $\,a = p\bar a\,$ for a prime $\,p\,$ so $\,p\bar a\mid bc\,\Rightarrow\,p\mid b\,$ or $\,p\mid c,\,$ so $\,\color{#c00}{p\mid c}\,$ by $\,(p,b)=1\,$ by $\,(p\bar a,b)=1$. Cancelling $\,p\,$ from $\,p\bar a\mid bc\Rightarrow \bar a\mid b\,\color{#c00}{c/p},\,$ and $\,(\bar a,b)=1\,$ by $\,(p\bar a,b)=1.\,$ Notice $\,\bar a\,$ has fewer  prime factors than $\,a=p\bar a,\,$ thus $\,\bar a\mid \color{#c00}{c/p}\underset{\textstyle\times\, p}\Rightarrow p\bar a\mid c\ $ (i.e. $\,a\mid c),\,$ by induction.
Exercise $ $ Make explicit all  implicit uses of the existence and uniqueness of prime factorizations that are employed in the proof (necessary to be completely rigorous).
Comment: Nice argument! But does it mean that my proof isn't thorough? How do I improve it?
Comment: I think you made a typo. In last part you're multiplying by $p$.
Comment: @Hassuni You could use multisets of primes as sketched [here](https://math.stackexchange.com/a/3320206/242). Or you could use [$p$-adic valuations](https://en.wikipedia.org/wiki/P-adic_order)  $\nu_p(x)=$  the highest power of $p$ dividing $x$. Usually informal proofs like yours are accepted as rigorous since it is clear how to convert them to rigorous inductive proofs. (yes, typo fixed, thanks).
Comment: @Hassuni [Here](https://math.stackexchange.com/a/647665/242) is another nice application of set arithmetic on multisets of prime factors.


Change problem from combination to permutation

Question: I have this problem:

Randomly choose 2 vertices of
  the prism. Calculate the probability that those vertices both belong to a line that's parallel to the
  axis 0z.

Here is a picture of the prism:

The answer is
$$\frac{^2C_2+ ^2C_2+^2C_2}{^6C_2} = \frac{3}{15} = \frac{1}{5}$$

My question is, how would you change this problem so that instead of
using $$\frac{n!}{(n-k)!k!}$$ you would have to use
$$\frac{n!}{(n-k)!}$$ to solve this problem?

I drew some tables so it is easier to visualise the sets

Basically I want that to solve this problem, table I is used instead of table one.
This question is a follow-up of Permutations, Combinations and Geometry
Answer: You could ask: "Randomly choose four different vertices in order (v1,v2,v3,v4). What is the probability that they are arranged in clockwise order around one of the rectangular faces (viewing the face from the outside towards the center of the prism?"
The key in changing from combination to permutation is for it to be important in what order the points are selected.
The solution is:
\begin{equation} \frac{4\times3}{^6P_4} = \frac{12}{360} = \frac{1}{30} \end{equation}
Comment: Why did you use 4*3?  I think you are only counting the faces that are rectangular. What about the triangular ones?
Comment: In that case, would the solution be $\frac{^4A_2+^3A_2}{^6A_4}$?
Comment: A is the same as the P you used in your answer.
Comment: I edited to include only the rectangular faces. It doesn't make sense to have the triangular faces because there are four points. We could also choose three points and ask the same question, but include the triangle.  Then the answer is (4x3+3x2)/P(6,3)


Consecutive days excluding weekends SQL 2008

Question: I am working on an out of office report, that as suggested shows when someone is off. I've been asked to include a returning to work date. So I need to write a query that checks the consecutive dates that the person is off. I've managed to find a query which is close, but it trips up due to weekends.
So the default data is :
StaffCode   HolidayDate
J.Smith     2017-04-03 00:00:00.000
J.Smith     2017-04-04 00:00:00.000
J.Smith     2017-04-05 00:00:00.000
J.Smith     2017-04-06 00:00:00.000
J.Smith     2017-04-07 00:00:00.000
J.Smith     2017-04-10 00:00:00.000
J.Smith     2017-04-11 00:00:00.000
J.Smith     2017-04-12 00:00:00.000
J.Smith     2017-04-13 00:00:00.000
J.Smith     2017-04-18 00:00:00.000

When I run the query it returns
FirstDay            LastDay
2017-04-03          2017-04-07
2017-04-10          2017-04-13
2017-04-18          2017-04-18

But what I want is
firstDay                lastDay
2017-04-03              2017-04-13

This is the query im using, Is there a way of excluding weekends?
WITH t AS (
  SELECT HolidayDate d,ROW_NUMBER() OVER(ORDER BY HolidayDate) i
  FROM tblHoliday
  WHERE StaffCode = 'j.Smith'
        AND HolidayDate >= '27-Feb-2017'
  GROUP BY HolidayDate
)
SELECT MIN(d),MAX(d)
FROM t
GROUP BY DATEDIFF(day,i,d)

Comment: FYI:you would be getting more answers(more visibilty),if you include generic tag(in this case sql server ) and then version
Comment: you mean to say mindate and max date from  consecutive date excluding weekend. isn't it ? then why 2017-04-18 is lastday as it do not fall under consecutive. Last day should be 2017-04-13
Comment: sorry @kumarharsh the example i used has a bank holiday in it so the Monday wasn't a working day. but i can ignore those. thanks.
Answer: This is where a Dates table comes into handy. There are many blog posts recommending adding a Dates table to a database, for situations where you need to tackle dates.
In order to create a Dates table you can use a recursive CTE:
;with dates as (
select cast('19000101' as datetime) [current_date]
union all
select dateadd(day, 1, current_date)
from dates
where current_date <= cast('20991231' as datetime)
)
select
    [current_date]
    , NULL [holiday]
    , case datename(weekday, prev_date)
        when 'Saturday'
            then 1
        when 'Sunday'
            then 1
        else 0
    end     [weekend]
into Dates
from dates
option(maxrecursion 0);

As you can see I added two extra columns which might be helpful in the future. One could contain a boolean to point if a specific day is a holiday/national day off - [holiday] column.
The 3rd column also contains a boolean to point if a day is a weekend day or not.
So, using the Dates table, in a single-query you could do something like this (it's not pretty):
-- I'll also create the sample data and store it into a timeOff table
create table timeOff (staffCode varchar(25), holidayDate datetime);

insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-03T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-04T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-05T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-06T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-07T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-10T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-11T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-12T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-13T00:00:00.000' AS DateTime));
insert [dbo].[timeOff] ([staffCode], [holidayDate]) values (N'J.Smith', CAST(N'2017-04-18T00:00:00.000' AS DateTime));

-- And now for the query itself (it's not pretty but I came up with it in a short time)

select
    [staffCode]
    , min([current_date])   [firstDay]
    , max([current_date])   [lastDay]
from
    (select d.[current_date]
        , t.staffCode
        , min(case when d.weekend = 0 and t.holidayDate is null then d.[current_date] else null end) over () [last_date]
    from
        (select [staffCode]
            , min(holidayDate) [mindate]
            , max(holidayDate) [maxdate]
        from timeOff t
        where staffcode = 'J.Smith'
        group by staffCode) r
    inner join dates d on d.[current_date] between mindate and maxdate
    left join timeOff t on d.[current_date] = t.holidayDate ) r
where [current_date] < [last_date]
    and staffCode is not null
group by staffCode;

Comment: I've actually tried implementing this however if there is another request in later in the year it uses that date as the last day...
Comment: @GPH I'm sorry, I don't understand your comment. Maybe you can add more details to your question and the expected output?
Comment: ok, if there are 2 holiday requests. one for a week in june and one for a week in december the query just looks at the last date it can see. which in this case is december. so the Holiday startdate shows as 1st June and the End date shows as december..
Comment: @GPH Ok, then it means that your expected output is wrong. You would be looking for `2017-04-03  ... 2017-04-13`, right?
Comment: @GPH You're lucky I kept my answer from a few days ago. And what I originally understood from your question when I skimmed through it. Give me a minute to re-edit.
Comment: @GPH You should find my current answer to be what you were looking for initially.


Custom sorting method for dhtmlx grid not working

Question: Could anyone provide custom sorting method for dhtmlx grid? Mine is not working. Do not know what I am missing.
Answer: I use this function to sort ignoring the string case:
function str_uncase(a, b, order) {
    return (a.toLowerCase() > b.toLowerCase() ? 1 : -1) * (order === "asc" ? 1 : -1);
}

Call it like:
grid1.setColSorting("str_uncase,str_uncase,...   ");


Prove why the 'elimination method' of solving simultaneous equations works.

Question: [This has been deleted due to me stressing out over something obvious that I didn't see; apologies if I seemed aggressive, I was merely stressed. Thanks.
Comment: What do you mean by "arbitrary"? You could edit the question to be more specific about what you think the elimination method would be for these equations, what step (or steps) you find troubling, and why you are troubled about those steps. That might get better answers.
Comment: It just seems that a new rule has been thrown in for no reasons; this method is sort of like column multiplication with algebraic equations, something that doesn't crop up anywhere else (well, in a standard GCSE syllabus at least).
Comment: What method would you invent yourself if you had to solve a $2\times2$ system ? A $3\times3$ ? And a $10\times10$ ?
Comment: I see four steps of the method illustrated in the revised question. Which of these steps do you doubt? (Presumably, there must be at least one step whose correctness is not clear to you; otherwise it seems strange to ask "why" the procedure works.)
Comment: see https://en.wikipedia.org/wiki/Linear_independence, Assume that $\{x_1,x_2,\dots,x_n\}$ is a linear independent set of vecotrs, then try to prove that $a_1x_1 + c_2(a_2x_2+b_2x_1)+c_3(a_3x_3+b_3x_1)+\dots +c_n(a_nx_n+b_nx_1)=0\implies a_1=c_2=c_3=\dots=c_n=0$
Comment: Hi David K. The step that troubles me the most is the 'column subtraction' step.' It just seems like we are adding (or rather, subtracting, heh) a rather arbitrary rule in order to solve this sim equs. I am seeking a proof for why we can 'column subtract.'
Comment: To get what you want,remove what you don't want  *in a way that it wont appear again*
Answer: The rationale of the elimination method is rather obvious: as you can't solve an equation in two unknowns directly, you transform the system in a way to get an equation in a single unknown, which is easily solved.
You'll soon learn that this process generalizes to a system of $n$ equations in $n$ unknowns, where you transform a square system in a triangular one. The approach is very smart and very efficient.
The method works because you are allowed to replace an equation by a linear combination of itself and other equations (as you combine equal expressions, the equality $LHS=RHS$ isn't lost).

Any system of equations (linear or not) can be written as equalities to zero of some functions of the unknowns.
$$f(x,y)=ax+by-n=0,\\g(x,y)=cx+dy-m=0.$$
You are "allowed" to transform the system into another, provided you don't introduce new solutions nor discard valid ones.
For instance, omitting the arguments $(x,y)$, the single equation $$f^2+g^2=0$$ has the same solution set, $f=0,g=0$.
In particular, you can form linear combinations, such as
$$\alpha f+\beta g=0,\\\gamma f+\delta g=0,$$ provided that the corresponding system isn't indeterminate, i.e. if $\alpha\delta-\beta\gamma\ne0$.
A special case is that used in elimination, where you add an equation to another and keep the other unchanged,
$$f=0,\\\gamma f+g=0.$$
It obviously fulfills the criterion.
This new system is equivalent to
$$ax+by=n,\\(\gamma a +c)x+(\gamma b+d)y=\gamma n+m,$$
and you are free to choose $\gamma$ so that the term in $y$ vanishes.
Comment: "The method works because you are allowed to replace an equation by a linear combination of itself and other equations (as you combine equal expressions, the equality LHS=RHS isn't lost)." This helped me a lot to understand this. Thanks.
Comment: @BagelEnthusiast: glad to know. I was unsure about what aspect of elimination was unclear to you. I have updated the explanation.
Answer: I've been searching around the internet looking for an explanation for my Algebra students as to why one can solve a system by elimination. It's not immediately clear as to why you can just "combine" equations, resulting in a new equation (which if graphed, creates a new line, but happens to go through the same solution point!)
My students are comfortable with the idea of substitution (sure, if something is equivalent, then I can replace it somewhere else in the equation with what it's equivalent to!). The intuition is lost when we get to solving by elimination. Well, finally I've come across an accessible answer for these 7th and 8th graders! These are my notes:
Question: Why does the elimination method work?
My two equations are:

$x-2y=1$
$3x+2y=11$

We know that we can add something to both sides of an equation and maintain equality. For example I can take
$3x+2y=11$
and add 1 to both sides to get
$3x+2y+1=12$
And from the first equation, we know that $x-2y=1$, which we can substitute back in.
$3x+2y+1=12$ becomes $3x+2y+x-2y=12$
Combine like-terms to get $4x=12$. Solve for $x$, then solve for $y$.
Then I guess I would show my students how doing it in columns saves a lot of time, and also makes it more obvious of multiplying the equations by some constant to ensure they will eventually eliminate a variable.
Answer: Lets have:
$$5x + 2y = 3$$
$$7x -3y = 1$$
You can sum something at both sides of an equation (See this link for discussion: Why we can add an element on both sides like this?)
Now we add something to the first equation:
$$5x + 2y + (7x -3y) = 3 + (7x -3y)$$
But this something equals to 1, then:
$$5x + 2y + (7x -3y) = 3 + (1)$$
And rearranging:
$$5x + 7x + 2y -3y = 3 + (1)$$
Finally:
$$12x - y = 4$$
This new equation is called a linear combination of both original equations. Since we added something at both sides in the first equation of the system, the new equation is like the first one but transformed and has the same solutions, the same way that:
$$x + y = 3$$
and
$$ 2x + 2y = 6$$
(In this last case we multiplied a something by another something)
By the way, I think this is not so obvious. I started to think about it studying the first chaper of Hoffman-Kunze book.
Comment: This adds nothing to the answers provided several years ago.
Comment: I think is more clear and intuitive.
Answer: We have:
$$x=\dfrac{n-by}{a}$$
$$x=\dfrac{m-dy}{c}$$
so we eliminate $x$ by writing:
$$\dfrac{n-by}{a}=\dfrac{m-dy}{c}$$
$$cn-bcy=am-ady$$
$$y(ad-bc)=am-cn$$
$$y=\dfrac{am-cn}{ad-bc}$$
Answer: I think maybe something's not being said here that's really important. (This is really a long comment, and only kind of an answer.)
You say things like "the rule seems arbitrary," and "has been thrown in for no reason." This is a rather strange way of looking at mathematics, as if for any given situation put in front of you, there are some rules for how to solve it and you just follow them. If this was the case, computers would just do all math and there'd be no mathematicians.
But this isn't what mathematics is like at all. Instead, we have some starting points we call axioms. These are arbitrary, but in some sense they are designed to conform to our expectations. Commutativity, associativity, distributivity, all of these are basic building blocks which we intuitively understand as true.
From here, we go about proving theorems, and solving problems. By this I mean, using the basic axioms and definitions to prove properties of certain things, like equations or geometric objects or algebraic systems. This method produces something new which we didn't know before, and in the case of your particular question, is how the solution is worked out. In algebra of real numbers, we have a rule for cancelling and a rule for adding/subtracting/multiplying/dividing equally to both sides of an equation. These are the axioms for algebra with real numbers. It turns out that by just using these basic properties, we can determine what the solution to the problem is. In short, it isn't some rule which is just made up arbitrarily, it is the result of thinking through the difficulties and using the properties to reach a solution.
To get an intuitive picture of what all this means, think of it like this. You have two equations in two variables, each has infinitely many possible solutions since they are like lines, but you want to find only the solutions that satisfy both. That is to say, you want to restrict your search to only look for solutions of one guy that also satisfy the other. To do this, you must somehow insert as a restriction the requirement that the other equation hold. That is to say, you must combine the two relationships between $y$ and $x$ so that you can find a solution to both.
So what you do, is solve one equation for one of the variables. This is just rewriting the same relationship in different terms. But once one of the equations is solved in terms of one variable, substituting that equation into the first is the restriction we need. We are saying "this equation satisfies the relationship it expresses itself, but it also has this other relation we have just inserted into it." Now you can do algebra in one variable to solve, and then use this information to find the other variable.
So really we are not applying any arbitrary rules, we are thinking through the problem and applying the basic concepts we know to reach a solution.
Comment: Thanks for your reply, but I was looking for a proof of why we can 'column subtract' when solving using the elimination method. The elimination method and substitution method are two disparate methods.


How do I use student's-t distribution without the sample size?

Question: Here is my question (homework obviously):
A sample from a normal population produced variance 4.0.
Find the size of the sample if the sample mean deviates from the population
mean by no more than 2.0 with a probability of at least 0.95.
So I'm trying to find $n$, the sample size, having only $\hat{\sigma}$, the sample variance, and a bound on the distance between $\bar{x}$ and $\mu$. My intuition was normally in this situation we need to use the t distribution since $\hat{\sigma}$ is an unbiased estimate for $\sigma$ (we did all the proofs in class).The problem is the t distribution changes depending on $n$, the sample size, so which distribution (how many degrees of freedom) should I consult when looking up the t-values containing 95% of the probability mass? I tried it for different values of $n$, and then squared the values to compare them to the d.f. of the t distribution - the closest I could get was 0.6 off. (I took the t-value at $\alpha = 0.025$ (right-tail) for 5 d.f., implying $n$ is 6, and squaring the t-value gave me 6.61, which is a discrepancy of 0.61 (isn't this large?). The reason I squared the t-values becomes apparent if you "normalize" the bound on the means into a t-statistic. Am I going about this correctly? This doesn't seem right...
(edit - this is what I did):
We have $P(\left| \bar{x} - \mu \right| \leq 2.0) \geq 0.95$, also given is $\hat{\sigma} = 2$, need to find $n$. So:
$$-\sqrt{n}\frac{2.0}{\hat{\sigma}} \leq \sqrt{n}\frac{\left( \bar{x} - \mu \right)}{\hat{\sigma}} \leq \sqrt{n}\frac{2.0}{\hat{\sigma}}$$
filling in values:
$$-\sqrt{n}\frac{2.0}{2} \leq \sqrt{n}\frac{\left( \bar{x} - \mu \right)}{\hat{\sigma}} \leq \sqrt{n}\frac{2.0}{2}$$
then:
$$-\sqrt{n} \leq \sqrt{n}\frac{\left( \bar{x} - \mu \right)}{\hat{\sigma}} \leq \sqrt{n}$$
at this point I was pretty confused, so what I did was look up values for $\alpha = 0.025$ at different degrees of freedom for the t-distribution, and then since d.f. = n - 1, I took that t-value (which is $\sqrt{n}$ from what I've derived) and compared it to the value of n implied from the d.f. I was using...For example take the t distribution with 5 d.f. (implying sample size is 6). The t-value is 2.571 for my $\alpha$. Squaring this to get n, we get 6.61. So this n clearly $\neq$ 6 which was implied in the distribution I was using. All of this seems kind of ridiculous...Where did I fudge things?
Comment: I'm not sure where else you posted it but it's definitely on topic here on Cross-Validated so I'd delete the other one, whatever it is.
Comment: FYI, it's generally considered bad form to post the same question to multiple SE sites simultaneously.
Comment: should i delete one? which one?
Comment: ...or flag it so a moderator can look after it for you...
Answer: Your basic approach of using the t distribution is on the right track, but I think you go off the rails somewhere.
Consider that the range you know about the value of the mean is actually a half width confidence interval.
Having come back to this - interesting question
By half width confidence interval I mean the 2; your estimate +/-2 is within a 95% confidence interval.  So if I understand correctly you need to solve:
$2=t_{(0.975,n-1)}\sqrt{\frac{4}{n-1}}$
Ie find the value of n that 97.5th percentile of the t distribution with n-1 degrees of freedom, multiplied by the estimated standard error of your estimate, equals your half width confidence interval of 2.  If n were a really large number so your statistic approximates a normal distribution t would be 1.96; the question is to find what it actually is, at the same time as n features as an unknown in your estimate of the sample variance.
This cannot be solved directly but you can find the value of n (which must be an integer) to give the closest match through other methods.
Hopefully I haven't gone too far given this is homework.  .
Comment: I'm not sure I understand that bit about the half width confidence interval. I'll also edit my post to explain more clearly what I did.


Management for Netapp filers and vFilers

Question: How can I manage the system files on a filer or vFiler in Netapp? There are a couple of really important system files in every filer that it's really only feasible to manage by hand. While there are sometimes tools to manage them from a GUI, it's inconsistent. I find myself managing the following things by hand the most:

/etc/exports
/etc/group
/etc/passwd
/etc/cifs_homedir.cfg
/etc/rc (real filers only)
/etc/hosts
/etc/quotas
Comment: I find we end up hand editing `/etc/quotas` as well.
Comment: Yeah, that's a good one.
Answer: There are a few ways to edit these systems. You can mount them using NFS or CIFS, or you can use commands on the main filer. You could also use FTP. Either of the mount options relies on the protocol (CIFS or NFS) being enabled.
NFS
You can mount the /etc directory on any NFS client and have access to all the files. The only restriction that matters is that you have to be root on the system you're using. If you're not the admin for the server, you can still mount the directory, but you can't modify things (at least not without making things less secure). If you have a properly configured LDAP environment, this may not be an issue.
CIFS
CIFS is another way to get to /etc. When you set up the CIFS daemon on Netapp, you have the opportunity to create a local administrator account- it's a good idea. When you try to browse to \\filer\etc$\, you'll be prompted for a login. Use the username filer\administrator and the password you set up during the cifs setup command.
Filer commands
Of course, sometimes you might need to use the native command line sometimes for this. Unfortunately, the primary tools provided for this are a little kludgy: rdfile and wrfile will allow you to read and write to any location, however every time the system decides to spit something out into the terminal, it'll mess up the spacing of your line. Any time this happens, it doesn't actually make it into your file, and you can press control-r to get the line you're working on back from the beginning.
If you can't mount /etc/, it's usually because you aren't on the same network as a vFiler. One way to get around this restriction is to use ndmpcopy to copy the file you need to edit back to a filer that is on the same network, where you could mount a volume and edit the file in an editor in Windows or Unix/Mac.
FTP
This is much riskier, but if you have no other option, you can use FTP to access any data on the filer. There's an option to allow complete access to the filer through FTP that defaults to off. I'd recommend leaving that off, and instead, while you're doing your work, allow FTP access to just /etc. Remember that this is FTP- passwords are sent in plaintext.


Fatal error - Media module

Question: I keep getting the following error for some reason:

Fatal error: Cannot redeclare media_views_invalidate_cache() (previously declared in /var/www/html/sitename/sites/all/modules/media/media.views.inc:140) in /var/www/html/sitename/profiles/dkan/modules/contrib/media/media.views.inc on line 140

Is there any reason I'm getting the error?
I'm using Drupal 7.54.
Answer: Looks like you have media installed twice. Once as part of your installation profile (or distribution) and once as a 'loose' module. Which I suppose occurred because there was a security update and you did not want to wait for the distribution to update.
Make a backup and remove <code>/sites/all/modules/media</code>. That should solve it.
Comment: Well I did that, however, it shows the following error message: User warning: The following module has moved within the file system: media. In order to fix this, clear caches or put the module back in its original location. For more information, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /var/www/html/sitename/includes/bootstrap.inc).  I also did a drush rr and it crashed the system and just a regular clean cache and it also crashes the system.
Comment: And what if you disable or uninstall it first? You'll need to get rid of the 2nd installation somehow

Fatal error - Media module


Drupal 8 Views or Pixture Reloaded paging/formatting problem

Question: Looks like I may have tripped over yet another bug in either Views or Pixture Reloaded in D8.
I created a view to show a simple content type I created called Newsletters. I can use the pager supplied by views to navigate to page 2 without a problem, but when I click page 3 or Next Page I get a screwed up display.
Excerpts from page 2 that displays properly.

Excerpts from page 3

View that I created.

Do you think this is a Views problem or a Pixture Reloaded problem?
Answer: Problem solved.
Looks like I had a corrupted instance of my Newsletter content type. When I deleted it the problem went away.


How to remove text from a line starting from the fourth tab to the end of the line?

Question: I've just started programming, therefore I'm kinda noob.
I'm trying to use python to remove a column from a .txt table. All columns are separated by tabs.
This is an example line:
100226.SCO0401  1   440 COG0001 glutamate-1-semialdehyde 2,1-aminomutase

I want to remove all text in the line after the fourth tab (the "glutamate-1-semialdehyde 2,1-aminomutase" part).
I've seen some people importing csv to work around this issue, but I was thinking of something simple like:
def remove(infilename, outfilename):
    # Open original file and output file
    infile = open(infilename, 'rt')
    outfile = open(outfilename, 'wt')

    # Read lines and remove annotation
    for line in infile:
        outfile.write(line['**everything-until-the-fourth-tab**']

    # Close files
    infile.close()
    outfile.close()

The bold part is my issue right now. Any suggestions?
Thanks in advance.
Answer: Use .split('\t') to split the entries in the row into an array. You can then slice the array with [:4], keeping only the first 4 elements. Finally, join it back up again with '\t'.join:
for line in infile:
     columns = line.split('\t')
     columns = columns[:4]
     outfile.write('\t'.join(columns))

As a one-liner:
for line in infile:
     outfile.write('\t'.join(line.split('\t')[:4]))

Comment: Gonna try that ASAP. Can you just 'translate' the last line? The '\t'.join part. I got the (columns[:4]) one ^^'
Comment: @EdwardCoelho  `'\t'.join(columns)` is equivalent to `columns[0]+'\t'+columns[1]+'\t'+columns[2]+'\t'+columns[3]`
Comment: Thanks, worked like a charm. I just added a \n at the end to keep the 'table look'
Answer: I submit that using the csv module may be the simplest solution:
with open(infilename, 'rb') as infile, open(outfilename, 'wb') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    for row in csv.reader(infile, delimiter='\t'):
        writer.writerow(row[:4])


Bijective compositions implies each function is bijective.

Question: Let $X,Y,Z$ and $W$ sets, $f:X \to Y$, $g:Y \to Z$ and $h:Z \to W$ functions. If $g \circ f$ and $h \circ g$ are bijective, then $f,g$ and $h$ are bijective.
My attemp of proof goes as follows: As $g \circ f$ and $h \circ g$ are both injective and surjective, then $f$ and $g$ are injective, $g$ and $h$ are surjective. So $g$ is bijective. How do I prove that $f$ is surjetive and $h$ is injective in order to show that $f$ and $h$ are also bijective?
Thanks.
Answer: As you have already noted the information given shows that $g$ is bijective and hence so is $g^{-1}$. Since a composition of bijections is a bijection we have that $f = g^{-1} \circ g \circ f$ is a bijection and similarly for $h$.
Answer: Because $g \circ f$ is bijective and $g^{-1}$ exists and is bijective, $g^{-1} \circ (g \circ f)$ is also bijective.


matriz inverter position C

Question: I tried to invert using the loop but on the second iteration the result was not expected,
<code>#include <locale.h>
#include <stdio.h>
#include <stdlib.h>

void main(){
 setlocale(LC_ALL,"");
 printf("Exercício de Fixação - Inverter as Linhas da Matriz\n");
 int matriz[2][2];
 matriz[0][1]= 50;
 matriz[0][0]= 52;
 matriz[1][1]= 31;
 matriz[1][0]= 13;

 //matriz  in descending positionte
 for(int linha=0 ; 2 > linha; linha++){
     for(int coluna=0 ; 2 > coluna; coluna++){
       printf("%d ", matriz[linha][coluna]);
         }
        printf("\n");
     }

  //inverted matrix
 for(int  linha=2; linha > 0 ; linha--){
    for(int  coluna=2; coluna > 0 ; coluna--){
      printf("%d \n", matriz[linha][coluna]);
   }
printf("\n");
  }

}
</code>
The way I did it is not working, :/
why is that even reversing the position in the loop the result not following the loop instruction
Comment: Why was it not expected? What did you get? What did you expect?
Answer: When counting in reverse, you're starting the index at 2 and ending at 1.  You need to adjust these to start at 1 and end at 0.
<code> for(int  linha=1; linha >= 0 ; linha--){
    for(int  coluna=1; coluna >= 0 ; coluna--){
      printf("%d \n", matriz[linha][coluna]);
   }
   printf("\n");
  }
</code>

matriz inverter position C


How to check if the correlation between two continous variables is influenced by a categorical factor?

Question: I have a data frame (df) where I see correlation between two continuous variables (c1 and c2). I need to know whether the observed correlation between the two variables differs between groups, which are identified with a categorical variable (v1)?
I tried to find interaction using lm function in R. I tried lm(c1~c2*v1,data=df) and looked for p value of the interaction c2:v1. I am not sure if this is correct. Please correct me if I am wrong.
Answer: I think you should implement a Sperman correlation (by group).
See this link, to another stackexchange.com question.
In alternative, see this other link, to another stackexchange.com question.
Comment: Thank you for those links. But I also need to know if the correlations obtained by factors are statistically different. Any comment on that?
Comment: Doesn't R give you p-values as well? That's what you should look at.
Comment: I meant if I get correlation in subset1 is 0.4 and subset2 is 0.6, I need to know if correlation in subset1 is statistically different from correlation in subset2. Hope you get me.
Comment: Lets say I am looking for the correlation between the blood insulin and glucose levels in a group of participants. Suppose if i need to know how the correlation varies, if i group them in to diabetics and non-diabetics, what should I do.
Comment: I have tried to clarify your question. Roll it back if you do not like it or distort the meaning of your initial question.
Comment: Ok, given what I have understood now, it seems that your initial approach makes sense. One thing though (I am not a doctor), is there any reason to think that  being diabetics per se does not affect C1?
Comment: That is an example I gave, since its well known fact.
Comment: Normally, when you use an interaction in your regression, you should add also the main effects; instead, you would exclude the main effects of v1 or c2 only if you had a very strong reason for doing that. So, probably your command should be: lm(c1~c2*v1 + c2 + v1,data=df). But I am not sure it is the best way of doing that.
Comment: See the previous comment. The coefficient on c2 would give you the effect of c2 on c1 when v1 is 0. When v1 is 1, the total effect of c2 on c1 would be given by the sum of the coefficients on c2 and c2*v1. The coefficient on v1 would give you the effect of v1 on c1. If there was no difference between groups in terms of effect of c2 on c1, the p-value of the interaction effect would have you rejecting the H0.


Ao utilizar back() no laravel este deve ser precedido por redirect()?

Question: Observando muitas implementações vi que o pessoal utiliza com uma certa frequência return redirect()->back()... Minha dúvida é:
Qual a diferença entre return redirect()->back()... e return back()...
Answer: Essas são duas formas de fazer a mesma coisa, ou seja, redirecionar para o local anterior e são funções que retornam a instância da classe Redirector e tem como principal objetivo facilitar no desenvolvimento.
Estruturas:
back()
function back($status = 302, $headers = [], $fallback = false)
{
    return app('redirect')->back($status, $headers, $fallback);
}

redirect()
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
    if (is_null($to)) {
        return app('redirect');
    }

    return app('redirect')->to($to, $status, $headers, $secure);
}

Sobre as estruturas, é que o redirect pode chamar os outros métodos, enquanto back() já seria a chamada do método, as duas formas são corretas, mas, a back() nesse caso é que se encaixa melhor.


Displaying tiled and overlapping images

Question: I'm trying to make a simple browser game without relying on anything fancy like flash or html5.  I was doing pretty well in getting everything set up, but when I got to the ground I ran into trouble as I'm not very good at setting up html pages.  I want to have a tiled ground that I can put objects on, then click on the objects to take the user to another page.  I'm not sure how to go about something like this and am looking for some direction.
I have a fairly good grasp on PHP, understand basic html, very limited css and am starting to learn javascript and am planning on picking up jQuery.
Answer: I don't really understand what you want, but this might help:
Live Demo
To understand how the positioning works, see:

http://css-tricks.com/absolute-positioning-inside-relative-positioning/
http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

HTML:

CSS:
#gameContainer {
    width: 320px;
    height: 320px;
    border: 1px solid #000;
    background: url(https://i.stack.imgur.com/sFV9k.png);
    position: relative
}

.wall {
    background: url(https://i.stack.imgur.com/IFjyp.png);
    width: 32px;
    height: 32px;
    position: absolute
}

Comment: This looks EXACTLY like what I need!  Thank you so much!

Displaying tiled and overlapping images


Which are the suitable classification algorithms when the number of categories are more than 1000

Question: Combination of categories is not possible as each class is a distinct brand.
One similar challenge was classifying objects using images (link below) but I could get any specific direction from few papers published regarding the same http://www.image-net.org/challenges/LSVRC/2014/
Alternative approach if algo is not suitable is to build Wordnet/frequency based structure out of available brand-word data & create distance matrix from it Another one is to aggregate the categories & build 2 levels of brand prediction (not sure if it will be effective at all)
Comment: + Not a clustering problem
Comment: I am not sure I understand your problem, how big is your dataset ? Why is the number of clusters a problem ? (It is a naive question as I've never thought it could be a problem)
Comment: My data set is about 100K rows with product information(scraped from web) & high level product category (about 500 distinct categories) with product brands (about 35K) which I want to predict
Comment: Well if you have no separation problem and all your classes are somewhat balanced in your training dataset then I don't see why a simple GLM with variables selection wouldn't work (though it will take some time to fit it considering the dataset). There's also random forests but they are doing worse than GLM when trying to predict outside of their 'training ranges' so I would stick to GLM
Comment: Clustering and classification aren't that fundamentally different in my opinion, both tries to group similar individuals in clusters whether or not you actually have a prior insight on the clusters (supervised or unsupervised). The means and approach are different but not the endpoint, I have seen uses of k-means clusters for further 'predictions'.
Comment: @kjetil Could you please provide a wiki excerpt for [many-categories]?
Comment: will do! ..................................
Answer: With the limited information that you've given about the dataset, here are few questions that you can consider. I believe you'll need to frame your problem better and purely classification algorithm A Vs. B is not the issue.
Things to Consider

Do you fundamentally believe that the information/independent columns can predict your labels?
Do you really need the classification to accurately work for all kind of brand labels?

For certain top level brands you can derive the correlation (if product categories are sportswear and sport equipment it is likely to be a Nike). But for certain brands where # of products are small, deriving such correlation may not be possible.

The problem looks ill posed due to size of dataset (100k rows Vs. 35k labels). A large number of your categories are going to have a single data point where most of the methods are going to fail (for example, it will be hard to do cross-validation on many categories).

Suggestion

Re-frame your problem. Check if you really want to predict 35k possible categories or you are better off considering, let us say, top 100 brands which contribute most of the products.
For such large scale categorization problems, you can start with neighborhood based models.
Check the discussion discussion forum of this wikipedia categorization challenge on Kaggle for more ideas. [1]