ajax jquery - Invalid JSON format

Question: I am trying to send a json object to a webservice. I am getting below error in the firebug.
{"Message":"Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected. (3423): {\u0027GUID\u0027:\u0027urhhh1bqbezjvb45dnqlgj45\u0027,\u0027RuleName\u0027:\u0027Summary Check\u0027,\u0027LinkArray\u0027:\u0027[{\"from\":\"Start\",\"to\":\"Count\",\"text\":\"Next\",\"fromPort\":\"5\",\"toPort\":\"1\"},{\"from\":\"Count.6\",\"to\":\"Multiple Decisions\",\"text\":\"Next\",\"fromPort\":\"5\",\"toPort\":\"1\"},{\"from\":\"Multiple Decisions\",\"to\":\"Status\",\"text\":\"True\",\"fromPort\":\"3\",\"toPort\":\"7\"},{\"from\":\"Multiple Decisions\",\"to\":\"Finish\",\"text\":\"False\",\"fromPort\":\"5\",\"toPort\":\"1\"},{\"from\":\"Status\",\"to\":\"Finish.14\",\"text\":\"Next\",\"fromPort\":\"3\",\"toPort\":\"7\"},{\"from\":\"Count\",\"to\":\"Count.6\",\"text\":\"Next\",\"fromPort\":\"5\",\"toPort\":\"1\"}]\u0027,\u0027NArray\u0027:\u0027[{\"key\":\"StatusText\",\"category\":\"Comment\",\"location\":\"10 10\",\"text\":\"Step 10\\rEvent = PAEditQuote\\rModel = PAStatementValidation\",\"figure\":\"RoundedRectangle\"},{\"key\":\"Start\",\"category\":\"begin\",\"type\":\"Start\",\"location\":\"169 124\",\"size\":\"57 55\",\"text\":\"\",\"tooltip\":\"Datasource=\",\"break\":\"false\",\"Properties\":{\"Name\":\"Start\"}},{\"key\":\"Count.6\",\"category\":\"image\",\"type\":\"Count\",\"location\":\"172 378\",\"size\":\"49 49\",\"text\":\"# of Sele QA's\",\"tooltip\":\"Number of Sele Question Answers=Statement Sele QA Where Statement Sele Answer Required equals Y\",\"break\":\"false\",\"Properties\":{\"Variable\":\"[:000013]\",\"Name\":\"Count\",\"Message\":\"Count\",\"ShortName\":\"Statement Sele QA\",\"Operand1\":\"equals\",\"Value1\":\"Y\",\"CountType1\":\"All\",\"DecShortName\":\"Statement Sele Answer Required\",\"DataBase\":\"DB1\",\"Table\":\"SHSeleQuestions\",\"XMLPath\":\"DB1\\\\SHSeleQuestions\",\"DecXMLPath\":\"DB1\\\\SHSeleQuestions\\\\ResponseReqInd\"}},{\"key\":\"Multiple Decisions\",\"category\":\"Decision\",\"type\":\"DecPlus\",\"location\":\"169 508\",\"size\":\"75 56\",\"text\":\"If no required answers given\",\"tooltip\":\"Number of Sele Question Answers is greater than 0\",\"break\":\"false\",\"Properties\":{\"DecisionInd\":\"True\",\"Variable1\":\"[:000013]\",\"Operand1_1\":\"is greater than\",\"Value1_1\":\"0\",\"Name\":\"DecPlus\",\"Variable2\":\"[:000015]\",\"Operand1_2\":\"equals\",\"Value1_2\":\"0\"}},{\"key\":\"Finish\",\"category\":\"end\",\"type\":\"Finish\",\"location\":\"172 625\",\"size\":\"57 55\",\"text\":\"\",\"tooltip\":\"\",\"break\":\"false\",\"Properties\":{\"Name\":\"Finish\"}},{\"key\":\"Status\",\"category\":\"image\",\"type\":\"Status\",\"location\":\"313 508\",\"size\":\"53 49\",\"text\":\"HOST003\",\"tooltip\":\"Warning=HOST003 - All Questions must be answered on the Statement Page.\",\"break\":\"false\",\"Properties\":{\"Name\":\"Status\",\"Message\":\"Validation.IValidation\",\"StatusCode\":\"PADriver002\",\"StatusType\":\"Error\",\"StatusMessage\":\"All Questions must be answered on the Statement Page.\",\"StatusPage\":\"PAStatement.aspx\",\"Unique\":\"False\"},\"Unique\":\"False\"},{\"key\":\"Finish.14\",\"category\":\"end\",\"type\":\"Finish\",\"location\":\"461 508\",\"size\":\"57 55\",\"text\":\"Stop Model\",\"tooltip\":\"\",\"break\":\"false\",\"Properties\":{\"Name\":\"Finish\",\"Termination\":\"StopModel\"}},{\"key\":\"Count\",\"category\":\"image\",\"type\":\"MultiCount\",\"location\":\"172 252\",\"size\":\"49 49\",\"selected\":\"true\",\"text\":\"Statement Answer\",\"tooltip\":\"=\",\"break\":\"false\",\"Properties\":{\"Variable\":\"[:000015]\",\"Name\":\"MultiCount\",\"Message\":\"MultiCount\",\"ShortName\":\"Statement Answer\",\"CountType1\":\"All\",\"ShortName1\":\"Statement Answer\",\"Operand1_1\":\"does not equal\",\"Item\":\"1\",\"XMLDoc\":\"PagePolicyData\",\"XMLPath\":\"PagePolicyData\\\\ValidationMessage\\\\PageContent\\\\ACORD\\\\PersAutoLineBusiness\\\\QuestionAnswer\\\\YesNoCd\",\"XMLPath1\":\"PagePolicyData\\\\ValidationMessage\\\\PageContent\\\\ACORD\\\\PersAutoLineBusiness\\\\QuestionAnswer\\\\YesNoCd\",\"XMLCondPath\":\"Root\\\\PagePolicyData\\\\ValidationMessage\\\\PageContent\\\\ACORD\\\\PersAutoLineBusiness\\\\QuestionAnswer{((YesNoCd != \u0027\u0027))}\\\\YesNoCd\"}},{\"category\":\"Comment\",\"location\":\"450 50\",\"size\":\"150 38\",\"figure\":\"RoundedRectangle\",\"text\":\"Summary Check\"}]\u0027,\u0027RulesArray\u0027:\u0027{\"0\":\"Check Bypass\",\"1\":\"Bypass Edorsement\",\"2\":\"Statement Questions\"}\u0027}","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

Jquery ajax call to webservice is below:
    var LinkArray = localStorage['LinkArray'];
    var NodeArray = localStorage['NArray'].replace("'", "\'");
    var RulesArray=localStorage['TabList'];
    var Parameters = "{'GUID':'" + GetQueryStringValue('GUID') + "','RuleName':'" + $("#rulename").text() + "','LinkArray':'" + LinkArray + "','NArray':'" + NodeArray + "','RulesArray':'" + RulesArray + "'}";
    //var Parameters = '{"GUID":"' + GetQueryStringValue("GUID") + '","RuleName":"' + $('#rulename').text() + '","LinkArray":"' + LinkArray + '","NArray":"' + NodeArray + '","RulesArray":"' + RulesArray + '"}';

    $.ajax({
        type: "POST",
        url: "../RulesWebService.asmx/UpdateAllProperties",
        data: Parameters,
        contentType: 'application/json; charset=utf-8',
        crossBrowser: true,
        success: function (GetStatusRs) {

        },
        //onerror throw error.
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Error Getting status for parameters: - Error:' + errorThrown);
        }
    });

My webmethod has below structure :
<WebMethod(EnableSession:=True)> _
  Public Function UpdateAllProperties(ByVal GUID As String, ByVal RuleName As String, ByVal LinkArray As String, ByVal NArray As String, ByVal RulesArray As String) As String
  'some stuff here.
End Function

Below is the Parameters value which I am posting it to the server.
{'GUID':'urhhh1bqbezjvb45dnqlgj45','RuleName':'Summary Check','LinkArray':'[{"from":"Start","to":"Count","text":"Next","fromPort":"5","toPort":"1"},{"from":"Count.6","to":"Multiple Decisions","text":"Next","fromPort":"5","toPort":"1"},{"from":"Multiple Decisions","to":"Status","text":"True","fromPort":"3","toPort":"7"},{"from":"Multiple Decisions","to":"Finish","text":"False","fromPort":"5","toPort":"1"},{"from":"Status","to":"Finish.14","text":"Next","fromPort":"3","toPort":"7"},{"from":"Count","to":"Count.6","text":"Next","fromPort":"5","toPort":"1"}]','NArray':'[{"key":"StatusText","category":"Comment","location":"10 10","text":"Step 10\rEvent = PAEditQuote\rModel = PAStatementValidation","figure":"RoundedRectangle"},{"key":"Start","category":"begin","type":"Start","location":"169 124","size":"57 55","text":"","tooltip":"Datasource=","break":"false","Properties":{"Name":"Start"}},{"key":"Count.6","category":"image","type":"Count","location":"172 378","size":"49 49","text":"# of Sele QA's","tooltip":"Number of Sele Question Answers=Statement Sele QA Where Statement Sele Answer Required equals Y","break":"false","Properties":{"Variable":"[:000013]","Name":"Count","Message":"Count","ShortName":"Statement Sele QA","Operand1":"equals","Value1":"Y","CountType1":"All","DecShortName":"Statement Sele Answer Required","DataBase":"DB1","Table":"SHSeleQuestions","XMLPath":"DB1\\SHSeleQuestions","DecXMLPath":"DB1\\SHSeleQuestions\\ResponseReqInd"}},{"key":"Multiple Decisions","category":"Decision","type":"DecPlus","location":"169 508","size":"75 56","text":"If no required answers given","tooltip":"Number of Sele Question Answers is greater than 0","break":"false","Properties":{"DecisionInd":"True","Variable1":"[:000013]","Operand1_1":"is greater than","Value1_1":"0","Name":"DecPlus","Variable2":"[:000015]","Operand1_2":"equals","Value1_2":"0"}},{"key":"Finish","category":"end","type":"Finish","location":"172 625","size":"57 55","text":"","tooltip":"","break":"false","Properties":{"Name":"Finish"}},{"key":"Status","category":"image","type":"Status","location":"313 508","size":"53 49","text":"HOST003","tooltip":"Warning=HOST003 - All Questions must be answered on the Statement Page.","break":"false","Properties":{"Name":"Status","Message":"Validation.IValidation","StatusCode":"PADriver002","StatusType":"Error","StatusMessage":"All Questions must be answered on the Statement Page.","StatusPage":"PAStatement.aspx","Unique":"False"},"Unique":"False"},{"key":"Finish.14","category":"end","type":"Finish","location":"461 508","size":"57 55","text":"Stop Model","tooltip":"","break":"false","Properties":{"Name":"Finish","Termination":"StopModel"}},{"key":"Count","category":"image","type":"MultiCount","location":"172 252","size":"49 49","selected":"true","text":"Statement Answer","tooltip":"=","break":"false","Properties":{"Variable":"[:000015]","Name":"MultiCount","Message":"MultiCount","ShortName":"Statement Answer","CountType1":"All","ShortName1":"Statement Answer","Operand1_1":"does not equal","Item":"1","XMLDoc":"PagePolicyData","XMLPath":"PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer\\YesNoCd","XMLPath1":"PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer\\YesNoCd","XMLCondPath":"Root\\PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer{((YesNoCd != ''))}\\YesNoCd"}},{"category":"Comment","location":"450 50","size":"150 38","figure":"RoundedRectangle","text":"Summary Check"}]','RulesArray':'{"0":"Check Bypass","1":"Bypass Edorsement","2":"Statement Questions"}'}

Answer: Have you tried using JSON.stringify(). Also with JSON.stringify you could use an object to store each of the values and use stringify to make it JSON.
var LinkArray = localStorage['LinkArray'];
    var NodeArray = localStorage['NArray'].replace("'", "\'");
    var RulesArray=localStorage['TabList'];
    var Parameters = "{'GUID':'" + GetQueryStringValue('GUID') + "','RuleName':'" + $("#rulename").text() + "','LinkArray':'" + LinkArray + "','NArray':'" + NodeArray + "','RulesArray':'" + RulesArray + "'}";
    //var Parameters = '{"GUID":"' + GetQueryStringValue("GUID") + '","RuleName":"' + $('#rulename').text() + '","LinkArray":"' + LinkArray + '","NArray":"' + NodeArray + '","RulesArray":"' + RulesArray + '"}';

$.ajax({
    type: "POST",
    url: "../RulesWebService.asmx/UpdateAllProperties",
    data: JSON.stringify(Parameters),
    contentType: 'application/json; charset=utf-8',
    crossBrowser: true,
    success: function (GetStatusRs) {

    },
    //onerror throw error.
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Error Getting status for parameters: - Error:' + errorThrown);
    }
});

