问:
how to pass date format from controller to directive using angularjs
how to pass variable "$scope.dateformat" to "format" in
           directive.Please
           let me know if any examples are available or suggested.
           Please suggest me more examples on this.</p>

```<code>     $scope.dateformat ="yyyy-mm-dd";

      menuModule.directive("datepicker", function(){
      return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
               format: "yyyy-mm-dd", // Above $scope.dateformat should be
                                             //   called here
            }).on("changeDate", function(e){
                return scope.$apply(function(){
                    console.log(attr);
                    return scope.ngModel = e.format();
                });
            });

            return scope.$watch("ngModel", function(newValue){
                $(elem).datepicker("update", newValue);
            });
             }
          };
         });
</code>```

答:
You don't have a $scope variable in the global scope (I hope).

First approach

If this dataFormat is meant as a global configuration, you could register it in angular as a constant like this:

```<code>menuModule.constant('DATE_FORMAT', 'yyyy-mm-dd');
</code>```

and then inject it in your directive:

```<code>menuModule.directive("datepicker", function(DATE_FORMAT){
    return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
                format: DATE_FORMAT
        });

        // .. rest is omitted
    };
});
</code>```

Second approach

If you want the format to be passed to the directive through the attributes (and thus make it available in the scope) you'll add it as a scope binding like this:

```<code>menuModule.directive("datepicker", function(){
    return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "=",
            "dateFormat": "@"
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
                format: scope.dateFormat
        });

        // .. rest is omitted
    };
});
</code>```

then whenever you use the directive, you can pass the format like this:

```<code><datepicker date-format="yyyy-mm-dd"></datepicker>
</code>```

or if it comes from a controller

```<code><datepicker date-format="{{$ctrl.dateFormat}}"></datepicker>
</code>```

Body:
how to pass variable "$scope.dateformat" to "format" in
           directive.Please
           let me know if any examples are available or suggested.
           Please suggest me more examples on this.

     $scope.dateformat ="yyyy-mm-dd";

      menuModule.directive("datepicker", function(){
      return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
               format: "yyyy-mm-dd", // Above $scope.dateformat should be
                                             //   called here
            }).on("changeDate", function(e){
                return scope.$apply(function(){
                    console.log(attr);
                    return scope.ngModel = e.format();
                });
            });

            return scope.$watch("ngModel", function(newValue){
                $(elem).datepicker("update", newValue);
            });
             }
          };
         });

Body:
You don't have a $scope variable in the global scope (I hope).

First approach

If this dataFormat is meant as a global configuration, you could register it in angular as a constant like this:

menuModule.constant('DATE_FORMAT', 'yyyy-mm-dd');

and then inject it in your directive:

menuModule.directive("datepicker", function(DATE_FORMAT){
    return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
                format: DATE_FORMAT
        });

        // .. rest is omitted
    };
});

Second approach

If you want the format to be passed to the directive through the attributes (and thus make it available in the scope) you'll add it as a scope binding like this:

menuModule.directive("datepicker", function(){
    return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "=",
            "dateFormat": "@"
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
                format: scope.dateFormat
        });

        // .. rest is omitted
    };
});

then whenever you use the directive, you can pass the format like this:

<datepicker date-format="yyyy-mm-dd"></datepicker>

or if it comes from a controller

<datepicker date-format="{{$ctrl.dateFormat}}"></datepicker>


来源: stackexchange

问:
How to fetch two Json response Json Object and Array
How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Login response in Logcat

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
</code>```

only the 1st response was returned in this Logcat

```<code>D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

