问:
Retrofit returns null response body when issuing a GET request
I am using retrofit to receive JSON data from my API. I am able to receive the JSON data when the data contains a single object. But when I try to a get list of all the employees I get an error.

JSON data for /api/Employee/1 is (working fine):

```<code>{
  "id": 10,
  "name": "Arpit",
  "number": "7777777777",
  "city": "noida",
  "depid": 4,
}
</code>```

Code to get this JSON object is working. PFB the code.

Retrofit Code:

```<code>public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());}
</code>```

EmployeeAPI.java

```<code>public interface EmployeeAPI {
@GET("/assignment1/api/Employee/1")
Call<EmployeeResponse> load_employee();}
</code>```

EmployeeResponse.java

```<code>public class EmployeeResponse {
@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("city")
public String city;
@SerializedName("number")
public String number;}
</code>```

But when I am trying to get the list of all Employees from /api/Employee I get the following error:

```<code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
</code>```

JSON data for api/Employee is ():

```<code>[
   {
  "id":10,
  "name":"Arpit Jain",
  "number":"7777777777",
  "city":"noida",
  "depid":4,
   },
   {
  "id":32,
  "name":"Ish Chawla",
  "number":"9999999999",
  "city":"Noida",
  "depid":1,
   },
   {
  "id":39,
  "name":"Laxman",
  "number":"6666666666",
  "city":"GZB",
  "depid":1,
   },
   {
  "id":44,
  "name":"Ishan",
  "number":"9839060055",
  "city":"Kanpur",
  "depid":3,
   }
]
</code>```

Code to get the list of employees is:

Retrofit Code

```<code>public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Log.d("employee details", response.body().toString());
        list = response.body().list;
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());
}
</code>```

EmployeeAPI.java

```<code> public interface EmployeeAPI {
    @GET("/assignment1/api/Employee")
    Call<EmployeeResponse> load_employee();
}
</code>```

EmployeeResponse.java

```<code>   public class EmployeeResponse {
    public ArrayList<Employee> list;
}
</code>```

Kindly tell me the changes required to get the data correctly.

答:
```<code>public class EmployeeResponse {
   @SerializedName("id")
   public String id;
   @SerializedName("name")
   public String name;
   @SerializedName("city")
   public String city;
   @SerializedName("number")
   public String number;
}
</code>```

Make use of above class as model

```<code>public interface EmployeeAPI {
  @GET("/assignment1/api/Employee")
  Call<ArrayList<EmployeeResponse>> load_employee();
}
</code>```

and since you return a list make call object accept a list to accept a list of employees

Body:
I am using retrofit to receive JSON data from my API. I am able to receive the JSON data when the data contains a single object. But when I try to a get list of all the employees I get an error.

JSON data for /api/Employee/1 is (working fine):

{
  "id": 10,
  "name": "Arpit",
  "number": "7777777777",
  "city": "noida",
  "depid": 4,
}

Code to get this JSON object is working. PFB the code.

Retrofit Code:

public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());}

EmployeeAPI.java

public interface EmployeeAPI {
@GET("/assignment1/api/Employee/1")
Call<EmployeeResponse> load_employee();}

EmployeeResponse.java

public class EmployeeResponse {
@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("city")
public String city;
@SerializedName("number")
public String number;}

But when I am trying to get the list of all Employees from /api/Employee I get the following error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

JSON data for api/Employee is ():

[
   {
  "id":10,
  "name":"Arpit Jain",
  "number":"7777777777",
  "city":"noida",
  "depid":4,
   },
   {
  "id":32,
  "name":"Ish Chawla",
  "number":"9999999999",
  "city":"Noida",
  "depid":1,
   },
   {
  "id":39,
  "name":"Laxman",
  "number":"6666666666",
  "city":"GZB",
  "depid":1,
   },
   {
  "id":44,
  "name":"Ishan",
  "number":"9839060055",
  "city":"Kanpur",
  "depid":3,
   }
]

Code to get the list of employees is:

Retrofit Code

public void onResponse(Response<EmployeeResponse> response, Retrofit retrofit) {
    if (response.raw().toString()!=null) {
        Log.d("employee details", response.body().toString());
        list = response.body().list;
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
    else
        Log.d("No data recieved",response.raw().toString());
}

@Override
public void onFailure(Throwable t) {
    Log.d("Fail",t.getMessage());
}

EmployeeAPI.java

 public interface EmployeeAPI {
    @GET("/assignment1/api/Employee")
    Call<EmployeeResponse> load_employee();
}

EmployeeResponse.java

   public class EmployeeResponse {
    public ArrayList<Employee> list;
}

Kindly tell me the changes required to get the data correctly.

Body:
public class EmployeeResponse {
   @SerializedName("id")
   public String id;
   @SerializedName("name")
   public String name;
   @SerializedName("city")
   public String city;
   @SerializedName("number")
   public String number;
}

Make use of above class as model

public interface EmployeeAPI {
  @GET("/assignment1/api/Employee")
  Call<ArrayList<EmployeeResponse>> load_employee();
}

and since you return a list make call object accept a list to accept a list of employees


来源: stackexchange

问:
XML cleanup - unmatched tags
I am trying to format xml entries I have so that I can use the xmltextreader without getting errors.  I added a default header and footer in the event I notice there is no opening or closing  tags. I remove illegal characters and check for unicode but I always find an issue where an entry slips in and gives the error:
data at the root level is invalid
and when I check that entry is slipped through the cleaning process or just has an unmatched tag somewhere. Now I use

```<code>   Dim stringSplitter() As String = {"</entry>"}
        ' split the file content based on the closing entry tag
        sampleResults = _html.Split(stringSplitter, StringSplitOptions.RemoveEmptyEntries)
</code>```

to split my xml into individual entries before I start the cleanup process. Here are my default headers;

```<code>Private defaultheader = "xmlns=""http://www.w3.org/2005/Atom"""
    Private headerl As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbNewLine & "<entry " & defaultNameSpace & ">"
    Private footer As String = "</entry>"
</code>```

is there any tool in the .net framework that can detect and cleanup unmatched tags so that I can get this to work

答:
I think you are looking in the wrong direction for a solution :)
I think what you need is to check out the IXmlSerializer.

check out this article:
Proper way to implement IXmlSerializable?

My approach would be to create an entry object, make it serializable, and read it via the serializer.

Create another serialized object called CleanedEntry, and give that the entry object in the constructor.

If the input never contains any errors, you should be able to make this work quite easily.

(of course this depends a bit on how the source looks like, and what you want to do with it.)
Please give an example of expected input /output if my answer seems hazy, and I will try to elaborate on it. (if I have the time ; )  )

ContentLicense: CC BY-SA 2.5

Title: XML cleanup - unmatched tags

Body:
I am trying to format xml entries I have so that I can use the xmltextreader without getting errors.  I added a default header and footer in the event I notice there is no opening or closing  tags. I remove illegal characters and check for unicode but I always find an issue where an entry slips in and gives the error:
data at the root level is invalid
and when I check that entry is slipped through the cleaning process or just has an unmatched tag somewhere. Now I use

   Dim stringSplitter() As String = {"</entry>"}
        ' split the file content based on the closing entry tag
        sampleResults = _html.Split(stringSplitter, StringSplitOptions.RemoveEmptyEntries)

to split my xml into individual entries before I start the cleanup process. Here are my default headers;

Private defaultheader = "xmlns=""http://www.w3.org/2005/Atom"""
    Private headerl As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbNewLine & "<entry " & defaultNameSpace & ">"
    Private footer As String = "</entry>"

is there any tool in the .net framework that can detect and cleanup unmatched tags so that I can get this to work


问:
Implementing correct CSP rules for CDN
I'm currently undertaking a introduction to mobile webapplications development course at my university and am struggling setting up bootstrap on my mithril application.

I've previously set up bootstrap fine on "normal" web applications, but I'm struggling understanding how to properly set up Content Security Policy in my Mithril.js application.

It should be noted that this is not a required part of my current assignment, but I'm rather trying to understand the concept of CSP on my own hand since it is a highly important thing to understand (OWASP top 10, yo!).

So I'm not asking for anyone to help me finish an assignment or so, rather to help me understand where I'm going wrong with this extra-curricular application of CSP.

This is how my CSP looks right now:

```<code><meta http-equiv="Content-Security-Policy"
content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval';
         style-src 'self' 'unsafe-inline' http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css;
         media-src *; img-src 'self' data: content:;
         script-src https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
         http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js;">
</code>```

The CDN urls work fine and are currently implemented accross multiple other websites I've setup, but I'm getting these errors whilst checking the console on Chrome:

Refused to load the script 'http://localhost:8013/cordova.js' because
  it violates the following Content Security Policy directive:
  "script-src
  https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
                                                              http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js".

index.html:1 Refused to load the script
  'http://localhost:8013/bin/app.js' because it violates the following
  Content Security Policy directive: "script-src
  https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
                                                              http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js".

jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff2'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.ttf'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 http://localhost:8013/favicon.ico Failed
  to load resource: the server responded with a status of 404 (Not
  Found)

答:
Answering this question in our chat as well, but for others here is the short answer. Put your url to the css file in front of 'unsafe-inline', so it is

```<code>style-src 'self' bootstrap.css 'unsafe-inline';
</code>```

And the you need 'self' in script-src prior to jquery and bootstrap.js.

ContentLicense: CC BY-SA 3.0

Title: Implementing correct CSP rules for CDN

Body:
I'm currently undertaking a introduction to mobile webapplications development course at my university and am struggling setting up bootstrap on my mithril application.

I've previously set up bootstrap fine on "normal" web applications, but I'm struggling understanding how to properly set up Content Security Policy in my Mithril.js application.

It should be noted that this is not a required part of my current assignment, but I'm rather trying to understand the concept of CSP on my own hand since it is a highly important thing to understand (OWASP top 10, yo!).

So I'm not asking for anyone to help me finish an assignment or so, rather to help me understand where I'm going wrong with this extra-curricular application of CSP.

This is how my CSP looks right now:

<meta http-equiv="Content-Security-Policy"
content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval';
         style-src 'self' 'unsafe-inline' http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css;
         media-src *; img-src 'self' data: content:;
         script-src https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
         http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js;">

The CDN urls work fine and are currently implemented accross multiple other websites I've setup, but I'm getting these errors whilst checking the console on Chrome:

Refused to load the script 'http://localhost:8013/cordova.js' because
  it violates the following Content Security Policy directive:
  "script-src
  https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
                                                              http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js".

index.html:1 Refused to load the script
  'http://localhost:8013/bin/app.js' because it violates the following
  Content Security Policy directive: "script-src
  https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
                                                              http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js".

jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff2'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 jquery.min.js:2 Refused to load the font
  'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.ttf'
  because it violates the following Content Security Policy directive:
  "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
  Note that 'font-src' was not explicitly set, so 'default-src' is used
  as a fallback.

(anonymous) @ jquery.min.js:2 http://localhost:8013/favicon.ico Failed
  to load resource: the server responded with a status of 404 (Not
  Found)

Body:
Answering this question in our chat as well, but for others here is the short answer. Put your url to the css file in front of 'unsafe-inline', so it is

style-src 'self' bootstrap.css 'unsafe-inline';

And the you need 'self' in script-src prior to jquery and bootstrap.js.


问:
Check in controller which input element has been modified
I need to check which input element has modified in update form.

```<code>    <form name="utilizationForm" role="form" novalidate>
    <div class="row" data-ng-repeat="i in [1,2,3,4]">
            <div class="col-md-3">
                <div asterick class="form-group" ng-class="{'form-group has-success': !error['resource_type'] && (submitted), 'form-group has-error': (error['resource_type']) && (submitted)}">
                    <label for="resourceType">Resource Type</label>
                    <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                                        <select name="resourceType" id="resourceType" ng-model="data['resource_type' + i]" class="form-control" ng-required="true"  >
                                            <option ng-repeat="option in resourceTypeJson" value="{{option}}">{{option}}</option>
                                        </select>
                    <span class="er-block" ng-show="utilizationForm.resourceType.$touched && utilizationForm.resourceType.$error.required">Please provide Resource type.</span>
                    <span ng-show="error.resource_type1" class="er-block">{{error.resource_type1}}</span>
                </div>
            </div>
            <div class="col-md-3">
                <label for="efforts">Efforts (in hours)</label>
                <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                <input type="text"  test-change name="efforts" id="efforts" class="form-control" ng-model="data['efforts' + i]"  value="">
            </div>
        </div>
        <div class="text-right" ng-class="{'col-md-6 mt25': showCompletion}">
            <button class="btn btn-primary" ng-disabled="utilizationForm.$invalid" ng-click="addUtilizationReport()">{{buttonText}}</button>
        </div>

    </form>
</code>```

Now when I click on update button I need to check which input element has modified in update form in controller. Please help.

答:
If you put the input in a form with a name attribute and then give the input a name attribute, you can also access the input's $dirty property.

```<code><div ng-controller="MyController">
  <form name="myForm">
    <input type="text" name="first" ng-model="firstName">
    <input type="text" name="last" ng-model="lastName">
  </form>
</div>
</code>```

```<code>app.controller('MyController', function($scope) {
  // Here you have access to the inputs' `$dirty` property
  console.log($scope.myForm.first.$dirty);
  console.log($scope.myForm.last.$dirty);
});
</code>```

You can use $scope.myForm.$dirty to see if any fields have changed, and the $dirty property on each input's property on the form to see if that input has changed. You can even iterate over the myForm object (non-input-field objects have keys prefixed with a $):

```<code>angular.forEach($scope.myForm, function(value, key) {
  if(key[0] == '$') return;
  console.log(key, value.$dirty)
});
</code>```

Body:
I need to check which input element has modified in update form.

    <form name="utilizationForm" role="form" novalidate>

                    Resource Type
                    <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                                        <select name="resourceType" id="resourceType" ng-model="data['resource_type' + i]" class="form-control" ng-required="true"  >
                                            <option ng-repeat="option in resourceTypeJson" value="{{option}}">{{option}}</option>
                                        </select>
                    Please provide Resource type.
                    {{error.resource_type1}}

                Efforts (in hours)
                <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                <input type="text"  test-change name="efforts" id="efforts" class="form-control" ng-model="data['efforts' + i]"  value="">

            <button class="btn btn-primary" ng-disabled="utilizationForm.$invalid" ng-click="addUtilizationReport()">{{buttonText}}</button>

    </form>

Now when I click on update button I need to check which input element has modified in update form in controller. Please help.

Body:
If you put the input in a form with a name attribute and then give the input a name attribute, you can also access the input's $dirty property.

<div ng-controller="MyController">
  <form name="myForm">
    <input type="text" name="first" ng-model="firstName">
    <input type="text" name="last" ng-model="lastName">
  </form>
</div>

app.controller('MyController', function($scope) {
  // Here you have access to the inputs' `$dirty` property
  console.log($scope.myForm.first.$dirty);
  console.log($scope.myForm.last.$dirty);
});

You can use $scope.myForm.$dirty to see if any fields have changed, and the $dirty property on each input's property on the form to see if that input has changed. You can even iterate over the myForm object (non-input-field objects have keys prefixed with a $):

angular.forEach($scope.myForm, function(value, key) {
  if(key[0] == '$') return;
  console.log(key, value.$dirty)
});


问:
android:spinner;slected value donot popup
Android :spinner : when value is selected, spinner  gives an error:W/InputEventReceiver:Attempted to finish an input event but the input event receiver has already been disposed."

```<code>enter code here
</code>```

package com.example.yasir.ztailors;

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.parse.LogOutCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

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

import static com.example.yasir.ztailors.R.id.catagerious;

public class ZtailorFeeds extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
    FloatingActionButton logout;
    String user;
    Spinner catageriousSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ztailor_feeds);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        logout= (FloatingActionButton) findViewById(R.id.logout);
        Intent i=getIntent();
        user=i.getStringExtra("username");
        setTitle(user+"'s Menu");
        catageriousSpinner= (Spinner) findViewById(catagerious);

        ArrayList<String> catageriousGender =new ArrayList<String>();

       catageriousGender.add("Men");
        catageriousGender.add("Women");
        catageriousGender.add("Kids");

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,catageriousGender);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        catageriousSpinner.setAdapter(arrayAdapter);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ParseUser.logOutInBackground(new LogOutCallback() {
                    @Override
                    public void done(ParseException e) {
                        if(e==null){
                            Intent i=new Intent(ZtailorFeeds.this,MainActivity.class);
                            startActivity(i);
                            Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i=new Intent(ZtailorFeeds.this,MainActivity.class);
        startActivity(i);
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
    Log.i("AppInfo", String.valueOf(parent.getItemAtPosition(position)));
}catch (Exception e){
    e.printStackTrace();
}
    }

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

    }
}
    enter code here