Edit 1:
Your object should look like:
var Parameters = {};
Parameters.Guid = 'your value';
// the rest of the fields from your object.

Comment: I tried your solution as well but with this chnage I am getting below error."Message":"Type \u0027System.String\u0027 is not supported for deserialization of an array."
Comment: because you didn't read carefully, will post an example as soon as I can
Comment: check again with new suggestion.
Comment: I tried with the new suggestion as well. Its sending me same error. Also FYI : data stored in  localStorage['LinkArray'] and  localStorage['NArray'] these is already stringigy format.
Comment: then try to send only Parameters.Guid as stringyfied and go from there on. I think you do stringify twice which is causing the problem
Comment: Floradu88 thanks for your help. I removed content type and its working fine now.
Comment: Floradu88: I have used your solution and in addition to that I just removed the content type. So your solution partially worked for me and it gave me lead in the resolution.
Comment: As you wish, but this is how this site works, and maybe if you continue on this path no one will try to help you.
Comment: I didn't said you have to accept my answer, you should have posted the correct answer(yours) and mark it as accepted.
Comment: Thanks, if you edit the question, might gain more. Mark the error as code markup by using {} symbol
Answer: Parameters value which you posting server is in wrong format. use http://jsonlint.com/ to correct your json. Now try it with thisas parameters..
{
        "GUID": "urhhh1bqbezjvb45dnqlgj45",
        "RuleName": "SummaryCheck",
        "LinkArray": [
            {
                "from": "Start",
                "to": "Count",
                "text": "Next",
                "fromPort": "5",
                "toPort": "1"
            },
            {
                "from": "Count.6",
                "to": "Multiple Decisions",
                "text": "Next",
                "fromPort": "5",
                "toPort": "1"
            },
            {
                "from": "Multiple Decisions",
                "to": "Status",
                "text": "True",
                "fromPort": "3",
                "toPort": "7"
            },
            {
                "from": "Multiple Decisions",
                "to": "Finish",
                "text": "False",
                "fromPort": "5",
                "toPort": "1"
            },
            {
                "from": "Status",
                "to": "Finish.14",
                "text": "Next",
                "fromPort": "3",
                "toPort": "7"
            },
            {
                "from": "Count",
                "to": "Count.6",
                "text": "Next",
                "fromPort": "5",
                "toPort": "1"
            }
        ],
        "NArray": [
            {
                "key": "StatusText",
                "category": "Comment",
                "location": "10 10",
                "text": "Step 10\rEvent = PAEditQuote\rModel = PAStatementValidation",
                "figure": "RoundedRectangle"
            },
            {
                "key": "Start",
                "category": "begin",
                "type": "Start",
                "location": "169 124",
                "size": "57 55",
                "text": "",
                "tooltip": "Datasource=",
                "break": "false",
                "Properties": {
                    "Name": "Start"
                }
            },
            {
                "key": "Count.6",
                "category": "image",
                "type": "Count",
                "location": "172 378",
                "size": "49 49",
                "text": "# of Sele QA's",
                "tooltip": "Number of Sele Question Answers=Statement Sele QA Where Statement Sele Answer Required equals Y",
                "break": "false",
                "Properties": {
                    "Variable": "[:000013]",
                    "Name": "Count",
                    "Message": "Count",
                    "ShortName": "Statement Sele QA",
                    "Operand1": "equals",
                    "Value1": "Y",
                    "CountType1": "All",
                    "DecShortName": "Statement Sele Answer Required",
                    "DataBase": "DB1",
                    "Table": "SHSeleQuestions",
                    "XMLPath": "DB1\\SHSeleQuestions",
                    "DecXMLPath": "DB1\\SHSeleQuestions\\ResponseReqInd"
                }
            },
            {
                "key": "Multiple Decisions",
                "category": "Decision",
                "type": "DecPlus",
                "location": "169 508",
                "size": "75 56",
                "text": "If no required answers given",
                "tooltip": "Number of Sele Question Answers is greater than 0",
                "break": "false",
                "Properties": {
                    "DecisionInd": "True",
                    "Variable1": "[:000013]",
                    "Operand1_1": "is greater than",
                    "Value1_1": "0",
                    "Name": "DecPlus",
                    "Variable2": "[:000015]",
                    "Operand1_2": "equals",
                    "Value1_2": "0"
                }
            },
            {
                "key": "Finish",
                "category": "end",
                "type": "Finish",
                "location": "172 625",
                "size": "57 55",
                "text": "",
                "tooltip": "",
                "break": "false",
                "Properties": {
                    "Name": "Finish"
                }
            },
            {
                "key": "Status",
                "category": "image",
                "type": "Status",
                "location": "313 508",
                "size": "53 49",
                "text": "HOST003",
                "tooltip": "Warning=HOST003 - All Questions must be answered on the Statement Page.",
                "break": "false",
                "Properties": {
                    "Name": "Status",
                    "Message": "Validation.IValidation",
                    "StatusCode": "PADriver002",
                    "StatusType": "Error",
                    "StatusMessage": "All Questions must be answered on the Statement Page.",
                    "StatusPage": "PAStatement.aspx",
                    "Unique": "False"
                },
                "Unique": "False"
            },
            {
                "key": "Finish.14",
                "category": "end",
                "type": "Finish",
                "location": "461 508",
                "size": "57 55",
                "text": "Stop Model",
                "tooltip": "",
                "break": "false",
                "Properties": {
                    "Name": "Finish",
                    "Termination": "StopModel"
                }
            },
            {
                "key": "Count",
                "category": "image",
                "type": "MultiCount",
                "location": "172 252",
                "size": "49 49",
                "selected": "true",
                "text": "Statement Answer",
                "tooltip": "=",
                "break": "false",
                "Properties": {
                    "Variable": "[:000015]",
                    "Name": "MultiCount",
                    "Message": "MultiCount",
                    "ShortName": "Statement Answer",
                    "CountType1": "All",
                    "ShortName1": "Statement Answer",
                    "Operand1_1": "does not equal",
                    "Item": "1",
                    "XMLDoc": "PagePolicyData",
                    "XMLPath": "PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer\\YesNoCd",
                    "XMLPath1": "PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer\\YesNoCd",
                    "XMLCondPath": "Root\\PagePolicyData\\ValidationMessage\\PageContent\\ACORD\\PersAutoLineBusiness\\QuestionAnswer{((YesNoCd != ''))}\\YesNoCd"
                }
            },
            {
                "category": "Comment",
                "location": "450 50",
                "size": "150 38",
                "figure": "RoundedRectangle",
                "text": "Summary Check"
            }
        ],
        "RulesArray": {
            "0": "Check Bypass",
            "1": "Bypass Edorsement",
            "2": "Statement Questions"
        }
    }

Comment: Shiju Shaji- I tried your advise and changed JSON to the format you suggesed. Now when I post it to server I am receiving new error as below: "Message":"Type \u0027System.String\u0027 is not supported for deserialization of an array."

ajax jquery - Invalid JSON format


Can a car that retired join back the race?

Question: Just saw this on the F1 facebook page
https://www.facebook.com/Formula1/videos/1075139512643030/
It talks about an old austrian grand prix, where it took 3 starts to get under way. The 3rd one being almost 2 hours after the first one.
So it made me wonder, if somebody that had a minor crash on the first launch, decided to retire because the car wouldn't be ready for the 2nd start, but then, when they saw it would take a while before the race starts again repaired the car in time for the 3rd start, would they be able to?
Or is a Retired status definitive for the grand prix?
Answer: In theory yes, you can restart after "retiring" from a Grand Prix but the way the rules are nowadays it is pretty unlikely.
For example, in the 1970-90s teams brought 3 cars to each race, one for each driver and a spare or "T" car.  If a driver retired at the start he could jump into the spare car in case the race was restarted etc.
Here's the current rule regards spare cars: (by "competitor" they mean "team")

Each competitor may have no more than two cars available for use at
any one time during an Event. Article 23.1 of the 2018 FIA Sporting
Regulations Teams may have no more than two cars available for use at
any one time. Spare cars are not allowed

So if you have to retire your car nowadays due to a technical fault, it usually means you have to abandon the car on the track and walk back to the pits.
The rules were changed largely as a cost saving measure, back in 2008.
The last famous event involving a spare car I can remember off the top of my head was James Hunt winning the 1976 British Grand Prix although he didn't actually use the spare car, but other drivers did:
https://en.wikipedia.org/wiki/1976_British_Grand_Prix
There are some other incidents of note, Hamilton rejoined the 2007 European Grand Prix after being lifted back onto the track by a crane:
https://www.grandprix.com/races/european-gp-2007.html
It happens from time to time that a car with a mechanical problem returns to the pits and the mechanics fix the car for the driver to rejoin, usually several laps down and out of contention.
In the really old days, 1950s etc, the lead driver of a team would often take their team-mates car if theirs developed a fault or broke down.
https://www.firstpost.com/sports/italian-gp-when-collins-gifted-his-car-and-title-to-championship-rival-fangio-1700895.html
Comment: @KebabProgrammer F1 considers technicalities quite strongly. If they did not actually retire, they did not technically retire, either. If you can find a report stating they retired and then returned to the race, as required, it can be added with that support.