This is the 1st Json response. Was parse and stored in SQLite

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
</code>```

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in SQLite

```<code>{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

Whole JSON response

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This is my Login.java

```<code>try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
</code>```

SQlitehandler.java

```<code>public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}
</code>```

Logcat message

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

Login.php

```<code><?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "<br />" .$username. "<br />";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>
</code>```

答:
This is the correct format of your Json Response :

```<code>{
    "object1":{
        "error":false,
            "user":{
        "br_code":12,
                "mem_id":13,
                "username":"novalyn",
                "email":"gsac_tabaco@yahoo.com",
                "created_at":"2016-07-22 09:05:21"
    }
    }
    "object2":{
        "error":false,
            "sl_summ":
        [
        {
            "sl_desc":"PA : Savings Account",
                "tr_date":"2015-08-17",
                "actual_balance":"483.67",
                "available_balance":"483.67"
        },
        {
            "sl_desc":"PA : Savings - Cash Bond",
                "tr_date":"2015-08-28",
                "actual_balance":"10129.43",
                "available_balance":"10129.43"
        }
        ]
    }
}
</code>```

Now parse your response using below method.

```<code>private void parseJsonResponse(String jsonString)
{
    try
    {
        JSONObject rootJsonObject = new JSONObject(jsonString);
        JSONObject object1 = rootJsonObject.has("object1") ? rootJsonObject.getJSONObject("object1") : new JSONObject();
        JSONObject object2 = rootJsonObject.has("object2") ? rootJsonObject.getJSONObject("object2") : new JSONObject();

       // Now get remaining values from object1 and object2

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Login response in Logcat

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}

only the 1st response was returned in this Logcat

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ

This is the 1st Json response. Was parse and stored in SQLite

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in SQLite

{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

Whole JSON response

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This is my Login.java

try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}

SQlitehandler.java

public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}

Logcat message

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

Login.php

<?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "
" .$username. "
";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>

Body:
This is the correct format of your Json Response :

{
    "object1":{
        "error":false,
            "user":{
        "br_code":12,
                "mem_id":13,
                "username":"novalyn",
                "email":"gsac_tabaco@yahoo.com",
                "created_at":"2016-07-22 09:05:21"
    }
    }
    "object2":{
        "error":false,
            "sl_summ":
        [
        {
            "sl_desc":"PA : Savings Account",
                "tr_date":"2015-08-17",
                "actual_balance":"483.67",
                "available_balance":"483.67"
        },
        {
            "sl_desc":"PA : Savings - Cash Bond",
                "tr_date":"2015-08-28",
                "actual_balance":"10129.43",
                "available_balance":"10129.43"
        }
        ]
    }
}

Now parse your response using below method.

private void parseJsonResponse(String jsonString)
{
    try
    {
        JSONObject rootJsonObject = new JSONObject(jsonString);
        JSONObject object1 = rootJsonObject.has("object1") ? rootJsonObject.getJSONObject("object1") : new JSONObject();
        JSONObject object2 = rootJsonObject.has("object2") ? rootJsonObject.getJSONObject("object2") : new JSONObject();

       // Now get remaining values from object1 and object2

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}


问:
pgfortran equivalent of -J switch in gfortran
When I compile code in gfortran I can use the -J/dir/ switch to set an output directory for .mod files.
Now I'm switching to compile with the PGI pgfortran compiler but can't find the equivalent.

What is the pgfortran equivalent of -J?

答:
For the PGI compiler (and Intel's) the -module option is the one you want.  This isn't entirely obvious, depending on which documentation you read.

From pgf90 -help:

-module <dir>       Add search directory for module information files

but from the reference manual

-module <moduledir> (F90/F95 only) Save/search for module files in directory <moduledir>

So, -module both saves generated module files to the chosen directory and adds that directory to the search path.


问:
Bindings not updating inside datagrid
I have a datagrid where I change a cell depending on what is chosen from the other column.

Let's say, my first column shows Weekdays (enums). If the user choose "Monday", the cell in the second column will be a TextBox. If the user chosoe a different day(eg. Friday), it'll become a Textblock with Text="Hooray!", else Textblock Text="".

Both Textbox and Textblock binds in the same property. But this binding does not work. Please help...

XAML

```<code><DataGrid Margin="0,10,0,0"
                          x:Name="dataGrid"
                          AutoGenerateColumns="False"
                          IsSynchronizedWithCurrentItem="True"
                          ItemsSource="{Binding TheCollection}"
                          SelectedItem="{Binding TheSelectedItemFromTheCollection}">
                    <DataGrid.Columns>
                        <DataGridTemplateColumn Header="Days"
                                                CanUserReorder="False"
                                                CanUserResize="False"
                                                CellTemplate="{StaticResource local.DataGridDays}" />
                        <DataGridTemplateColumn Header="Value"
                                                CanUserReorder="False"
                                                CanUserResize="False"
                                                CellTemplate="{StaticResource local.DataGridValue}" />
                    </DataGrid.Columns>
</DataGrid>

<DataTemplate x:Key="local.DataGridValuesEditable">
    <StackPanel>
        <Border Background="White"
                BorderThickness="1"
                Padding="4">
            <TextBox Text="{Binding InitialValue, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}"
                     VerticalAlignment="Bottom"
                     Margin="0" />
        </Border>
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="local.DataGridValuesDefault">
    <StackPanel>
        <Border Background="White"
                BorderThickness="1"
                Height="30"
                Padding="4">
            <TextBlock  Text="{Binding InitialValue, Mode=TwoWay, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}"
                        VerticalAlignment="Bottom"
                        Margin="0"
                        Width="55" />
        </Border>
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="local.DataGridValue">
    <ContentControl>
        <ContentControl.Style>
            <Style TargetType="ContentControl">
                <Setter Property="ContentTemplate"
                        Value="{DynamicResource local.DataGridValuesDefault}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedDay, UpdateSourceTrigger=PropertyChanged}"
                                 Value="Monday">
                        <Setter Property="ContentTemplate"
                                Value="{DynamicResource local.DataGridValuesEditable}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>
</code>```

ViewModel

```<code>private ObservableCollection<TheModel> _theCollection;

public ObservableCollection<TheModel> TheCollection
{
    get
    {
        if (_theCollection == null)
            _theCollection = new ObservableCollection<TheModel>();
        return _theCollection;
    }
    set
    {
        _theCollection = value;
    }
}

private TheModel _theSelectedItemFromTheCollection;

public TheModel TheSelectedItemFromTheCollection
{
    get
    {
        if (_theSelectedItemFromTheCollection == null)
            _theSelectedItemFromTheCollection = new TheModel();
        return _theSelectedItemFromTheCollection;
    }
    set
    {
        _theSelectedItemFromTheCollection = value;
        NotifyPropertyChanged("TheSelectedItemFromTheCollection");
    }
}
</code>```

Model

```<code>public string SelectedDay
{
    get { return day; }
    set
    {
        day = value;
        if (day == TheWeekDays.Friday.ToString())
        {
            InitialValue = "Hooray!!";
        }
        else
            InitialValue = string.Empty;
        NotifyPropertyChanged("SelectedDay");
    }
}

private string _initialValue;
public string InitialValue
{
    get { return _initialValue; }
    set
    {
        _initialValue = value;
        NotifyPropertyChanged("InitialValue");
    }
}

public IEnumerable<WeekDays> TheWeekDays
{
    get
    {
        return Enum.GetValues(typeof(WeekDays))
                    .Cast<WeekDays>();
    }
}
</code>```

答:
The following is the desired situation:

The DataContext of local.DataGridValuesDefault and local.DataGridValuesEditable should be the row item TheModel.

With this DataContext, the bindings can be written as follows:

```<code><TextBox Text="{Binding InitialValue,UpdateSourceTrigger=PropertyChanged}"
</code>```

and

```<code><TextBlock Text="{Binding InitialValue}"
</code>```

The DataContext of local.DataGridValue contains the desired item. A ContentControl will turn its Content into the DataContext of its ContentTemplate, so the Content needs to be linked with the outer DataContext. Also, the trigger binding can be simplified:

```<code><DataTemplate x:Key="local.DataGridValue">
    <ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style TargetType="ContentControl">
                <Setter Property="ContentTemplate"
                        Value="{DynamicResource local.DataGridValuesDefault}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedDay}"
                                 Value="Monday">
                        <Setter Property="ContentTemplate"
                                Value="{DynamicResource local.DataGridValuesEditable}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>
</code>```

Title: Bindings not updating inside datagrid

Body:
I have a datagrid where I change a cell depending on what is chosen from the other column.

Let's say, my first column shows Weekdays (enums). If the user choose "Monday", the cell in the second column will be a TextBox. If the user chosoe a different day(eg. Friday), it'll become a Textblock with Text="Hooray!", else Textblock Text="".

Both Textbox and Textblock binds in the same property. But this binding does not work. Please help...

XAML

<DataGrid Margin="0,10,0,0"
                          x:Name="dataGrid"
                          AutoGenerateColumns="False"
                          IsSynchronizedWithCurrentItem="True"
                          ItemsSource="{Binding TheCollection}"
                          SelectedItem="{Binding TheSelectedItemFromTheCollection}">
                    <DataGrid.Columns>
                        <DataGridTemplateColumn Header="Days"
                                                CanUserReorder="False"
                                                CanUserResize="False"
                                                CellTemplate="{StaticResource local.DataGridDays}" />
                        <DataGridTemplateColumn Header="Value"
                                                CanUserReorder="False"
                                                CanUserResize="False"
                                                CellTemplate="{StaticResource local.DataGridValue}" />
                    </DataGrid.Columns>
</DataGrid>

<DataTemplate x:Key="local.DataGridValuesEditable">
    <StackPanel>
        <Border Background="White"
                BorderThickness="1"
                Padding="4">
            <TextBox Text="{Binding InitialValue, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}"
                     VerticalAlignment="Bottom"
                     Margin="0" />
        </Border>
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="local.DataGridValuesDefault">
    <StackPanel>
        <Border Background="White"
                BorderThickness="1"
                Height="30"
                Padding="4">
            <TextBlock  Text="{Binding InitialValue, Mode=TwoWay, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}"
                        VerticalAlignment="Bottom"
                        Margin="0"
                        Width="55" />
        </Border>
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="local.DataGridValue">
    <ContentControl>
        <ContentControl.Style>

            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>

ViewModel

private ObservableCollection<TheModel> _theCollection;

public ObservableCollection<TheModel> TheCollection
{
    get
    {
        if (_theCollection == null)
            _theCollection = new ObservableCollection<TheModel>();
        return _theCollection;
    }
    set
    {
        _theCollection = value;
    }
}

private TheModel _theSelectedItemFromTheCollection;

public TheModel TheSelectedItemFromTheCollection
{
    get
    {
        if (_theSelectedItemFromTheCollection == null)
            _theSelectedItemFromTheCollection = new TheModel();
        return _theSelectedItemFromTheCollection;
    }
    set
    {
        _theSelectedItemFromTheCollection = value;
        NotifyPropertyChanged("TheSelectedItemFromTheCollection");
    }
}

Model

public string SelectedDay
{
    get { return day; }
    set
    {
        day = value;
        if (day == TheWeekDays.Friday.ToString())
        {
            InitialValue = "Hooray!!";
        }
        else
            InitialValue = string.Empty;
        NotifyPropertyChanged("SelectedDay");
    }
}

private string _initialValue;
public string InitialValue
{
    get { return _initialValue; }
    set
    {
        _initialValue = value;
        NotifyPropertyChanged("InitialValue");
    }
}

public IEnumerable<WeekDays> TheWeekDays
{
    get
    {
        return Enum.GetValues(typeof(WeekDays))
                    .Cast<WeekDays>();
    }
}

Body:
The following is the desired situation:

The DataContext of local.DataGridValuesDefault and local.DataGridValuesEditable should be the row item TheModel.

With this DataContext, the bindings can be written as follows:

<TextBox Text="{Binding InitialValue,UpdateSourceTrigger=PropertyChanged}"

and

<TextBlock Text="{Binding InitialValue}"

The DataContext of local.DataGridValue contains the desired item. A ContentControl will turn its Content into the DataContext of its ContentTemplate, so the Content needs to be linked with the outer DataContext. Also, the trigger binding can be simplified:

<DataTemplate x:Key="local.DataGridValue">
    <ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style TargetType="ContentControl">
                <Setter Property="ContentTemplate"
                        Value="{DynamicResource local.DataGridValuesDefault}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedDay}"
                                 Value="Monday">
                        <Setter Property="ContentTemplate"
                                Value="{DynamicResource local.DataGridValuesEditable}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>


问:
How to get start date of current year in iOS
I don't know how to use NSDate or NSCalendar in this condition.

Help me to solve this issue.

答:
This can be done much cleaner than the other answers:

```<code>NSDate *startOfYear;

[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitYear startDate:&startOfYear interval:0 forDate:[NSDate date]];
</code>```

startOfYear now holds midnight at January 1st of the current year.

Body:
This can be done much cleaner than the other answers:

NSDate *startOfYear;

[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitYear startDate:&startOfYear interval:0 forDate:[NSDate date]];

startOfYear now holds midnight at January 1st of the current year.


问:
I need to apply the css for a specific class and id
I need to apply CSS to a specific class and id of an element like this.

```<code><div class="contents" id="contents">
</code>```

I tried

```<code>#contents .contents { ... }
</code>```

but it doesn't seem to work.

How to apply the css for a specific class and id ?

ADDED

With

```<code>#contents.contents {...}
</code>```

It works OK.

答:
In your example, if you're looking for only that ID, you can just use:

```<code>#contents { ... }
</code>```

The class is unnecessary because the ID is unique and will only find that element.

However, if you want to apply it to that ID AND anything with that class, you want:

```<code>#contents, .contents { ... }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to apply CSS to a specific class and id of an element like this.

I tried

#contents .contents { ... }

but it doesn't seem to work.

How to apply the css for a specific class and id ?

ADDED

With

#contents.contents {...}

It works OK.

Body:
In your example, if you're looking for only that ID, you can just use:

#contents { ... }

The class is unnecessary because the ID is unique and will only find that element.

However, if you want to apply it to that ID AND anything with that class, you want:

#contents, .contents { ... }


问:
matplotlib: How to pick up shift click on figure?
I have a matplotlib and I have created a button_press_event like this:

```<code>self.fig.canvas.mpl_connect('button_press_event', self.onClick)

def onClick(self, event)
    if event.button == 1:
        # draw some artists on left click

    elif event.button == 2:
        # draw a vertical line on the mouse x location on wheel click

    elif event.button == 3:
        # clear artists on right click
</code>```

Now is it possible to modify the wheel click handler to something like this

```<code>    elif event.button == 2 or (event.button == 1 and event.key == "shift"):
        # draw a vertical line on the mouse x location
        # on wheel click or on shift+left click
        # (alternative way if there is no wheel for example)
</code>```

It seems that button_press_event doesn't support keys and key_press_event doesn't support mouse button clicks, but I'm not sure.

Is there a way?

答:
If you are on Qt then you can simply use:</p>

```<code>def onClick(self, event)
    # queries the pressed modifier keys
    mods = QGuiApplication.queryKeyboardModifiers()
    if event.button == 1 and mods == Qt.ShiftModifier:
        # do something when shift-clicking
</code>```

Body:
I have a matplotlib and I have created a button_press_event like this:

self.fig.canvas.mpl_connect('button_press_event', self.onClick)

def onClick(self, event)
    if event.button == 1:
        # draw some artists on left click

    elif event.button == 2:
        # draw a vertical line on the mouse x location on wheel click

    elif event.button == 3:
        # clear artists on right click

Now is it possible to modify the wheel click handler to something like this

    elif event.button == 2 or (event.button == 1 and event.key == "shift"):
        # draw a vertical line on the mouse x location
        # on wheel click or on shift+left click
        # (alternative way if there is no wheel for example)

It seems that button_press_event doesn't support keys and key_press_event doesn't support mouse button clicks, but I'm not sure.

Is there a way?

Body:
If you are on Qt then you can simply use:

def onClick(self, event)
    # queries the pressed modifier keys
    mods = QGuiApplication.queryKeyboardModifiers()
    if event.button == 1 and mods == Qt.ShiftModifier:
        # do something when shift-clicking

ContentLicense: CC BY-SA 4.0


问:
Intel Compiler 17 on Amd Ryzen
My dev environment is Visual Studio 2015 and Intel Compiler 17. I just switched on a new machine with an AMD Ryzen processor.

On my old Intel 3930K everything worked, but now, on this new machine, the Intel Compiler R17, even if is installed, is not present in the properties of my projects.

Properties of a project:

Does anyone know anything about this?

答:
I think you should think about switching compilers if you do not use any low-level Intel compiler features.

Try http://developer.amd.com/x86-open64-compiler-suite/ instead?

Also take note of Intel's compiler notice https://software.intel.com/en-us/articles/optimization-notice#opt-en

Title: Intel Compiler 17 on Amd Ryzen


问:
How to use embeded spark with existing SnappyData
I have used snappy-sql and there I created some tables and did some inserts and queries... everything ok

Then, as I need to import a lot of data from csv file I created a scala script that read each of the files and extract the data and tries to insert into the database

For this I am using the spark that comes with snappydata, I connect using

./bin/spark-shell --conf spark.snappydata.store.sys-disk-dir=snappydatadir --conf spark.snappydata.store.log-file=snappydatadir/quickstart.log

The directory exists and everything "runs" "ok"... (not quite true)

Here is the problem... when I try to do queries over the tables I created in snappy-sql... the spark-shell tells me that the tables do not exist... and when the script gets to the insert command happens the same

So my question, as I am a newbi...

How do I connect to that spark-shell (snappydir/bin/spark-shell...) and use the tables that already exists in snappydata??

I bet I am nod adding some specific configuration...

Thanks for the help... as I said... I am less than basic in snappydata and spark so I am feeling a little lost trying to configure and set-up my environment...

答:
To import CSV data into SnappyData you can create an external tables and use 'insert into' command to import the data. You don't have to have to use spark-shell, just use snappy-sql shell. For example:

-- this assumes locator is running on the localhost
snappy> connect client 'localhost:1527';
-- create an external table
snappy> CREATE EXTERNAL TABLE table1_staging (col1 int, col2 int, col3 string) USING csv OPTIONS (path ‘path_to_csv_file’);
--import data into table1
snappy>insert into table1 select * from table1_staging;

path_to_csv_file should be available on all servers. Refer to how-to section in docs for other ways to import data.

To use spark-shell, make use of property snappydata.connection to connect to SnappyData cluster. The value of this property would be of the form 'locatorHost:clientConnectionPort' (default client connection port is 1527)

For example:

bin/spark-shell  --master local[*] --conf spark.snappydata.connection=localhost:1527 --conf spark.ui.port=4041

Refer to the documentation for more details about how to connect using spark-shell.


问:
Angular ng build -prod error: Supplied parameters do not match any signature of call target
When I run ng build --target=production I get the following error:

ERROR in
  C:/Repo/NewCo/src/$$_gendir/app/fu/bar/fubar.component.ngfactory.ts
  (4011,35): Supplied parameters do not match any signature of call
  target.

I don't even know where to start with this...It would be useful if ng build gave me a little more insight into:

Which supplied parameters

Which call target

Which line number

Exactly where this error is occurring

Can anyone explain how I can identify any of the above?

答:
You are probably calling a method from your template which shouldn't (or should) have parameters.

Something like this:

*ngIf="shouldShow()"

shouldShow(show: boolean){//do some}

As you can see these the supplied parameters do not match any signature of call target.


问:
Is HIPE with RabbitMQ production ready?
does anyone enabled HIPE on RabbitMQ on production servers, if yes, did you face any problems beside the Rabbimq start-up time ,</p>

答:
About HIPE there are different opinions, someone uses HIPE without problems, but I'd be careful with it.

My suggestion is to test a lot in your environment before put it in production (Especially for mission critical applications).

You should use Erlang versions >= 19.2 because of (https://bugs.erlang.org/browse/ERL-205).

RabbitMQ can be tuned in different ways, and I'd start form there.

Title: Is HIPE with RabbitMQ production ready?


问:
textbox isReadonly to change with combobox selecteditem
I have datatemplate and list of 5 rows. So in every row, there is combobox with two comboboxitems "yes" and "no". So when the window is loaded, textboxes inside ListBox rows are set to readonly="True" inside the Datatemplate. But when I select "no" from combobox items in individual row, then textbox should become editable and isReadonly="False" for each individual row in the List. My ListBox items are 5. How to do this?</p>

```<code>//xaml
 <ListBox x:Name="wbListDataTemplate"
                                  ItemsSource="{Binding wbVisibleItems}"
                                  DataContext="{DynamicResource wbItem}"
                                  Background="{x:Null}"
                                 SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=Default}"
                                 IsSynchronizedWithCurrentItem="True" Canvas.Top="33"  Height="152" Width="628" LostFocus="wbListDataTemplate_LostFocus" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Initialized="wbListDataTemplate_Initialized_1">

                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="39" Width="642" Margin="0,0,0,-14" >
                                        <Grid x:Name="Grid1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >

                                            <Label Margin="0,3,0,5" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"/>

                                            <ComboBox x:Name="wbselect" Margin="0,0,60,1" Grid.Column="0"  Grid.ColumnSpan="2" Grid.Row="0" Loaded="wbselect_Loaded" >
                                                <ComboBoxItem x:Name="wbyes" IsSelected="True" Content="yes"></ComboBoxItem>
                                                <ComboBoxItem x:Name="wbno" Content="no"></ComboBoxItem>
                                            </ComboBox>
                                            <TextBox x:Name="wbdepth" Text="" MaxLength="20" Margin="217,0,230,1" LostKeyboardFocus="wbdepth_LostKeyboardFocus" Grid.ColumnSpan="2" IsReadOnly="True"/>

                                        </Grid>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
</code>```

答:
Although I would recommend against using a ComboBox for this purpose (and prefer to use a CheckBox or ToggleButton), you may use a DataTrigger on the SelectedIndex property of the ComboBox in a TextBox Style:

```<code><DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="cb" SelectedIndex="0">
            <ComboBoxItem>Yes</ComboBoxItem>
            <ComboBoxItem>No</ComboBoxItem>
        </ComboBox>
        <TextBox Grid.Column="1">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedIndex, ElementName=cb}"
                                     Value="0">
                            <Setter Property="IsReadOnly" Value="True"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>
</DataTemplate>
</code>```

Body:
I have datatemplate and list of 5 rows. So in every row, there is combobox with two comboboxitems "yes" and "no". So when the window is loaded, textboxes inside ListBox rows are set to readonly="True" inside the Datatemplate. But when I select "no" from combobox items in individual row, then textbox should become editable and isReadonly="False" for each individual row in the List. My ListBox items are 5. How to do this?

//xaml
 <ListBox x:Name="wbListDataTemplate"
                                  ItemsSource="{Binding wbVisibleItems}"
                                  DataContext="{DynamicResource wbItem}"
                                  Background="{x:Null}"
                                 SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=Default}"
                                 IsSynchronizedWithCurrentItem="True" Canvas.Top="33"  Height="152" Width="628" LostFocus="wbListDataTemplate_LostFocus" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Initialized="wbListDataTemplate_Initialized_1">

                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="39" Width="642" Margin="0,0,0,-14" >
                                        <Grid x:Name="Grid1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >

                                            <ComboBox x:Name="wbselect" Margin="0,0,60,1" Grid.Column="0"  Grid.ColumnSpan="2" Grid.Row="0" Loaded="wbselect_Loaded" >
                                                <ComboBoxItem x:Name="wbyes" IsSelected="True" Content="yes"></ComboBoxItem>
                                                <ComboBoxItem x:Name="wbno" Content="no"></ComboBoxItem>
                                            </ComboBox>
                                            <TextBox x:Name="wbdepth" Text="" MaxLength="20" Margin="217,0,230,1" LostKeyboardFocus="wbdepth_LostKeyboardFocus" Grid.ColumnSpan="2" IsReadOnly="True"/>

                                        </Grid>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

Body:
Although I would recommend against using a ComboBox for this purpose (and prefer to use a CheckBox or ToggleButton), you may use a DataTrigger on the SelectedIndex property of the ComboBox in a TextBox Style:

<DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="cb" SelectedIndex="0">
            <ComboBoxItem>Yes</ComboBoxItem>
            <ComboBoxItem>No</ComboBoxItem>
        </ComboBox>
        <TextBox Grid.Column="1">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedIndex, ElementName=cb}"
                                     Value="0">
                            <Setter Property="IsReadOnly" Value="True"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>
</DataTemplate>


问:
Java String quote delimiter
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

```<code>String s = "Quote marks like this \" are just the best, here are a few more \" \" \""
</code>```

答: No, there is no such option. Sorry.</p>

Title: Java String quote delimiter

Body:
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

String s = "Quote marks like this \" are just the best, here are a few more \" \" \""

Body: No, there is no such option. Sorry.


问:
Read the table data from the PDF file and save in the MySQL database as it is
I have a requirement to read the value form a PDF file and save the result in a db.
I have converted Pdf to text .
Now the  text data looks like this:

      Test Name         Results    Units Bio. Ref. Interval

LIPID PROFILE, BASIC, SERUM

    Cholesterol Total   166.00      mg/dL        <200.00
    Triglycerides       118.00      mg/dL        <150.00 ```

My requirement is to read the table data from the Pdf file  and save in the MySQL database as it is.

答: use java io to read the text file and jdbc to safe the information in the mysql via sql. </p>

Body:
I have a requirement to read the value form a PDF file and save the result in a db.
I have converted Pdf to text .
Now the  text data looks like this:

      Test Name         Results    Units Bio. Ref. Interval

LIPID PROFILE, BASIC, SERUM

    Cholesterol Total   166.00      mg/dL        <200.00
    Triglycerides       118.00      mg/dL        <150.00

My requirement is to read the table data from the Pdf file  and save in the MySQL database as it is.


问:
Openlayers 4.11 : no style applied when programatically selecting a feature
I'm using the accepted answer from here to programatically select a feature on my map.

All ok, except that my custom select style is not applied (the element looks just like before).

I'm using this code to setup my Select interaction:

```<code>var selectSingleOrDoubleClick = new ol.interaction.Select({
    style: this.selectCustomStyle,
    condition: function(mapBrowserEvent) {
        return ol.events.condition.singleClick(mapBrowserEvent) || ol.events.condition.doubleClick(mapBrowserEvent);
    },
    filter: function(feature, layer) {
        ...
    }
});
</code>```

I'm doing this in order to programmatically select my feature:

```<code>selectSingleOrDoubleClick.getFeatures().clear();
selectSingleOrDoubleClick.getFeatures().push(featureToSelect);

selectControl.dispatchEvent({
    type: 'select',
    selected: [featureToSelect],
    deselected: []
});
</code>```

I should not that my feature IS considered selected (for example if I select another feature via user interaction, my previously-selected feature becomes unselected, etc.

答:
Apparently, this is normal behavior in Openlayers, whenever the Features involved in your selection already have a non-default style applied.

So if you want to fix this, then you need to use select/unselect events to apply whatever style you need to have applied, and remove it as necessary.

Body:
I'm using the accepted answer from here to programatically select a feature on my map.

All ok, except that my custom select style is not applied (the element looks just like before).

I'm using this code to setup my Select interaction:

var selectSingleOrDoubleClick = new ol.interaction.Select({
    style: this.selectCustomStyle,
    condition: function(mapBrowserEvent) {
        return ol.events.condition.singleClick(mapBrowserEvent) || ol.events.condition.doubleClick(mapBrowserEvent);
    },
    filter: function(feature, layer) {
        ...
    }
});

I'm doing this in order to programmatically select my feature:

selectSingleOrDoubleClick.getFeatures().clear();
selectSingleOrDoubleClick.getFeatures().push(featureToSelect);

selectControl.dispatchEvent({
    type: 'select',
    selected: [featureToSelect],
    deselected: []
});

I should not that my feature IS considered selected (for example if I select another feature via user interaction, my previously-selected feature becomes unselected, etc.


问:
How to give styling for active tab of nav-tab
This is my HTML Code. I want css styling for active nav-tab.Now i want when my page loads Location tab should have blue background how can i get that

```<code><div class="row">
        <div class="col-sm-12 col-xs-12 col-lg-12 col-md-12 welcome">
            <ul class="nav navbar-nav navbar-nav-primary">
                <li class="active">
                    <a href="#one" data-toggle="tab">
                        <i class="fa fa-map-marker" aria-hidden="true"></i>
         <span class="li-text">Location</span>
                    </a>
                </li>
                <li>
                    <a href="#two" data-toggle="tab">
                        <i class="fa fa-heartbeat" aria-hidden="true"></i> <span class="li-text">Heartbeats</span>
                    </a>
                </li>
                <li>
                    <a href="#three" data-toggle="tab">
                        <i class="fa fa-power-off" aria-hidden="true"></i>
                        <span class="li-text">Reboots</span>
                    </a>
                </li>
                <li>
                    <a href="#four" data-toggle="tab">
                        <i class="fa fa-compress" aria-hidden="true"></i>
                        <span class="li-text">Reconnects</span>
                    </a>
                </li>
                <li>
                    <a href="#five" data-toggle="tab">
                        <i class="fa fa-battery-full" aria-hidden="true"></i>
                        <span class="li-text">Charge</span>
                    </a>
                </li>

            </ul>

        </div>
</code>```

Location tab is the active tab

```<code>         <div id="one" class="tab-pane active">

                <div class="row">
                    <div class="col-sm-offset-10 col-md-offset-10 col-xs-offset-10 col-lg-offset-10 col-sm-2 col-md-2 col-xs-2 col-lg-2 searchDiv">
                        <div class="row">
                            <div class="col-sm-1 col-xs-1 col-lg-1 col-md-1">
                                <i class="fa fa-search fa-2x" aria-hidden="true"></i>
                            </div>
                            <div class="col-sm-1 col-md-1 col-lg-1 col-xs-1">

                                <i class="fa fa-ellipsis-v fa-2x" aria-hidden="true"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane active" id="1a">
                    <div ui-grid="gridOptions" class="grid-table" ui-grid-auto-resize ui-grid-cellNav ui-grid-edit ui-grid-resize-columns ui-grid-pinning ng-style="getTableHeight()"></div>
                </div>
            </div>
</code>```

Now i want when my page loads Location tab should have blue background how can i get that.

答:
You can use it like this</p>

```<code>.tab-pane.active {
   background : blue; // or your desired color code.
}
</code>```

Body:
This is my HTML Code. I want css styling for active nav-tab.Now i want when my page loads Location tab should have blue background how can i get that

         Location

                         Heartbeats

                        Reboots

                        Reconnects

                        Charge

Location tab is the active tab

Now i want when my page loads Location tab should have blue background how can i get that.

Body:
You can use it like this

.tab-pane.active {
   background : blue; // or your desired color code.
}


问:
Stepped line with null values in chart.js
I have data: [10,5,null,10,5], and labels: [2010, 2011, 2012, 2013, 2014]

I'd like to draw a stepped line which has a gap between 2012 and 2013.
When I set steppedLine to true, it only drew a vertical line at 2011 but no horizontal line to connect 2011 and 2012, as the value of 2012 is null. If I set spanGaps to true, it will draw a line from 2011 to 2013 at value 5.

Basically what I'm looking for is to draw a line if the starting value is a number and the ending value is null, but not vice versa

JSFiddle

Related codes in controller:

```<code>    _this.lines = {};
    _this.lines.labels = [2010,2011,2012,2013,2014];
    _this.lines.data = [
        [10, 5, null, 10, 5]
    ];
    _this.lines.series = ['Now'];
    _this.lines.options = {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    parser: 'DD MMM YYYY'
                }
            }],
            yAxes: [{
                type: 'linear',
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    };
    _this.lines.datasetOverride = [{
        fill: false,
        spanGaps: true,
        steppedLine: true
        },
    ];
</code>```

HTML:

```<code><canvas class="chart chart-line" chart-labels="ctrl.lines.labels" chart-data="ctrl.lines.data" chart-options="ctrl.lines.options" chart-series="ctrl.lines.series" chart-dataset-override="ctrl.lines.datasetOverride" height="140" responsive=true></canvas>
</code>```

答:
This might not be exactly what you want but you can just add another point at 2012 with the same value as 2011 and then another data point at 2012 will null so it'll create a gap between 2012 and 2013, although it will create a point at 2012.

JSFiddle

```<code>_this.lines.labels = [2010,2011,2012,2012,2013,2014];
_this.lines.data = [
    [10, 5,5,null, 10, 5]
];
</code>```

This would be the only change to your current code

Body:
I have data: [10,5,null,10,5], and labels: [2010, 2011, 2012, 2013, 2014]

I'd like to draw a stepped line which has a gap between 2012 and 2013.
When I set steppedLine to true, it only drew a vertical line at 2011 but no horizontal line to connect 2011 and 2012, as the value of 2012 is null. If I set spanGaps to true, it will draw a line from 2011 to 2013 at value 5.

Basically what I'm looking for is to draw a line if the starting value is a number and the ending value is null, but not vice versa

JSFiddle

Related codes in controller:

    _this.lines = {};
    _this.lines.labels = [2010,2011,2012,2013,2014];
    _this.lines.data = [
        [10, 5, null, 10, 5]
    ];
    _this.lines.series = ['Now'];
    _this.lines.options = {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    parser: 'DD MMM YYYY'
                }
            }],
            yAxes: [{
                type: 'linear',
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    };
    _this.lines.datasetOverride = [{
        fill: false,
        spanGaps: true,
        steppedLine: true
        },
    ];

HTML:

<canvas class="chart chart-line" chart-labels="ctrl.lines.labels" chart-data="ctrl.lines.data" chart-options="ctrl.lines.options" chart-series="ctrl.lines.series" chart-dataset-override="ctrl.lines.datasetOverride" height="140" responsive=true></canvas>

Body:
This might not be exactly what you want but you can just add another point at 2012 with the same value as 2011 and then another data point at 2012 will null so it'll create a gap between 2012 and 2013, although it will create a point at 2012.

JSFiddle

_this.lines.labels = [2010,2011,2012,2012,2013,2014];
_this.lines.data = [
    [10, 5,5,null, 10, 5]
];

This would be the only change to your current code


问:
exception Convert ToInt32 dans c#
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.</p>

```<code>      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "<br>" + val;
            }
        }
        return Valreturn;
    }
