Toggling A Click Handler Function On an Input Event Listener — Javascript

Question: I'm setting up a form that submits to a MySQL database via PHP and there are server-side validations that take place for security reasons. I would like the frontend validation messages to be handled with JavasScript because there are many similar forms on the site, and would like these linked to the input event listener.
In the following code the submit button has a preventDefault() method on it until the title is more than 10 characters long. I've read that the best way to add and remove preventDefault is via a click handler function, which I'm using.
By default the button has a .prevent-default class on it and this is removed when the input passes the validation.
The Issue I'm Experiencing
The preventDefault and the error message work if the form is submitted when less than 10 characters are typed, and of course if more than 10 characters are typed the form will just submit as expected.
However, when more than 10 characters are initially typed, and the user then deletes some characters to bring the count back below 10, the form still submits on the front end? I would like it to fail again, with the same error message showing after the submit button is clicked.
I think the solution is to toggle the checkValidations() function. I can't seem to be able to do this though.
NOTE: Some of the elements use the forEach loop because on the full site there will be multiple instances of the form.
CodePen Link: https://codepen.io/thechewy/pen/GROEmoN

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {
    evt.preventDefault()
    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""

        // call the function that removes the preventDefault method
        checkValidations()
      }
    })
  }

function checkValidations(){
  if (dmTitle.value.length > 10) {
    preventSubmit.forEach(item => {
      item.removeEventListener('click', clickHandler, false)
      item.classList.remove('prevent-submit')
    })
  }
}

} // end of 'if (preventSubmit)' statement
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}
<form method="post">

    <input id="dm-title" name="dm-title">

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>
Answer: Looks like you do need to remove validation everytime when all is OK, just execute preventDefault if an error is detected:

var dmForm = document.querySelector("form"),

// class name on the submit button
preventSubmit = document.querySelectorAll(".prevent-submit"),
dmTitle = document.querySelector("#dm-title"),

// empty element for error message
dmTitleError = document.querySelector(".js-dm-title-error")

// function that prevents default click action on button and adds warning message
var clickHandler = function(evt) {

    if(dmTitle.value.length < 10) {
        dmTitleError.classList.add('warning')
        dmTitleError.textContent = "Title must be more than 10 characters"
evt.preventDefault(); // <-- prevent from sending and show warning
    }
}

// checks for 'prevent-submit' class and if present invokes the clickHander function above
if (preventSubmit) {
  preventSubmit.forEach(item => {
    item.addEventListener('click', clickHandler, false)
})

  // removes warning when the user types more than 10 characters
  if (dmForm) {
    dmTitle.addEventListener('input', () => {
      if( dmTitle.value.length > 10) {
        dmTitleError.classList.remove('warning')
        dmTitleError.textContent = ""
      }

    })
  }

} // end of 'if (preventSubmit)' statement
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

input,
button {
  padding: 0.5rem;
}

.js-error-message.warning {
    background: #cc1f1f;
    transition: background .5s;
    padding: 0.2rem 0.5rem;
    margin-top: 0.5rem;
    display: inline-block;
    position: absolute;
    bottom: -5rem;
}
<form method="post">

    <input id="dm-title" name="dm-title">

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>
Answer: Checking form.onsubmit event would be more suitable.
https://codepen.io/_yigitt/pen/JjOpmPW
form1.onsubmit = function () {
    if (inputFirstName.value.length < 10) {
        p_error.classList.add("warning");
        p_error.textContent = "Title must be more than 10 characters";
        return false;
    }
};

inputFirstName.oninput = function () {
    if (this.value.length > 10) {
        p_error.classList.remove("warning");
        p_error.textContent = "";
    }
};

Answer: This is easier to implement if you use the inbuilt DOM Constraint Validation API :

let form = document.querySelector("form");
let error = document.querySelector(".js-dm-title-error")
let title = document.getElementById('dm-title');

title.setAttribute("minLength", '10');

title.addEventListener('input', function(e) {
  if (!title.validity.valid) {
    // if you want to nag on every character entered
    //showError("Title must be more than 10 characters");
  } else {
    showError('');
  }
});

form.addEventListener('submit', function(event) {
  // check each field
  if (!title.validity.valid) {
    showError("Title must be more than 10 characters");
    event.preventDefault();
    return false;
  }

  // mimicking form submit
  output.innerHTML += `Sending ${title.value}...<br>`;
  event.preventDefault();
  return false;
});

function showError(msg) {
  if (msg) {
    error.classList.add('warning')
    error.textContent = msg;
  } else {
    error.classList.remove('warning');
  }
}
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 0;
}

form {
  display: flex;
  align-items: center;
}

.input-wrapper {
  position: relative;
}

input {
  display: block;
  margin-right: 0.5rem;
  border-radius: 0.3rem;
}

input:invalid {
  background-color: rgb(255, 220, 220);
}

input:invalid:required {
  border: 1px dashed red;
}

input:valid {
  background-color: rgb(211, 255, 211);
}

.js-error-message {
  display: none;
  position: absolute;
  top: 100%;
}

.js-error-message.warning {
  display: inline-block;
  padding: .2rem;
  width: 169px;
  font-size: 80%;
  color: white;
  background-color: #900;
  border-radius: 0 0 5px 5px;
  box-sizing: border-box;
}
<form method="post" novalidate>

    <input id="dm-title" name="dm-title" required>

  <button name="dm-submit" class="prevent-submit">SEND MESSAGE</button>
</form>

Answer: The validation needed is already built in -- no JavaScript is required. It's better UX to flash error messages when there's a real error. It's irritating to see messages popping up about requirements not being met when you just started typing. It's best just to show error messages at the submit event.
The input found in the example below has two attributes:

minlength="11" At submit if the input has 10 or less characters, the form will cease submitting and an error message pops up.

required At submit if the input is empty, the form will cease submitting and an error message pops up.

Also, there's no weird behavior (ex. enter 12 chars, remove 5 and submit successfully) in this simple validation. Also in the example, data is sent to a live test server and the iframe is there to show server response.

<!DOCTYPE html>

  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <form action='https://httpbin.org/post' method="post" target='response'>
      <fieldset>
        <legend>Direct Message</legend>
        <input id="message" name="message" minlength='11' required>
        <button name='btn'>Send Message</button>
      </fieldset>
      <fieldset>
        <legend>Server Response</legend>

      </fieldset>
    </form>


Função Python na AWS Lambda

Question: Estou precisando rodar a seguinte função abaixo no AWS Lambda:
def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

# check if the partial sum is equals to target
if s == target:
    print("sum(%s)=%s" % (partial, target))
if s >= target:
    return  # if we reach the number why bother to continue

for i in range(len(numbers)):
    n = numbers[i]
    remaining = numbers[i + 1:]
    subset_sum(remaining, target, partial + [n])

if __name__ == "__main__":
    subset_sum([1,2,3], 5)

Contudo aparece este e não consigo resolver:
{
  "errorMessage": "'>=' not supported between instances of 'int' and 'LambdaContext'",
  "errorType": "TypeError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      7,
      "subset_sum",
      "if s >= target:"
    ]
  ]
}

A função original tem mais valores que demoram muito tempo por isto estou tentando rodar no Lambda. A função retorna a combinação de números que resultam na soma do valor definido (no caso 5)
No computador utilizando py subset_sum.py funciona normalmente e retornar 2 e 3 (que combinados é igual a 5).
ATUALIZAÇÃO
Fiz a modificação conforme resposta do Tom. Agora reporta outro erro.
def lambda_handler(event, context):

    s = sum(event['partial'])

    if s == 5:
        print("sum(%s)=%s" % (event['partial'], 5))
        exit()
    if s >= 5:
        return

    for i in range(len(event['numbers'])):
        n = event['numbers'][i]
        remaining = event['numbers'][i + 1:]
        dict = {'numbers' : remaining, 'partial' : event['partial'] + [n]}
        lambda_handler(dict)

if __name__ == "__main__":
    dict = {'numbers' : [1,2,3], 'partial' : []}
    lambda_handler(dict)

Saída do Lambda
{
  "errorMessage": "'partial'",
  "errorType": "KeyError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      5,
      "lambda_handler",
      "s = sum(event['partial'])"
    ]
  ]
}

Saída print(event) logo no início do handler
START RequestId: f3a45f36-b1fc-11e7-8f6d-d5a3a428a4fd Version: $LATEST
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
'partial': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 7, in lambda_handler
    s = sum(event['partial'])
KeyError: 'partial'
END RequestId: f3a45f36-b1fc-11e7-8f6d-d5a3a428a4fd

Comment: Dica:
Existem ferramentas que simulam um ambiente lambda na tua máquina (ex: serveless framework), usa elas pra testar teu código localmente e depois de testar faz deploy do código no lambda, isso ajuda muito a encontrar erros antes deles ir para a amazon (já sofri bastante com isso).
Answer: Se você definiu a função subset_sum como handler da sua Função Lambda, os parametros que são passados são diferentes do seu teste subset_sum([1,2,3], 5).
O invoke do handler recebe os parametros:

event - Evento responsável pela execução da Lambda Function (API Gateway, CloudWatch e etc);
context - Informação de runtime.

O erro acontece pela comparação que você está fazendo entre um int e um objeto LambdaContext.
Os parâmetros devem ser acessados através do evento, ex:
def my_handler(event, context):
    partial = event['partial']
    target = event['target']

    print(partial)
    print(target)

Documentação: http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html
EDIT

Pra definir os valores do evento de teste através do console:
Lambda -> (Selecione sua Função Lambda) -> Select a test event -> Configure test events
Comment: Fantástico Tom! Muito obrigado!

Consegui corrigir corretamente. Agora ainda está dando um errinho pra rodar:

"errorMessage": "'partial'",
"errorType": "KeyError".

Estou investigando.
Comment: Coloque um print do event para ver a estrutura de dados que está chegando no seu handler e veja o log no CloudWatch. Por onde você está chamando a função Lambda? API Gateway ? CLI ? Cron no CloudWatch ?
Comment: Fiz um update na pergunta @tom-melo. Na verdade estou testando a função primeiramente clicando em "Test" diretamente no AWS Lambda.
Comment: coloque um print(event) logo no começo do handler, vai aparecer o log no CloudWatch,
Comment: Show, Tom. Coloquei uma atualização na resposta. Obrigado pelo apoio, é bem importante a resolução desta questão.
Comment: Pelo log não existe a Key "partial", só existe o dict: {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}, no seu teste você deve passar o JSON que você espera no seu código: { "partial": [], "numbers": [1, 2, 3] }
Comment: Compreendo... O engraçado é que eu chamo ele, olha:

if __name__ == "__main__":
dict = {'numbers' : [1,2,3], 'partial' : []}
lambda_handler(dict)
Comment: Não, digo o "teste pelo console", quando o core do AWS Lambda faz o invoke da sua Lambda Function ele não passa pelo if name == 'main', ele chama apenas sua função handler injetando o envento e o contexto. La no console da aws da um "edit and test" e coloca o input(json) correto.
Comment: Perfeito, Tom. Agora entendi... E onde defino os valores iniciais de event? Desculpes pelas simples perguntas. Tentei definir dentro de Environment. Preciso que seja {'numbers' : [1,2,3], 'partial' : []}.
Comment: Editei a resposta, vê se você consegue encontrar no console da aws.
Comment: Tom... Deu certo!!! São pessoas como você que fazem a diferença!!! Vou detalhar a resposta aqui e no StackOverflow US. Lá não havia consegui uma resposta como a sua. Agora estou entendo o tempo/memória/cpu pra executar a função com a quantidade de termos que preciso. Sucesso!

Função Python na AWS Lambda


JavascriptSerializer, Deserializer, not able to deserialize my object

Question: I am unable to deserialize my custom object.
public class UserInfo
{
  public int Id1 { get; set; }
  public string Code { get; set; }
  public int Id2 { get; set; }
  public List<string> Roles { get; set; }
  public string Eg1 { get; set; }
  public DateTime Time{ get; set; }
  public string Eg2 { get; set; }
  public string Version { get; set; }
}

JavaScriptSerializer serializer = new JavaScriptSerializer();

return serializer.Deserialize<UserInfo>(raw);

The Deserialize is throwing an exception
"Cannot convert object of type 'System.String' to type 'UserInfo'"
JSON Contents:
"\"{\\\"Id1\\\":0,\\\"Code\\\":null,\\\"Id2\\\":0,\\\"Roles\\\":null,\\\"Eg1\\\":\\\"Eg2\\\",\\\"Time\\\":\\\"\\\\/Date(-62135596800000)\\\\/\\\",\\\"Version\\\":\\\"126.96.36.199\\\"}\""

Note: Let me know, if it is unclear. I'll edit the question.
-- edited. ID2 changed to Id2. The real class is different in terms of variable names. Hence the issue.
Comment: Surely there aren't all those \'s in the JSON! Make sure to put the *actual [JSON] text* in the post, not the inspector-what-if-this-were-a-string-literal value .. if this was done it *would be obvious* that the *text* value is `"json junk which is in a string and not a JSON object"`.
Comment: Thanks ... Seems i was on sleeping pills. When I looked at it I was serializing twice! hence unable to re-cast. It is working now. Updated the correct JSON.
Answer: Your string is a C# string containing a JavaScript string containing JSON. Short of fixing what you're being sent, here's how you would deserialize:
var jsonString = serializer.Deserialize<string>(raw);
return serializer.Deserialize<UserInfo>(jsonString);

Comment: This will not work. string does not have a parameterless constructor.
Comment: Thank you! I have been looking for a method of approach this clean. I never thought of the type casting to string prior... Works like a charm
Answer: You are passing a Javascript string to your deserializer because you have your object within an escaped string.
After unescaping it, this is what the serializer receives:
"{\"Id1\":0,\"Code\":null,\"Id2\":0,\"Roles\":null,\"Eg1\":\"Eg2\",\"Time\":\"\\/Date(-62135596800000)\\/\",\"Version\":\"220.127.116.11\"}"
What you really want to send it is:
{"Id1":0,"Code":null,"Id2":0,"Roles":null,"Eg1":"Eg2","Time":"\/Date(-62135596800000)\/","Version":"22.214.171.124"}"
Answer: Your ID2 is all caps in the JSON and the Id2 is not in your class.
EDIT:
Try creating an instance of the object and serialize it to JSON to compare and see if the JSON is correct or not. You can then use that string to properly format.
Answer: The code below should help someone get up and running.
the above code will cause an error on  because string has no default constructor.
If a string is passed in from JSON.stringify() client JavaScript method the second Deserialize may work if the object passed in maps to the public fields in the  object.
Let's look at a quick example presuming an .ASHX file receives the request from a jQuery call that looks like this:
//Called from with a jQuery ready() in a simple html page

var getNewPerson = function ()
{
var NewPerson       = new Object();
NewPerson.PersonID  = "0";
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName  = $("#LastName").val();
NewPerson.Address   = $("#Address").val();
NewPerson.City      = $("#City").val();
NewPerson.State     = $("#State").val();
NewPerson.Zip       = $("#Zip").val();

var arrObj;
var str = "";
var webMethod = "http://someserver.com/admin/DataHandler.ashx";
$.ajax({
cache: false,
url: webMethod,
type: "POST",
dataType: "json",
 /* for hashtable or .net web service -  data: "{\"NewPerson\":" + JSON.stringify(NewPerson) + "}", */
data: JSON.stringify(NewPerson),
contentType: "application/json; charset=utf-8"
}
)
.done( function(){}... code here ...etc)

//Valid JSON object format: {"PersonID":"1","FirstName":"Rick","LastName":"Wright","Address":"4520 No Such address Ave.","City":"Riverside","State":"CA","Zip":"92503"}

//And here is a sample class on the C# side in the .ashx handler page.
public class NewPerson
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    } //  EOC Person

// And in the process request
public void ProcessRequest(HttpContext context)
{
string jsonString = "";
string rawJson = "";
System.Diagnostics.Debugger.Break();

HttpContext.Current.Request.InputStream.Position = 0;
string responseString;
var jsonSerializer = new JavaScriptSerializer();
/*Set the stream position to 0 */
context.Request.InputStream.Position = 0;

using (System.IO.StreamReader inputStream = new StreamReader(context.Request.InputStream))
{
rawJson = inputStream.ReadToEnd();
}
var objNewPerson = jsonSerializer.Deserialize<NewPerson>(rawJson);
if (clientList != null)
{

responseString = objNewPerson.FirstName + " " + objNewPerson.LastName ;
}
else
resp="No Record Found";
} // eof ProcessRequest


Why did the Indian team change their jersey colour in the middle of World Cup 2019?

Question: In the middle of World Cup 2019, the Indian cricket team changed their jersey colour:

Why did they do this?
Answer: There is a new ICC regulation that teams in televised matches must have contrasting kits, just as in football or many other sports1. As India's normal blue jersey would clash with England's, one of the teams had to change - and the rules are that England always get priority as the home team for this World Cup, so India played the England match in their second kit.
A similar situation has already happened with South Africa who wore their yellow kit against Bangladesh; the oddity here almost that neither team has changed kit in the England-Afghanistan and India-Afghanistan matches.
Cricinfo has some more details.

 1. It's obviously somewhat less critical in cricket that the teams were contrasting colours than in football. You could argue it's for the benefit of new television viewers who are used to seeing two "different" teams, you could argue that it's to sell more jerseys...


Server is not sending the response in java using socket programming

Question: When I'm sending some data to server from client, server is not giving me the response. When I enter all the data till Gender, the cursor blinks there. It seems it wants the user to insert more data. It is accepting data as much as I'm inserting. I have provided all my code below
My client side code is
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        int age,carPrice,temp,temp1;
        String gender, s_temp;
        Scanner sc = new Scanner(System.in);
        Socket socket = new Socket("127.0.0.1",1342);
        Scanner sc1 = new Scanner(socket.getInputStream());
        PrintStream p = new PrintStream(socket.getOutputStream(), true);

        System.out.println("Enter Your Age: ");
        age = sc.nextInt();
        p.println(age);

        System.out.println("Enter the Cost of Vehicle: ");
        carPrice = sc.nextInt();
        p.println(carPrice);

        System.out.println("Enter Your Gender: ");
        gender = sc.next();
        p.println(gender);
        p.flush();

        temp = sc1.nextInt();
        System.out.println(temp);

        s_temp = sc1.next();
        System.out.println("The Gender is: " + s_temp);

        temp1 = sc1.nextInt();
        System.out.println(temp1);

        socket.close();
    }
}

My server side code:
public class Server {
    public static void main(String args[]) throws IOException, SQLException{
        ServerSocket ssocket = null;
        Socket socket = null;
        System.out.println("Server Listening.......*");
        ssocket=new ServerSocket(1342);
        while(true){
            try{
                socket = ssocket.accept();
                System.out.println("Connection Established.");
                ServerThread st = new ServerThread(socket);
                st.start();
            }
            catch(Exception e){
                System.out.println("Connection Error....");
            }
        }
    }
}

class ServerThread extends Thread{
    Socket s1 =null;
    Scanner sc = null;
    PrintStream p=null;

    int age,carPrice,temp;
    String gender,temp1;

    public ServerThread(Socket s){
        s1=s;
    }

    public void run(){
        try{
            sc = new Scanner(s1.getInputStream());
            p = new PrintStream(s1.getOutputStream(),true);

            age = sc.nextInt();
            gender = sc.next();
            carPrice = sc.nextInt();

            p.println(age*2);
            p.println(carPrice);
            p.println("Your gender is: " +gender);

            s1.close();
            System.out.println("Connection Closed....");
        }
        catch(Exception e){
        }
    }
}

Tell me why my server is not sending a response. Correct it so that it can send respond to the client.
Answer: Age, car price and gender inputs, not read with send order. It must be read from the client in order.
Change below snippet. Also, add sc.nextLine() to skip newline after int read.
Server
age = sc.nextInt();
carPrice = sc.nextInt();
sc.nextLine();  // skip newline
gender = sc.next();

... instead of
age = sc.nextInt();
gender = sc.next();
carPrice = sc.nextInt();

On the client-side, read order is not matched with send order. Also sc.next() reads one word, but you send many words while sending gender. So you have to change method with sc.nextLine()
Client
temp = sc1.nextInt();
System.out.println(temp);

temp1 = sc1.nextInt();
System.out.println(temp1);

sc1.nextLine();  // skip newline

s_temp = sc1.nextLine();
System.out.println("The Gender is: " + s_temp);

.. instead of
temp = sc1.nextInt();
System.out.println(temp);