Mensagem de login inválido aparece sempre no CakePHP

Question: Quando entro para a minha página de login, aparece logo a mensagem de aviso a dizer que o utilizador ou a passwords estão inválidos, mas isso devia só aparecer depois de carregar no botão para fazer login. Não dá para contornar isto?
Minha view:

        <?php echo $this->Session->flash(); ?>
   <?php echo $this->Form->create('User');?>
    <fieldset>
        <?php echo $this->Form->input('email');
        echo $this->Form->input('password');
    ?>
    </fieldset>
<?php echo $this->Form->submit('Login', array('class' => 'button'));?>

Minha action:
          public function login() {
    if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
    } else {
        $this->Session->setFlash(__('Username ou password inválidos!'));
    }
}

Comment: Nunca trabalhei com Cakephp, mas parece-me que ele está a fazer logo submit quando carrega a página, e como os campos estão vazios e o utilizador é inválido dá erro. Agora, dar-te uma solução não consigo :/
Comment: eu também acho isso, mas não sei porque está a fazer o submit logo. Não tem lógica.
Answer: É porque a sua action está tentando autenticar assim que carrega.
// Verifica o tipo de requisição, se for POST(form submit) tenta logar.
if($this->request->is('post')) {
    if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
    } else {
        $this->Session->setFlash(__('Username ou password inválidos!'));
    }
}

Comment: @Ricardo Costa, esta resposta atendeu a pergunta?
Comment: Valeu Marcelo. Sim, funcionou!
Comment: @RicardoCosta marca "aceitar resposta" para finalizar a questão por favor... ;)
Comment: odne faço isso?
Comment: No canto superior esquerdo da resposta, aonde está o número 4, você passa o mouse mais abaixo e clica no "vezinho" verde.


How to pass values that are in a List Object in C#?

Question: This maybe a simple one. That is I have a some JSON details which comes as a list and then it converts to object. So now the object contains 2 values since it is a list. So I wanted to pass them into the database. How do I achieve this.
Here's what I tried.
public IHttpActionResult PostRegister([FromBody] dynamic register)
{
    try
    {
        Newtonsoft.Json.Linq.JArray qualificationRes = (Newtonsoft.Json.Linq.JArray)register.qualification;
        var qualification = qualificationRes.ToObject<List<Qualification>>(); //conversion to the List object
        var sta2 = QMgrt.InsertQualifications(qualification,nid); //passing of List value.
        return Ok("success");
    }

    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return Ok("fail");
    }
}

This is how I trying to insert it to the database
public bool InsertQualifications(List<Qualification> quali,int newid) //Getting the List values
{
    foreach (Qualification q in quali) // This is where the issues comes only one set of object is passed to the database
    {
        try
        {
            var status = db.AddQualiDetails("Insert_QualiDetails", q.Description, q.University, q.Date_of_award, q.Qauli_id, q.Quali_type, newid, q.Duration);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    return true;
}

For more reference I have added this screenshot

As seen in the screenshot there are two set of object. How do I pass all of them into the database. Help would be really appreciated
Answer: I don't know if I understand you right but maybe this could be the problem:
public bool InsertQualifications(List<Qualification> quali,int newid) //Getting the List values
{
    foreach (Qualification q in quali) // This is where the issues comes only one set of object is passed to the database
    {
        try
        {
            var status = db.AddQualiDetails("Insert_QualiDetails", q.Description, q.University, q.Date_of_award, q.Qauli_id, q.Quali_type, newid, q.Duration);
            return true; <<<<<-------
        }
        catch (Exception)
        {
            return false;
        }
    }

    return true;
}

You insert one List entry into your database and the return true;
When you use return you exit the method and stop the foreach.
Regarding to this, your code is adding only one entry of your list.
Try to just remove this return true;
Also check any exception occurred during the insertion.
Comment: Yup. Removing of the `return true` solved my issue. Thanks :)
Answer: As far as i see you didn't call db.SaveChanges(). SaveChanges will commit your changes to database. Also there is return true; in your loop, it breaks the loop.
Here is correct code to save your data to database:
public bool InsertQualifications(List<Qualification> quali,int newid) //Getting the List values
    {

        foreach (Qualification q in quali) // This is where the issues comes only one set of object is passed to the database
        {
            try
            {
                var status = db.AddQualiDetails("Insert_QualiDetails", q.Description, q.University, q.Date_of_award, q.Qauli_id, q.Quali_type, newid, q.Duration);
            }
            catch (Exception)
            {
                return false;
            }
        }
        db.SaveChanges();
        return true;
    }
}

Comment: Removing the return true helped me solve the issue. Thanks. :)


Jquery click event fire twice

Question: I am building something with Jquery, and I am making some Ajax calls. So after my ajax calls, I need to call functions to trace clicks on some elements again. Here an example of such a function:
$(document).ready(function () {
    initSomething();
});
function initSomething(){
    $('.something').click(function(){
        alert('hello');
    });
}

And now an ajax function:
$('#AddSomething').click(function(){
    $.post('somewhere.php',{data},function(data){
        initSomething();
    });
});

And the problem is: I feel like when I initSomething(); for the second time, it's like it's readding a click event on the elements already traced by the first initSomething called on document ready.
So I tried something like e.preventDefault and e.preventPropagation(), but it doesn't seem to work, what am I missing?
Thanks for your answers and have a nice day!
EDIT: As saw on the answers, I forgot to say that the Ajax call is inserting new .something elements in the DOM...
EDIT 2: Here a jsfiddle: https://jsfiddle.net/wpsnz7op/
Comment: The best thing for us to help you will be if you provide a jsfiddle
Comment: Does ths changes anything?

    function initSomething(){
        $('.something').off('click');
        $('.something').click(function(){
            alert('hello');
        });
    }
Comment: May `#Addsomething` and `.something` be the same element or one is the child of the other?
Comment: To clarify - do you add **new** `.something` elements during the ajax call that you need to also attach the click handler to?
Comment: Exactly, a new .something is inserted in the DOM with the ajax call
Comment: use **.off()** jquery api to remoe the click event and then re assign the event like '$('#item').of('click').on('click',function(){ });'
Answer: Try .off() api to remove the already attached event and reassign the event like following.
function initSomething(){
    $('.something').off('click').click(function(){
        alert('hello');
    });
}