</code>```

答:
is not valid format I corrected by this code and is working</p>

```<code>  val = ChaineTextArea.Substring(i, 1);
char []chars = val.ToCharArray();
result = Convert.ToInt32(chars[0]);
</code>```

Title: exception Convert ToInt32 dans c#

Body:
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.

      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "
" + val;
            }
        }
        return Valreturn;
    }

Body:
is not valid format I corrected by this code and is working

  val = ChaineTextArea.Substring(i, 1);
char []chars = val.ToCharArray();
result = Convert.ToInt32(chars[0]);


问:
What are BLPOP, BRPOP, and BRPOPLPUSH in Redis?
Was trying to study the metrics of Redis and came along these terms. Have no idea about them. Can someone please explain the terms in lay man words? </p>

答:
As Per REDIS Commands Documentation :

BLPOP

BLPOP is a blocking list pop primitive. It is the blocking
  version of LPOP because it blocks the connection when there are no
  elements to pop from any of the given lists. An element is popped from
  the head of the first list that is non-empty, with the given keys
  being checked in the order that they are given.

In Brief : See BLPOP

BRPOP

BRPOP is a blocking list pop primitive. It is the blocking
  version of RPOP because it blocks the connection when there are no
  elements to pop from any of the given lists. An element is popped from
  the tail of the first list that is non-empty, with the given keys
  being checked in the order that they are given.

In Brief : See BRPOP

BRPOPLPUSH

BRPOPLPUSH is the blocking variant of RPOPLPUSH. When source
  contains elements, this command behaves exactly like RPOPLPUSH. When
  used inside a MULTI/EXEC block, this command behaves exactly like
  RPOPLPUSH. When source is empty, Redis will block the connection until
  another client pushes to it or until timeout is reached. A timeout of
  zero can be used to block indefinitely.

In Brief : See BRPOPLPUSH


问:
bad content-type header, no multipart boundary nodejs
I have an API that returns content with content-type: "multipart/form-data; charset=utf-8". However, in my nodejs app, when I make the following call through superagent:

```<code>request
    .get(ApiUrl + id)
    .set('Authorization', basicHttpAuth)
    .set('client_id', clientId)
    .set('client_secret', clientSecret)
    .end(function (err, res) {
        if (err) {
            callback(null, err)
            console.log(err);
        }
        else {
            callback(null, res);
        }
    })