s_temp = sc1.next();
System.out.println("The Gender is: " + s_temp);

temp1 = sc1.nextInt();
System.out.println(temp1);


Spinner não carrega dados da string.xml

Question: Meu spinner so aparece a seta. no 1 tem que mostra os Estados e assim que informado o 2 mostra as cidades desse estado

Esse é o código java.
public class PropertyRegisterActivity extends AppCompatActivity implements OnItemSelectedListener{

private Spinner spProvincias;
private Spinner spLocalidades;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_property_register);

    this.spProvincias = (Spinner) findViewById(R.id.sp_provincia);
    this.spLocalidades = (Spinner) findViewById(R.id.sp_localidad);

    loadSpinnerProvincias();

}

private void loadSpinnerProvincias() {

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.provincias, R.layout.spinner_item);

    adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

    this.spProvincias.setAdapter(adapter);

    this.spProvincias.setOnItemSelectedListener( this);
    this.spLocalidades.setOnItemSelectedListener(this);

}

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos,
                               long id) {

        switch (parent.getId()) {
            case R.id.sp_provincia:

                TypedArray arrayLocalidades = getResources().obtainTypedArray(
                        R.array.array_provincia_a_localidades);
                CharSequence[] localidades = arrayLocalidades.getTextArray(pos);
                arrayLocalidades.recycle();

                ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
                        this, R.layout.spinner_item,
                        android.R.id.text1, localidades);

                adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

                this.spLocalidades.setAdapter(adapter);

                break;

            case R.id.sp_localidad:

                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

Essa e xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="view.PropertyRegisterActivity">

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="360dp"
        android:layout_height="82dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:contentDescription="TODO"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/ic_cadastrodepropiedade_logo"
        tools:ignore="VectorDrawableCompat" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="23dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/property_register_description"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.56"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView5"
        app:layout_constraintVertical_bias="0.096" />

    <EditText
        android:id="@+id/editYear"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/hint_year"
        android:inputType="numberDecimal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView5"
        app:layout_constraintVertical_bias="0.309" />

    <EditText
        android:id="@+id/editProperty"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/hint_property"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView5"
        tools:ignore="MissingConstraints,UnknownId" />

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/custom_button"
        android:text="@string/save"
        android:textColor="@color/text_color"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="UnknownId" />

    <Spinner
        android:id="@+id/sp_provincia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:spinnerMode="dropdown"
        android:prompt="@string/provincia_prompt"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView5"
        app:layout_constraintVertical_bias="0.648" />

    <Spinner
        android:id="@+id/sp_localidad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:spinnerMode="dropdown"
        android:prompt="@string/localidad_prompt"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView5"
        app:layout_constraintVertical_bias="0.805" />

</android.support.constraint.ConstraintLayout>

Esses sao os layouts para o spinner.
spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="#ff0000" />

spinner_dropdown_item.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:ellipsize="marquee"
    android:textColor="#aa66cc"/>

Answer: Tente mudar de prompt para entries
android:entries="@array/tiposPessoa"

no strings.xml coloque os dados
    <string-array name="tiposPessoa">
     <item>Selecione uma opção</item>
     <item>Usuário</item>
     <item>Gestor</item>
     <item>Usuário/Gestor</item>
    </string-array>

Spinner não carrega dados da string.xml


Confused about Pattern Recognition Network in Matlab Documentation

Question: In the Matlab documentation for the Pattern Recognition Network (patternnet()), I am confused about a line of code in the documentation:
[x,t] = iris_dataset;
net = patternnet(10);
net = train(net,x,t);
view(net)
y = net(x);
perf = perform(net,t,y);
classes = vec2ind(y);

Why is y = net(x)?  So, I am assuming that y is the output vector, but why is it set to the column of the input vector, x?  I see that the net is the matrix containing the information from the train() function call, but why would it be asking for the inputs?
Reference: http://www.mathworks.com/help/nnet/ref/patternnet.html
Answer: The y = net(x) is the inference - using the trained model to predict y given a test input x. I suspect that the model is internally splitting the data of x in training, validation and test sub-sets, but keeping that only as index references. Thus it needs the input vector to pull the test sub-set out of it. See if the example code makes better sense.
Comment: Thanks for the other example.  But what I don't understand is why it's being called an `output`, if it's the neural network's input?  Is `net(input)` returned an array that I'm not understanding?
Comment: While being trained, the NN is trying to "discover" a function `f(x)` such that `f(x_train) = t` with `t` being the labels. After the model is trained, the purpose of `f(x)` is to produce predictions. If `x_test` is the input, then `y = f(x_test)` is the output. I think the confusion comes from the vector `x` containing both `x_train` and `x_test` which have completely different purposes.


Can i port theme settings also in a feature

Question: I tried to port a theme settings like default theme, other theme settings in a feature. But when i enable this feature along with the theme on a new website. It does not take effect.
Answer: Theme settings are usually stored as a variable, which is exportable with strongarm. Note that some things in the theming system is cached.
Comment: I see the feature in new website that 'theme_default' variable is taken effect and it says its default. But the theme was not still enabled
Comment: Most likely the problem is that features don't change the variable fast enough then, or like I said earlier, the cache is messing with you.


What is the expectation of the fourth and fifth die?

Question: Suppose we have a fair die and I am allowed to roll it up to 6 times. What is the expectation for the fourth and fifth die?
So I know that the expectation of the first roll is 3.5, second is 4.25, third is 14/3.
Now do I get this right, the fourth is 1/6*6+1/6*5+2/3*(14/3)? which is 89/18?
and the fifth die is 1/6*6+1/6*5+2/3*(89/18)? which is 277/54?
and how many rolls do I need to roll before I will only accept 6?
Comment: Do you mean the expectation of the maximum roll?
Comment: I think this needs clarification.  Do you mean "you are searching for a 6.  if you get it on the first roll, you stop.  If you don't get it on the first roll, you may throw again.  And so on.  What is the expectation if you must stop at four tosses?  Five tosses?  Six tosses?"
Comment: I'm sorry for my ignorance, but can someone explain where these numbers are coming from?
Comment: @pMarkov.  I'm trying to sort that out too.  My current theory is that  the OP is trying to maximize the result of the toss.  If you have at most two tosses, say, then you take the first if it is 4, 5, or 6.  If you get  1, 2, 3, you roll again (with an expectation of 3.5).  This rule at least gives 4.25 as the total expectation.
Answer: I believe the OP is asking this question:
"Consider the following game, played with a single fair die.  A positive integer n is fixed, this is the largest number of tosses you are allowed.  Your goal is to get the highest value on a single toss. After any toss you may keep the value you just got, or you may discard your current value and toss again (subject to the n toss cap). Find $E_n$, the expected value of this game."
$E_1$ = 3.5, clearly.
To get $E_2$ note that, should you discard your first toss you will be back in the one toss game, hence your expectation will be 3.5 .  Accordingly, your optimal strategy is to keep the first toss if you get 4, 5, 6 and discard it otherwise.  Thus $$E_2 = \frac{1}{2} 5 + \frac{1}{2}3.5 = 4.25$$
Similarly, we proceed recursively.  The recursion is a little ugly as your strategy changes with n (as long as the expectation is below 5, you'll keep that first 5, and so on).
$$E_3 = \frac{1}{3} 5.5 + \frac{2}{3}4.25 = \frac{14}{3}$$
This is still less than 5 so
$$E_4 = \frac{1}{3} 5.5 + \frac{2}{3}\frac{14}{3} = \frac{89}{18}$$
Still less than 5 so:
$$E_5 = \frac{1}{3} 5.5 + \frac{2}{3}\frac{89}{18} = \frac{277}{54}$$
(note this confirms the OP's calculation!)
Finally this is over 5!  Thus we need n=6 before we demand a 6 on the first throw.  Now the recursion becomes stable!  We get, for n ≥ 6
$$E_n = \frac{1}{6}6 + \frac{5}{6} E_{n-1}$$
So, in particular,
$$E_6 = \frac{1}{6}6 + \frac{5}{6}\frac{277}{54} = \frac{1709}{324}$$
Assuming no arithmetic error was made (always a risky assumption).


Pegar dados de uma tabela dinâmica e salvar no mysql

Question: boa noite.
Faz tempo que não programo! Estou enferrujado, rsrs
Preciso de ajuda. Estou fazendo um sistema para controlar orçamentos.
o meu problema é que preciso pegar essas informações de produtos e jogar em uma tabela do mysql(tb_orcamentos). Eu não sei como devo fazer isso. =\
segue foto:
Código para exibir os campos do form:

                <form method="post" action="cad-novo-pdc.php">
                    <input type='text' class='username' id='username_1' name="username_1" placeholder='Informe o produto'>
                    <input type='text' class='id' id='id_1' name="id_1" readonly>
                    <input type='text' class='name' id='name_1'  name="name_1" required>
                    <input type='text' class='salary' id='salary_1' name="salary_1" onKeyUp="moeda(this);" required>

                <button type="button" class="btn btn-warning" onclick="remove(this)">Excluir</button>

Código JS para dar a funcionalidade de "adicionar item":
$('#addmore').click(function(){

                // Get last id
                var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
                var split_id = lastname_id.split('_');

                // New index
                var index = Number(split_id[1]) + 1;

                // Create row with input elements
                var html = "
\n\
                            <input type='text' class='username' id='username_"+index+"' placeholder='Informe o produto'>	\n\
                            <input type='text' class='id_' id='id_"+index+"' readonly>	\n\
                            <input type='text' class='name' id='name_"+index+"' >	\n\
                            <input type='text' class='salary' id='salary_"+index+"' onKeyUp='moeda(this);'  >	\n\
                            <button type='button' class='btn btn-warning' onclick='remove(this)'>Excluir</button>
";

                // Append data
                $('tbody').append(html);

            });

eu criei um método post no form, mas ele só envia a primeira linha de produto inserida. Agora, não sei o que fazer para pegar um ou 50 itens que forem digitados no orçamento. Conseguem me dar uma ajuda? xD
A função de gravar deve entrar em ação quando se clicar no botão "finalizar pedido".
Realmente estou a mais de 5 anos sem pegar em um code =\
saudações a todos \o/
Answer: Está faltando apenas adicionar o atributo name nos campos gerados dinamicamente pelo seu código JS. Para resolver, adicione o atributo name nos campos gerados via javascript.
Exemplo: ao lado de id='username_"+index+"', adicione name='username_"+index+"', e assim por diante para todos os 4 campos.
Explicação: Sem o atributo name, o campo do formulário não é enviado via POST pelo navegador. E é por isso que só a primeira linha está sendo enviada, pois no HTML fixado para o item 1 você colocou o name corretamente. O problema está só na parte dinâmica (linha 2 em diante).
Depois que você tiver feito isso, conseguirá acessar todas as variáveis via POST por meio do PHP. Para testar que todos os valores estão chegando corretamente, substitua o conteúdo do arquivo cad-novo-pdc.php, provisoriamente, por <?php var_dump($_POST); ?> e submeta o formulário.
Comment: não funcionou meu amigo.
Comment: Para te ajudar a debuggar, faça o seguinte: inspecione os campos gerados dinamicamente (utilizando a ferramenta DevTools do navegador Google Chrome, por exemplo, apertando a tecla F12 do navegador), e veja se os campos da 2ª linha garanham os ids e names corretos.
Comment: Outro problema que eu identifiquei: a sua tag `` está dentro da tag ``. Para que todas as informações sejam submetidas, o formulário deve estar por fora da ``. Deve ser algo assim (apenas exemplificando a estrutura): ``.
Comment: obrigado amigo!
a saída ficou:
`array (size=8)
  'username_1' => string 'calha dutotec' (length=13)
  'id_1' => string '2' (length=1)
  'name_1' => string '3' (length=1)
  'salary_1' => string '1000.24' (length=7)
  'username_2' => string 'fita isolante' (length=13)
  'id_2' => string '15' (length=2)
  'name_2' => string '10' (length=2)
  'salary_2' => string '17.80' (length=5)`
**porém quando coloco a pagina cad-novo-pdc exibe apenas o primeiro, exemplo de como está:**

`$razao = $_POST['username_1'];
$fantasia = $_POST['name_1'];
$endereco = $_POST['salary_1'];`
Comment: Isso que está hardcoded (username_1, etc), você vai ter que deixar dinâmico. Como o seu frontend não tem limitador de registros, você tem que fazer um loop infinito e forçar a parada quando perceber que chegou ao fim. Exemplo:
Comment: meu amigo, muito obrigado, mas eu não consigo mais passar daqui...nao sei o que fazer. coloquei esse while que vc pediu na pagina cad-novo-pdc mas fica em loop carregando....
Comment: @RonierickHolanda vi que você é um usuário novo do StackOverflow, bem vindo! Vou te dar algumas dicas que vão ajudar você a tirar suas dúvidas. Esse é um site de perguntas e respostas diretas, objetivas, então precisamos evitar ficar conversando pelos comentários. Se estamos tendo muita conversa pelos comentários, significa que a sua pergunta está com escopo muito amplo.
Comment: Recomendo que faça o seguinte: edite a sua pergunta atual, e deixe ela bem objetiva, diminuindo o escopo. Remova a parte sobre banco de dados da pergunta. Como minha resposta já resolveu seu problema da parte que vai do frontend até o $_POST, recomendo que você marque a minha resposta como aceita, e faça outra pergunta pedindo ajuda para fazer um loop sobre os dados do $_POST. Assim, eu e outros usuários podemos te ajudar, de forma mais organizada, sobre o restante da sua dúvida. Ou seja, sempre quebre seu problema em perguntas pequenas, e vamos resolvendo uma coisa de cada vez.


How to use grunt-forever and grunt-watch together

Question: I have both files: app.js which starts the http server, and main.js which is compiled by browserify and used in html as
So I have a Grunt configured with forever, browserify and watch.
I want that on app.js chance, the http must be restarted (via forever:restart), and when main.js changes, the build must be browserified (via browserify)
so, when i run grunt, says forever:start does not exist, any help ?
$ grunt
Warning: Task "forever:server1:start" not found. Use --force to continue.

this is my gruntfile:
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    browserify: {
      dist: {
        files: {
          'examples/public/js/module.js': ['examples/main.js']
        }
      }
    },
    forever: {
      server1: {
        options: {
          index: 'examples/app.js',
          logDir: 'examples/logs'
        }
      }
    },
    watch: {
      app: {
        files: ['examples/*.js', 'examples/templates/*' ],
        tasks: ['forever:server1:start']
      },
      web: {
        files: ['examples/*.js', 'examples/templates/*' ],
        tasks: ['browserify']
      },
    }
  });

  //grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['browserify', 'forever:server1:start']);
  grunt.registerTask('restart', ['browserify', 'forever:server1:restart']);

};