Hope this helps....
Comment: Well, it is working great! Thanks! And it's the solution that helps me best keep my actual code...
Answer: There is no need to rebind clicks from what I can see of the code you have there.
Just do not rebind and you will not have a multiple click issue.
Comment: Then should use event delegation with `.on` instead. The way the question is written it is very hard to tell what is going on here... :-(
Answer: Use event delegation instead of that.
 $(document).on('click','.something',function(){
        alert('hello');
    });

Then there is no need for calling the initSomething(); function after ajax.
Comment: this would be proper approach, not sure why it got down voted. Explanation could be improved though
Comment: How does this answer the question? There will **still** be multiple click events handled on one object.
Comment: ^^ This.  I'd +1 this if it explained why, and especially explained why you should remove the subsequent calls to `initSomething()`, and why.  As it is this will make no sense to someone that would ask the question.
Comment: @Neal user is trying to bind the event again,. Probably it should be for the new elements created after ajax.

Jquery click event fire twice


Decidability of Interpreted Theory

Question: If a theory $T'$ is interpretable in a theory $T$ and $T$ is decidable, is it true that $T'$ must be decidable as well?
Comment: @HanulJeon Technically one needs to care that the translation of formulas corresponding to the interpretation is computable. It is always the case  if the signature of interpreted theory is finite. But for infinite signatures one could have non-computable interpretation of an undecidable theory in a decidable one.
Comment: @FedorPakhomov I was not careful; I did not notice there are such an example.
Answer: No. For example, the theory $T'$ of groups is known to be undecidable, but it is clearly interpretable in the theory $T$ of torsion-free divisible abelian groups $(\mathbb{Q}$-vector spaces), which is decidable.
On the other hand, if $T'$ a complete theory which is interpretable in $T$, via a computable interpretation, and $T$ is decidable, then $T'$ is decidable.
And if $T'$ and $T$ are bi-interpretable, via computable interpretations, and $T$ is decidable, then $T'$ is decidable.
Computable here means that the function assigning to each symbol of the language $L'$ of $T'$ its corresponding formula in the language $L$ of $T$ must be computable. It follows that the map $\varphi\mapsto \hat{\varphi}$ from $L'$-formulas to corresponding $L$-formulas is computable.
So given an $L'$-sentence $\varphi$, we know that if $T'\vdash \varphi$, then $T\vdash \hat{\varphi}$. If we knew the converse, that if $T\vdash \hat{\varphi}$, then $T'\vdash \varphi$, then we could computably reduce the question of whether $T\vdash \varphi$ to the question of whether $T\vdash \hat{\varphi}$.
If $T'$ is complete, then if $T'\not\vdash \varphi$, then $T'\vdash \lnot \varphi$, so $T\vdash \lnot \varphi$, and $T\not \vdash \varphi$. So we have the desired converse. If $T'$ is not complete, but $T'$ and $T$ are bi-interpretable, we can also get the converse: If $T\vdash \hat{\varphi}$, then $T'\vdash \hat{\hat{\varphi}}$, which implies $T\vdash \varphi$ (using the definition of bi-interpretation).

Decidability of Interpreted Theory


Completely standardized indirect effect (Preacher & Kelley, 2011) in lavaan

Question: Preacher & Kelley (2011) have proposed an effect size (i.e., completely standardized indirect effect) that quantifies the magnitude of an indirect effect. My question is whether lavaan's Std.all represents this effect size, or whether there are distinctions?
Preacher, K. J., & Kelley, K. (2011). Effect size measures for mediation models: Quantitative strategies for communicating indirect effects. Psychological Methods, 16(2), 93–115. https://doi.org/10.1037/a0022658
Answer: Let's not forget that "completely standardized indirect effect"  is simply the product of standardized regression coefficients, which is not directly attributable to Preacher & Kelley (2011) and is in fact quite old.
So yes, having the Std.all argument in lavaan will give you standardized effects and thus standardized indirect effects.
Mathematically, the standardized effect is obtained from $\beta_{xy} = b_{xy}\frac{\sigma_x}{\sigma_y}$, or by standardizing all the variables so that $\sigma_x = \sigma_y = 1$. The "completely standardized indirect effect" is obtained from  $$\beta_{xm} \beta_{my}= b_{xm}\frac{\sigma_x}{\sigma_m}b_{my}\frac{\sigma_m}{\sigma_y}=b_{xm}b_{my}\frac{\sigma_x}{\sigma_y},$$ or by standardizing all the variables.


Apply a ranged contextual filter to a date in Views

Question: I have an entity with a timestamp field that I would like to filter based on date. I can add a standard filter "between two date", type in two dates, and everything works great. However, contextual ranges do not work. I've read online that Drupal 7 allowed 2016-01-10--2017-01-01 or 20160101--20170101 as input and would display all results in 2016. These do not seem to work in Drupal 8. Is there a way to do range contextual filters in D8?
I've tried using a datetime field instead of a timestamp, and I am unable to filter this either.
Answer: Views Contextual Range Filter might do the trick for you. Install the latest beta and then see if you need to apply this patch. It's got just the functionality you're looking for.
Comment: Thanks! I saw this, but the 'releases' list does not show the 8.x version, so I assumed there was none.
Comment: I noticed that. I thought it was too useful a module not to have something in the works for D8 so I checked the repository.
Comment: Unfortunately is doesn't install. The code is probably based on the beta versions of D8.
Comment: This module has been updated and now function for D8.4


Bayes Theorem where the number of tosses depends on tosses

Question: There are two fair coins (i.e. Heads and Tails are equally likely for tosses of both). Coin
$1$ is tossed $3$ times. Let $X$ be the number of Heads that occur. After this, Coin $2$ is
tossed $X$ times. Let $Y$ be the number of Heads we get with Coin $2$. The probability
$Pr(X ≥ 2|Y = 1)$ equals ?
I tried to solve it using Bayes' theorem such that
$Pr(X\geq 2|Y=1)={Pr(X\geq 2)\cdot[Pr(Y=1|X=2)+Pr(Y=1|X=3)]\over Pr(X>=2)\cdot[Pr(Y=1|X=2)+Pr(Y=1|X=3)]+Pr(X<2)\cdot[Pr(Y=1|X=0)+Pr(Y=1|X=1)]} $
and i got the answer $7/11$ which seems to be wrong. Can anyone help me understand why this method fails to work?
Comment: Hi!  Welcome to MSE.  You can find a MathJax tutorial [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).  I'll tidy this one up, and then if you click "edit" you can see what I did.
Comment: Please make the title about the mathematical content of the post, and not something generic like it currently is..
Comment: Your equation is so hard to read I can't even tell if it is one formula or two.  Can you space it out or something?
Answer: $$P(X\geq 2 | Y=1) = \frac{P(X \geq 2 \text{ and } Y=1)}{P(Y=1)}$$
We can solve for the numerator and the denominator separately.
$X$ can be $0,1,2,$ or $3$.
$Y$ can equal $1$ in $3$ different ways, because if $X=0$ then $Y$ cannot be $1$.  Each of those is a product, so the denominator is a sum of three terms.
The numerator is easier.  We can split that up into
$$P(X \geq 2 \text{ and } Y = 1) = P(Y = 1 | X \geq 2) \cdot P(X \geq 2)$$
The numerator is two cases, if $X=2$ and if $X = 3$, so the numerator will be a sum of two products:
$$P(Y=1|X=2)\cdot P(X=2) + P(Y=1|X=3)\cdot P(X=3)$$
From there you can put the answer together.  It's hard to read your equation, but I think your problem is that you were trying to factor out a term where there is no common factor.  You have to compute each specific product separately, then add.

I tried to solve it using Bayes' theorem such that
$Pr(X\geq 2|Y=1)={Pr(X\geq 2)\cdot[Pr(Y=1|X=2)+Pr(Y=1|X=3)]\over Pr(X>=2)\cdot[Pr(Y=1|X=2)+Pr(Y=1|X=3)]+Pr(X<2)\cdot[Pr(Y=1|X=0)+Pr(Y=1|X=1)]} $

Problem: $\Pr(Y=1\mid X\geq 2)\neq \Pr(Y=1\mid X=2)+\Pr(Y=1\mid X=3)$ as the Additive Law applies to unions of disjoint events, not conditions.
Solution: Deal with the union before the conditioning.
In summary:
$\begin{align}\Pr(X\geq 2\mid Y=1)&=\dfrac{\Pr(X=2,Y=1)+\Pr(X=3,Y=1)}{\Pr(X=1,Y=1)+\Pr(X=2,Y=1)+\Pr(X=3,Y=1)}\\[1ex]&=\tfrac{\Pr(X=2)\Pr(Y=1\mid X=2)+\Pr(X=3)\Pr(Y=1\mid X=3)}{\Pr(X=1)\Pr(Y=1\mid X=1)+\Pr(X=2)\Pr(Y=1\mid X=2)+\Pr(X=3)\Pr(Y=1\mid X=3)}\\[1ex]&=\dfrac{5}{9}\end{align}$


Rails3 jquery mobile All Conditional Items showing up in the Nav Bar

Question: The following nav bar code produces a nav bar with 6 slots when logged out (e.g. Send, Get, Account, Sign in, Full, and blank.  The max for the nav bar is 5 items without wrapping.  I want jquery mobile to recognize that there are only 5 items.  Is there some syntax for accomplishing this?
![navbar]: http://ponzicode.com/so/navbar.jpg

<%= link_to "Send",  %>

<%= link_to "Get",   %>

<%= link_to "Account", root_path %>

        <% if user_signed_in? %>

<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>

        <% else %>

<%= link_to "Sign in", new_user_session_path %>

        <% end %>
        <% if mobile_device? %>

<%= link_to "Full", :mobile => 0 %>

        <% else %>

<%= link_to "Mobile", :mobile => 1 %>

        <% end %>

application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :prepare_for_mobile

   private

   def mobile_device?
     if session[:mobile_param]
      session[:mobile_param] == "1"
     else
       request.user_agent =~ /Mobile|webOS/
     end
   end

   helper_method :mobile_device?

   def prepare_for_mobile
     session[:mobile_param] = params[:mobile] if params[:mobile]
     request.format = :mobile if mobile_device?
   end
end

Answer: Is this copied from your project?  Your code should only be producing 5
 elements by my count.
I notice the second
 element is not a close tag--that should be

Edit:
Try commenting out your code and pasting this in:

<%= link_to "Test", "" %>

<%= link_to "Test", "" %>

<%= link_to "Test", "" %>

<%= link_to "Test", "" %>

<%= link_to "Test", "" %>

Something tells me that this is going to wrap too--in which case 4 is your max (at least with the current styling)
Comment: Received an answer in jquery mobile forum, you must use either add data-grid="d" to the data-role or .ui-grid-d to the list. A reference in the docs can be found here http://jquerymobile.com/demos/1.0b3/docs/content/content-grids.html.
Comment: I agree with you on the 5 s but the result is 5 with a blank item position.  I'm going to try and put up a screen shot. As for the , I edited the closing tag to reflect what it is in my code .  I copied and pasted it from my code, the only thing I can think of is pressed Ctrl-K to format the code it changed that tag.
Comment: could you also paste in the snippet this renders to on mobile and on desktop?
Comment: Ah, I meant the HTML code generated.  The image actually looks like there are only 5 `li`s.  Have you been able to make an unordered list with 5 list items that does **not** wrap?  It's possible that this is a sizing issue (test it out by using the code in my edit)
Comment: You are absolutely correct. I tested it and the same thing happens, even when the link test is 1,2,3,4,5.


Can running git-bash raise security concerns?

Question: Executing the portable git for 64-bit Windows from https://git-scm.com/download/win  caused a  cybersecurity alarm in a company. Why could it happen?
Can running the file indeed raise security concerns?
Answer: It can happen depending on the structure of the archive (an auto-extracting exe)
But executing it is one option.
Another way to "install" it is to use a uncompress tool, like Peazip, which includes 7zip, and can  uncompress pretty much anything.
Make a pzxx.bat in a folder which is referenced by your %PATH% (type set PATH to see its value, and choose a folder)
@echo off
set "sz=C:\Program Files\PeaZip\res\7z\7z.exe"
rem https://superuser.com/questions/194659/how-to-disable-the-output-of-7-zip
for /F %%i in ("%1") do "%sz%" x -aos -pdefault -sccUTF-8 "%%i" -o%%~ni -bso0 -bsp1

From there, go to the folder where you have the PortableGit-2.37.1-64-bit.7z.exe file and type:
pzxx PortableGit-2.37.1-64-bit.7z.exe

You will get a folder name PortableGit-2.37.1-64-bit.7z in which you will have the latest 2.37.1 Git ready to use.
Type mklink /J current PortableGit-2.37.1-64-bit.7z and add to your %PATH%:
set "GH=%C:\path\to\Git\current"
set "PATH=%GH%\bin;%GH%\cmd;%GH%\usr\bin;%GH%\mingw64\bin;%GH%\mingw64\libexec\git-core;%PATH%"

Since GH reference a junction folder "current", the PATH to Git will never change. All you need to do for the next Git is:
cd C:\Path\to\Git
pzxx PortableGit-2.38.0-64-bit.7z.exe
rmdir current
mklink /J current PortableGit-2.38.0-64-bit.7z

The %PATH% won't need to change.
Comment: Thanks. Is it the extraction done by running executable PortableGit-2.37.1-64-bit.7z.exe which raised the alarm? Not running git-bash in the extracted files? Why is that dangerous?
Comment: @Tim The auto-extracted exe did trigger the anti-virus. But uncompressing it through 7Zip should not. Nothing to do with git bash though
Comment: @Tim I suspect because it was so recently release its signature wasn't fully analyzed/validated yet. This should resolve itself in the next few days.
Comment: Are self-extracting executable files monitored differently from other executables (like git bash itself) by cybersecurity departments?
Comment: @Tim No, this is more about the fact it is a recent file, not yet fully vetted by AV.
Answer: Yes , allowing a service that uses a more than 5 ports to send / receove is definitely a security threat.


How to determine the creator of my calendar event in Office 365?

Question: I'm using the Office 365 API to request events from my calender. To be specific I have a shared calender (the one I shared it with can edit the calendar) but when requesting data from the API I can't see the difference in organisator of the events. As I would like to send different messages based on who has added the event, I would like to know who has added it.
Is there any other property or way to identify who has added/updated the event?
Comment: I'm using the REST API
Comment: Would you provide with more detail on what Office.js API methods you are using and what information you get with them, as well as what would you like to get. Are you trying to get organizer of the event and/or attendee list? Is your add-in invocation happen for reading of the event item? You don't talk about creating event, right?
Comment: Looking at the latest API, it is contained in the Office.context.mailbox.item object:

organizer :EmailAddressDetails

Gets the email address of the meeting organizer for a specified meeting. Read mode only.

Type:
•EmailAddressDetails

Example
var organizerName = Office.context.mailbox.item.organizer.displayName;
var organizerAddress = Office.context.mailbox.item.organizer.emailAddress;

HTH,
Jim
Comment: Could you clarify if you're asking about the REST API or the Office.js Add-in framework? Two very different stacks.
Answer: The Power Automate trigger named When an event is added, updated or deleted (V3) outputs a GraphCalendarEventClientWithActionType which contains a property called Organizer.

Example of accessing the Organizer property in a Power Automate flow:

Note: For some reason Power Automate was not displaying this property when my cursor was in the Body field (only when my cursor is in the Subject field).
You can work around this by getting the value via an Expression:


Understanding Ruby variables and symbols?

Question: I am having some trouble understanding the syntax of variables and symbols in Ruby. I am reading a book called Agile Web Development with Rails 4. I am trying to learn both Ruby and Rails so that I can build websites.
The books and tutorials I have been reading sometimes have variables with the "@" symbol in front of them, and then some variables do not have the @ symbol in front of them. What is the difference between them?
Also, I am getting confused with the colon. Sometimes I see variables where the colon is in the front, such as :order, and then I see variables where the colon is at the end, such as colon:. I do not understand what the colon is doing.
Please help me understand the Ruby syntax.
Comment: Since Rails is a framework built on Ruby, start with a Ruby tutorial to get a handle on the actual language, then move to Rails.
Comment: Recommended reading: http://www.ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/index.html
Comment: agreed with @iamnotmaynard. Without basic ruby knowledge, you will suffer hard with rails, especially when you will encounter metaprogramming and other clever ruby tricks that the rails contributors use... I'd recommmend those books : [the well grounded rubyist](http://www.manning.com/black2/), [eloquent ruby](http://eloquentruby.com/), [the ruby way](http://therubyway.org/)  and of course [the universal reference : the pickaxe](http://pragprog.com/book/ruby/programming-ruby)
Comment: And [wade through several of these questions](http://stackoverflow.com/search?q=%5Bruby%5D+variable+%22%40%22)
Comment: Sameer, diving into Ruby _and_ Rails at the same time is not easy but it's doable. I consider it a valid way of learning them - the "dive" method. You'll swallow a lot of water but don't be discouraged when people tell you "you have to learn Ruby first" because eventually you'll find your way around.
Comment: See "[Ruby — understanding symbols](http://stackoverflow.com/questions/2341837/understanding-symbols-in-ruby)", and follow the related links.
Comment: @mjnissim It's possible, but masochistic - I know it for sure... that's what I've done ;). Rails is almost a DSL in itself, heavily uses advanced features of ruby (metaprog...) and boasts a LOT of magic that make it hard to understand what is going on if you don't have a solid ruby knowledge. Moreover, knowing the difference between the different kinds of vars is just the matter of following a basic tutorial, so I think it's a bare, reasonable minimum
Comment: @m_x I agree with you! It makes sense, and like you, I've also dived straight into Rails myself. As hard as it was, I don't regret it ha ha!
Answer: Variables starting with @ are instance variables, "properties" in other languages. Whereas 'classic' variables are local to the scope of their method/block, instance variables are local to a specific instance of an object, for example:
class Foo

  def initialize(bar)
    @bar = bar
  end

  def bar
    @bar # the variable is specific to this instance
  end

  def buzz
    buzz = 'buzz' # this variable is not accessible outside of this method
  end

end

You may also see variables starting with @@, which are class variables, and are accessible by every instance of the class and shared with every instance of the subclass. Usage of those variables is usually discouraged, primarily because subclasses share the variable, which can cause a lot of mess.
In Ruby everything is an object, classes are objects (instances of class Class), so you can also have class instance variables:
class Foo

  def self.bar
    @bar #we are in class Foo's scope, which is an instance of class Class
  end

  def self.bar=(bar)
    @bar = bar
  end

  def bar
    @bar # Foo.new.bar != Foo.bar
  end

end

What you call "variables with a colon" are not variables. They are a particular type of string, called a symbol, that is immutable and optimized for quick identification by the interpreter, in fact, those are stored internally as pointers, so that :this == :this is a very quick operation.
This property makes them good candidates for hash keys because they offer quick retrieval or for "flags" to pass to a method; Think of them as a sort of loose constant that "stands for" what they say. Their immutability is also dangerous: All symbols ever created never get garbage collected; It's easy to create a memory-leak by creating thousands of symbols, so use them wisely.
UPDATE since ruby 2.2 symbols may be garbage-collected in certain cases (when no reference is kept and no comparison is needed)
Comment: Your dire warnings about class variables and symbols only really apply to careless use. Abuse of anything in programming can lead to problems; Abusing symbols can lead to excessive memory consumption, but normal code won't have the problem, it'd take dynamically creating them in an unusual situation to cause that. Using class variables needs to be done carefully, and their existence is often a red-flag that variable scoping is being abused, but they also make it possible to share variable state between instances of an object cleanly. We always have to know what we're doing or chaos happens.
Comment: I don't know why the -1, but I suspect it's because of what I commented on above.
Answer: Variables with an @ symbol are instance variables. What this means is that they persist as long as the instance of the class they are declared in persists. So if you have a class called Message and each message has a variable called @subject, when you instantiate a new message it will keep that subject variable in memory as long as the message object itself lives. Now if it did not have the @ symbol, once the function it was declared in "went out of scope" aka finished, the variable would be "lost" as the function was complete and the memory was reclaimed by the Ruby VM. There are also "class variables" that are prefaced with two @ symbols. This means the variable is shared across all instances of a class.
As for the colon, if it is before a variable that means it is a "symbol", which is usually used as an identifer for hashes and other bits of data in Ruby. If it is at the end of a word that means it is the key portion of a hash identifier in Ruby 1.9+ syntax.
Comment: For the sake of completeness, if the colon is at the end of a word, it's the key portion of a hash *and* is a symbol.
Answer:
sometimes have variables with the "@" symbol in front of them, and then some variables do not have the @ symbol in front of them.

Variables with the "@" symbol are instance variables,which are not preceded by @,can be constants or local variables or global variables. Read Ruby Programming/Syntax/Variables and Constants.

Sometimes I see variables where the colon is in the front, such as :order

They are called symbols.

and then I see variables where the colon is at the end, such as colon:. I do not understand what the colon is doing.

These probably the Hash syntax(as you give us hints,so I would guess),where keys are symbols. Example : {foo: 1} - this is a Hash.
Also read as you requested :

Normal Variables Vs Instance variable in Ruby, Whats the difference?
Comment: What are the differences between instance variables, local variables and global variables? What are instance variables used for?
Comment: @SameerAnand You should spend some time reading about object oriented theory, and variable scope.  These are not ruby-specific concepts.
Comment: I know all about Object Oriented programming, I use Java all of the time. However, I am having trouble moving over to Ruby on Rails because the syntax is completely different, Rails is something completely new to me, and Web Development is something I never did in Java.
Comment: @SameerAnand Then you know what instance variables are, and the differences between locals, globals, and instance variables. The syntax and precise semantics are covered in most any Ruby programming guide. In Rails, instance variables are also used to transfer data to the view layer.
Answer: Instance Variables: (@foo = '123') An instance variable is defined and keeps its value throughout the current instance of the request.  In the rails mvc paradigm, the most common use of instance variables are used to help communicate data from the controller to the view, and allows you ro define things in one part of the controller and use in another.
class ProjectsController < ApplicationController
  before_filter :find_project

  def show; end

  def update
    if @project.update_attributes(params[:project])
      ...
    end
  end

  private
  def find_project
    @project = Project.find(params[:id])
  end
end

In the above code, you can see that there is a before filter that gets ran before every method.  In the above case, we find the current project and save it to an instance variable.  And because its an instance method, its able to be access anywhere within this class as well as the views used to render the html.
Local Variables: (foo = '123') Pretty much exactly what the name implies, they are only able to be accessed within the current method (def) of where they are defined.


Monotouch: Downgrade to 3.2.6 (More Stable) Version

Question: Since MT 4 version still has some bugs for WCF services, I would downgrade it to 3.2.6.
I've recovered this old version but now it doesn't work because I have a more recent mono-framework version. What steps do I have to follow for disinstalling mono-framework 2.10.1_3 and recovering the old one?
Thank you. Regards.
Update: For those interested in, rembember to uninstall previous mono version. See this link: Uninstall Mono
Answer: Old mono-framework will recognize, that you are installing an older version over an newer one and prompt you to continue
Comment: Thank you for your reply..I would reinstall 2.10 mono-fr. Where can I find this version? Thanks.
Comment: But for MT 3.2.6 i would rather choose mono 2.6.7
Comment: Thank you Karl. I'll try to fix it. Regards.


adjusting Kalman estimates for no data

Question: I have a kalman filter like set up, when I get the current value of an observable process, and update my estimate of the state variable with it.
However, my observations are non-uniform in time, and I am trying to add the logic, that if the last observation was really long ago, I should forget about it, and use an a priori estimate X.
I can just switch to X, if time since the last observation is > T. But I was hoping to put in some general setting, which will be consistent with the Kalman filter logic. Does anyone have suggestions/references for it?
Many thanks.
Comment: If you are observing $V_t, V_{t-1}, \ldots$ to update the system state $X_t$, why not observe $(V_t, V_{t-1})$ jointly and update the state only when $V_t = V_{t-1}$?
Comment: Sorry, I don't understand your suggestion. Say, I have a stream of observations: 3 at t_1, 5 at t_2, 3 at t_3, 5 at t_4 - are you suggesting to ignore all of those?
Comment: And are you directly observing a state here? For instance, you *observe* 3 at time 1, but does that mean the *state* is 3 at time 1... the observations need not be the states, you could be observing acceleration in a vehicle and predicting its location on a road for instance.
Comment: Yes, for simplicity, assume, that we are observing the state.
Comment: Then my example would not yield any valid state for the observations you present.
Answer: If the Kalman filter-like model includes a covariance for the error-states, and if this covariance is being propagated in time such that it grows in the absence of new measurements, then a natural solution to the problem is to periodically check the trace of the error covariance against a ceiling threshold.  If the threshold is exceeded we assume the filter has lost all useful information about the state, and that the state estimate should be reset to the a-priori value.  Since the KF is usually a linearized approximation for a non-linear problem there is good reason to question the usefulness of the information stored in the covariance if the state error covariance is large.

adjusting Kalman estimates for no data


writeInt(Integer) overwrites zero

Question: Using RandomAccessFile class, I'm trying to test the concept of writing/reading to/from a file in java. So I tried this code:
public static void main (String[] args) throws IOException {
        RandomAccessFile storage = new RandomAccessFile("FILE.txt", "rw");

        storage.seek(0);
        storage.writeInt(1);

        storage.seek(1);
        storage.writeInt(2);

        storage.seek(2);
        storage.writeInt(3);

        storage.seek(3);
        storage.writeInt(4);

        storage.seek(4);
        storage.writeInt(5);

        System.out.println(storage.readInt());
        System.out.println(storage.readInt());
        System.out.println(storage.readInt());
        System.out.println(storage.readInt());
        System.out.println(storage.readInt());

        storage.close();

I think it should print :
1
2
3
4
5
but what happens is that it prints:
3
4
5
EOFException... why?
Comment: `writeInt` writes 4 bytes, but the argument to `seek` is just in terms of bytes - so you've overwritten a load of data. Why are you calling `seek` at all? Just remove the calls to `seek` and it should be fine - except you *should* call `storage.seek(0)` before you start to read.
Answer: There are 2 problems here - you are not allowing 4 bytes per int written, and you are not seeking back to the start of the file when reading the ints back into memory.
First, the seek method takes an argument of the number of bytes as an offset into the file.

pos - the offset position, measured in bytes from the beginning of the file, at which to set the file pointer.

But in Java ints have 4 bytes, so you are overwriting 3 of the previous int's 4 bytes with each subsequent write.  Either explicitly set the mark to 4 bytes later each time:
storage.seek(4);
storage.writeInt(2);

storage.seek(8);
storage.writeInt(3);

// etc.

Or even easier, the mark "does the right thing" and moves forward the appropriate number of bytes.  Just leave out the seeks here.
storage.writeInt(1);
storage.writeInt(2);
storage.writeInt(3);
storage.writeInt(4);
storage.writeInt(5);

The second problem is that when reading the bytes back, you don't reset the mark back to the beginning of the file, causing an EOFException.  Add a call to seek(0) to send the mark back to the beginning of the file.
storage.seek(0);

System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());

Then I get the output:
1
2
3
4
5

Answer: I see two issues here:

You aren't seek-ing between your last write and your first read, so you're starting your reads after the end of where you last wrote. (The fact that you're not immediately getting EOFException indicates that your file was not empty at the beginning of this program run.)
seek takes an argument representing a byte position, but writeInt and readInt write and read four bytes. So if you don't want your integers to overlap each other, you'll need to seek to positions 0, 4, 8, etc., instead of 0, 1, 2, etc. (Though as it happens, you don't actually need your current calls to seek if your goal is for the integers to be adjacent.)

writeInt(Integer) overwrites zero


Single row subqueries error

Question: I have a table on oracle sql called employees. What I'm trying to do is return the department ID and minimum salary of all employees, grouped by
department ID, having a minimum salary greater than the minimum salary of those
employees whose department ID is not equal to 50.
This is what I came up with:
select department_id, min(salary)
from employees where min(salary)>(select min(salary) from employees
where department_id!=50)
group by department_id;

Oracle is giving me error: ORA-00934: group function is not allowed here
Anyone have any idea why this is happening?
Answer: Since you are using an aggregate function for filtering, you need to place that code in a HAVING clause. You cannot use an aggregate function in a WHERE clause:
select department_id, min(salary)
from employees
group by department_id
having min(salary)>(select min(salary)
                     from employees
                     where department_id!=50)

Comment: Shoot, I didn't even think about that! Thanks a bunch!

Single row subqueries error


Haystack UnicodeDecodeError

Question: I'm using haystack and solr on Django. I get UnicodeDecodeError and I think the reason is the unicode data in the database are either converted to str or decoded to utf-8 which makes a later UnicodeDecodeError when sending via httplib or printing to the console.
I think the problem should before the haystack full_prepare function, since as I checked afterwards data is already ruined.
Any thoughts?
I setup.pyed install (haystack, pysolr, django)
and used the binary of lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/
<code>Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Pouria\Desktop\conference\conference>python manage.py rebuild_index

WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y

Removing all documents from your index because you said so.
Failed to clear Solr index: [Reason: Error 404 Not Found]
All documents removed.
C:\Python27\lib\site-packages\django\db\models\fields\__init__.py:808: RuntimeWarning: DateTimeField
 received a naive datetime (2013-02-09 08:47:27.110000) while time zone support is active.
  RuntimeWarning)
Indexing 2 conferences.
ERROR:root:Error updating conferences using default
Traceback (most recent call last):
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 210, in handle_label
    self.update_backend(label, using)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 256, in update_backend
    do_update(backend, index, qs, start, end, total, self.verbosity)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 78, in do_update
    backend.update(index, current_qs)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\backends\solr_backend.py", line 72, i
n update
    self.conn.add(docs, commit=commit, boost=index.get_field_weights())
  File "C:\Python27\lib\site-packages\pysolr.py", line 786, in add
    return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
  File "C:\Python27\lib\site-packages\pysolr.py", line 379, in _update
    return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
  File "C:\Python27\lib\site-packages\pysolr.py", line 291, in _send_request
    timeout=self.timeout)
  File "C:\Python27\lib\site-packages\requests\api.py", line 87, in post
    return request('post', url, data=data, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 279, in request
    resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies
)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 373, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python27\lib\site-packages\requests\adapters.py", line 171, in send
    timeout=timeout
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 421, in url
open
    body=body, headers=headers)
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 273, in _ma
ke_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Python27\lib\httplib.py", line 949, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 990, in _send_request
    self.endheaders(body)
  File "C:\Python27\lib\httplib.py", line 943, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 810, in _send_output
    self.send(message_body)
  File "C:\Python27\lib\httplib.py", line 775, in send
    self.sock.sendall(str)
  File "C:\Python27\lib\socket.py", line 222, in meth
    return getattr(self._sock,name)(*args)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 143-149: ordinal not in range(
128)
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 443, in execute_from
_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\rebuild_index.py"
, line 15, in handle
    call_command('update_index', **options)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 150, in call_command

    return klass.execute(*args, **defaults)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 184, in handle
    return super(Command, self).handle(*items, **options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 341, in handle
    label_output = self.handle_label(label, **options)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 210, in handle_label
    self.update_backend(label, using)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 256, in update_backend
    do_update(backend, index, qs, start, end, total, self.verbosity)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\management\commands\update_index.py",
 line 78, in do_update
    backend.update(index, current_qs)
  File "C:\Users\Pouria\Desktop\conference\conference\haystack\backends\solr_backend.py", line 72, i
n update
    self.conn.add(docs, commit=commit, boost=index.get_field_weights())
  File "C:\Python27\lib\site-packages\pysolr.py", line 786, in add
    return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher)
  File "C:\Python27\lib\site-packages\pysolr.py", line 379, in _update
    return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
  File "C:\Python27\lib\site-packages\pysolr.py", line 291, in _send_request
    timeout=self.timeout)
  File "C:\Python27\lib\site-packages\requests\api.py", line 87, in post
    return request('post', url, data=data, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 279, in request
    resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies
)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 373, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python27\lib\site-packages\requests\adapters.py", line 171, in send
    timeout=timeout
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 421, in url
open
    body=body, headers=headers)
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 273, in _ma
ke_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Python27\lib\httplib.py", line 949, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 990, in _send_request
    self.endheaders(body)
  File "C:\Python27\lib\httplib.py", line 943, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 810, in _send_output
    self.send(message_body)
  File "C:\Python27\lib\httplib.py", line 775, in send
    self.sock.sendall(str)
  File "C:\Python27\lib\socket.py", line 222, in meth
    return getattr(self._sock,name)(*args)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 143-149: ordinal not in range(
128)
</code>
Comment: I had a similar error, my URL in HAYSTACK_CONNECTION in setting.py was "http://localhost:8983/solr/#/tester" but i should actually be "http://localhost:8983/solr/tester". Hope this helps.
Answer: I had the same error. It's seams to be fixed on master https://github.com/toastdriven/django-haystack. So you should use haystack 2.0 alpha/beta.