</code>```

I get this error:

Error: bad content-type header, no multipart boundary

Any idea what's wrong?

Stack Trace:

```<code>Error: bad content-type header, no multipart boundary
    at IncomingForm._parseContentType (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:271:19)
    at IncomingForm.writeHeaders (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:142:8)
    at IncomingForm.parse (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:110:8)
    at ClientRequest.<anonymous> (/Users/mike/Svr/Server/node_modules/superagent/lib/node/index.js:869:9)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:115:13)
    at ClientRequest.emit (events.js:210:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:564:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
    at TLSSocket.socketOnData (_http_client.js:453:20) response: undefined }
</code>```

Here is the server response header:

```<code>Access-Control-Allow-Origin →*
Connection →keep-alive
Content-Length →44691
Content-Type →multipart/form-data; charset=utf-8
Date →Wed, 05 Jul 2017 03:44:23 GMT
</code>```

And the body is big blob of text / string.

答:
According to RFC2045:

...while the "boundary" parameter is required for any subtype of the "multipart" media type.

In your case, the server doesn't set that parameter, so the response is invalid and superagent (which tries to parse the response) throws an error.

You may be able to use an alternative HTTP client, provided that it doesn't try to parse multipart/form-data responses.

You could use the built-in http(s).get(), or perhaps the request package.

EDIT: if you're stuck with superagent, then you may be able to monkeypatch it so it will detect the broken response and treat it as text/plain.

Add the following somewhere "high up" in your code (before using superagent):

```<code>const Utils     = require('superagent/lib/utils');
const UtilsType = Utils.type;
Utils.type = function(type) {
  if (type === 'multipart/form-data; charset=utf-8') {
    type = 'text/plain; charset=utf-8';
  }
  return UtilsType.call(this, type);
};
</code>```

Body:
I have an API that returns content with content-type: "multipart/form-data; charset=utf-8". However, in my nodejs app, when I make the following call through superagent:

request
    .get(ApiUrl + id)
    .set('Authorization', basicHttpAuth)
    .set('client_id', clientId)
    .set('client_secret', clientSecret)
    .end(function (err, res) {
        if (err) {
            callback(null, err)
            console.log(err);
        }
        else {
            callback(null, res);
        }
    })

I get this error:

Error: bad content-type header, no multipart boundary

Any idea what's wrong?

Stack Trace:

Error: bad content-type header, no multipart boundary
    at IncomingForm._parseContentType (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:271:19)
    at IncomingForm.writeHeaders (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:142:8)
    at IncomingForm.parse (/Users/mike/Svr/Server/node_modules/formidable/lib/incoming_form.js:110:8)
    at ClientRequest.<anonymous> (/Users/mike/Svr/Server/node_modules/superagent/lib/node/index.js:869:9)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:115:13)
    at ClientRequest.emit (events.js:210:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:564:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
    at TLSSocket.socketOnData (_http_client.js:453:20) response: undefined }

Here is the server response header:

Access-Control-Allow-Origin →*
Connection →keep-alive
Content-Length →44691
Content-Type →multipart/form-data; charset=utf-8
Date →Wed, 05 Jul 2017 03:44:23 GMT

And the body is big blob of text / string.

Body:
According to RFC2045:

...while the "boundary" parameter is required for any subtype of the "multipart" media type.

In your case, the server doesn't set that parameter, so the response is invalid and superagent (which tries to parse the response) throws an error.

You may be able to use an alternative HTTP client, provided that it doesn't try to parse multipart/form-data responses.

You could use the built-in http(s).get(), or perhaps the request package.

EDIT: if you're stuck with superagent, then you may be able to monkeypatch it so it will detect the broken response and treat it as text/plain.

Add the following somewhere "high up" in your code (before using superagent):

const Utils     = require('superagent/lib/utils');
const UtilsType = Utils.type;
Utils.type = function(type) {
  if (type === 'multipart/form-data; charset=utf-8') {
    type = 'text/plain; charset=utf-8';
  }
  return UtilsType.call(this, type);
};


问:
why do we even need VPTR?
And why don't we use the same method for non virtual functions?

I mean, why do we use virtual functions in that way? Can't we just use them as non-virtaul ones and override them?

And if this method is saving us time/space or what ever, why don't we use the same method for non-virtual functions? I mean it would make sense that there would be one table of functions for a specific class.

Anyway, thanks in advance, I am just a bit confused.

答: The compiler essentially generates a direct call to non-virtual methods.  With a virtual method call, the compiler generates code to lookup the address of the method and then makes a call to that address.  Thus, it is, in theory, at least one more lookup when calling a virtual function.  There would be no reason to incur that cost otherwise.</p>

Title: why do we even need VPTR?


问:
Query which can round to the previous 30minutes interval
I am querying database to get the results during 30minutes interval

1) Suppose if i am querying at 11:05am i should get the data from 10:30AM to 11:00AM
2) If I am querying at 11:35 I should get the data from 11:00AM TO 11;30AM.

In short I am looking for a query which can round to the previous 30minutes interval.

答:
Find the difference between the SYSDATE and the SYSDATE truncated to the start of the hour; if it is greater than 30 minutes (1/48th of a day) then the start of the range is the SYSDATE truncated to the nearest hour otherwise it is the SYSDATE truncated to the nearest hour minus 30 minutes. The end of the range is just 30 minutes later.

```<code>SELECT *
FROM   your_table
WHERE  date_column >= TRUNC( SYSDATE, 'HH24' )
                      - CASE WHEN SYSDATE - TRUNC( SYSDATE, 'HH24' ) >= 1/48
                             THEN 0
                             ELSE 1/48 END