</code>```

答:
```<code>add spinner in XML

 <Spinner
        android:id="@+id/spinner"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="224dp" />

and get in java code

 catageriousSpinner= (Spinner) findViewById(R.id.spinner);
</code>```

Body:
Android :spinner : when value is selected, spinner  gives an error:W/InputEventReceiver:Attempted to finish an input event but the input event receiver has already been disposed."

enter code here

package com.example.yasir.ztailors;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.parse.LogOutCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

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

import static com.example.yasir.ztailors.R.id.catagerious;

public class ZtailorFeeds extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
    FloatingActionButton logout;
    String user;
    Spinner catageriousSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ztailor_feeds);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        logout= (FloatingActionButton) findViewById(R.id.logout);
        Intent i=getIntent();
        user=i.getStringExtra("username");
        setTitle(user+"'s Menu");
        catageriousSpinner= (Spinner) findViewById(catagerious);

        ArrayList<String> catageriousGender =new ArrayList<String>();

       catageriousGender.add("Men");
        catageriousGender.add("Women");
        catageriousGender.add("Kids");

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,catageriousGender);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        catageriousSpinner.setAdapter(arrayAdapter);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ParseUser.logOutInBackground(new LogOutCallback() {
                    @Override
                    public void done(ParseException e) {
                        if(e==null){
                            Intent i=new Intent(ZtailorFeeds.this,MainActivity.class);
                            startActivity(i);
                            Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i=new Intent(ZtailorFeeds.this,MainActivity.class);
        startActivity(i);
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
    Log.i("AppInfo", String.valueOf(parent.getItemAtPosition(position)));
}catch (Exception e){
    e.printStackTrace();
}
    }

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

    }
}
    enter code here


问:
File removed with option removing references and deleted from finder directly now showing the warning XCode 8
How can I remove the warning that is showing in XCode?

Warning:

file:///Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m:

warning: Missing file: /Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m is missing from working copy

Actually, I have tried all the methods cleaning the project and deleting the installed app from simulator and also deleting the build from library.

Certainly, there is a way to suppress the warning by hiding it. I don't want to hide the warnings. I want to remove them. Could someone suggest me the good way because I am trying this from months and not getting the solution to remove them.

Edited: I have selected remove references for ViewController.m and then deleted the file from finder and it is then showing me the warning.

答: If you are using SVN/GIT/.. etc, Commit and Push your code and restart your xcode. Missing file warnings will remove. </p>


问:
How to see exception generated into django template variable?
Inside a Django template, one can call an object method like this :

```<code>{{ my_object.my_method }}
</code>```

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

```<code>DEBUG = True
TEMPLATE_DEBUG = True
</code>```

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?

答: I'd use a Unit tests to isolate the problem. I know this is an indirect answer but I feel this is the ideal way to solve and prevent the problem from returning. </p>

Body:
Inside a Django template, one can call an object method like this :

{{ my_object.my_method }}

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

DEBUG = True
TEMPLATE_DEBUG = True

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?


答:
Its because of you are fetching whole employee list and its an Array.

```<code>  public interface EmployeeAPI {
     @GET("/assignment1/api/Employee")
     Call<Employee[]> load_employee();

     @GET("/assignment1/api/Employee/1")
     Call<Employee> load_employee();
    }
</code>```

And Don't create EmployeeResponse class. Use @SerializedName in Employee pojo class.

After getting response

```<code>if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }
</code>```

Dont need to set this.

Title: Retrofit returns null response body when issuing a GET request

Body:
Its because of you are fetching whole employee list and its an Array.

  public interface EmployeeAPI {
     @GET("/assignment1/api/Employee")
     Call<Employee[]> load_employee();

     @GET("/assignment1/api/Employee/1")
     Call<Employee> load_employee();
    }

And Don't create EmployeeResponse class. Use @SerializedName in Employee pojo class.

After getting response

if (response.raw().toString()!=null) {
        Employee e = new Employee();
        e.setId(response.body().id);
        e.setName(response.body().name);
        e.setCity(response.body().city);
        e.setNumber(response.body().number);
        Log.d("employee details", e.toString());
        list.add(e);
        rv.setAdapter(new SimpleItemRecyclerViewAdapter(list));
    }

Dont need to set this.


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答:
Use INSERT IGNORE rather than INSERT

```<code>INSERT IGNORE INTO person_tbl (classId, userId)
VALUES( '{$classId}', '{$userId}')
</code>```

Note: On duplicate insertion, this statement won't generate an error.

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')

Body:
Use INSERT IGNORE rather than INSERT

INSERT IGNORE INTO person_tbl (classId, userId)
VALUES( '{$classId}', '{$userId}')

Note: On duplicate insertion, this statement won't generate an error.


问:
SQL: doing math on COUNT column just carried over
```<code>SELECT January.customer_id AS Jancust_id,
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'
</code>```

Ok, can I not do math on a column in the same query that uses COUNT & was just brought over?  Error message below.

"#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'DISTINCT payments.customer_id) as Jan_retain_cust,
  Jan_retain_cust/ 1533 AS CAC_' at line 3"

答:
You are missing a group by clause. Also, you are trying to use alias Jan_retain_cust in expression in the same select which is not allowed. Just the replace the alias Jan_retain_cust with original expression i.e. COUNT (DISTINCT payments.customer_id).

```<code>select January.customer_id as Jancust_id,
    COUNT(distinct January.customer_id) as Jan_orig_cust,
    COUNT(distinct payments.customer_id) as Jan_retain_cust,
    COUNT(distinct payments.customer_id) / 1533 as CAC_referral
from January_Cohort January
left join telemon_payments_data payments on January.customer_id = payments.customer_id
where January.acquisition_source = 'referral'
    and payments.payment_date between '2016-06-01' and '2016-06-31'
group by January.customer_id;
</code>```

Body:
SELECT January.customer_id AS Jancust_id,
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'

Ok, can I not do math on a column in the same query that uses COUNT & was just brought over?  Error message below.

"#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'DISTINCT payments.customer_id) as Jan_retain_cust,
  Jan_retain_cust/ 1533 AS CAC_' at line 3"

Body:
You are missing a group by clause. Also, you are trying to use alias Jan_retain_cust in expression in the same select which is not allowed. Just the replace the alias Jan_retain_cust with original expression i.e. COUNT (DISTINCT payments.customer_id).

select January.customer_id as Jancust_id,
    COUNT(distinct January.customer_id) as Jan_orig_cust,
    COUNT(distinct payments.customer_id) as Jan_retain_cust,
    COUNT(distinct payments.customer_id) / 1533 as CAC_referral
from January_Cohort January
left join telemon_payments_data payments on January.customer_id = payments.customer_id
where January.acquisition_source = 'referral'
    and payments.payment_date between '2016-06-01' and '2016-06-31'
group by January.customer_id;


问:
how to print given array in for each using javascript
I have an array like below.

```<code>[{
  'i_id':'119',
  'name':'Brinjal-250',
  'weight':'250.Gm',
  'qty':'1',
  'price':'5',
  'market':'55',
  'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
 },
 {
  'i_id':'101',
  'name':'Tomato',
  'weight':'500.Gm',
  'qty':'1',
  'price':'4',
  'market':'44',
  'image':'f_control/images/vegetables/tometo-min.jpg'
}]
</code>```

And i want it to in for each loop using java script, It is possible?
If possible then please guide me in right direction, Thanks.

The demo output

答:
Why are you using different array for each object ? You can push both objects in a single array , then you can use forEach loop like this :-`</p>

```<code>var array = [
    {
        'i_id':'119',
        'name':'Brinjal-250',
        'weight':'250.Gm',
        'qty':'1',
        'price':'5',
        'market':'55',
        'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
    },
    {
        'i_id':'101',
        'name':'Tomato',
        'weight':'500.Gm',
        'qty':'1',
        'price':'4',
        'market':'44',
        'image':'f_control/images/vegetables/tometo-min.jpg'
    }
    ];
        array.forEach(function(value){
            console.log(value.name);
        });`