Haystack UnicodeDecodeError


Android OpenGL: Bitmap.getHeight() > actual height

Question: Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.background);

My background.png has a size of 512x512px
I use BitmapFactory to load the Bitmap of the background resource file.
The strang thing:
Log.d("bitmap height", bmp.getHeight() + "px");

always returns 768px.
How is this possible?
My openGL is setup like this:
width = 480;
height = 800;
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0.0f, width, 0.0f, height, -1.0f, 1.0f);

gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glEnable(GL10.GL_TEXTURE_2D);

gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

Answer: 768 / 512 = 1.5
This is the factor used for your screen resolution.
Comment: Well, I suppose you're putting your png in the drawable-mdpi folder and you're using an hdpi device (240 dpi). For this reason your bitmap is scaled x1.5. Let's have a deep look at that: http://developer.android.com/guide/practices/screens_support.html
Comment: Can I change this factor, or do I have to render all sprites with lower size? Where does this factor come from?
Comment: I suppose you're asking that because your background exceed screen bounds. In my app I used android:scaleType="fitXY" for the background ImageView and I forgot about png dimensions. Is this useful?
Comment: No, not really. My "background" is a "normal" sprite. I don't make any difference between a background or an other image sprite. I am using OpenGL to draw these sprites, so I can't make any settings like "scaleType" or what every :/
Comment: Thanks for your advise. Im going to check this out.
Answer: BitmapFactory will scale the bitmap when the bitmap's DPI doesn't match the screen's DPI. The solution is to set the inScaled option to false:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
    R.drawable.background, opts);