Answer: The task isn't found because you're missing grunt.loadNpmTasks('grunt-forever'). You might also find more success using something like nodemon instead of grunt.
Comment: Yeah @Reinis you're right, thanks for the help!.
I'm interesting in using grunt because I want the webapp to be restarted not only on changes on itself but on other files. Also I want other build tasks to be done, this is where grunt comes in help.


Why my for-loop has only one result after a python list iterator?

Question: The following codes with for-loop only return one-item while I expected it could return many-item. For example,
It returned actually:
0.3273

What I expected is
0.8372
0.2847
0.1837
0.3273
...

Should I use .append() or something else? Please give me some detailed code advice. Thank you.
def phrase_similarity(phrase):
    phrase_vec = phrase_model[phrase]
    for a_word in phrase_model.keys():
        a_val = phrase_model[a_word]
        cos_dis = cosine_similarity(phrase_vec, a_val) #it's numpy.ndarray
        cos_dis_str = str(cos_dis.tolist()).strip('[[]]')

    return cos_dis_str

Comment: You are overwriting the value of `cos_dis_str` at each step (and `cos_dis`, for that matter), rather than accumulating results.
Comment: If you print `cos_dis` during iteration, what does it print? (just a few please, [mcve])
Answer: Let cos_dis_str be an empty list
cos_dis_str=[]

Then a simple append would fix that
cos_dis_str.append(str(cos_dis.tolist()).strip('[[]]'))

Answer: When the For loop is executing, each time the os_dis_str is getting overwritten.
So make sure that you create a list for that and keep on appending onto that. Then return the list. You can access each of the individual values from there.
cos_dis_str.append(str(cos_dis.tolist()).strip('[[]]'))

Also initialize cos_dis_str = [], outside the For loop but within the function.
Hope this helps to get an understanding.
Answer: you can change your code this way.
def phrase_similarity(phrase):

    phrase_vec = phrase_model[phrase]
    cos_dis_str = []

    for a_word, a_val in phrase_model.items():
        cos_dis = cosine_similarity(phrase_vec, a_val).tolist()).strip('[[]]') #it's numpy.ndarray
        cos_dis_str.append(str(cos_dis))

    return '\n'.join(cos_dis_str)


Given that a matrix represents an enlargement followed by a rotation, find the scale factor of the enlargement and the angle of the rotation.

Question: The question is as follows:
The matrix M is defined by:
\begin{bmatrix}
  -1 & -1 \\
  1 & -1 \\
\end{bmatrix}
Given that M represents an enlargement followed by a rotation, find the scale factor
of the enlargement and the angle of the rotation.
Isn't there multiple different correct answers for this question?
According to this exam paper there is only one
Exam Paper Question 6(b)(i)
http://filestore.aqa.org.uk/subjects/AQA-MFP1-QP-JUN12.PDF
Mark scheme Question 6(b)(i) http://filestore.aqa.org.uk/subjects/AQA-MFP1-W-MS-JUN12.PDF
Answer: At the very least, there are two answers: scale factor $c$ and rotation $\theta$, and scale $-c$ and rotation $\theta + \pi$. Perhaps "enlargement", in the language of this test, means that the scale factor must be positive.
Answer: One has $\det(M)=2$, which implies that $M$ enlarges areas by a factor of $2$. The linear zoom factor is then $\sqrt{2}$. Therefore let us write $M$ as a product in the following form:
$$M=\left[\matrix{-{1\over\sqrt{2}} & -{1\over\sqrt{2}} \cr
{1\over\sqrt{2}}&-{1\over\sqrt{2}}\cr}\right]\>\left[\matrix{\sqrt{2} & 0 \cr
0&\sqrt{2}\cr}\right]\ .$$
We are told that the left hand factor here is a rotation $T$. The first column of $[T]$ gives $Te_1=\bigl(-{1\over\sqrt{2}}, \>{1\over\sqrt{2}}\bigr)$, whence $T$ rotates $e_1$ (and therewith the full plane) by $\theta={3\pi\over4}$.


Neural network trained with potentially incomplete data set