AND    date_column <  TRUNC( SYSDATE, 'HH24' )
                      + CASE WHEN SYSDATE - TRUNC( SYSDATE, 'HH24' ) >= 1/48
                             THEN 1/48
                             ELSE 0 END;
</code>```

Body:
Find the difference between the SYSDATE and the SYSDATE truncated to the start of the hour; if it is greater than 30 minutes (1/48th of a day) then the start of the range is the SYSDATE truncated to the nearest hour otherwise it is the SYSDATE truncated to the nearest hour minus 30 minutes. The end of the range is just 30 minutes later.

SELECT *
FROM   your_table
WHERE  date_column >= TRUNC( SYSDATE, 'HH24' )
                      - CASE WHEN SYSDATE - TRUNC( SYSDATE, 'HH24' ) >= 1/48
                             THEN 0
                             ELSE 1/48 END
AND    date_column <  TRUNC( SYSDATE, 'HH24' )
                      + CASE WHEN SYSDATE - TRUNC( SYSDATE, 'HH24' ) >= 1/48
                             THEN 1/48
                             ELSE 0 END;


问:
How to debug Laravel error 500 with no logs, no information
I'm working on an existing Laravel application in order to develop new feature but after installing the app on my computer, I have an error 500 and no clue to resolve it.

In my app.php file I have set :

```<code>'env' => env('APP_ENV', 'local'),
'debug' => env('APP_DEBUG', true),
</code>```

But still I have no information, no logs are generated in storage/logs . I have no idea of what could be the problem.

The previous developer was on windows and I'm working on Linux but I'm not sure this is revelant.

EDIT:

I also have those variable in my config/app.php

```<code>'log' => env('APP_LOG', 'daily'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),
</code>```

答: Next to looking into your .env file, make sure permissions are correctly set (and good practice to create the storage/logs folder(s) manually - at least on windows that causes problems).

Body:
I'm working on an existing Laravel application in order to develop new feature but after installing the app on my computer, I have an error 500 and no clue to resolve it.

In my app.php file I have set :

'env' => env('APP_ENV', 'local'),
'debug' => env('APP_DEBUG', true),

But still I have no information, no logs are generated in storage/logs . I have no idea of what could be the problem.

The previous developer was on windows and I'm working on Linux but I'm not sure this is revelant.

EDIT:

I also have those variable in my config/app.php

'log' => env('APP_LOG', 'daily'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),


问:
Regex - everything except string
I would like to replace every char that is not a string for a given char like | or ; or whatever.
I have simple regex patern: ([a-zA-Z])\w+

...and the problem is to replace everything except matches of that pattern.

Example: qwerty 123456 ;,.'[]?/ asd

Result: qwerty|||||||||||||||||asd

Thanks in advance.

答:
You can filter/match/replace in two Ways

First Variant:

```<code>[a-z0-9] // filter/match/replace everything that is included in the defined Character set
</code>```

Second Variant:

```<code>[^a-z0-9] // filter/match/replace everything that is NOT included in the defined Character set
</code>```

As you see, the only Difference is the ^. ^ is the negation Operator within a Character Set.

Title: Regex - everything except string

Body:
You can filter/match/replace in two Ways

First Variant:

[a-z0-9] // filter/match/replace everything that is included in the defined Character set

Second Variant:

[^a-z0-9] // filter/match/replace everything that is NOT included in the defined Character set

As you see, the only Difference is the ^. ^ is the negation Operator within a Character Set.


问:
Can I loop on a method?
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

```<code>Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}
</code>```

Or is it better to assign a variable to that result and loop on the variable?

答:
You can do this, but be aware that if the method call returns a null reference rather than an empty IEnumerable you will get a System.NullReferenceException when you try to iterate it.

Storing the method call result in a variable instead would not in itself solve this problem, but would give you a chance to check for null before performing the foreach loop.

Title: Can I loop on a method?

Body:
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}

Or is it better to assign a variable to that result and loop on the variable?


问:
Select next row based on current row field within one query
Let's say the table contains a list of waypoints.

```<code> id | nextID
----+--------
  1 |      2
  2 |      4
  3 |      5
  4 |      1
  5 |      0