Solução/alternativa para eregi_replace obsoleto

Question: Estou recebendo o seguinte erro:
<code>Deprecated: Function eregi_replace() is deprecated in C:\wamp\www\ajax\paginator.inc.php on line 202
</code>
Esse é uma linha de um script que faz paginação com php+mysql+ajax
Linha 202:
<code>$_pagi_sqlConta = eregi_replace("select[[:space:]](.*)[[:space:]]from", "SELECT COUNT(*) FROM", $_pagi_sql);
</code>
Boa parte das querys estão obsoletos, e eu estou adaptando do mysql para mysqli. Porém, a 'eregi_replace' eu não conhecia até o momento, e depois de pesquisar, não consegui achar uma solução/alternativa para ela.
Comment: [Erro Deprecated: Function ereg](http://pt.stackoverflow.com/q/11870/91)
Answer: Substitua por preg_replace e faça o teste.
<code>$_pagi_sqlConta = preg_replace("/select[[:space:]]'\(.*\)'[[:space:]]from/", "SELECT COUNT(*) FROM", $_pagi_sql);
</code>
Comment: Editei, tente agora.
Comment: Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in C:\wamp\www\ajax\paginator.inc.php on line 202

Eu estava tentando exatamente ela agora, mas recebi o erro acima e também não consigo resolver.
Comment: Parece que o erro do preg_replace foi solucionado. Porém, um erro ocorreu linhas abaixo:
Fatal error: Call to undefined function mysqli_result() in C:\wamp\www\ajax\paginator.inc.php on line 208. Linha 208:  $_pagi_totalReg = mysql_result($_pagi_result2,0,0);//total de registros
Comment: Ai é outro erro, não sei te dizer o que pode ser pois não estou vendo como está implementado.
Comment: Tudo bem, entendo. Estarei marcando a resposta como correta, pois realmente resolveu a questão, e o que veio depois é consequência. Creio que seja melhor criar uma outra pergunta, não é? Ah... obrigado!


Noise of same order of magnitude than seasonality in a time series

Question: everyone! I'm new in this field of statistics and I looked for an answer to this question here but couldn't find any related questions. I'm working with the Lending Club Loan Data, available on Kaggle and I'm trying to decompose a time series into trend, seasonality and noise. This is what I got using the decompose command from R, setting its type to additive. The plot on the right side is the same graph in the log scale.

The random noise seems to be of the same order of magnitude as the seasonality without even considering those strange peaks after 2014. Does this fact (noise of same magnitude as seasonality) mean the time series has no seasonality at all?
Comment: @TommasoGuerrini, just uploaded the plot in log scale.
Comment: Hi! Welcome to stackexchange! I'm trying to understand, but it's very difficult to see the actual values until 2012.. Could you either plot each part separately or plot it on a logarithmic scale ?
Answer: First of all welcome to StackExchange!
Thank you for uploading the log scale plot which makes more clear what happens.
What decompose(ts, type = 'additive' ) does is to rewrite the time series as:
$X_t = Trend_t + Seasonal_t + Random_t$
The series you are studying has no particular seasonality and this can be seen once you detrend the series: I didn't download the data, but you can see it with:
decompose(log(ts))$x - decompose(log(ts))$trend

which corresponds to:
$log(X_t) - Trend_t = Seasonal_t + Random_t$
If you have patience just upload the that plot and then you'll see there is no periodicity (so no seasonal part there).


how to add this github project to use in ruby class

Question: I am learning how to use the data structure in ruby.
I found this library on github : https://github.com/kanwei/algorithms/tree/master.
I have created a word_count.rb file locally.
I want to use the library I mentioned, locally in my ruby class file.
The link I mentioned has following project structure :

how can I use this project in class file ?
Comment: Don't make us go to Github just to understand what you're trying to do. Instead, you are supposed to include a summarized version of that information *in your question*. *WHEN* that link breaks it will make your question nonsensical instantly without that. In addition, what have you tried? You need to show your attempt to make this work, instead of simply asking for someone to do it for you.
Answer: It is published as a gem (just the page you found does not document that fact): https://rubygems.org/gems/algorithms
So if you have a Gemfile in your project, add the line:
gem "algorithms", "~> 0.6.1"

Otherwise, run the following command:
gem install algorithms

and use it like you would any other gem, with
require 'algorithms'

in one of your source files.
Answer: require 'algorithms'
include Containers
http://kanwei.github.io/algorithms/


Can the GAN objective function be written as related to a log-likelihood of some "classical" statistical model?

Question: Can the objective function that GAN (Generative Adversarial Network) models optimize be written as a lower bound of the log-likelihood of some "classical" statistical model?
I am reading through the (as I understand) first description of a GAN, and a lot of the notation, vocabulary and writing/description conventions are unfamiliar to me. For posterity, the objective function is
$$
\mathbb{E}_{x \sim p_{\text{data}}(x)}[\log D(x)] + \mathbb{E}_{z \sim p_{z}(z)}[\log (1 - D(G(z))].
$$
Notation:

$x$: observed data vector
$z$: standard normal variates
$D$: a "discriminator" that maps data to the probability of that data being "real"
$G$: the "generator" which maps standard normal variates into something that looks like data

Actually, to be totally honest, I'm not positive that this is the objective because, in addition to what I mentioned earlier, they appeal to game-theoretic concepts (which I'm not familiar with). Equation (1) of that same paper writes that
$$
\min_G \max_D V(D,G) =
\mathbb{E}_{x \sim p_{\text{data}}(x)}[\log D(x)] + \mathbb{E}_{z \sim p_{z}(z)}[\log (1 - D(G(z))].
$$
Is that right, though? Or should they be dropping the $\min$ and the $\max$ on the left hand side?
Comment: The only difference is algorithmic. It's still a straightforward latent variable model. The fitting procedure comes down to a different representation of the evidence lower bound. I can post more details later on.
Answer: Do NOT take my word as gospel. That said, I think it's impossible. Or possible in a very specific way.
First problem is that D() and G() are not functions proper, they are variables. The second problem is that they are not independent. Worse, they are not only interdependent, they are recursively dependent on D-1(x) and G-1(x).
Note that the minmax on the left hand side you mentioned has subscripts, D and G. They are quite significant; what that equation is saying is that, from the system's POV, you're trying to find a pair of functions, where G(X) is the simplest possible function that causes the current D(X) to be wrong.
Let's say you pick D(x) = x1, then the optimal G+1 will be something like, say G(x1) := (1 - x1) := x2, which then forces D+1(x2) to be, say, D(x2) := x2+1 = x1+2... and that's just with univariate linear functions.
The only reason an idealized GAN stabilizes is that you've exhausted the limits of your architecture; otherwise, it's an infinitely iterated game of cops-and-robbers between two functions evolving to counter each other.


Ergodicity of MCMC in a hierarchical model

Question: Many of the Bayesian hierarchical models that I am studying use a Markov chain as the model. These hierarchical models use different MCMC techniques to sample low-level and high-level parameters. My question is: does using different MCMC techniques for different parameters affect the ergodicity/convergence of the Markov chain in any way?
For example, in Rasmussen 2000's infinite Gaussian mixture model:

The variance of the Gaussian components are given an inverse Gamma prior, $p(\sigma^{-2}) \sim \mathcal{G}(\beta, w^-1)$. Within this, the $\beta$ hyper itself is given an inverse Gamma prior $\mathcal{G}(1,1)$, and the conditional posterior of $\beta$ is sampled using ARS.

In his subsequent paper on infinite mixtures of Gaussian Process experts, he also employs a similar hierarchical model, where he learns the kernel parameters using Hamiltonian Monte Carlo.

The indicator/latent variables are sampled using Gibbs sampling.
The Dirichlet process concentration parameter $\alpha$ is sampled using ARS.

Is there some sort of ergodicity guarantee for such models based on, say, the reversibility of the individual techniques used in each step in the chain, or is the proof a bit more subtle?
Answer: Supose the posterior distribution is denoted by $\pi$ defined on a subset of $\mathbb{R}^d$. Then the Markov chain that samples from this distribution is a general state space Markov chain. Here are the conditions needed for a Markov chain to be ergodic (the definitions are simplified).

$\pi$ is the stationary distribution of the Markov chain
the Markov chain is aperiodic, i.e., it does not get stuck in a deterministic cycle of sets in $\mathbb{R}^d$.
the Markov chain is irreducible, i.e., in some number of steps it can potentially go from any part of the space to any other part of the space.
the Markov chain is Harris recurrent, i.e., it does the above infinitely often

So any Markov chain constructed for general state spaces must satisfy the above properties to ensure Monte Carlo averages converge.

If all full conditionals of distribution are well behaved (non-negative pdfs etc), then the Gibbs sampler will be ergodic, even though they may not be reversible. The right stationary distribution comes from the fact that each full conditional yields a Markov chain with stationary distribution $\pi$. Thus, a convolution (although non reversible), has stationary distribution $\pi$.
All Metropolis-Hastings samplers are ergodic as long as the proposal distributions are well-defined. Hamiltonian Monte Carlo is a M-H sampler with an unusual proposal distribution which turns out to be well-behaved. So it is ergodic. The right stationary distribution comes from the fact that M-H are reversible with respect to $\pi$.

Ergodicity guarantees convergence of the Markov chain. However, the tricky part is trying to choose a Markov chain that converges at a fast rate. Rates of convergence of Markov chain is much more difficult to establish.
Main reference for all the above: Roberts and Rosenthal (2004)
Comment: Irreducibility may be an issue in either Gibbs or M-H samplers.
Comment: My bad, a more accurate way to phrase it would probably be "each individual sampling step", because we are performing multiple steps (the Gibbs sampling step, the HMC step, etc.) per iteration.
Comment: Am I correct to infer from your answer that the stationary distribution $\pi$ for the Markov chain is guaranteed because _each individual technique leaves the distribution invariant_?
Comment: @peco I am not sure what that means? What is the "each individual technique" and how are you combining them?


Practice exercises functional analysis

Question: I am following a course functional analysis and i am using the book linear functional analysis of Bryan Rynne and Martin Youngson.
I have noticed that the questions are relatively easy and i need to practice more, so does anyone know a source of practice-exercises which are related to inner products/norms/linear operators/banach/hilbert spaces etc....?
Kees
Answer: Exercises in functional analysis   by Costara, Constantin Popa, Dumitru
https://books.google.co.in/books/about/Exercises_in_Functional_Analysis.html?id=iZ1962_xt7sC

Practice exercises functional analysis


Help with solving linear differential equations using an integrating factor

Question: I'm trying to solve this equation for $x=1$ using an integrating factor however for some reason my answer keeps turning out different from the book
In part a) I'm asked to find out $y$ using Euler's method when $x = 0.2$, my answer is correct here as $y = 4.46$.
The following equation is the one I'm trying to solve for $x=1$
$$\frac{dy}{dx} - 4xy = e^{2x^2}$$
In using taking $-4x$ and turning into the  integrating factor I get
$$I(x) = e^{-2x^2}$$
Thus the equation becomes the following after multiplying through by the integrating factor
$$\frac{d}{dx}(e^{-2x^2}y) = 1$$
So in following that line of logic I integrate both sides and try to find the value of $c$ using my knowledge from part a) but I keep coming up with the wrong answer
The integrated version for clarity
$$e^{-2x^2}y = x + c$$