Question: I want to build a neural network that can predict some outcome "x". I have training data that contains 1000's of variables for each case. I have no idea if in the 1000's of variables is/are the real reason(s) for the outcome x.
Is my neural network useless?
If the neural network is able to predict outcome x with some degree of accuracy using test data, does that mean the real reason(s) for outcome x is/are buried somewhere in the 1000's of variables?
Comment: Possible duplicate of [Expected best performance possible on a data set](https://stats.stackexchange.com/questions/28057/expected-best-performance-possible-on-a-data-set)
Comment: Mostly correct, but a small nitpick, it means that _some_ of "the real reason(s) for outcome x is/are buried somewhere in the 1000's of variables". There may still be explanatory variables left out even if you can achieve better-than-random performance.
Answer: No you're neural network is not necessarily useless just because you aren't aware of a relationship between your inputs and your outputs.
It's possible there is a relationship between your inputs and your outputs that you are not aware of.
If your NN reliably predicts the correct output given your inputs, then you can probably assume there exists a relationship between the inputs and the output.
Answer: Deep Learning has a deep mathematical foundation on statistics.   And any pattern it has to associate has to be ideally also known to the human beings.   Generally even if you are not sure of the statistical association between the data, then it is hard for DL to discover anything new.
https://www.quora.com/How-important-is-statistics-to-deep-learning
http://blog.shakirm.com/ml-series/a-statistical-view-of-deep-learning/
Garbage in garbage out.
But if the pattern is simple enough then it is always possible discover the simple pattern unsupervised.   The degree of difficulty will correspond with the amount of data to discover the correlation, generally.
Comment: This does not match my experience with Convolutional Neural Networks. The reason I use CNNs is because I don't want to sit there and design hundreds of filters by hand, and if I did I'd likely still end up with worse results on tasks like image classification. It really depends on what you mean by patterns being "known" to the humans, but at a very technical level I do not "know" the filters beforehand.


Some questions about variance and expectation values

Question: I'm reading Probability and Statistics with R by Ugarte, Militino, and Arnholt and there's a few questions I have related to variance. They state:
$Var[X] = \sigma^2_X=E[(X-\mu)^2]=E[X^2]-\mu^2$
However, I am not getting this last portion. I am getting:
$E[(X-\mu)^2] = E[X^2-2\mu X +\mu^2] = E[X^2]-2\mu E[X] + \mu^2$
Perhaps my understanding of the definition of $E[X]$ is incorrect but I don't see how they not only managed to get rid of the $-2\mu E[X]$ term altogether but also have a different sign for the $\mu^2$ term. Could someone please explain?
Later in the book they state $Var[aX+b] = a^2Var[X]$. They show a derivation which I understood but they said that in showing this derivation, it is "implicitly" shown that $Var[aX] = a^2Var[X]$ and $Var[b]=0$. However, if $Var[X]=E[(X-\mu)^2]$ then shouldn't $Var[b]=E[(b-μ)^2]=\sum_{x \in X}(b-μ)^2p(x)=(b-\mu)^2$? How would it be $0$?
Maybe I'm not doing these manipulations correctly. Someone please correct me if I am wrong, thanks.
Comment: For the first question: you're doing it exactly right—you just have to remember that the definition of $\mu$ is $\mu=E[X]$, which makes the expression magically work out!
Comment: Similar for the second comment: $\mu$ isn't an arbitary constant, but rather the expectation of the relevant random variable. So if the random variable is the constant $b$, then $\mu=b$.
Answer: The book must have defined $\mu=E[X]$ earlier.
Therefore,
$$\operatorname{Var}[X]=\operatorname{E}[X^2]-2\mu\operatorname{E}[X]+\mu^2=\operatorname {E}[X^2]-2\mu^2+\mu^2=\operatorname{E}[X^2]-\mu^2.$$
In the second case, we have a constante random variable $X=b$. Therefore, $\operatorname{E}[X]=b=\mu$, then $\operatorname{Var}[b]=0$.
Comment: I don't know how I didn't see that before, /_-. Thank you so much!


Update não atualiza registros do banco

Question: No meu sistema tem uma página de cadastro e uma página com uma tabela com as informações dos cadastrados. Nessa tabela tem um botão de edição que linka com um formulário igual da página de cadastro.
O que deveria acontecer:
Ao clicar no botão salvar, os campos modificados deveriam ser alterados no registro.
O que está acontecendo:
Quando tento alterar o registro aparece o alert de "salvo com sucesso" e volta pra página anterior, como deveria acontecer. Mas olhando pelo phpMyAdmin, o registro continua inalterado
A conexão:
<?php
    $connection = mysqli_connect("localhost", "root", "", "db_formacao");

    if (mysqli_connect_errno())
    {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
?>

Formulário de edição:
<?php
    require 'conn.php';
    $queryColaboradores = mysqli_query($connection, "SELECT FORMACAO FROM participantes");
    $turma = filter_input(INPUT_POST, 'TURMA');
    $formacao = filter_input(INPUT_POST, 'FORMACAO');
    $colaborador = filter_input(INPUT_POST, 'COLABORADOR');
    $Realizado = filter_input(INPUT_POST, 'REALIZADO');
    $id = filter_input(INPUT_POST, 'ID');
    var_dump($queryColaboradores);
?>

Inscrição

                    <form id="cadastro" method="post" action="banco/updateEdicao.php" style="
                        text-align: left;
                        margin-top:50px;">
                        <fieldset disabled>

                                    Formação:
                                    <input  type="text" required class="form-control" id="FORMACAO" name="FORMACAO" value="<?php echo $formacao; ?>">

                        </fieldset>
                        <fieldset disabled>

                                    Turma:
                                    <input  type="text" required class="form-control" id="TURMA" name="TURMA" value="<?php echo $turma; ?>">

                        </fieldset>
                        <fieldset disabled>

                                    Colaborador:
                                    <input  type="text" required class="form-control" id="COLABORADOR" name="COLABORADOR" value="<?php echo $colaborador; ?>">

                        </fieldset>
                        <fieldset disabled>

                                    ID participante:
                                    <input  type="text" required class="form-control" id="PARTICIPANTE" name="PARTICIPANTE" value="<?php echo $id; ?>">
                                    <input type="hidden" name="id" value="<?php echo $id ?>" />

                        </fieldset>

                            <fieldset disabled>

                                    Status
                                    <input type="text" id="PREVISTO" name="PREVISTO" class="form-control" value="Previsto">

                            </fieldset>

                                Realizado:
                                <input  type="text" required class="form-control" id="REALIZADO" name="REALIZADO" value="Realizado">

                            <button type="submit" class="btn btn-primary btn-lg btn-block">Salvar</button>

                    </form>

O update:
<?php

$previsto = filter_input(INPUT_POST, 'PREVISTO');
$realizado = filter_input(INPUT_POST, 'REALIZADO');
$id = filter_input(INPUT_POST, 'ID');

$strcon = mysqli_connect('localhost', 'root', '', 'db_formacao') or die('Erro ao conectar ao banco de dados');
$sql = " UPDATE participantes SET REALIZADO = '$realizado' WHERE ID = '$id' ";
mysqli_query($strcon,$sql) or die("Erro ao tentar atualizar registro. " . mysqli_error($strcon));
mysqli_close($strcon);

echo '';

var_dump($id)
?>

OBS: Se eu tirar o WHERE ID = '$id' todos os registros são atualizados normalmente, mas com o WHERE não.
Comment: Você já viu se você está mesmo recebendo o valor do ID em `$id = filter_input(INPUT_POST, 'ID');` ? As vezes a variavel `$id` está vindo nulla.
Comment: Sim, eu dei um var_dump e está recebendo NULL
Comment: Pelo seu código, toda vez que você chamar essa página de update ele vai aparecer `Alterado com sucesso`, sugiro que faça uma verificação para ver se realmente está sendo alterado no banco utilizando `mysqli_affected_rows($con);`, sugiro também que retire o `window.history.go(-1);` para permanecer na página e você conseguir ver o erro.
Comment: Estou verificando se o registro está sendo alterado pelo phpMyAdmin, já tirei o window.history.go(-1) pra ver o erro mas só printa o var_dump.
Comment: Disabled não passa o valor para o fomulário, além de não poder editar.
Comment: Sim, não poder editar é exatamente o que eu quero para os campos que estão com o disabled, que são os campos que foram preenchidos na hora do cadastro. Só um campo está disponível para edição, que é o Realizado.
Comment: Eu tenho um capo disabled que está recebendo o valor do ID da participação a ser editada.
Comment: Readonly envia o valor para o formulário e também não pode editar
Comment: Vou colocar uma imagem do meu formulário.
Comment: Vou colocar o link de uma outra pergunta minha sobre outro problema no mesmo formulário que tem a ver com o que você está dizendo. Os campos disabled deviam estar recebendo um value importado do banco e não está recebendo.
Comment: https://pt.stackoverflow.com/questions/234124/formul%C3%A1rio-n%C3%A3o-importa-values-do-banco-de-dados
Comment: seu formulario está um tanto curioso, disabled com required mas não pode editar
Comment: Porque eu quero que esse campo exista e seja preenchido com as informações vindas da tabela do banco, mas que não possa editar. Isso só pra mostrar ao usuário as informações que ele digitou no cadastro anterior, mas que ele não pode alterar. O único campo alterável é o último, o Realizado.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/65177/discussion-between-mariana-ferreira-and-leo-caracciolo).
Answer: O <input type="hidden" name="id" value="<?php echo $id ?>" /> por estar dentro de <fieldset disabled> além de não poder editar não passa o valor.
Já que o input do id é do tipo hidden você pode colocar ele no final do formulário, fora do <fieldset disabled> alterando o name="id" para name="ID" pois parece ser também problema Case-sensitive
 ................
 ................
 <input type="hidden" name="ID" value="<?php echo $id ?>" />
 </form>

ou se preferir não mudar o name do input

na edicao $id = filter_input(INPUT_POST, 'id');
na update $id = filter_input(INPUT_POST, 'id');
pois este id no filter_input parece ser Case-sensitive

Update não atualiza registros do banco


How do I get only the last string in a text to be renamed

Question: i first locate the last word in my richtextbox   then i check if that string matches a particular string .
then i replace the string with another string.
the problem is that whenever i enter the same string and click my "rename"
 button it renames both strings because if both strings are now "dog" then it will recognize lastWord as dog and not as the FINAL most recently entered word thus it will be renamed to something else .
private sub getwords()

    dval = dval + 1

    Dim lastWord As String = RichTextBox1.Text.Split(" ").Last

    If dval = 1 And lastWord = "meu" Then

        RichTextBox1.Text = RichTextBox1.Text.Replace(lastWord, "dog")

    End If

    MsgBox(lastWord)

    If dval = 2 And RichTextBox1.Text.EndsWith("dog") And lastWord = "dog" Then

        RichTextBox1.Text = RichTextBox1.Text.Replace(lastWord, "cat")
        dval =0
    End If

end sub

Comment: Maybe put it in an `Else`? Also, you should use `AndAlso` instead of `And` in general.
Comment: thank you very much , AndAlso  world very well , i am rather new to visual studio so i am unfamiliar with the vb syntax
Answer: How about this naive solution, it removes the last word then concats it to the end.
private sub getwords()

    dval = dval + 1

    Dim lastWord As String = RichTextBox1.Text.Split(" ").Last

    If dval = 1 AndAlso lastWord = "meu" Then

        RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.Text.Length - lastWord.Length) & "dog"

    End If

    MsgBox(lastWord)

    If dval = 2 AndAlso RichTextBox1.Text.EndsWith("dog") AndAlso lastWord = "dog" Then

        RichTextBox1.Text = RichTextBox1.Text.Remove(RichTextBox1.Text.Length - lastWord.Length) & "cat"
        dval = 0
    End If

End Sub

Comment: Why use `String.Concat`? `&` is a lot easier on the eyes…


Can a chromatic harmonica play double notes or triple notes?