</code>```

Based on this table we have two pathes

Circular (1 - 2 - 4 - 1)

Linear (3 - 5)

How do I query the table to get these results:

```<code>      When starting ID = 1
 id | nextID
----+--------
  1 |      2
  2 |      4
  4 |      1

      When starting ID = 3
 id | nextID
----+--------
  3 |      5
  5 |      0
</code>```

答:
For the linear problem, you can do this. Note that I've used NULL instead of 0 for orphans...</p>

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT PRIMARY KEY
,nextID INT NULL
);

INSERT INTO my_table VALUES
(1,2),
(2,4),
(3,5),
(4,1),
(5,NULL);

SELECT CONCAT_WS(',',a.id,b.id,c.id) path
  FROM my_table a
  LEFT
  JOIN my_table b
    ON b.nextID = a.id
  LEFT
  JOIN my_table c
    ON c.nextID = b.id
 WHERE a.nextID IS NULL;
+------+
| path |
+------+
| 5,3  |
+------+
</code>```

Body:
Let's say the table contains a list of waypoints.

 id | nextID
----+--------
  1 |      2
  2 |      4
  3 |      5
  4 |      1
  5 |      0

Based on this table we have two pathes

Circular (1 - 2 - 4 - 1)

Linear (3 - 5)

How do I query the table to get these results:

      When starting ID = 1
 id | nextID