</code>```

Body:
I have an array like below.

[{
  'i_id':'119',
  'name':'Brinjal-250',
  'weight':'250.Gm',
  'qty':'1',
  'price':'5',
  'market':'55',
  'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
 },
 {
  'i_id':'101',
  'name':'Tomato',
  'weight':'500.Gm',
  'qty':'1',
  'price':'4',
  'market':'44',
  'image':'f_control/images/vegetables/tometo-min.jpg'
}]

And i want it to in for each loop using java script, It is possible?
If possible then please guide me in right direction, Thanks.

The demo output

Body:
Why are you using different array for each object ? You can push both objects in a single array , then you can use forEach loop like this :-`

var array = [
    {
        'i_id':'119',
        'name':'Brinjal-250',
        'weight':'250.Gm',
        'qty':'1',
        'price':'5',
        'market':'55',
        'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
    },
    {
        'i_id':'101',
        'name':'Tomato',
        'weight':'500.Gm',
        'qty':'1',
        'price':'4',
        'market':'44',
        'image':'f_control/images/vegetables/tometo-min.jpg'
    }
    ];
        array.forEach(function(value){
            console.log(value.name);
        });`


问:
Firebase security - let each user to write himself
I have the following structure of 'neighbors' in firebase:

```<code>neighbors: {
user100:{
    user200:{
        from:'1.2'
    },
    user300:{
        from:'4.2'
    },
    user400:{
        from:'2.4'
    }
},
user700:{
    user200:{
        from:'8.7'
    },
    user500:{
        from:'10.3'
    }
}

}
</code>```

support user100, user200 are auth-ids.
I want to let each user to write only him-self, but to do it for every other user he want.
For example, I want to let user200 to write that he is neighbor of user500, but I don't want to let him write that other user (like user 800) is neighbor of someone.

I tried hard but didn't success.
By default I tried this following solution but still not work!!!
the solution was to change the structure to look like:

```<code>neighbors:  {
user100:{
    user200:{
        from:'1.2',
        neighbor:'user200'
    },
    user300:{
        from:'4.2',
        neighbor:'user300'
    },
    user400:{
        from:'2.4',
        neighbor:'user400'
    }
},
user700:{
    user200:{
        from:'8.7',
        neighbor:'user200'
    },
    user500:{
        from:'10.3',
        neighbor:'user500'
    }
}

  }
</code>```

And the rule is:

```<code> neighbors:{
    ".write":"newData.child('neighbor').val() == auth.uid
 }
</code>```

But I get permission-denied!

Any solution?

答:
Your rule checks for an immediate child of the neighbours object.
It seems like you're writing to a child of each child of the neighbours object.

For example, in your example above the path to the first neighbor value would look something like neighbor/user100/user200/neighbor

The rule would have to be something like.

```<code>neighbors:{
    $user_id {
        ".write":"newData.child('neighbor').val() == auth.uid"
    }
}
</code>```

Or, if you just want to check the parent keys, which seem to be identical to the value of neighbor (?):

```<code>neighbors:{
    $user_id {
        ".write":"$user_id == auth.uid"
    }
}
</code>```

In these example $user_id is a stand in for the key the rule applies to.

Body:
I have the following structure of 'neighbors' in firebase:

neighbors: {
user100:{
    user200:{
        from:'1.2'
    },
    user300:{
        from:'4.2'
    },
    user400:{
        from:'2.4'
    }
},
user700:{
    user200:{
        from:'8.7'
    },
    user500:{
        from:'10.3'
    }
}

}

support user100, user200 are auth-ids.
I want to let each user to write only him-self, but to do it for every other user he want.
For example, I want to let user200 to write that he is neighbor of user500, but I don't want to let him write that other user (like user 800) is neighbor of someone.

I tried hard but didn't success.
By default I tried this following solution but still not work!!!
the solution was to change the structure to look like:

neighbors:  {
user100:{
    user200:{
        from:'1.2',
        neighbor:'user200'
    },
    user300:{
        from:'4.2',
        neighbor:'user300'
    },
    user400:{
        from:'2.4',
        neighbor:'user400'
    }
},
user700:{
    user200:{
        from:'8.7',
        neighbor:'user200'
    },
    user500:{
        from:'10.3',
        neighbor:'user500'
    }
}

  }

And the rule is:

 neighbors:{
    ".write":"newData.child('neighbor').val() == auth.uid
 }

But I get permission-denied!

Any solution?

Body:
Your rule checks for an immediate child of the neighbours object.
It seems like you're writing to a child of each child of the neighbours object.

For example, in your example above the path to the first neighbor value would look something like neighbor/user100/user200/neighbor

The rule would have to be something like.

neighbors:{
    $user_id {
        ".write":"newData.child('neighbor').val() == auth.uid"
    }
}

Or, if you just want to check the parent keys, which seem to be identical to the value of neighbor (?):

neighbors:{
    $user_id {
        ".write":"$user_id == auth.uid"
    }
}

In these example $user_id is a stand in for the key the rule applies to.


问:
JQuery Ajax gives error on sending multiple data

name = "name1";
uname = "username";
pass = "password";
$.ajax({
  type: 'POST',
  url: "url",
  data: {
    name: name,
    username: uname,
    password: pass
  },
  success: function(data, textStatus, jqXHR) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error");
  }

});
```

This code gives an error while running :

Uncaught TypeError: Illegal invocation

But if I change the number of parameters at data to 1, it runs fine.
I tried to specify datatype, but to no avail

答:
have you tried JSON.stringify? See the following code example:

JAVASRIPT

```<code>name="name1";
uname = "username";
pass = "password";

var data = { name:name , username:uname , password: pass};

$.ajax({
    type: 'POST',
    url: "url",
    data: JSON.stringify(data),
    success: function (data, textStatus, jqXHR) {
      alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert("Error");
    }
});
</code>```

w3schools

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().

Body:
name = "name1";
uname = "username";
pass = "password";
$.ajax({
  type: 'POST',
  url: "url",
  data: {
    name: name,
    username: uname,
    password: pass
  },
  success: function(data, textStatus, jqXHR) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error");
  }

});

This code gives an error while running :

Uncaught TypeError: Illegal invocation

But if I change the number of parameters at data to 1, it runs fine.
I tried to specify datatype, but to no avail

Body:
have you tried JSON.stringify? See the following code example:

JAVASRIPT

name="name1";
uname = "username";
pass = "password";

var data = { name:name , username:uname , password: pass};

$.ajax({
    type: 'POST',
    url: "url",
    data: JSON.stringify(data),
    success: function (data, textStatus, jqXHR) {
      alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert("Error");
    }
});

w3schools

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().


问:
Using jquery, how to populate my table rows with matching pictures using img src="javascript:?
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

```<code>$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="javascript:source_foto" height="80" width="80"/></div>');
        });
</code>```

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.

答:
```<code>$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(", ");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="'+source_foto+'" height="80" width="80"/></div>');
        });
</code>```

You don't need the javascript: you can just use the variable name.  Also, your split should be on ", " and not just ","

Body:
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'

');
        });

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.

Body:
$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(", ");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="'+source_foto+'" height="80" width="80"/></div>');
        });

You don't need the javascript: you can just use the variable name.  Also, your split should be on ", " and not just ","


问:
Pure Data chord selection based on input MIDI note scale causes crash
I'm working on a patch in Pure Data which uses an 8 number scale to decide which chords can be played. E.g. if a chord uses a note that is not in the scale, re-roll. Obviously this isn't the most musical soultion as we usually expect accidentals and such, but here we are looking at a primitive method for procedural music. Here is the problem patch:

CreateChords patch

As soon as I attempt to use a new scale, pure data freezes and requires an immediate restart.

Any suggestions would be greatly appreciated.

Thanks,

Liam

答:
It would be massively more efficient and easier to use an object like [coll] or [textfile] to store your chord patterns. Instead of having each pattern in a message object, which you then need to feed individually through all of the processing, you would just have one object, and feed your random number generator into it, which will then spit out the corresponding code. something like this

your patch reworked

there you have it. A spaghetti mess of wires and boxes reduced to 11 objects and 11 cables. There are several other ways to accomplish similar things, but this was the first to come to mind. If this one works for your purpose, cool, or else lemme know and I'll show you other ways.


答:
You can't refer alias column in same query.

```<code>SELECT January.customer_id AS Jancust_id,
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral    <--- You can not do.
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'
</code>```