Question: Can a chromatic harmonica play double notes or triple notes?
I wonder if it could play some of the complicated piano songs
Comment: This is why people invented the Melodica. All the reedy goodness of a harmonica tone, in a convenient keyboard layout.
Comment: @CalebHines - Excellent comment!
Answer: Short answer: yes, you can play two and three note chords on chromatic harmonica, but not any two and three note chords; it is very unlikely that you would be able to play any reasonably complicated piano repertoire on chromatic harmonica, without significant editing. The most you would probably be able to do would be do play certain lines (melody lines, for instance) and add some supporting harmony notes.
I have read somewhere (a while ago…) that Larry Adler could play Bach chorales on the chromatic harmonica, but a few things to bear in mind, even if this was the case: he was a brilliant harmonica player; this type of music is not necessarily that similar to a lot of piano repertoire; I bet he couldn't play every Bach chorale…! (It seems more likely to me that he played chorale melodies and added harmony…)
In the end, the chromatic harmonica is a fantastic instrument, which you can use to perform a wide variety of interesting music, but if you want to play piano music you really want to play it on piano or some kind of keyboard.
Answer: The harmonica is capable of playing multiple notes at once, but those notes must be present in adjacent holes, with the same direction of air, and in the case of chromatic harmonica, with the same setting of the side key.
Different chromatic harmonicas are set up in different keys, so even with a fully chromatic instrument, the musical key of the harmonica significantly impacts what notes can be played at the same time. There are some good diagrams on this Wikipedia page that show which notes are present on which holes for which direction of air (blow or draw) and for which setting of the button/key.
The instrument is still fully chromatic, which means while you will be able to play single line melodies written for an instrument like the piano, you will in no way be able to play pieces considered part of the piano repertoire. It may be possible to arrange simple pieces of music for the chromatic harmonica to conform to its limitations.
Comment: Actually, you can play notes that aren't on adjacent holes, by using the tongue to block a hole (or holes) between them. But this is a pretty advanced technique. And, as you say, you can't play both blow and draw notes at the same time!
Comment: You *can* blow and draw at the same time--I just tried it--but the technique to do so is not very convenient and will sound and look unattractive: put part of the harmonica over your mouth and another part over your nose. Then take advantage of circular breathing (i.e. puff up your cheeks with air, and inhale with your nose while letting the air in your cheeks out).
Comment: The adjacent hole scenario in this answer isn't accurate. As a kid, I used to play harmony with the instrument playing two notes with tongue blocking a hole or two between them. True, both blow or both draw.


Direct limit of certain $C^*$ algebras is simple

Question: Let $X$ be a compact Hausdorff space. Let $(x_n)$ be a sequence in $X$.Assume $X$ has no isolated points.
Define $A_n = C(X, M_{2^n}(\mathbb{C}) )$ and define $\phi_{n+1,n} : A_n \to A_{n+1}$ by $$\phi_{n+1,n}(f)=\begin{bmatrix}f&0\\0&f(x_n)\mathbb{1}_{A_n}\end{bmatrix}.$$
Show that $A:= \varinjlim A_n$ is simple if and only if the sequence $(x_n)$ is dense in $X$.
Solution:
First, observe that the connecting maps are injective, so we can think about the direct limit as the closure of the increasing union of the $A_n$'s.
Also,ideals in $A_n$ are of the form $C(X\setminus Y,M_{2^n})$, i.e. functions that vanish at $Y$, where $Y\subseteq X$ is a closed subset.
$\Rightarrow)$ Suppose $(x_n)$ is not dense in $X$.
Define for $n\in \mathbb{N}$ $$I_n=\left\{(f_{ij})_{i,j}\in C(X,M_{2^n})|\forall i,j    \  \ f_{ij}|_{\overline{\cup_{n}\{x_n\}}}=0\right\}.$$ The sequence is not dense, so $I_n$ is a non-trivial ideal in $A_n$. Define $I=\overline{\cup I_n}$ ideal in $A$, because the union is increasing. We have $I \ne (0)$ because $I_1\ne (0)$ and $I_n\subseteq I_{n+1}$. Also $I \ne A$ , otherwise $1_A \in I$ so there exists some $n$ and $x\in I_n$ s.t. $\|1_A-x\|<1$,  thus $x$ is invertible in $A$. But all the $A_n$'s contain $1_A$, and in particular that implies $x$ is invertible in $I_n$, contradicting the fact $I_n\ne A_n$.
$\Leftarrow$) Suppose $I$ is a proper ideal in $A$. $I=\overline{\cup (I\cap A_n)}=\overline{\cup I_n}$, and each $I_n$ correspond to some $Y_n\subseteq X$ closed, as I mentioned before. $I$ is prper, thus any $I_n$ is proper, and $\forall n, \ Y_n \ne \emptyset$.  From the inclusion $I_n\subseteq I_{n+1}$, we know that $\phi (I_n)\subseteq I_{n+1}$.
Consequently, if $f\in I_n$ (vanishes at $Y_n$) then $\begin{bmatrix}f&0\\0&f(x_n)\mathbb{1}_{A_n}\end{bmatrix}|Y_{n+1}=0$, i.e. $Y_{n+1}\subseteq Y_n$ and $x_n\in Y_n$. Similarily, by applying $\phi _{n+m,n}$, we get $\forall m\geq n \ \  x_m\in Y_n$.$(*)$(This conclusion is right for each $n\in \Bbb{N})$
Assume by contradiction that there exists $k$ s.t. $Y_k \subsetneq X$.
From density of $\{x_n\}_n$ there exists $n$ s.t. $x_n \notin Y_k$.
We've assumed that $X$ has no isolated points, therefore there exist infinitely many points from the sequence $\{x_n\}_n$ which are not in $Y_k$.
This is a contadiction to $(*)$.
So, $\forall k \ \ Y_k=X$ implies $I_k=(0)$ $\rightarrow I=(0)$, as required.
Comment: What is the motivation for looking at those limits ?
Comment: @Shirly: I'm sorry to say it again, but maybe you could also accept this answer. Every time you get a suitable answer, you should accept it. For instance you could accept these answers : [(1)](http://math.stackexchange.com/questions/1754029), [(2)](http://math.stackexchange.com/questions/1793797), [(3)](http://math.stackexchange.com/questions/1787144), [(4)](http://math.stackexchange.com/questions/1803002), **and so on**. Thank you very much!
Comment: These answers could be accepted: http://math.stackexchange.com/questions/711095, http://math.stackexchange.com/questions/713226/integrals-proving-equality, http://math.stackexchange.com/questions/711343, http://math.stackexchange.com/questions/722416, http://math.stackexchange.com/questions/731160, and many others :-)
Answer: Note that in your definition of $I_n$ you have some confusing use of $n$, which is fixed but also appears in $\cup_n\{x_n\}$, which is probably better written as $\overline{\{x_k:\ k\in\mathbb N\}}$.
I'm not particularly comfortable with the way you argue that $I\ne A$. It is enough to show that $I$ cannot contain any function that is nonzero on $\overline{\{x_n:\ n\in\mathbb N\}}$.
For the converse, It think that your argument with the $Y_k$ is fine.
Comment: I didn't spend time thinking of the details, so I'm not a 100% sure. But the way I see it, you can show that $f(x_n)=0$ for all $f\in Y$, which implies $x_n\in Y$ (for all $n$).
Comment: Thanks. you're right about the confusing use of n.
So, I'll just try to undestand what I scribbled in the converse direction.
Do I need to use the definition of direct limit as I did in the last paragraph?
I'm not sure how $\exists x_k \notin Y_n $ helps me...
Comment: Unfortunately I couldn't finish the argument.
If I "recognize" right the set $Y$ with the ideal $I$ as the intesection of the $Yn$'s, I need to show that $\forall n, Y_n\ne \emptyset$ implies $\forall n, x_n\in Y$. So, as $I_n \subseteq I_{n+1}$ I think it means $\phi_{n+1,n} (I_n) \subseteq I_{n+1}$ so $\begin{bmatrix} f&0\\0&f(x_n) \end{bmatrix}$ is $0$ on $Y_{n+1}$, i.e. $Y_{n+1}\subseteq Y_n$ and $x_n \in Y_n$. similarily, $\forall k\geq n$ I think that $x_k \in Y_n$. However, that's not all the points in the sequence and I think I don't understand correctly the idea behind those ideals.
Comment: I just saw your  comment. I'll try to answer tomorrow.
Comment: O.K, there was a missing assumption- $X$ has no isolated points.
I've succeed to finish the proof. Thank you.
Comment: Great! $\ \ \ $


Switch General MIDI instruments from device? (Roland Sound Canvas, Reaper)

Question: I have an Swissonic EasyKey61 MIDI keyboard, and it is connected to the VST plugin "Roland Sound Canvas" via Reaper.
I am wondering how sound banks/instruments (e.g. "Piano 1", "Piccolo", "Tinkle Bell", ...; i.e. those available in the VST plugin) can be changed using input from my MIDI keyboard.
In the VST's menu, I selected "Param" --> "MIDI link" --> "Program Change", but nothing seems to change (I don't know how this option knows about which input knob, button, ... on the device I'd like to assign). Also, I tried "MIDI learn" from the menu, but this also does not seem to change anything.
Does anyone have an idea how to switch between the sound banks using my MIDI device?
Answer: You do not have to remap anything. The EasyKey can send bank change and program change messages with the BANK MSB, BANK LSB, and PROG keys in edit mode (see page 12/13 of the manual - link to PDF).
Answer: Have you tried sending Program Change instructions with the EasyKey:

press Edit
press the key which is labeled Prog
enter another program number using the keyboard keys
press the key labeled Enter
press the Edit button again.


Probability distribution on a transformed variable problem

Question: I am not sure if my process to solve this particular problem is correct and not looking for particular solutions.
The Question:

Given $X^3 $~ $ N( \mu , \sigma^2), $ x>0$  $ and $Y=(\frac{X^2}{4})$, find distribution of Y