Edit: I am given the initial condition $y=4$, $x=0$. I keep getting an answer in the region of $36$. My book is getting an answer of $x=1$, $y=4.55$.
Comment: Re the suggestion you say you found in your book, note that if $y'(x)=e^{2x^2}+4xy(x)$ and $y(0)\geqslant0$ then $y'(x)\geqslant1$ for every $x\geqslant0$, thus, $y(x)\geqslant y(0)+x$ for every $x\geqslant0$ hence, if $y(0)=4$ then $y(1)\geqslant5$, and the condition that $y(1)=4.55$ is absurd.
Comment: Hence: **typo** (either in your book or in your transcription of your book).
Comment: What is the Initial Condition here?
Comment: initial condition $y =4$,  $x=0$
Comment: What is the answer at $x=1$ according to your book?
Comment: Hmmm... $y(0)=4$ hence $c=$ $__$ and $y(1)=e^2(1+c)=$ $___$. Where is the problem?
Comment: @R.Singh at x = 1 y = 4.55 in my book
Comment: @Did I dont understand what you're trying to say, you have empty boxes after your equals signs
Comment: Sorry but I am not "trying" to say anything, rather I am **telling** you how to completely solve your question, if only you have the slightest idea of what you wrote actually means. *Simply - fill - the -boxes*.
Comment: *"For some reason my answer keeps turning out different from the book"*. What answer are you getting?
Comment: @projectilemotion i keep getting something in the region of 36
Comment: I am getting a similar answer to yours: $y(1)=5e^2\approx 36.945$. Your book is probably incorrect.
Comment: @Did I gathered that's what you were steering me to do but i've already tried to calculate the relevant variables using those steps but it keeps resulting in the wrong answer
Comment: @Adrian I added the information you provided in the comments to your post, so that we can clean the comments. Is that ok?
Answer: Your book's solution of $y(1)=4.55$ is certainly incorrect.