Also, as pointed by @GurV, you are also missing group by clause.

Title: SQL: doing math on COUNT column just carried over

Body:
You can't refer alias column in same query.

SELECT January.customer_id AS Jancust_id,
COUNT( DISTINCT January.customer_id ) AS Jan_orig_cust,
COUNT (DISTINCT payments.customer_id) as Jan_retain_cust,
Jan_retain_cust/ 1533 AS CAC_referral    <--- You can not do.
FROM January_Cohort January
LEFT JOIN telemon_payments_data payments
ON January.customer_id = payments.customer_id
WHERE January.acquisition_source = 'referral'
AND
payments.payment_date BETWEEN '2016-06-01' and '2016-06-31'

Also, as pointed by @GurV, you are also missing group by clause.


问:
jquery - .split is not a function
I am using the same code in some other place, which is working fine. but now i am using it, but is throwing me error i.e. .split is not a function

Below is code i am using:

```<code>var classList = $(this).attr('class').split(/\s+/);
</code>```

I have checked in Console, class name is coming like Cls_abc-XYZ and i want to get "abc-XYZ" from it.
Any suggestion

答:
split is a string function.

your syntax is correct but what is $(this)
You can log $(this).attr('class') value on console you can see this value does not string.

forExample

```<code>$('body').attr('class').split(/\s+/);
</code>```

returned array object  ["boxed","pattern-5"]

Title: jquery - .split is not a function

Body:
I am using the same code in some other place, which is working fine. but now i am using it, but is throwing me error i.e. .split is not a function

Below is code i am using:

var classList = $(this).attr('class').split(/\s+/);

I have checked in Console, class name is coming like Cls_abc-XYZ and i want to get "abc-XYZ" from it.
Any suggestion

Body:
split is a string function.

your syntax is correct but what is $(this)
You can log $(this).attr('class') value on console you can see this value does not string.

forExample

$('body').attr('class').split(/\s+/);

returned array object  ["boxed","pattern-5"]


问:
How to control order of rendering in vue.js for sibling component
I have following kind of code:

```<code><div>
  <compA />
  <compB />
</div>
</code>```

How do I make sure that first compA is rendered only after it compB is rendered.

Why I want is I have some dependency on  few elements of compA, and style of compB depends on presence of those elements.

Why in details:

I have some complex UI design, where one box will become fixed when you scroll. SO It will not go above the screen when you scroll, it will be fixed once you start scrolling and it start touching the header. So I am using jquery-visible to find if a div with a particular id is visible on the screen, if it is not visible, I change the style and make that box fixed. Following code should give the idea what I am doing:

```<code>methods: {
  onScroll () {
    if ($('#divId').visible(false, false, 'vertical')) { // This is div from the compA, so I want to make sure it is rendered first and it is visible
      this.isFixed = false
    } else {
      this.isFixed = true
    }
  }
},
mounted () {
  window.addEventListener('scroll', this.onScroll() }
},
destroyed () {
  window.removeEventListener('scroll', this.onScroll)
}
</code>```

I dont want to make those in same component as one reason is it dont make sense as the nature of these components, and other I use compA at many places, while compB is specific to only one page. Also layout of these  does not allow me to make compB child of compA as suggested in comments.

Any suggestions are welcome.

答:
After going through the edit I realised that the dependency is not data driven but event driven (onscroll). I have tried something and looks like it works (the setTimeout in the code is for demonstration).

My implementation is slightly different from that of Jonatas.

```<code><div id="app">
  RenderSwitch: {{ renderSwitch }} // for demonstration
  <template v-if='renderSwitch'>
    <comp-a></comp-a>
  </template>
  <comp-b @rendered='renderSwitchSet'></comp-b>
</div>
</code>```

When the component-B is rendered it emits an event, which just sets a data property in the parent of both component-A and component-B.

The surrounding <template> tags are there to reduce additional markup for a v-if.

The moment renderSwitch is set to true. component-a gets created.

Body:
I have following kind of code:

  <compA />
  <compB />

How do I make sure that first compA is rendered only after it compB is rendered.

Why I want is I have some dependency on  few elements of compA, and style of compB depends on presence of those elements.

Why in details:

I have some complex UI design, where one box will become fixed when you scroll. SO It will not go above the screen when you scroll, it will be fixed once you start scrolling and it start touching the header. So I am using jquery-visible to find if a div with a particular id is visible on the screen, if it is not visible, I change the style and make that box fixed. Following code should give the idea what I am doing:

methods: {
  onScroll () {
    if ($('#divId').visible(false, false, 'vertical')) { // This is div from the compA, so I want to make sure it is rendered first and it is visible
      this.isFixed = false
    } else {
      this.isFixed = true
    }
  }
},
mounted () {
  window.addEventListener('scroll', this.onScroll() }
},
destroyed () {
  window.removeEventListener('scroll', this.onScroll)
}

I dont want to make those in same component as one reason is it dont make sense as the nature of these components, and other I use compA at many places, while compB is specific to only one page. Also layout of these  does not allow me to make compB child of compA as suggested in comments.

Any suggestions are welcome.

Body:
After going through the edit I realised that the dependency is not data driven but event driven (onscroll). I have tried something and looks like it works (the setTimeout in the code is for demonstration).

My implementation is slightly different from that of Jonatas.

<div id="app">
  RenderSwitch: {{ renderSwitch }} // for demonstration
  <template v-if='renderSwitch'>
    <comp-a></comp-a>
  </template>
  <comp-b @rendered='renderSwitchSet'></comp-b>
</div>

When the component-B is rendered it emits an event, which just sets a data property in the parent of both component-A and component-B.

The surrounding <template> tags are there to reduce additional markup for a v-if.

The moment renderSwitch is set to true. component-a gets created.


问:
How to load external properties file with Java without rebuilding the Jar?
I use gradle which structures projects in maven style so I have the following

src/main/java/Hello.java and src/main/resources/test.properties

My Hello.java look like this