My attempt:
$Y^{3/2}=(\frac{X^2}{4})^{3/2})=\frac{X^3}{8}$
$\frac{d}{dx}y^{3/2}=\frac{x}{4}>0, x>0$
so we can find the pdf of $Y^{3/2}$ with inverse:
$r(y^{3/2})^{-1}=8y^{3/2}, y>0$
$f(y)=f_x(r(y)^{-1})\frac{d}{dy}[r(y)^{-1}]$
$=stuff$
and then getting it back to pdf of Y with :
$f(y)=stuff^{2/3}$
I got lazy typing out the normal distribution parts but that is what is in place of "stuff" and the other substitutions.
Comment: If $X>0$ then $X^{3}>0$ so $X^{3}$ cannot have a normal distribution.
Answer: Let $W = X^3$. Then $Y = 1/4 W^{2/3}$.
Furthermore,
$$
P( Y < y ) = P( \frac{1}{4} W^{2/3} < y ) = P( W < 8y^{3/2})
= \Phi( u ),
$$
where $\Phi$ is CDF of standard normal and $u = (8y^{3/2} - \mu)/\sigma$.
Probability density of $Y$ is
$$
p_Y(y) = \frac{ d\Phi(u)}{du} \frac{du}{dy}
= 12 \frac{\sqrt{y}}{\sqrt{2 \pi}\sigma}e^{-\frac{(8y^{3/2}-\mu)^2}{2\sigma^2}}
$$
Comment: Oh great thanks, I think the part that tricked me was that I needed to use a change of variable


Why does this MySQL stored function return null?

Question: can anybody explain, why the following MySQL stored function returns always null? If I replace exchange_rate within SET @dollar = euro * exchange_rate; by 1.1013 it works great.
DROP FUNCTION IF EXISTS euro_to_dollar;
DELIMITER $$
CREATE FUNCTION euro_to_dollar(euro double) returns double
BEGIN
  DECLARE dollar double;
  DECLARE exchange_rate double;
  SET @exchange_rate = 1.1013;
  SET @dollar = euro * exchange_rate;
  RETURN @dollar;
END $$
DELIMITER ;

Comment: You are mixing different variables . . . try `SET @dollar = euro * @exchange_rate`.
Answer: You have to make reference to @exchange_rate like this:
DROP FUNCTION IF EXISTS euro_to_dollar;
DELIMITER $$
CREATE FUNCTION euro_to_dollar(euro double) returns double
BEGIN
  DECLARE dollar double;
  DECLARE exchange_rate double;
  SET @exchange_rate = 1.1013;
  SET @dollar = euro * @exchange_rate;
  RETURN @dollar;
END $$
DELIMITER ;

Comment: Thanks a lot that was the solution! :)


How do we capture SMDR\CDR from PBX?

Question: I just try to build Call Monitor system that reading SMDR\CDR from my PABX through Serial port or IP. So that I can produce some reports from that data. I know data output format is different from each manufacturer, so how can we handle this problem? Is there any libraries or sample projects that easy to get started?
Comment: Did you find anything useful? At least any documentation about the data?
Comment: @bojan, I haven't found it yet.
Comment: try a solution like "pbx data logger". It will capture, parse data and store it to your database. Then you can use this parsed data and build any reports.
Answer: There is a free tool to capture SMDR info for you, if that is the route you wish to take.
Simple SMDR
Answer: I have written parser for several output formats from many different vendors and actually there are often very easy the read and "parse" the data because it is well defined ASCII data (mostly, sometimes in bianry format but still its very well defined), I havent found any librarys to ease the task of getting hold of the data, but the hard part has always been to figure out how to intepret different vendors values.
I can try to provide some resources if you can tell me what pabx you are targeting.
Comment: @wendelstam, I would think on Panasonic. Thanks
Comment: too bad, I have no experience with panasonic.

How do we capture SMDR\CDR from PBX?


A connected open set is path connected

Question: My analysis course states that a connected open set is path connected but I haven't been able to prove it.
Here we consider a subset of the field of complex number but I suppose it works for a general topological space.
Cheers
Comment: It doesn't work for arbitrary topological spaces, but it works for locally path-connected spaces.
Comment: The proof is here: https://proofwiki.org/wiki/Connected_Open_Subset_of_Euclidean_Space_is_Path-Connected
Answer: Hint: Show that if $U$ is an open set in a normed space, then for each $x \in U$ the set of points that are path-connected to $x$ is open and closed (relative to $U$).

A connected open set is path connected


Mapping existing file against a new content type

Question: I am facing a situation here.
I have a content type A with an image field(field_upload_snaps) in it. There is another content type B which also contains an image field(field_valid_snaps).
Now user will upload the pics from A content type. So if user upload 3 pics via A then 3 FID and their corresponding URIs will be created in file_managed table in Drupal 7.
Now I have a requirement where I have to insert 2 images out of 3 programatically using Drupal code. Now there is no need to generate any new image copy in public URI as images already exist via A.
I tried two approaches:-
1) I have created a new node of Type B. I tried to fetch file URI,filesize,filemime and all relevant parameter from existing fid and associate with the node using this.
 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $file = (object) array(
  'uid' => $user->uid,
  'uri' => 'public://1.jpeg" ,
  'filemime' => 'image/jpeg',
  'status' => 1,
 );

 $node->field_upload_snaps['und'][] = (array)$file;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

But it gives me an error that "Cant insert duplicate value in file_managed". It will give because such value already exist in file_managed via A. So I am not able to save value.
2) I saved node first and then manually insert in the image field like this.
 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

 db_insert('field_data_field_valid_snaps')
    ->fields(array(
    'entity_type' => 'node',
    'bundle' => 'user_actualD_snaps',
    'deleted'=> 0,
    'entity_id'=>$node->nid,
    'delta'=>0,
    'field_valid_snaps_fid'=>517,
    'field_valid_snaps_alt'=>'',
    'field_valid_snaps_title'=>'',
    'field_valid_snaps_width'=>200,
    'field_valid_snaps_height'=>300,
    ))
    ->execute();

But the line after node_save() doesnt execute in this case. So I am not able to save it.
Are there any functions available which will map existing images into another table?
Answer: I think the File Field sources module will solve your problem.  (The D7 version works directly with the core Field module).  It will, among other things, allow you to re-use files by an auto-complete textfield.
Btw: Any file appearing in file_managed can only appear once in that table, so you should not be allowed to do what you try to do in your first approach.
Comment: Will there be any logic references to create a new node from existing saved file. I want PHP code to do this stuff as I did it for 2 approaches. If there are any other suggestion other than going for custom module then please let me know.
Answer: File_load API solved my problem of getting the dimensions of existing file and save in another content type.


Unexpected garbage pixels in logo demo for Amstrad CPC emulator

Question: I'm "emulating" the Nintendo Gameboy logo demo in an Amstrad CPC Emulator (WinApe) in mode video 1, encoded in assembly for the Z80.
When I "paint" only the logo (until the line 25 and comment the others lines in main loop), It paints good, but when I try to create the animation (paint, erase, paint, etc.), appears some "garbage" pixels not painted previously.
This is my code:
<code>;; testlogo.asm
;;
.cls    equ &BC14   ;; Clear screen
org &4000
run &4000
;;
call cls
ld hl, #c020        ;; initial position of video
ld a,#05        ;; times logo down
call loop1      ;; call main loop
jr $
;;
loop1:
   ld bc,logo       ;; initial position of logo
                    ;; bc remains until logo
                    ;; is fully painted
   ld e,#08
   call loop_paint
   ld de, #c050
   add hl,de
                    ;; the second 8 row group pixels
   ld e,#08
   call loop_paint
   ld de,#c050
   add hl,de
                    ;; wait until 'down' logo
   ld b,#cc
   call wait
   ld de, #ff60     ;; recover hl position
                    ;; to 'erase' upward logo
   add hl,de
   ld e,#08
   call loop_erase1 ;; call to 'erase' pixels
                    ;; from logo
                    ;; (it could be optimized in one calling)
   ld de, #c050
   add hl,de
   ld e,#08
   call loop_erase1
   ld de, #c050
   add hl,de
   dec a
jr nz, loop1
ret
;;
loop_paint:
   ld d,#0b
   call loop_logo   ;; call to paint logo
   push bc          ;; save bc in stack
                    ;; for using adding in bc
   ld bc,#07f5      ;; 800 for next row (minus) 0b last column
   add hl,bc
   pop bc
   dec e
jr nz, loop_paint
ret
;;
loop_logo:          ;; finally 'paints' logo
                    ;; in memory video
   push af          ;; save 'a' register
                    ;; because is used
                    ;; as counter in main loop
   ld a, (bc)
   ld (hl), a
   pop af
   inc l
   inc c
   dec d
jr nz,loop_logo
ret
;;
loop_erase1:        ;; row by row in mode 1 video
   ld d,#0b
   call loop_erase2
   ld bc,#07f5      ;;800 next row - 0b last column
   add hl,bc
   dec e
jr nz,loop_erase1
ret
;;
loop_erase2:        ;; column by column in mode 1 video
   ld (hl), #00
   inc l
   dec d
jr nz,loop_erase2
ret
;;
logo:
db #00, #00, #00, #00, #00, #00, #00, #00, #00, #00, #00
db #00, #00, #00, #00, #00, #00, #00, #00, #00, #00, #00
db #00, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #88, #00
db #33, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #EE, #00
db #33, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #E6, #00
db #FC, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F1, #88
db #FD, #F5, #FB, #F5, #FE, #FF, #F3, #F3, #FB, #FD, #88
db #FD, #F9, #FB, #FD, #F0, #F8, #F4, #FA, #F1, #F1, #88
db #FD, #F1, #FA, #FD, #F6, #FF, #F4, #FB, #F9, #F1, #88
db #FD, #F9, #FA, #F5, #F2, #F1, #F4, #FA, #F1, #F1, #88
db #FD, #F5, #FA, #F5, #FE, #FF, #F3, #F2, #F1, #F1, #88
db #FC, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F1, #88
db #33, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #F0, #E6, #00
db #33, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #EE, #00
db #00, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #FF, #88, #00
db #00, #00, #00, #00, #00, #00, #00, #00, #00, #00, #00
ret
;;
wait:
  halt
  dec b
jr nz,wait
ret
</code>
And this is the result in the emulator window:

Last line of logo must be in red only and no contains another color, logo is in red and yellow.
Comment: Did you check that you have no 8-bit overflow? All your pointer increments are only 8 bit wide. Why don't you use 16-bit increments for the pointers?
Answer: Problem was resolved when I change from 8 to 16-bit increments for the pointers: "inc l" for "inc hl", "inc c" for "inc bc".
Thanks to   "the busybee" user.
Comment: Just a little tip, you can actually use 8-bit increments if you align your table so that its beginning address has a low byte of `00`. Then, as long as your table is less than 256 bytes in size you only need 8-bit increments, and you also only need the high byte of its base pointer. This can easily triple your lookup speed if done properly.