----+--------
  1 |      2
  2 |      4
  4 |      1

      When starting ID = 3
 id | nextID
----+--------
  3 |      5
  5 |      0

Body:
For the linear problem, you can do this. Note that I've used NULL instead of 0 for orphans...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT PRIMARY KEY
,nextID INT NULL
);

INSERT INTO my_table VALUES
(1,2),
(2,4),
(3,5),
(4,1),
(5,NULL);

SELECT CONCAT_WS(',',a.id,b.id,c.id) path
  FROM my_table a
  LEFT
  JOIN my_table b
    ON b.nextID = a.id
  LEFT
  JOIN my_table c
    ON c.nextID = b.id
 WHERE a.nextID IS NULL;
+------+
| path |
+------+
| 5,3  |
+------+


问:
Get Class Type of inherited object?
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

```<code>public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}
</code>```

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC

答:
```<code>using System;

class MyClass
{
}

class MyClass2: MyClass
{
}
namespace Appl
{
   class Program
   {
      static void Main(string[] args)
      {
         System.Console.WriteLine(typeof(MyClass2).BaseType.Name);
      }
   }
}
</code>```

Title: Get Class Type of inherited object?

Body:
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC


问:
Installation of Torch not working
I have installed Torch by following the instructions here, which comes with Lua 5.1, but Lua 5.3 was installed previously on my system. Now when I try to run a program using Torch, I get the following error messages:

```<code>/Users/Marcel/torch/install/share/lua/5.1/trepl/init.lua:389: module 'Settings.arguments' not found:No LuaRocks module found for Settings.arguments
    no field package.preload['Settings.arguments']

no file '/usr/local/share/lua/5.1/Settings/arguments.lua'
no file '/usr/local/share/lua/5.1/Settings/arguments/init.lua'
</code>```

It would seem as if Torch is looking for its own version of Lua in the system directories, which only contain the previously installed version. Is there any way to fix this, or must I uninstall the Lua 5.3?

Thanks!

答:
Simply change TORCH_LUA_VERSION value to LUAXX, as it is explain in installation instructions with 5.2 version. For 5.3 version, use LUA53:

```<code>git clone https://github.com/torch/distro.git ~/torch --recursive
cd ~/torch

# clean old torch installation
./clean.sh
# optional clean command (for older torch versions)
# curl -s https://raw.githubusercontent.com/torch/ezinstall/master/clean-old.sh | bash

# https://github.com/torch/distro : set env to use lua
TORCH_LUA_VERSION=LUA53 ./install.sh
</code>```

Title: Installation of Torch not working

Body:
I have installed Torch by following the instructions here, which comes with Lua 5.1, but Lua 5.3 was installed previously on my system. Now when I try to run a program using Torch, I get the following error messages:

/Users/Marcel/torch/install/share/lua/5.1/trepl/init.lua:389: module 'Settings.arguments' not found:No LuaRocks module found for Settings.arguments
    no field package.preload['Settings.arguments']

no file '/usr/local/share/lua/5.1/Settings/arguments.lua'
no file '/usr/local/share/lua/5.1/Settings/arguments/init.lua'

It would seem as if Torch is looking for its own version of Lua in the system directories, which only contain the previously installed version. Is there any way to fix this, or must I uninstall the Lua 5.3?

Thanks!

Body:
Simply change TORCH_LUA_VERSION value to LUAXX, as it is explain in installation instructions with 5.2 version. For 5.3 version, use LUA53:

git clone https://github.com/torch/distro.git ~/torch --recursive
cd ~/torch

# clean old torch installation
./clean.sh
# optional clean command (for older torch versions)
# curl -s https://raw.githubusercontent.com/torch/ezinstall/master/clean-old.sh | bash

# https://github.com/torch/distro : set env to use lua
TORCH_LUA_VERSION=LUA53 ./install.sh