```<code>public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?

答:
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath

```<code>public class Hello {

    public static void main(String[] args) {
        String configPath = "test.properties";

        if (args.length > 0) {
            configPath = args[0];
        } else if (System.getenv("CONFIG_TEST") != null) {
            configPath = System.getenv("CONFIG_TEST");
        }

        File file = new File(configPath);
        try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
            Properties configProperties = new Properties();
            configProperties.load(input);
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
</code>```

You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST

Body:
I use gradle which structures projects in maven style so I have the following

src/main/java/Hello.java and src/main/resources/test.properties

My Hello.java look like this

public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?

Body:
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath

public class Hello {

    public static void main(String[] args) {
        String configPath = "test.properties";

        if (args.length > 0) {
            configPath = args[0];
        } else if (System.getenv("CONFIG_TEST") != null) {
            configPath = System.getenv("CONFIG_TEST");
        }

        File file = new File(configPath);
        try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
            Properties configProperties = new Properties();
            configProperties.load(input);
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST


问:
Javascript add extra argument
Let's take a look at this code:

```<code>var mainFunction = function() {
  altFunction.apply(null, arguments);
}
</code>```

The arguments that are passed to mainFunction are dynamic -- they can be 4 or 10, doesn't matter. However, I have to pass them through to altFunction AND I have to add an EXTRA argument to the argument list.

I have tried this:

```<code>var mainFunction = function() {
  var mainArguments = arguments;
  mainArguments[mainArguments.length] = 'extra data'; // not +1 since length returns "human" count.

  altFunction.apply(null, mainArguments);
}
</code>```

But that does not seem to work. How can I do this?

答:
In this case it could be more comfortable to use call() instead of apply():

```<code>function first(parameter1, parameter2) {

  var parameter3 = "123";

  secondFunction.call(
    this,
    parameter1,
    parameter2,
    parameter3);
},
</code>```

ContentLicense: CC BY-SA 4.0

Title: Javascript add extra argument

Body:
Let's take a look at this code:

var mainFunction = function() {
  altFunction.apply(null, arguments);
}

The arguments that are passed to mainFunction are dynamic -- they can be 4 or 10, doesn't matter. However, I have to pass them through to altFunction AND I have to add an EXTRA argument to the argument list.

I have tried this:

var mainFunction = function() {
  var mainArguments = arguments;
  mainArguments[mainArguments.length] = 'extra data'; // not +1 since length returns "human" count.

  altFunction.apply(null, mainArguments);
}

But that does not seem to work. How can I do this?

Body:
In this case it could be more comfortable to use call() instead of apply():

function first(parameter1, parameter2) {

  var parameter3 = "123";

  secondFunction.call(
    this,
    parameter1,
    parameter2,
    parameter3);
},


问:
How to use Redirect in ModelAndView
I Want to redirect my url to http://localhost:8080/ClickBuy/product/details to          http://localhost:8080/ClickBuy/home .

I have Define header.jsp and Include it in all my Pages.When I click home link from anywhere else url add /home from current url.So it shows 404 error.

Controller

```<code>public ModelAndView allProduct()
{
ModelAndView model=new ModelAndView("pl");
model.addObject("data", pd.getAllProducts());
return model;
}
</code>```

How can I use redirect:/ in ModelAndView return type method???

答:
To Use  redirect:/ in ModelAndView return type method, you are try following

```<code>ModelAndView modelAndView =  new ModelAndView("redirect:/abc.htm");
modelAndView.addObject("modelAttribute" , new ModelAttribute());
return modelAndView;
</code>```

You can also return home page using String returntype if you do not need any Model in home page

```<code>@RequestMapping(value = "/home.htm", method = RequestMethod.GET)
   public String homePage() {
      return "home";
   }
</code>```

Title: How to use Redirect in ModelAndView

Body:
I Want to redirect my url to http://localhost:8080/ClickBuy/product/details to          http://localhost:8080/ClickBuy/home .

I have Define header.jsp and Include it in all my Pages.When I click home link from anywhere else url add /home from current url.So it shows 404 error.

Controller

public ModelAndView allProduct()
{
ModelAndView model=new ModelAndView("pl");
model.addObject("data", pd.getAllProducts());
return model;
}

How can I use redirect:/ in ModelAndView return type method???

Body:
To Use  redirect:/ in ModelAndView return type method, you are try following

ModelAndView modelAndView =  new ModelAndView("redirect:/abc.htm");
modelAndView.addObject("modelAttribute" , new ModelAttribute());
return modelAndView;

You can also return home page using String returntype if you do not need any Model in home page

@RequestMapping(value = "/home.htm", method = RequestMethod.GET)
   public String homePage() {
      return "home";
   }


问:
Native messaging in window 10 anniversary edge browser
Is native messaging possible in window 10 anniversary edge browser. With anniversary update, edge supports extension. I cloned secureInput edge extension from GitHub that uses native messaging but it is not working in window 10 anniversary.

https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos/tree/master/SecureInput

please let me know the steps to make it run if it is possible to run in window 10 anniversary but If it needs window 10 creators, we need to wait for it.

答:
As per the API Roadmap page in the documentation (https://learn.microsoft.com/en-us/microsoft-edge/extensions/api-support/extension-api-roadmap), native messaging is supported in build 15002 and later. As a result, you'll be able to use native messaging in the Creators Update, or you can sign up for Windows Insider Preview builds (https://insider.windows.com) to get it early.

For more information, see https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/native-messaging


问:
Spring LdapTemplate - How do read values with same attribute name
I would like to read all groups of a user and put them into a list.

That's the ldap query:

ldapsearch -h [server_name] -p [port] -s sub -b
  "ou=people,ou=foo,o=bar,c=com" "(id=123)"

How the result looks like:

id: 123

name: John

firstname: BAKER

grouplist: cn=GROUP1.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

grouplist: cn=GROUP2.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

I use the LdapTemplate implementation of Spring. It works fine, but how can I handle results when they have multiple attributes with the same name (see above 'grouplist')? I tried to use the IncrementalAttributesMapper, but I didn't get it to work.

```<code>public MyUser getUser(String userId) {
   LdapQuery searchQuery = LdapQueryBuilder.query()
                .base("ou=people,ou=foo,o=bar,c=com")
                .searchScope(SearchScope.SUBTREE)
                .filter(new EqualsFilter("id", userId));

   return ldapTemplate.search(searchQuery, getUserAttributesMapper());
}

public static AttributesMapper getUserAttributesMapper() {
        return attributes -> {

            IncrementalAttributesMapper groupAttributesMapper = new DefaultIncrementalAttributesMapper("grouplist");

            MyUser myUser = MyUser.builder()
                 .id(attributes.get("id").get().toString())
                 .name(attributes.get("name").get().toString())
                 .firstname(attributes.get("firstname").get().toString())
                 .groupIds(groupAttributesMapper.getValues("cn"))
                 .build();

            return myUser;
        };
    }
</code>```

When I try to read the attribute as follows:

```<code>attributes.get("grouplist").get().toString()
</code>```

I get only the first group:

grouplist: cn=GROUP1.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

Thanks in advance for your support!

答:
I solved the similar problem using this code:

```<code>List values = DefaultIncrementalAttributesMapper.lookupAttributeValues(ldapTemplate, baseDN, "member");
</code>```

In that case I had group which contained a several members. Like this:

```<code>member: CN=Name1,OU=Users,DC=bar,DC=foo,DC=com
member: CN=Name2,OU=Users,DC=bar,DC=foo,DC=com
member: CN=Name3,OU=Users,DC=bar,DC=foo,DC=com
</code>```

As a result I've got a List of separated members of group.

Body:
I would like to read all groups of a user and put them into a list.

That's the ldap query:

ldapsearch -h [server_name] -p [port] -s sub -b
  "ou=people,ou=foo,o=bar,c=com" "(id=123)"

How the result looks like:

id: 123

name: John

firstname: BAKER

grouplist: cn=GROUP1.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

grouplist: cn=GROUP2.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

I use the LdapTemplate implementation of Spring. It works fine, but how can I handle results when they have multiple attributes with the same name (see above 'grouplist')? I tried to use the IncrementalAttributesMapper, but I didn't get it to work.

public MyUser getUser(String userId) {
   LdapQuery searchQuery = LdapQueryBuilder.query()
                .base("ou=people,ou=foo,o=bar,c=com")
                .searchScope(SearchScope.SUBTREE)
                .filter(new EqualsFilter("id", userId));

   return ldapTemplate.search(searchQuery, getUserAttributesMapper());
}

public static AttributesMapper getUserAttributesMapper() {
        return attributes -> {

            IncrementalAttributesMapper groupAttributesMapper = new DefaultIncrementalAttributesMapper("grouplist");

            MyUser myUser = MyUser.builder()
                 .id(attributes.get("id").get().toString())
                 .name(attributes.get("name").get().toString())
                 .firstname(attributes.get("firstname").get().toString())
                 .groupIds(groupAttributesMapper.getValues("cn"))
                 .build();

            return myUser;
        };
    }

When I try to read the attribute as follows:

attributes.get("grouplist").get().toString()

I get only the first group:

grouplist: cn=GROUP1.COM,cn=GROUPS,ou=FOO,o=BAR,c=COM

Thanks in advance for your support!

Body:
I solved the similar problem using this code:

List values = DefaultIncrementalAttributesMapper.lookupAttributeValues(ldapTemplate, baseDN, "member");

In that case I had group which contained a several members. Like this:

member: CN=Name1,OU=Users,DC=bar,DC=foo,DC=com
member: CN=Name2,OU=Users,DC=bar,DC=foo,DC=com
member: CN=Name3,OU=Users,DC=bar,DC=foo,DC=com

As a result I've got a List of separated members of group.


问:
Codeigniter 3.x Login with Form Validation -Boiler plate
I have been reading couple of questions here from different newbies about Login and validation in codeigniter, some have mixed JavaScript and J-query. Codeigniter itself provide a robust form validation along with custom error setting support. I have decided to share with you the easiest way to kickstart in codeigniter with login boilerplate which I have created and I am sharing it with you. It has

Controller
Login

Model: Login_model

Views: Login and success

And basic configurations

答:
Step-1

Download Codeigniter 3.x from Official Website

Step-2

Extract in a folder in your localhost root. (htdocs in xampp and www in wamp)

Step-3. Configuration

Open the folder you have extracted the codeigniter in go to
application->config->autoload.php. Go to line 55 and autoload these two libraries

```<code>$autoload['libraries'] = array('database', 'session');
</code>```

Go to line 67 and load two helpers

```<code>$autoload['helper'] = array('url', 'file');
</code>```

Save the file and now go the application->config->config.php

Set Base URL on line 19 as

```<code>$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/folder_name/';
</code>```

On line 31 remove the index.php from value and change it to

```<code>$config['index_page'] = '';
</code>```

on line 49 set uri_protocol from AUTO to REQUEST_URI

```<code>$config['uri_protocol'] = 'REQUEST_URI';
</code>```

on line 229 set an encryption key

```<code>$config['encryption_key'] = '!@#$%^&*()ASDFGHJKL:ZXCVBNM<>QWERTYUIOP';
// I recommend you create a hash and place it here
</code>```

Save the file

Step-4 .htaccess

On the root of codeigniter installation folder create an .htaccess file write following in it and save

```<code><IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
</code>```

Step-5. Create Database

Open your phpmyadmin or mysql terminal create a database , create a table users in it , you can use following query

```<code>CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `status` enum('pending','approved') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Step -6. Connecting Database to Codeigniter

Go to application->config->database.php. Assuming its a fresh install and you haven't created any environments. Go to line 52 and change the four lines to

```<code>$db['default']['username'] = 'username'; // will be root if you have xampp
$db['default']['password'] = 'password'; // will be empty if you haven't set
$db['default']['database'] = 'your_database_name';
$db['default']['dbdriver'] = 'mysqli'; // changed from mysql to mysqli
</code>```

Step-7. The View

Source Code

Step-8. The Controller

```<code>class Login extends CI_Controller {
function __construct()
{
    parent::__construct();
    $this->load->model('Login_model');
    $this->load->library('form_validation');
}

public function index()
{
    if($this->isLoggedin()){ redirect(base_url().'login/dashboard');}
    $data['title']='Login Boiler Plate';
    if($_POST)
    {
        $config=array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'trim|required'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run() == false) {
            // if validation has errors, save those errors in variable and send it to view
            $data['errors'] = validation_errors();
            $this->load->view('login',$data);
        } else {
            // if validation passes, check for user credentials from database
            $user = $this->Login_model->checkUser($_POST);
            if ($user) {
            // if an record of user is returned from model, save it in session and send user to dashboard
                $this->session->set_userdata($user);
                redirect(base_url() . 'Login/dashboard');
            } else {
            // if nothing returns from model , show an error
                $data['errors'] = 'Sorry! The credentials you have provided are not correct';
                $this->load->view('login',$data);
            }
        }

    }
    else
    {
        $this->load->view('login',$data);
    }

}
public function change_password()
{
    if($this->isLoggedin()){
        $data['title']='Change Password';
        if($_POST)
        {
            $config=array(
                array(
                    'field' => 'old_password',
                    'label' => 'Old Password',
                    'rules' => 'trim|required|callback_checkPassword'
                ),
                array(
                    'field' => 'password',
                    'label' => 'Password',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'conf_password',
                    'label' => 'Confirm Password',
                    'rules' => 'trim|required|matches[password]'
                )
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == false)
            {
                // if validation has errors, save those errors in variable and send it to view
                $data['errors'] = validation_errors();
                $this->load->view('change_password',$data);
            }
            else
            {
                // if validation passes, check for user credentials from database
                $this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
                $this->session->set_flashdata('log_success','Congratulations! Password Changed');
                redirect(base_url() . 'Login/dashboard');
            }

        }
        else
        {
            $this->load->view('change_password',$data);
        }
    }
    else
    {
        redirect(base_url().'Login');
    }

}

public function dashboard()
{
    if($this->isLoggedin())
    {
        $data['title']='Welcome! You are logged in';
        $this->load->view('success',$data);
    }
    else
    {
        redirect(base_url().'Login');
    }
}

public function logout()
{
    $this->session->sess_destroy();
    redirect(base_url().'Login');
}

public function isLoggedin()
{
    if(!empty($this->session->userdata['id']))
    {
        return true;
    }
    else
    {
        return false;
    }
}

}
</code>```

Step-8. The Model

```<code>$autoload['helper'] = array('url', 'file');
</code>```0

Step-9. Testing

Open Database in Phpmyadmin and insert sample data in to your table using following query

```<code>$autoload['helper'] = array('url', 'file');
</code>```1

Test-1
Empty Submit

It will produce the error, which we are storing in an errors index in Controller, passing it to view and displaying it in the view if the value exists.

Test-2. Wrong Credentials

Provide any username and password (random)

Test-3. Correct Credentials

Username: john
  Password: john

Success View Source Code

ALERTS!!

This is a basic code for kick starters and there is a lot more room for improvements like Security Features and Encryption

Complete Source Code

You can download the complete source code from Git at Boiler-Plates-Codeigniter-3.x-Login

Body:
Step-1

Download Codeigniter 3.x from Official Website

Step-2

Extract in a folder in your localhost root. (htdocs in xampp and www in wamp)

Step-3. Configuration

Open the folder you have extracted the codeigniter in go to
application->config->autoload.php. Go to line 55 and autoload these two libraries

$autoload['libraries'] = array('database', 'session');

Go to line 67 and load two helpers

$autoload['helper'] = array('url', 'file');

Save the file and now go the application->config->config.php

Set Base URL on line 19 as

$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/folder_name/';

On line 31 remove the index.php from value and change it to

$config['index_page'] = '';

on line 49 set uri_protocol from AUTO to REQUEST_URI

$config['uri_protocol'] = 'REQUEST_URI';

on line 229 set an encryption key

$config['encryption_key'] = '!@#$%^&*()ASDFGHJKL:ZXCVBNM<>QWERTYUIOP';
// I recommend you create a hash and place it here

Save the file

Step-4 .htaccess

On the root of codeigniter installation folder create an .htaccess file write following in it and save

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Step-5. Create Database

Open your phpmyadmin or mysql terminal create a database , create a table users in it , you can use following query

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `status` enum('pending','approved') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step -6. Connecting Database to Codeigniter

Go to application->config->database.php. Assuming its a fresh install and you haven't created any environments. Go to line 52 and change the four lines to

$db['default']['username'] = 'username'; // will be root if you have xampp
$db['default']['password'] = 'password'; // will be empty if you haven't set
$db['default']['database'] = 'your_database_name';
$db['default']['dbdriver'] = 'mysqli'; // changed from mysql to mysqli

Step-7. The View

Source Code

Step-8. The Controller

class Login extends CI_Controller {
function __construct()
{
    parent::__construct();
    $this->load->model('Login_model');
    $this->load->library('form_validation');
}

public function index()
{
    if($this->isLoggedin()){ redirect(base_url().'login/dashboard');}
    $data['title']='Login Boiler Plate';
    if($_POST)
    {
        $config=array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'trim|required'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run() == false) {
            // if validation has errors, save those errors in variable and send it to view
            $data['errors'] = validation_errors();
            $this->load->view('login',$data);
        } else {
            // if validation passes, check for user credentials from database
            $user = $this->Login_model->checkUser($_POST);
            if ($user) {
            // if an record of user is returned from model, save it in session and send user to dashboard
                $this->session->set_userdata($user);
                redirect(base_url() . 'Login/dashboard');
            } else {
            // if nothing returns from model , show an error
                $data['errors'] = 'Sorry! The credentials you have provided are not correct';
                $this->load->view('login',$data);
            }
        }

    }
    else
    {
        $this->load->view('login',$data);
    }

}
public function change_password()
{
    if($this->isLoggedin()){
        $data['title']='Change Password';
        if($_POST)
        {
            $config=array(
                array(
                    'field' => 'old_password',
                    'label' => 'Old Password',
                    'rules' => 'trim|required|callback_checkPassword'
                ),
                array(
                    'field' => 'password',
                    'label' => 'Password',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'conf_password',
                    'label' => 'Confirm Password',
                    'rules' => 'trim|required|matches[password]'
                )
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == false)
            {
                // if validation has errors, save those errors in variable and send it to view
                $data['errors'] = validation_errors();
                $this->load->view('change_password',$data);
            }
            else
            {
                // if validation passes, check for user credentials from database
                $this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
                $this->session->set_flashdata('log_success','Congratulations! Password Changed');
                redirect(base_url() . 'Login/dashboard');
            }

        }
        else
        {
            $this->load->view('change_password',$data);
        }
    }
    else
    {
        redirect(base_url().'Login');
    }

}

public function dashboard()
{
    if($this->isLoggedin())
    {
        $data['title']='Welcome! You are logged in';
        $this->load->view('success',$data);
    }
    else
    {
        redirect(base_url().'Login');
    }
}

public function logout()
{
    $this->session->sess_destroy();
    redirect(base_url().'Login');
}

public function isLoggedin()
{
    if(!empty($this->session->userdata['id']))
    {
        return true;
    }
    else
    {
        return false;
    }
}

}

Step-8. The Model

class Login_model extends CI_Model{
function __construct(){
    parent::__construct();
}

public function checkUser($data)
{
    $st=$this->db->SELECT('*')->from('users')
                    ->WHERE('username',$data['username'])
                    ->WHERE('password',sha1(md5($data['password'])))
                    ->get()->result_array();
    if(count($st)>0)
    {
        return $st[0];
    }
    else
    {
        return false;
    }
}
public function checkPassword($str)
{
    $st=$this->db->SELECT('*')->from('users')
        ->WHERE('id',$this->session->userdata['id'])
        ->WHERE('password',sha1(md5($str)))
        ->get()->result_array();
    if(count($st)>0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public function updatePassword($password,$id)
{
    $pass=array(
        'password' => sha1(md5($password))
    );
    $this->db->WHERE('id',$id)->update('users',$pass);
}
}

Step-9. Testing

Open Database in Phpmyadmin and insert sample data in to your table using following query

INSERT INTO `users` (`id`, `username`, `password`, `fullname`, `status`)
VALUES
(1, 'john', '56f5950b728849d0b97c1bccf1691c090ab6734c', 'John Vick',
'approved');

Test-1
Empty Submit

It will produce the error, which we are storing in an errors index in Controller, passing it to view and displaying it in the view if the value exists.

Test-2. Wrong Credentials

Provide any username and password (random)

Test-3. Correct Credentials

Username: john
  Password: john

Success View Source Code

ALERTS!!

This is a basic code for kick starters and there is a lot more room for improvements like Security Features and Encryption

Complete Source Code

You can download the complete source code from Git at Boiler-Plates-Codeigniter-3.x-Login


问:
Loop inside loop (or preferably workaround) for monte carlo simulation
This question is related to one I asked in Cross Validated section, this however is focused strictly on R coding.

I am trying to do monte carlo simulation to create Aggregated Yearly Loss Distribution. It draws random number of loss frequency from discrete distribution (in this case Poisson ) and then for each loss it draws random severity for each from continuous distribution (log-normal for example)

It is not very long or complicated piece of code, however I stumped on a problem.

First what I should say: I am beginner in writing loops in R (I do not use lapply or sapply function only for). I managed to generate the random number of losses with certain severity for each one, I have two versions:

(This part is for both versions, I am using "training" values for now)

```<code>lambda=5 # lambda for poisson distribution
lnormpar1=2 #mean for lognormal distribution
lnormpar2=1 #standard deviation for lognormal distribution
simvect=10 #number of repeteation for monte carlo simulation
</code>```

Ver1:

```<code>  vec.f=c()
  for(z in 1:1){
    vec.f[z]<- qpois(runif(1, min=0, max=1),lambda)
  }
  output=matrix(ncol=1,nrow=vec.f)
  for(i in 1:vec.f){
    output[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
  }
output
</code>```

or shorter but I am not sure more convenient version 2:

```<code>output2=c()
for(i in 1:qpois(runif(1, min=0, max=1),lambda)){
  output2[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
}
as.data.frame(output2)
</code>```

They both do same thing - generates "column" of random number of losses with assigned severity, using parameters i posted here example looks like:

Ver1 with matrix:

```<code>          [,1]
[1,]  3.825669
[2,]  6.612618
[3,] 31.890079
[4,]  3.400814
[5,] 11.453274
[6,] 12.498189
[7,]  3.773497
</code>```

Ver2:

```<code>    output2
1 18.632316
2 18.808997
3  1.526787
4  2.377593
5  5.786662
</code>```

Those are just randomly generated numbers to represent how those codes works. What is my issue is that I guess I have put those loop inside another loop that will repeat those operation certain number of times (determined by simvect=n where n=10^5 or n=10^6 in final version). I want it to look like this (manually crafted):

```<code>1.1 1.2 1.3
1.3 1.4 2.0
2.0 N/A 1.2
N/A N/A 3.0
N/A N/A 1.9
</code>```

So i want to generated random string then repeat the process and add those 2 together to created a data frame or to get better explanation - matrix with number of rows equals to max drawn number of frequencies and colnumber equals to chosen number of repetitions (denoted here as simvect)

This is long post but I believe it explains my issue. Thank you all in advance!

答:
I didn't fully understand what you would like to achieve at the end but this is what I came up with. Hope it helps!

```<code>lambda=5 # lambda for poisson distribution
lnormpar1=2 #mean for lognormal distribution
lnormpar2=1 #standard deviation for lognormal distribution
simvect=1000000 #number of repeteation for monte carlo simulation
</code>```

Vec and output retain values for us as we loop through:

```<code>Vec=rep(0,simvect)       # first component
for(z in 1:simvect){
    Vec[z]<- qpois(runif(1, min=0, max=1),lambda)
}
Vec    # printing (not necessary)

output = rep(0,simvect)   # second component
for(i in 1:simvect){
  output[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
}

matrix(c(Vec,output), ncol=2)    # merging them
</code>```

Body:
This question is related to one I asked in Cross Validated section, this however is focused strictly on R coding.

I am trying to do monte carlo simulation to create Aggregated Yearly Loss Distribution. It draws random number of loss frequency from discrete distribution (in this case Poisson ) and then for each loss it draws random severity for each from continuous distribution (log-normal for example)

It is not very long or complicated piece of code, however I stumped on a problem.

First what I should say: I am beginner in writing loops in R (I do not use lapply or sapply function only for). I managed to generate the random number of losses with certain severity for each one, I have two versions:

(This part is for both versions, I am using "training" values for now)

lambda=5 # lambda for poisson distribution
lnormpar1=2 #mean for lognormal distribution
lnormpar2=1 #standard deviation for lognormal distribution
simvect=10 #number of repeteation for monte carlo simulation

Ver1:

  vec.f=c()
  for(z in 1:1){
    vec.f[z]<- qpois(runif(1, min=0, max=1),lambda)
  }
  output=matrix(ncol=1,nrow=vec.f)
  for(i in 1:vec.f){
    output[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
  }
output

or shorter but I am not sure more convenient version 2:

output2=c()
for(i in 1:qpois(runif(1, min=0, max=1),lambda)){
  output2[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
}
as.data.frame(output2)

They both do same thing - generates "column" of random number of losses with assigned severity, using parameters i posted here example looks like:

Ver1 with matrix:

          [,1]
[1,]  3.825669
[2,]  6.612618
[3,] 31.890079
[4,]  3.400814
[5,] 11.453274
[6,] 12.498189
[7,]  3.773497

Ver2:

    output2
1 18.632316
2 18.808997
3  1.526787
4  2.377593
5  5.786662

Those are just randomly generated numbers to represent how those codes works. What is my issue is that I guess I have put those loop inside another loop that will repeat those operation certain number of times (determined by simvect=n where n=10^5 or n=10^6 in final version). I want it to look like this (manually crafted):

1.1 1.2 1.3
1.3 1.4 2.0
2.0 N/A 1.2
N/A N/A 3.0
N/A N/A 1.9

So i want to generated random string then repeat the process and add those 2 together to created a data frame or to get better explanation - matrix with number of rows equals to max drawn number of frequencies and colnumber equals to chosen number of repetitions (denoted here as simvect)

This is long post but I believe it explains my issue. Thank you all in advance!

Body:
I didn't fully understand what you would like to achieve at the end but this is what I came up with. Hope it helps!

lambda=5 # lambda for poisson distribution
lnormpar1=2 #mean for lognormal distribution
lnormpar2=1 #standard deviation for lognormal distribution
simvect=1000000 #number of repeteation for monte carlo simulation

Vec and output retain values for us as we loop through:

Vec=rep(0,simvect)       # first component
for(z in 1:simvect){
    Vec[z]<- qpois(runif(1, min=0, max=1),lambda)
}
Vec    # printing (not necessary)

output = rep(0,simvect)   # second component
for(i in 1:simvect){
  output[i]<- qlnorm(runif(1, min=0, max=1),meanlog=lnormpar1, sdlog=lnormpar2)
}

matrix(c(Vec,output), ncol=2)    # merging them