upload large file causing Error: "Payload content length greater than maximum allowed: 1048576"

Question: I am just trying to invoke one lambda function from another lambda function, and i am sending a payload into that lambda function. If I paas a payload of size upto 1 mb, then i don't get this error, this error arises when the payload size is greater than 1 mb only.
<code>import * as AWS from "aws-sdk";

const lambda = new AWS.Lambda({
  region: "us-east-1",
  endpoint: "http://localhost:3002",
});

const params = {
  FunctionName: "myFunction", // the lambda function we are going to invoke
  InvocationType: "RequestResponse",
  LogType: "Tail",
  Payload: JSON.stringify(data),
 };

const lambdaResult = await lambda.invoke(params).promise();
</code>
Comment: How did it go? Still unclear why you can't do that?
Answer: Lambda invocation has limits on payload (6MB).
If you want to send larger data then that, you have to save it first, for example to S3, and then have second function read it from S3. This way you just send S3 url to the second function, instead of the entire data file.


Square roots calculation without the use of a calculator

Question: How do you find a square root of a number when the square root isn't a whole number, without a calculator
Example: 35
Comment: The answers to the previous question [Square root algorithm](http://math.stackexchange.com/questions/439135/square-root-algorithm) present a number of alternative methods and comparisons.
Answer: There is a well known algorithm that is simillar to long division. Say you wish to find the square root of $x$, where $x = x_1x_2x_3...x_n$(this is not a product, but rather represents the digits of $x$, i.e if $x = 129, x_1 = 1, x_2 = 2, x_9 = 9$).
It is evalutated using the square root sign like you are doing long division. The number whose square root you will be taking(radicand) will be placed in the sign, and the answer will be written on the top. Just like long division, you will be computing 1 digit at a time.
The process consist of first, ordering the digits into pairs, then finding a number whose square is less than the first pair. This number will be the first digit of your answer. Subtract the numbers square from the first pair, and then bring down the next pair.
You will then bring down the first digit of the answer and then multiply it by 2, call this number $y$. Then you will find a number, say $z$ such that when you add it as the last digit of $y$ and then multiply it by $z$, you get a number less than or equal to the new number formed after bringing the previous pair down. Call this number $p$. Once you have done so, you will subtract $p$ from the pair, and $z$ will be the next digit of your answer.
Next you will bring down the entire answer(so far containing two digits) and multiply it by 2. You can then repeat the process above until you have reached your desired amount of digits.
You can read more about it here(in the section find square roots using an algorithm).
Comment: @hardmath edited*
Answer: Here is a good page to learn:
http://www.basic-mathematics.com/square-root-algorithm.html
Also Newton made a great approximation.
So pick an approximate square root, $A$. In this case it would be $6$ since $35$ is close to $36$. Then calculate,
$$\frac{1}{2} (\frac{N}{A}+A)$$
Where $N$ is the number ($35$).
So the approximation would be $\frac{1}{2} (\frac{35}{6}+6)= 5.91\bar6 $. The actual answer is about $5.91607978309962$.
Comment: It is an interesting historical fact that the Newton method for finding the positive solution of $x^2-a=0$ is the same as the "Babylonian method".


Atribuir valores de um select a uma variavel

Question: Bom estou montando um procedimento no MySQL, e dentro dele tenho o seguinte código:
  DECLARE valorConta DECIMAL DEFAULT 0;
  DECLARE valorPGConta DECIMAL DEFAULT 0;

  SELECT Valor INTO valorConta
  FROM Contas
  WHERE Cod = CodConta;

  IF valorPGConta >= valorConta THEN

  ELSE

  END IF;

Bom declarei 2 variáveis sendo elas valorConta e valorPGConta.
Na tabela Contas tenho os 2 campos Valor e ValorPG.
Preciso saber como atribuir os valores nas 2 variáveis para depois fazer a verificação no IF.
Answer: Primeiro tem que declarar o CodConta, depois faça dois "SELECT INTO":
--RECEBE CodConta para realizar o filtro
DECLARE CodConta DECIMAL DEFAULT 0;

--VALOR CONTA
SELECT Valor
INTO valorConta
FROM Contas
WHERE Cod = CodConta;

--VALOR PG CONTA
SELECT valorPGConta
INTO valorPGConta
FROM Contas
WHERE Cod = CodConta;

O IF está correto, aí no caso é só executar os comandos desejados dentro do dele.
Comment: Acabei achando uma forma de fazer usando apenas um `select`. Assim: `SELECT Valor, ValorPG INTO valorConta, valorPGConta`
Comment: voce pode postar sua solucao para a sua pergunta.


What is the fundamental group of the variety of singular matrices, without $0$?

Question: Consider $S = V(det) \subset M_n(\mathbb{C})$. I want to know what the fundamental group of $S \setminus {0}$ is. Equivalently, I want to know the fundamental group of $V(det) \subset \mathbb{P}^{n^2 - 1}$. (Using the homotopy long exact sequence.)
In some cases it's easy - if $n = 2$, then the variety is a full rank (smooth) quadric hypersurface in $P^3$, and is thus isomorphic to $P^1 \times P^1$, which is simply connected. If $n= 3$, I already have no idea how to proceed. It is also non-smooth for $n \geq 3$.
The result is a variety with a lot of symmetry - conjugation by $GL_n(\mathbb{C})$, left and right multiplication by $GL_n(C) \times GL_n(C)$. There are finitely many orbits for the latter action, classified by rank, and the closure of each orbit is the union of the lower rank orbits. Maybe this is useful?
To put something at stake, I guess that it is simply connected for all $n$. What about the higher homotopy groups? (Is the limit with the natural inclusions as $n \to \infty$ contractible?)
Comment: Have you looked up Lefshetz theorems? Hypersurfaces in projective spaces are very well behaved.
Comment: There are lots of orbits under the action of conjugation by $GL_n$ (in particular, conjugation doesn't change trace, and every number is the trace of some singular matrix once $n\geq 2$). To get orbits classified by rank, maybe we need $GL_n\times GL_n$ to act by left and right multiplication.
Comment: @JulianRosen Whoops, you are right, I was being sloppy.
Comment: @Mohan You are right, they solve it. Thanks! I'm writing up an answer in order to learn, but I'm happy to give you points if you submit your comment as an answer.
Comment: @Mohan (At least, they solve the lower homotopy groups.)
Answer: This is thanks to Mohan's comment.
The Lefschetz hyperplane theorem states (among other things):
If $X$ is an $n$-dimensional projective variety in $P^N$, and $Y$ is a hyperplane section of $X$ so that $X \setminus Y$ is smooth, then for $k < n -1$, the map induced by inclusion $\pi_k(Y) \to \pi_k(X)$ is an isomorphism, and is surjective for $k = n - 1$.
In particular, we let $v : X = P^{n^2 - 1} \to P^N$ be the degree $n$ veronese, so that $V(det) \subset X$ becomes a hyperplane section with smooth complement. Then by the theorem the first $n^2 - 2$ homotopy groups agree with those of $P^{n^2 - 1}$.
The homotopy groups of $CP^M$ can be related to those of $S^{2M + 1}$ via the fibration $U(1) \to S^{2M + 1} \to CP^M$. In particular, for $2 < k < 2M + 1$, $\pi_k(CP^M) = \pi_k(S^{2M + 1}) = 0$, and we get $\pi_2(CP^M) = \mathbb{Z}$ and $\pi_1(CP^M) = 0$. (That $CP^M$ is simply connected can also been seen from its 2 skeleton being a sphere.)
So the variety of singular matrices is always simply connected, but $\pi_2$ is $\mathbb{Z}$ as long as $2 < n^2 - 2$. (In particular, this tells us nothing about $\pi_2(CP^1 \times CP^1)$. That we can compute with the Hurewicz map since it is $2 - 1$ connected, so $\pi_2 (CP^1 \times CP^1) = H_2(CP^1 \times CP^1) = Z^2$, the later equality using Kunneth.)
The homotopy groups are then trivial until $\pi_{n^2 - 2}$, where all we know from the Lefschetz theorem is that $\pi_{n^2 - 2} (V(det))$ surjects onto $\pi_{n^2 - 2}(CP^{n^2 - 1}) = \pi_{n^2 - 2}(S^{2n^2}) = 0$, which is no information. I computed this group to be $\mathbb{Z}^2$ for the case $n = 2$, so I guess in general they are non-trivial. (I can conjecture that $\pi_{2n^2- 2}(det(X)) = \mathbb{Z}^n$, but jumping on the most obvious pattern.)
The higher homotopy groups are presumably mysterious.


Divs do slider slick.js sendo mostrada no carregamento

Question: Quando tento colocar slick.js no meu site, o carregamento das divs dentro aparece uma embaixo da outra e depois oculta, coisa de 1 segundo, como faço para resolver?

Aqui o código:

<picture>
<source srcset="imagem/imagem-1" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-2" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-3" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-4" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-5" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-6" media="(max-width: 768px)">

</picture>

<picture>
<source srcset="imagem/imagem-7" media="(max-width: 768px)">

</picture>

 <picture>
<source srcset="imagem/imagem-8" media="(max-width: 768px)">
 </picture>

Aqui meu JS e Requisições
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick-theme.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick.css" />

Meu site já tem Jquery, por isso não coloquei!
Como eu faria para resolver esse "flash das divs do slick"?
Answer: Como ninguém soube me ajudar, eu conseguir achar uma solução.
Usei os seguintes requisições do JS e CSS
//CSS
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick-theme.css" />

<link rel="stylesheet" type="text/css" href="//email@example.com/slick/slick.css"/>

//JS

E fiz as seguintes configurações de JS(no meu caso era banner, então 1 slide para todos)

Agora, para não ter o "flash dos sliders" eu coloquei o seguinte CSS.

Observação: Adicionei a classe slick-slider para todos os sliders, menos o
primeiro!

.carousel.slick-initialized{
    visibility:visible;
    opacity:1;
}

.carousel .slick-slider{
    display:none ;
}

.carousel .slick-slider:first-child{
    display:block; visibility:hidden;
}

.carousel.slick-initialized .slick-slider{
    display:block;visibility:visible!important;
}

Assim, durante o carregamento o primeiro slide estará visível, e os outros ocultos, logo quando eles se tornarem ativo eles fica em display:block;, assim eu resolvi meu problema e espero que ajude mais gente também!
Atenciosamento, Christiano.