Based on the initial condition $y(0)=4$, one can evaluate the value of $c$. We have:
$$e^{-2x}y=x+c$$
$$e^{0}\cdot 4=0+c$$
$$c=4$$
Therefore, we can deduce that the solution satisfying the initial condition is:
$$y=xe^{2x}+4e^{2x}$$
Thus, the value of $y$ at $x=1$ should be:
$$y(1)=1e^{2}+4e^{2}=5e^2\approx 36.94528049$$
Since you seem to be getting something "In the region of $36$", this is similar, if not exactly what you obtained.


Bind to a Usercontrol within ResourceDictionary

Question: i've a big Problem trying to bind a user Input to an object instanciated via a ResourceDictionary.
<ContentPage.Resources>
    <ResourceDictionary>
        <model:BusinessObjectsGraphDatasource x:Key="Testdata"
                                              Query="query {
                                                          test {
                                                            id
                                                            description
                                                            foo
                                                          }
                                                        }"

                                              Parameter="{Binding Source={x:Reference QueryParameterEntry}, Path=Text}"/>

    </ResourceDictionary>
</ContentPage.Resources>

<StackLayout HorizontalOptions="Center" VerticalOptions="Center" Orientation="Vertical">
    <Entry x:Name="QueryParameterEntry"/>

    <ListView ItemsSource="{Binding Source={x:StaticResource Testdata}, Path=Result}"/>

</StackLayout>

As you can see, i define an custom Datasource (BusinessObjectsGraphDatasource)object within the ContentPage resources. But this Datasource should be able to handle a parameter given by a Databinding from an Entry.
BusinessObjectGraphDatasource is a class that derives from BindableObject and publishs some BindableProperties (e.g. Parameter)
Can someone give me a hint, how to handle this scenario?
Special scenario notes within this app:
i don't have access to a viewmodel or to a code-behind file.
the only things i can do is writing controls and resources and use them within xaml.

The Problem here, is that i retrieve a "Sequence contains no matching Elements" exception as soon as i add the Binding to the datasource.
The stacktrace Looks like that:
       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
   at Xamarin.Forms.Xaml.ApplyPropertiesVisitor.TryAddToProperty(Object element, String localName, Object value, IXmlLineInfo lineInfo, XamlServiceProvider serviceProvider, Exception& exception)
   at Xamarin.Forms.Xaml.ApplyPropertiesVisitor.SetPropertyValue(Object xamlelement, XmlName propertyName, Object value, Object rootElement, INode node, HydratationContext context, IXmlLineInfo lineInfo)
   at Xamarin.Forms.Xaml.ApplyPropertiesVisitor.Visit(ElementNode node, INode parentNode)
   at Xamarin.Forms.Xaml.ElementNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
   at Xamarin.Forms.Xaml.ElementNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
   at Xamarin.Forms.Xaml.FillResourceDictionariesVisitor.Visit(ElementNode node, INode parentNode)
   at Xamarin.Forms.Xaml.ElementNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
   at Xamarin.Forms.Xaml.ElementNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
   at Xamarin.Forms.Xaml.RootNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
   at Xamarin.Forms.Xaml.XamlLoader.Visit(RootNode rootnode, HydratationContext visitorContext)
   at Xamarin.Forms.Xaml.XamlLoader.Load(Object view, String xaml)
   at Xamarin.Forms.Xaml.XamlLoader.Load(Object view, Type callingType)
   at Xamarin.Forms.Xaml.Extensions.LoadFromXaml[TXaml](TXaml view, Type callingType)
   at App1.MainPage.InitializeComponent()
   at App1.MainPage..ctor()
   at App1.App..ctor()
   at App1.UWP.MainPage..ctor()
   at App1.UWP.App1_UWP_XamlTypeInfo.XamlTypeInfoProvider.Activate_4_MainPage()
   at App1.UWP.App1_UWP_XamlTypeInfo.XamlUserType.ActivateInstance()

The Bindable Property is defined like that:
public BindableProperty ParameterProperty = BindableProperty.Create("Parameter", typeof(string),
            typeof(BusinessObjectsGraphDatasource), string.Empty, BindingMode.TwoWay, null, ParameterPropertyChanged);

        public string Parameter
        {
            get => (string)GetValue(ParameterProperty);
            set => SetValue(ParameterProperty, value);
        }

        private static void ParameterPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
        {
        }

cheers,
chris
Comment: To recreate the problem I need more code behind including BusinessObjectsGraphDatasource, etc. If you can share simple project I might be able to look
Comment: If you can't here is the hint. Check all your LINQ queries. One of them is throwing an exception when xaml is loaded. Check where you use First() or similar. Use debugger to find which line throws an exception
Answer: You might have to specify explicitly that it should be a two-way binding:
Parameter="{Binding Source={x:Reference QueryParameterEntry}, Path=Text, BindingMode=TwoWay}"

Comment: Hi Jon, i am getting not to that Point, that the binding is executed. I retrieve a "Sequence contains no matching Elements" exception when i try to show the page.


Add multilingual support to Drupal 8 Hello World module

Question: Today we already can upgrade contrib projects to Drupal 8 (#D8CX) and there are more and more "Hello World" code examples for Drupal 8. Some of them:

Drupal 8: Writing a Hello World Module
Drupal 8: Hello OOP, Hello world!
Drupal 8: Hello, Configuration Management
Drupal 8 module development #3 - adding a settings page - revision
Drupal 8 isn't Scary, Pt. 1: Introduction & Creating a Hello World Module

Can we add multilingual support to such simple modules?
Comment: Adding multilingual to one given piece of code would be a practical and answerable problem. Adding it to a blog post made by some guy who probably will not give us his password is another ;) I'm not saying what you want is wrong, just the way you stated it. And there are 3 close votes now, so I guess I'm not the only one to think that.
Comment: Hello. This looks like a feature request to numerous blogs and manuals (and none of them have an issue queue at drupal.org). This is not the best place for feature request to 3rd party websites. If you have [practical, answerable questions based on actual problem](http://drupal.stackexchange.com/help/dont-ask), please edit.
Comment: @Mołot,
I don't mind about someone's blogs and don't create feature requests. I just read it or not.
Comment: @Mołot, question is practical, because it's about important Drupal problem. Many Drupal 7 contribs just haven't multilingual support or use multilingual API incorrectly. I think we should talk and ask about i18n in Drupal 8 as early as possible.
I also created very practical answer with code which can be used as an example when you upgrade your modules from 7 to 8. If you have ideas how to edit question/answer you are welcome.
Comment: @Mołot, "Adding multilingual to one given piece of code" — Hello World isn't one given piece of code? If you check links above, you can see that Hello World modules are all the same.
Comment: @kalabro What Molot is getting at is that it is not our place to go harassing blog authors to add multilingual explanations to their tutorials.  If you'd like those blog posts extended with multilingual configuration, then the best thing to do is ask questions in the post comments.
Comment: This question appears to be off-topic because it is about external blog post content.
Answer: Drupal 8 has many improvements for interface, configuration and content translation. There are great series of articles from Gábor Hojtsy: Multilingual Drupal 8.
Let's make Hello World module settings from this article translatable.
Full module code is avalible here: https://github.com/kalabro/drupal-examples/tree/master/hello
This code was tested with core 8.x dev branch (ed8dfae 2014-05-19).
1. Preparing Drupal 8 installation

Enable "Language", "Interface Translation" and "Configuration Translation" modules.
Configure multiple languages.
Place "Language switcher" block.
Check how "Configuration Translation" with Site information form.

2. "Hello World" module

Use Drupal 8: Hello, Configuration Management article as base for "Hello World" module.
This module provides static /hello page with hardcoded "'Hello, World!'" message in it. The message can be outputted in normal or upper case. There is a setting for message case:

Play with the code until it becomes yours.
hello.info.yml:
name: Hello
description: '"Hello World" module with config translation support.'
core: 8.x
type: module
configure: hello.settings_form

3. More complex settings

Let's make message on /hello page configurable (dynamic).
For this purpose we should update form and controller.

Add 'hello_message' textfield in 'buildForm' method:
$form['hello_message'] = array(
  '#type' => 'textfield',
  '#title' => t('Your "Hello World!" message'),
  '#default_value' => $config->get('hello_message'),
  '#required' => TRUE,
);

Update HelloController to take hello message from setting instead of hardcoding it:
$hello_message = $config->get('hello_message');

Check full code in repository: HelloConfigForm.php, HelloController.php and etc. Feel free to ask any questions.

4. Make settings translatable
Our setting 'Your "Hello World!" message' should be translatable.

First of all we have to add config schema. It is recommended to add schema for any modules with configuration.
hello.schema.yml:
hello.settings:
  type: mapping
  label: 'Hello World settings'
  mapping:
    case:
      type: integer
      label: 'Letter case of your "Hello World!" message'
      # translatable: true
    hello_message:
      type: text # translatable by default.
      label: 'Your "Hello World!" message'

Now Drupal knows what kind of data is stored in module config. Some of config data types are translatable by default (text, label, mail). You can also add translatable: true to settings manually (try to do it for "case" setting).

Add Configuration Translation support.
hello.config_translation.yml:
  hello:
    title: 'Hello World settings'
    base_route_name: hello.settings_form
    names:
      - 'hello.settings'

Just small YAML file and that's all.

To see "Translate settings" tab you need existing default local task (See hello.local_tasks.yml for an example. Note: because of a change in Drupal core, this file name is no longer correct. It should be hello.links.task.yml now.).

Only translatable settings are appeared.

P.S.: In Drupal 7 i18n_variable API is used for this task.
Comment: Almost all works fine, but I had use "config_object" instead of "mapping"