问:
Redirect user based on their type
I am trying to make a login page in which there are 3 types of users: student, staff, admin and once they login they get redirected to their specific activities. The users would be stored in a field in the DB which will be called user_type. What do I need to add in order to make this work?

Login.php

```<code><?php

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

$response = array("error" => FALSE);

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

    $email = $_POST['email'];
    $password = $_POST['password'];

    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {

        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {

        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response);
    }
} else {

    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>
</code>```

DB_Functions.php

```<code><?php

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // conectare BD
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // incriptare parola
        $salt = $hash["salt"]; // salt

        $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
        $result = $stmt->execute();
        $stmt->close();

        // verifica stocarea cu succes
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }

    public function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            // verifica parola
            $salt = $user['salt'];
            $encrypted_password = $user['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);

            if ($encrypted_password == $hash) {
                // informatiile scrise sunt corecte
                return $user;
            }
        } else {
            return NULL;
        }
    }

    /**
     * Verifica daca user exista
     */
    public function isUserExisted($email) {
        $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user exista
            $stmt->close();
            return true;
        } else {
            // user nu exista
            $stmt->close();
            return false;
        }
    }

    /**
     * Incriptare parola
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decriptare parola

     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>
</code>```

LoginActivity.java

```<code>public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // 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");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // 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();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}
</code>```

答:
Do as @litelite said, and add a return with the type of the user. WHat you can return is an integer, with 0-x where x is the amount of login-types(student, teacher, admin, etc).

AFter you have returned the logintype, you have some options:

Intent.putExtra(or Bundle)

In this code:

```<code>    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
</code>```

before starting the activity, add:

```<code>intent.putExtra("usertype", userType);
</code>```

And in the receiving activity, add:

```<code>int userType = getIntent().getIntExtra("usertype", -1);//-1 is the default. If you use -1 for something, change it to any other number
</code>```

If you aren't familiar with get and putExtra, when using getExtra the last input is a default value. Meaning if it cannot be found, throw a new exception or redirect back to the login screen, whatever you feel like.

Multiple activities

This is different from above, as the above method assumes there is one activity where things are handled. FOr this method, you create one activity per login-type, and in the login activity you create an intent where you redirect to the appropriate class. You find the appropriate class by the integer input received from the login script.

static fields

You can add a static field in MainActivity to receive the integer from the login-script. Something to note is that you have to set it to -1 as default to make sure you receive input.

How you get the user type is up to you. You can access it from the database or return it from the PHP method.

To get data into Java from the PHP script

Apparently, you cannot just return the integer from a method. Using Volley makes it not that easy, as it isn't plain PHP or plain Java.

I was not aware you were using volley, and as I do not know how to use Volley, I will point you in the right direction.

You already use JSON to get data from the script. When you add data into the JSON object, add the integer with the user type. Then retrieve it, add it to the class(as a local variable, just save it so it can be used elsewhere later. If it is in the same method, you put it in the method, if not in the class).

Now that you have retrieved the integer, it may be in the form of a String. So you have to convert it from a string to integer by doing usertype = Integer.parseInt(stringInt). Now you can go and do one of the three steps I described earlier in the post. This will allow you to make sure the different users get a different experience(admins get access to what they need and students what they need)

Title: Redirect user based on their type

Body:
I am trying to make a login page in which there are 3 types of users: student, staff, admin and once they login they get redirected to their specific activities. The users would be stored in a field in the DB which will be called user_type. What do I need to add in order to make this work?

Login.php

<?php

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

$response = array("error" => FALSE);

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

    $email = $_POST['email'];
    $password = $_POST['password'];

    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {

        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {

        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response);
    }
} else {

    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>

DB_Functions.php

<?php

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // conectare BD
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // incriptare parola
        $salt = $hash["salt"]; // salt

        $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
        $result = $stmt->execute();
        $stmt->close();

        // verifica stocarea cu succes
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }

    public function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            // verifica parola
            $salt = $user['salt'];
            $encrypted_password = $user['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);

            if ($encrypted_password == $hash) {
                // informatiile scrise sunt corecte
                return $user;
            }
        } else {
            return NULL;
        }
    }

    /**
     * Verifica daca user exista
     */
    public function isUserExisted($email) {
        $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user exista
            $stmt->close();
            return true;
        } else {
            // user nu exista
            $stmt->close();
            return false;
        }
    }

    /**
     * Incriptare parola
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decriptare parola

     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>

LoginActivity.java

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // 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");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // 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();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Body:
Do as @litelite said, and add a return with the type of the user. WHat you can return is an integer, with 0-x where x is the amount of login-types(student, teacher, admin, etc).

AFter you have returned the logintype, you have some options:

Intent.putExtra(or Bundle)

In this code:

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

before starting the activity, add:

intent.putExtra("usertype", userType);

And in the receiving activity, add:

int userType = getIntent().getIntExtra("usertype", -1);//-1 is the default. If you use -1 for something, change it to any other number

If you aren't familiar with get and putExtra, when using getExtra the last input is a default value. Meaning if it cannot be found, throw a new exception or redirect back to the login screen, whatever you feel like.

Multiple activities

This is different from above, as the above method assumes there is one activity where things are handled. FOr this method, you create one activity per login-type, and in the login activity you create an intent where you redirect to the appropriate class. You find the appropriate class by the integer input received from the login script.

static fields

You can add a static field in MainActivity to receive the integer from the login-script. Something to note is that you have to set it to -1 as default to make sure you receive input.

How you get the user type is up to you. You can access it from the database or return it from the PHP method.

To get data into Java from the PHP script

Apparently, you cannot just return the integer from a method. Using Volley makes it not that easy, as it isn't plain PHP or plain Java.

I was not aware you were using volley, and as I do not know how to use Volley, I will point you in the right direction.

You already use JSON to get data from the script. When you add data into the JSON object, add the integer with the user type. Then retrieve it, add it to the class(as a local variable, just save it so it can be used elsewhere later. If it is in the same method, you put it in the method, if not in the class).

Now that you have retrieved the integer, it may be in the form of a String. So you have to convert it from a string to integer by doing usertype = Integer.parseInt(stringInt). Now you can go and do one of the three steps I described earlier in the post. This will allow you to make sure the different users get a different experience(admins get access to what they need and students what they need)


来源: stackexchange

问:
Karma [Jasmine] - how to separate code from test cases
Is there a standard way to separate code from tests by using Jasmine?

== functions.js

```<code>function sample() {
    return true;
}
</code>```

== functions.spec.js

```<code>describe('functions', function () {

    it('sample', function () {
        expect(sample()).toEqual(true);
    });

});
</code>```

== karma.config.js

```<code>module.exports = function (config) {
    config.set({
        basePath: __dirname + '/../public/',
        frameworks: [
            'jasmine'
        ],
        browsers : ['PhantomJS'],
        client: {
            jasmine: {
                stopOnFailure: true
            }
        },
        files: [
            'js/**/*.spec.js'
        ]
    });
};
</code>```

Thanks in advance!

I was trying to use 'browserify' without success:

== karma.config.js

```<code>browserify: {
        debug: true,
        plugin: ['proxyquireify/plugin'],
        extensions: ['.js']
    },
    preprocessors: {
        'js/**/*.spec.js': ['browserify']
    }
</code>```

== functions.spec.js

```<code>var source = require('./functions.js');
...
expect(source.sample()).toEqual(true);
</code>```

答:
A small change in the original file helps:

== functions.js

```<code>this.sample = function() {
    return true;
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a standard way to separate code from tests by using Jasmine?

== functions.js

function sample() {
    return true;
}

== functions.spec.js

describe('functions', function () {

    it('sample', function () {
        expect(sample()).toEqual(true);
    });

});

== karma.config.js

module.exports = function (config) {
    config.set({
        basePath: __dirname + '/../public/',
        frameworks: [
            'jasmine'
        ],
        browsers : ['PhantomJS'],
        client: {
            jasmine: {
                stopOnFailure: true
            }
        },
        files: [
            'js/**/*.spec.js'
        ]
    });
};

Thanks in advance!

I was trying to use 'browserify' without success:

== karma.config.js

browserify: {
        debug: true,
        plugin: ['proxyquireify/plugin'],
        extensions: ['.js']
    },
    preprocessors: {
        'js/**/*.spec.js': ['browserify']
    }

== functions.spec.js

var source = require('./functions.js');
...
expect(source.sample()).toEqual(true);

Body:
A small change in the original file helps:

== functions.js

this.sample = function() {
    return true;
};


问:
Order in draggable
This example : https://jqueryui.com/sortable/

```<code><ul id="sortable" ng-repeat="x in getTime(3)">
  <li class="ui-state-default">
   <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
   Item {{$index}} and order : ¿ {{order}} ?
  </li>
</ul>
</code>```

This generate :

```<code><li> item 1 and order 1 </li>
<li> item 2 and order 2 </li>
<li> item 3 and order 3 </li>
</code>```

But if i change the third
 at first, i would  Item 3 and order 1, i need update order in
 all

```<code><li> item 3 and order 1 </li>
<li> item 1 and order 2 </li>
<li> item 2 and order 3 </li>
</code>```

Any suggestion?

答:
you need to give set track by index in your ng-reapeat feild. if you add following code and try again.</p>

```<code><ul id="sortable" ng-repeat="x in listValue track by $index"">
  <li class="ui-state-default">
   <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
   Item {{$index}} and order : ¿ {{order}} ?
  </li>
</ul>
</code>```

Title: Order in draggable

Body:
This example : https://jqueryui.com/sortable/

   Item {{$index}} and order : ¿ {{order}} ?

This generate :

 item 1 and order 1

 item 2 and order 2

 item 3 and order 3

But if i change the third
 at first, i would  Item 3 and order 1, i need update order in
 all

 item 3 and order 1

 item 1 and order 2

 item 2 and order 3

Any suggestion?

Body:
you need to give set track by index in your ng-reapeat feild. if you add following code and try again.

<ul id="sortable" ng-repeat="x in listValue track by $index"">
  <li class="ui-state-default">
   <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
   Item {{$index}} and order : ¿ {{order}} ?
  </li>
</ul>


问:
Converting date in excel
I need to convert the below date format in excel.

Currently I have: Fri Jan 06 05:10:31 2017

Current Format : ddd MMM dd hh:mm:ss yyyy

I wanted to be in the following format: dd/mm/yyyy hh:mm:ss

答:
You need to remove the day from the string, convert it to a number then format the way you want.

To do the first two steps use this formula:

```<code>=--MID(A1,5,LEN(A1))
</code>```

The third is a custom format:

As per the comment:

Title: Converting date in excel

Body:
You need to remove the day from the string, convert it to a number then format the way you want.

To do the first two steps use this formula:

=--MID(A1,5,LEN(A1))

The third is a custom format:

As per the comment:


问:
recommendations for runtime configuration of backend API url in Angular 2 application
This has been bugging me for a while and it seems that every other week, I come up with a different set of pros and cons.

The gist of it is that a good SPA is split into 2 different parts. The front-end and the back-end. The front-end should only be about static files (javascript, css, html, etc.) while the back-end serves the actual data and is dynamic.
However, the one piece that I always seem to want dynamic with the front-end is the back-end URL.

What I mean is that I usually serve my app off let's say http://server:123/ and my API from http://other:456/api. Frequently, other and server are the same and the ports change, but as we scale, this is not always the case.

So, my question is: what are the best practices for providing configuration data to an Angular 2 application?

Here is what I thought of already:

proxy

Most web servers, even the mostly static-content-oriented ones, offer some sort of proxy configuration (nginx, angular-cli serve, etc.).
The problem with the proxy is that the request does do a double-hop. It first must be sent to the static server and then that server must turn around and make the real request.
I am not a fan of this architecture, though I did use it in the past on other applications.

configuration file

This is currently my favorite. I pretty much serve a static file (let's say /config.json) off my static-content server which contains one or more URL or other non-sensitive information.
I like this approach because it allows you to use a proxy, or not. It's up to you.
Most of the time, it is pretty simple to configure your web server to return a static file based on a url (let's say /config).

code configuration

This is my least favorite. In this approach, the configuration is written directly into a code file (config.ts for example) and has to be changed for each environment. I consider code and configuration to be 2 different tasks and in most of the company I have worked with, they are handled by 2 different teams.
It would be silly to have to recompile your code and redeploy just to change your back-end URL.

答:
I used configuration files but prefer setting environment variables by DevOps tools.

With containers, for simpler configuration, I use environment variables. Otherwise I pass configuration of a back-end config store, like Redis or now a days Kube Secrets (easier to use).


问:
using jersey-json to map field names with spaces
I have a gson generated POST application/json request like this to work with:

```<code>{"Process Name": "Urlaubsantrag", "Action Performed EmailId": "somebody@somewhere.de", "Process Step": "Start"}
</code>```

I want to use jersey to map json data to my bean. Like

```<code>@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String createVacation(Vacation aVacation)
{
    //DO something
}
</code>```

Where the class Vacation represents my model

```<code>    public class Vacation {
    String processName;
    String actionPerformedEmailID;
    String processStep;
    String actionName;
etc...
</code>```

Problem is, that all field names in the json code have white spaces in them. I have problems finding correct field names in my model so "process name" will map to processName.

How would I do this? Or is there an other approach to deal with it?

答:
It's probably too late to answer this question, but today I faced the same problem (except it was underscore instead of space in a field name). I fixed this using XML binding annotations.

So, we need to annotate the Vacation class and its fields in this way

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Vacation {
@XmlElement(name = "Process Name")
String name;
@XmlElement(name = "Action Performed EmailId")
String actionPerformedEmailID;
@XmlElement(name = "Process Step")
String processStep;
String actionName;
</code>```

etc.

You can omit @XmlElement annotation, if the names of the JSON field and the POJO field are equal.

Body:
I have a gson generated POST application/json request like this to work with:

{"Process Name": "Urlaubsantrag", "Action Performed EmailId": "somebody@somewhere.de", "Process Step": "Start"}

I want to use jersey to map json data to my bean. Like

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String createVacation(Vacation aVacation)
{
    //DO something
}

Where the class Vacation represents my model

    public class Vacation {
    String processName;
    String actionPerformedEmailID;
    String processStep;
    String actionName;
etc...

Problem is, that all field names in the json code have white spaces in them. I have problems finding correct field names in my model so "process name" will map to processName.

How would I do this? Or is there an other approach to deal with it?

Body:
It's probably too late to answer this question, but today I faced the same problem (except it was underscore instead of space in a field name). I fixed this using XML binding annotations.

So, we need to annotate the Vacation class and its fields in this way

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Vacation {
@XmlElement(name = "Process Name")
String name;
@XmlElement(name = "Action Performed EmailId")
String actionPerformedEmailID;
@XmlElement(name = "Process Step")
String processStep;
String actionName;

etc.

You can omit @XmlElement annotation, if the names of the JSON field and the POJO field are equal.


问:
Cache (potentially) changing values from the database in java
What is the current recommended approach for storing cached data in Java

I am looking for a particular approach that will update the cache when an insert or an update happens to particular table(s).

Ideally this should happen as quickly as possible so as to avoid any issues when cross referencing data.

Is there a technology that provides this (such as ehcache) or an advised programming standard which i could follow.

Thanks

答:
If you have access to springframework in your application you can do something like this:

```<code>@Cacheable(value="yournamescache")
public List<String> getNames(){
     return yourDao.findAll();
}

@CacheEvict(value="yournamescache") //a value has changed so clear cache when this method executes
public void updateNames(x) {
    yourDao.update(x);

}
</code>```

Behind the scenes use Ehcache for example.

you can find more information here Spring cache abstraction

Body:
If you have access to springframework in your application you can do something like this:

@Cacheable(value="yournamescache")
public List<String> getNames(){
     return yourDao.findAll();
}

@CacheEvict(value="yournamescache") //a value has changed so clear cache when this method executes
public void updateNames(x) {
    yourDao.update(x);

}

Behind the scenes use Ehcache for example.

you can find more information here Spring cache abstraction


问:
plotly giving incorrect text on hover in stacked bar charts
I'm using plotly with RStudio.

plotly is giving incorrect text on hover for stacked bars in the chart except for the top most bar.

Reproducible example

```<code>  df <- data.frame(
    make = rep(c('Toyota', 'Honda', 'Volkswagen'),4),
    segment =c(rep('high',3), rep('mid',3), rep('low',3), rep('entry',3) ),
    sales=c( 25,35,75, 35,35,30, 45,25,10, 80, 80, 20)
  )

df
         make segment sales
1      Toyota    high    25
2       Honda    high    35
3  Volkswagen    high    75
4      Toyota     mid    35
5       Honda     mid    35
6  Volkswagen     mid    30
7      Toyota     low    45
8       Honda     low    25
9  Volkswagen     low    10
10     Toyota   entry    80
11      Honda   entry    80
12 Volkswagen   entry    20

  p <- ggplot(df, aes(x=make, y=sales) ) +
    geom_bar(stat="identity", aes(fill=segment), position = "stack")
  ggplotly(p)
</code>```

What I get in RStudio is as in the pictures below. As you would see except for the top stacked bar, everything else is giving the wrong text on hover

Incorrect text on hover - based on data in df the correct value for sales is 20 - instead it is showing 135 - data - 12 Volkswagen   entry    20

Correct text on hover - only observed for the top most bar in stack.

```<code>> packageVersion('ggplot2')
[1] ‘2.2.1’
> packageVersion('plotly')
[1] ‘4.5.6’
>
</code>```

答:
maybe you could try adding it with:

```<code>p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value", sales))) + geom_bar(stat="identity")
ggplotly(p)
</code>```

and if you want to show only sales, you can also use:

```<code>ggplotly(p, tooltip = c("text"))
</code>```

using Shiny:

```<code>library(shiny)
ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlotly({
p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value:", sales))) + geom_bar(stat="identity")
ggplotly(p, tooltip = c("text"))
  })
}

shinyApp(ui, server)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using plotly with RStudio.

plotly is giving incorrect text on hover for stacked bars in the chart except for the top most bar.

Reproducible example

  df <- data.frame(
    make = rep(c('Toyota', 'Honda', 'Volkswagen'),4),
    segment =c(rep('high',3), rep('mid',3), rep('low',3), rep('entry',3) ),
    sales=c( 25,35,75, 35,35,30, 45,25,10, 80, 80, 20)
  )

df
         make segment sales
1      Toyota    high    25
2       Honda    high    35
3  Volkswagen    high    75
4      Toyota     mid    35
5       Honda     mid    35
6  Volkswagen     mid    30
7      Toyota     low    45
8       Honda     low    25
9  Volkswagen     low    10
10     Toyota   entry    80
11      Honda   entry    80
12 Volkswagen   entry    20

  p <- ggplot(df, aes(x=make, y=sales) ) +
    geom_bar(stat="identity", aes(fill=segment), position = "stack")
  ggplotly(p)

What I get in RStudio is as in the pictures below. As you would see except for the top stacked bar, everything else is giving the wrong text on hover

Incorrect text on hover - based on data in df the correct value for sales is 20 - instead it is showing 135 - data - 12 Volkswagen   entry    20

Correct text on hover - only observed for the top most bar in stack.

> packageVersion('ggplot2')
[1] ‘2.2.1’
> packageVersion('plotly')
[1] ‘4.5.6’
>

Body:
maybe you could try adding it with:

p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value", sales))) + geom_bar(stat="identity")
ggplotly(p)

and if you want to show only sales, you can also use:

ggplotly(p, tooltip = c("text"))

using Shiny:

library(shiny)
ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlotly({
p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value:", sales))) + geom_bar(stat="identity")
ggplotly(p, tooltip = c("text"))
  })
}

shinyApp(ui, server)


问:
Having URL without .aspx extensionStrange behavior with Facebook Multi Friend Selector
I bought and implemented this from Vatlab:
- http://demo.faceconn.net/InviteFriends.aspx

If you go here and click "SKIP" button on the top right, it works:
- http://www.leapup.com.au/invite.aspx

On the other hand if you go here and click "SKIP", it throws an error page:
- http://www.uniquevolve.com/Webform1.aspx

There is not a lot of difference between the two except for the AppID, APIKey, Secret, AppName and AppCanvasUrl. So I'm inclined to think that Vatlab's code is buggy.. even he has no clue how to fix it.

Do you know a good ASP .Net implementation of Facebook Multi Friend Selector?

Thank you.

答:
I strongly DISCOURAGE anyone to buy from Vatlab. There is no 30-days money back guarantee and the support lasts for 6 months only. Also it did not work for me as the code was buggy. It tries to use FBML language.

I would suggest using this IFRAME solution instead:

http://fbtutorial.computerbeacon.net/section1/fbconnect

ContentLicense: CC BY-SA 2.5


问:
JSch ChannelSftp.ls throws nullpointer
I'm trying to implement a graphical ssh browser in java, with JSch. I would like to retrieve the result of a ChannelSftp.ls call, but it gives me a nullpointer exception... I checked the session, it is open and logged in. When I open the channel for exec and send an ls command, I can retrieve the directory contents as String. The code is the following:

```<code>public Vector listContents () {
    Channel channel = null;
    ConnectionThread conn = SSHBrowser.conn;

    Session sess = conn.getSession();
    System.out.println(sess.getUserName()); //prints out the given username, not null, so the session is initialized
    try {
        channel = sess.openChannel("sftp");
    } catch (JSchException ex) {
        ex.printStackTrace();
    }
    Vector<ChannelSftp.LsEntry> result = null;

    try {

        result = ((ChannelSftp) channel).ls("/srv"); // throws nullpointer here
        for (ChannelSftp.LsEntry dir : result) {
            System.out.print(dir.getLongname());
        }

    } catch (SftpException e) {
        e.printStackTrace();
    }
    return result;
}
</code>```

The stack trace, I get is the following:

```<code>at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1747)
    at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1553)
    at ssh.browser.ResultElement.listContents(ResultElement.java:69)
    at ssh.browser.ConsoleCommand.lsTest(ConsoleCommand.java:68)
    at ssh.browser.SSHBrowser$3.handle(SSHBrowser.java:113)
    at ssh.browser.SSHBrowser$3.handle(SSHBrowser.java:103)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1570)
    ... 37 more
</code>```

I don't know what could possibly null here... Can you please help?

答:
You also need to connect to the channel.

```<code>ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();

for (Object entry : channel.ls("/srv")) {
    System.out.println(entry);
}
</code>```

Have a look at the SFTP example.

Title: JSch ChannelSftp.ls throws nullpointer

Body:
I'm trying to implement a graphical ssh browser in java, with JSch. I would like to retrieve the result of a ChannelSftp.ls call, but it gives me a nullpointer exception... I checked the session, it is open and logged in. When I open the channel for exec and send an ls command, I can retrieve the directory contents as String. The code is the following:

public Vector listContents () {
    Channel channel = null;
    ConnectionThread conn = SSHBrowser.conn;

    Session sess = conn.getSession();
    System.out.println(sess.getUserName()); //prints out the given username, not null, so the session is initialized
    try {
        channel = sess.openChannel("sftp");
    } catch (JSchException ex) {
        ex.printStackTrace();
    }
    Vector<ChannelSftp.LsEntry> result = null;

    try {

        result = ((ChannelSftp) channel).ls("/srv"); // throws nullpointer here
        for (ChannelSftp.LsEntry dir : result) {
            System.out.print(dir.getLongname());
        }

    } catch (SftpException e) {
        e.printStackTrace();
    }
    return result;
}

The stack trace, I get is the following:

at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1747)
    at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1553)
    at ssh.browser.ResultElement.listContents(ResultElement.java:69)
    at ssh.browser.ConsoleCommand.lsTest(ConsoleCommand.java:68)
    at ssh.browser.SSHBrowser$3.handle(SSHBrowser.java:113)
    at ssh.browser.SSHBrowser$3.handle(SSHBrowser.java:103)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1570)
    ... 37 more

I don't know what could possibly null here... Can you please help?

Body:
You also need to connect to the channel.

ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();

for (Object entry : channel.ls("/srv")) {
    System.out.println(entry);
}

Have a look at the SFTP example.


问:
Using cout with basic_string<unsigned char>
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

```<code>#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}
</code>```

This doesn't compile with

```<code>error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')
</code>```

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

答:
There is no matching std::ostream overload for it in the standard library. You can however, provide your own overload. Though you may have different behavior for characters that aren't std::isprint

```<code>#include <iostream>
#include <string>

std::ostream& operator << (std::ostream& os, const std::basic_string<unsigned char>& str){
    for(auto ch : str)
        os << static_cast<char>(ch);
    return os;
}

int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}
</code>```

Prints:

```<code>zzz
</code>```

Demo

Body:
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}

This doesn't compile with

error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

Body:
There is no matching std::ostream overload for it in the standard library. You can however, provide your own overload. Though you may have different behavior for characters that aren't std::isprint

#include <iostream>
#include <string>

std::ostream& operator << (std::ostream& os, const std::basic_string<unsigned char>& str){
    for(auto ch : str)
        os << static_cast<char>(ch);
    return os;
}

int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}

Prints:

zzz

Demo


问:
Possible to store string and integers in one object
Is it possible to store a string and 11 integers in the same object.

Thanks,

Alex

答:
Create a class that implements an object containing a string and 11 integers:</p>

```<code>public class StringAndInt extends Object
{
    private int[] user = new int[11];
    private String string = "";

    public StringAndInt(String s, int[] i){
        user = i;
        string = s;
    }
    public StringAndInt setInt(int[] i){
        number = i;
        return this;
    }
    public StringAndInt setString(String s){
        string = s;
        return this;
    }
    public int getInt(){
        return user;
    }
    public String getString(){
        return string;
    }
}
</code>```

Body:
Create a class that implements an object containing a string and 11 integers:

public class StringAndInt extends Object
{
    private int[] user = new int[11];
    private String string = "";

    public StringAndInt(String s, int[] i){
        user = i;
        string = s;
    }
    public StringAndInt setInt(int[] i){
        number = i;
        return this;
    }
    public StringAndInt setString(String s){
        string = s;
        return this;
    }
    public int getInt(){
        return user;
    }
    public String getString(){
        return string;
    }
}


问:
How to make sure the back button returns to my app after firing startActivity?
I have an app that interconnects with Google Drive through their Java Rest API to open documents.

I am using the following code to open the document on Google Drive

```<code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(results.get(0)));
startActivity(browserIntent);
</code>```

The thing is the user can return to my app with back button if Google Drive was previously closed, but if its already opened the user can't get back to my app with the back button and instead returns to previous activities inside Google Drive.

I tried setting several flags like the following to no avail

```<code>browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
</code>```

Using those flags don't fix my problem what flags can i use then?

答:
If you are opening another application then you can't control its Activities stack which makes sense.

So if App is already running then its stack might contain activities. Which comes to screen when user press back key.

Functionality which you want can be added, like we can check user came from another Application then kill my App(third party/launched App) on press of back. But what will happen according to the user perspective if he navigated through few options and put his App in background for later work then suddenly everything clear.

Body:
I have an app that interconnects with Google Drive through their Java Rest API to open documents.

I am using the following code to open the document on Google Drive

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(results.get(0)));
startActivity(browserIntent);

The thing is the user can return to my app with back button if Google Drive was previously closed, but if its already opened the user can't get back to my app with the back button and instead returns to previous activities inside Google Drive.

I tried setting several flags like the following to no avail

browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Using those flags don't fix my problem what flags can i use then?


问:
your data could not be encoded because it contains invalid UTF8 characters jms/serializer-bundle symfony
I am trying to serialize the data of -doctrine repository function- result  into JSON format, the operation faild... I am using jms/serializer-bundle... I need your help please

```<code>       $em = $this->getDoctrine()
                  ->getManager();
       $repository = $em->getRepository('navormvagBundle:Stationpompage');
       $data        = $repository->find($id);
       $serializer = $this->container->get('serializer');
       $data = $serializer->serialize($data, 'json');
</code>```

CRITICAL - Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters." at C:\ms4w\Apache\htdocs\ormvagProject\vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php line 36

var_dump($data);
object(nav\ormvagBundle\Entity\Communes)#358 (21) { ["objectid12":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid1":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid":"nav\ormvagBundle\Entity\Communes":private]=> int(461) ["codeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(13) "04.291.05.11." ["nomCommun":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "OULMES" ["typeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(1) "R" ["codeProvi":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "04.291" ["codeRegio":"nav\ormvagBundle\Entity\Communes":private]=> string(2) "04" ["pop2014":"nav\ormvagBundle\Entity\Communes":private]=> int(18786) ["m�nages":"nav\ormvagBundle\Entity\Communes":private]=> int(4688) ["etrangers":"nav\ormvagBundle\Entity\Communes":private]=> float(1) ["marocains":"nav\ormvagBundle\Entity\Communes":private]=> int(18785) ["nomCercle":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "Oulmes" ["x":"nav\ormvagBundle\Entity\Communes":private]=> float(441447.171109) ["y":"nav\ormvagBundle\Entity\Communes":private]=> float(310925.203251) ["nomProvin":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "Khemisset" ["shapeLeng":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.539535) ["codeCercl":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "04.291.05" ["shapeLength":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.54067987) ["shapeArea":"nav\ormvagBundle\Entity\Communes":private]=> float(542883719.60999) ["wkbGeometry":"nav\ormvagBundle\Entity\Communes":private]=> string(26344) "SRID=900914;MULTIPOLYGON(((446016.130999997 319730.371199999,446125.634599999 319486.142200001,446254.220299996 319308.2588,446308.889600001 319175.070700001,446355.217600003 319163.748,446550.325000003 319184.854800001,446615.303800002 319184.508400001,446652.349200003 319173.236499999,446762.549800001 319017.605599999,446827.104000002 318961.889600001,446929.385200001 318983.4965,447125.511100002 319137.504700001 )))" }

答:
I got it. m�nages not valid property name of the entity.
That's why serializer fired error.

Check your property names, file format (must be UTF-8) and also database configuration.
Hope, this will be helpful.

Good luck.

Body:
I am trying to serialize the data of -doctrine repository function- result  into JSON format, the operation faild... I am using jms/serializer-bundle... I need your help please

       $em = $this->getDoctrine()
                  ->getManager();
       $repository = $em->getRepository('navormvagBundle:Stationpompage');
       $data        = $repository->find($id);
       $serializer = $this->container->get('serializer');
       $data = $serializer->serialize($data, 'json');

CRITICAL - Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters." at C:\ms4w\Apache\htdocs\ormvagProject\vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php line 36

var_dump($data);
object(nav\ormvagBundle\Entity\Communes)#358 (21) { ["objectid12":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid1":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid":"nav\ormvagBundle\Entity\Communes":private]=> int(461) ["codeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(13) "04.291.05.11." ["nomCommun":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "OULMES" ["typeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(1) "R" ["codeProvi":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "04.291" ["codeRegio":"nav\ormvagBundle\Entity\Communes":private]=> string(2) "04" ["pop2014":"nav\ormvagBundle\Entity\Communes":private]=> int(18786) ["m�nages":"nav\ormvagBundle\Entity\Communes":private]=> int(4688) ["etrangers":"nav\ormvagBundle\Entity\Communes":private]=> float(1) ["marocains":"nav\ormvagBundle\Entity\Communes":private]=> int(18785) ["nomCercle":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "Oulmes" ["x":"nav\ormvagBundle\Entity\Communes":private]=> float(441447.171109) ["y":"nav\ormvagBundle\Entity\Communes":private]=> float(310925.203251) ["nomProvin":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "Khemisset" ["shapeLeng":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.539535) ["codeCercl":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "04.291.05" ["shapeLength":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.54067987) ["shapeArea":"nav\ormvagBundle\Entity\Communes":private]=> float(542883719.60999) ["wkbGeometry":"nav\ormvagBundle\Entity\Communes":private]=> string(26344) "SRID=900914;MULTIPOLYGON(((446016.130999997 319730.371199999,446125.634599999 319486.142200001,446254.220299996 319308.2588,446308.889600001 319175.070700001,446355.217600003 319163.748,446550.325000003 319184.854800001,446615.303800002 319184.508400001,446652.349200003 319173.236499999,446762.549800001 319017.605599999,446827.104000002 318961.889600001,446929.385200001 318983.4965,447125.511100002 319137.504700001 )))" }


问:
Convert Powershell to exe with parameters
I have a powershell script which looks like this:

```<code>param(
[string]$fullpath,
[string]$username,
[string]$password,
[string]$driveletter = "P:",
[bool]$storedrive = $False)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $storedrive, $username, $password)
</code>```

I tried to convert it to an executable with PS2EXE which worked fine.

If I try to run the .exe with name.exe -fullpath "\\192.168.1.120\share" -username "administrator" -password "test123" I get the error message Networkname not found

If I compile the following code to an executable

```<code>param(
[string]$fullpath = "\\192.168.1.120\share",
[string]$username = "administrator",
[string]$password ="test123",
[string]$driveletter = "P:",
[bool]$storedrive = $False)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $storedrive, $username, $password)
</code>```

...and run the .exe - it works and I get the network drive shown in the Explorer....

Any ideas why this doesn't work?

Regards
Markus

答:
I found a solution, now I'm justing using this script

```<code>param(
[string]$driveletter,
[string]$fullpath,
[string]$username,
[string]$password)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $false, $username, $password)
</code>```

which I convert into the .exe
This works fine.
The .exe uses the following "parameters"

```<code>run.exe "P:" "\\192.168.1.120\share" "administrator" "test123"
</code>```

There is some problem with converting of the boolean. However, it works now the way I want to.

Body:
I have a powershell script which looks like this:

param(
[string]$fullpath,
[string]$username,
[string]$password,
[string]$driveletter = "P:",
[bool]$storedrive = $False)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $storedrive, $username, $password)

I tried to convert it to an executable with PS2EXE which worked fine.

If I try to run the .exe with name.exe -fullpath "\\192.168.1.120\share" -username "administrator" -password "test123" I get the error message Networkname not found

If I compile the following code to an executable

param(
[string]$fullpath = "\\192.168.1.120\share",
[string]$username = "administrator",
[string]$password ="test123",
[string]$driveletter = "P:",
[bool]$storedrive = $False)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $storedrive, $username, $password)

...and run the .exe - it works and I get the network drive shown in the Explorer....

Any ideas why this doesn't work?

Regards
Markus

Body:
I found a solution, now I'm justing using this script

param(
[string]$driveletter,
[string]$fullpath,
[string]$username,
[string]$password)

$net = new-object -ComObject WScript.Network

$net.MapNetworkDrive($driveletter, $fullpath, $false, $username, $password)

which I convert into the .exe
This works fine.
The .exe uses the following "parameters"

run.exe "P:" "\\192.168.1.120\share" "administrator" "test123"

There is some problem with converting of the boolean. However, it works now the way I want to.


问:
NSFetchedResultsController result filtering
Is there an easy way to filter the results provided by the NSFetchedResultsController?

I am using the standard Core Data Template which works very well for simple tables.

What I have is a UITableVIew with a UISegmentedControl with two categories, one that displays all and one that when selected should display only events what were created today.

I have been able to accomplish this in two different tableViews (so i know how to use NSPredicate, that is not my problem; the problem is combining it into a single tableView).

I know you cannot change the fetchRequest once the NSFetchedResultsController has been created.

So I can guess that I will have to create a new NSFetchedResultsController.

Has anyone implemented something like this or have any ideas on how to accomplish this?

答: I haven't used NSFetchedResultsController much as my codebase predates it, however in the past i have just fired off an NSFetechedResults request with a different predicate depending on the state of the segmentedControl.</p>


问:
Forwarding all input to Java Process
I'm trying to forward the input to the process. It's a minecraft server so I need to send commands to it. I try in this way but it doesn't send anything. (I've also checked the log file)

```<code>public static void main(String[] args) throws IOException {
    File file = new File("spigot.jar");
    if(file.exists()) {
        ProcessBuilder builder = new ProcessBuilder("java", "-jar", "spigot.jar");
        Process p = builder.start();

        new Thread(() -> {
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String s = "";
            try {
                while((s = br.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()-> {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            String cmd = "";
            try {
                while((cmd = input.readLine()) != null) {
                    bw.write(cmd);
                    bw.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            while(true) {
                if(!p.isAlive()) {
                    System.out.println("Server closed.");
                    System.exit(0);
                }
            }
        }).start();

    } else {
        System.out.println("spigot.jar not found.");
        System.exit(0);
    }
}
</code>```

EDIT:
I rewrote the code using threads but i'm getting the same problem

答:
Solved.

I need to add "bw.newline()" to send ENTER, and make the server execute my command

Title: Forwarding all input to Java Process

Body:
I'm trying to forward the input to the process. It's a minecraft server so I need to send commands to it. I try in this way but it doesn't send anything. (I've also checked the log file)

public static void main(String[] args) throws IOException {
    File file = new File("spigot.jar");
    if(file.exists()) {
        ProcessBuilder builder = new ProcessBuilder("java", "-jar", "spigot.jar");
        Process p = builder.start();

        new Thread(() -> {
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String s = "";
            try {
                while((s = br.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()-> {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            String cmd = "";
            try {
                while((cmd = input.readLine()) != null) {
                    bw.write(cmd);
                    bw.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            while(true) {
                if(!p.isAlive()) {
                    System.out.println("Server closed.");
                    System.exit(0);
                }
            }
        }).start();

    } else {
        System.out.println("spigot.jar not found.");
        System.exit(0);
    }
}

EDIT:
I rewrote the code using threads but i'm getting the same problem


问:
How To Use Multi Value Title and Value From Settings Bundle
I have a multi value setting (location) defined in my settings bundle for an app.

The Titles are defined as long titles, for example, "London" and the corresponding value part of the setting is defined as "1".

[EDIT]

To expand this question I will add more information about the multi value setting:

How do I retrieve the Title of LONDON at Item 0.  As described above when I retrieve the objectForKey or valueForKey I get 1 always.  I want to display the string "LONDON" from the title in a label in the app but use the value 1 in core data. Note: I have set the value in the settings before the app runs so it does return a value but the value is always 1 as the Title does not seem to be accessible.

答:
I ran into the similar situation and answering the question that it'll help someone.

If I understand the question correctly, when user selects London from the settings the default value will be 1. when you read the settings bundle for locationSetting you get the value 1 and not LONDON, but you want the "LONDON" in your code rather than 1. It is not possible with the current structure of your plist. make the default value a dictionary instead of string and then you can have both titles and values inside that dictionary. you can then retrieve the text of the selected value.


问:
Linq group by and get count of occurence
I need to get topic name and number of times (count) a given topic occurs.

Example:

```<code>Name: John
Topic: X, Y, Z => these are List<string>

Name: Bob
Topic: Y

Name: Suzy
Topic: Y, Z

Should generate output:
X: 1
Y: 3
Z: 2
</code>```

I've tried this but it doesn't return correct result:

```<code>var result = from r in items
                         orderby r.Topic
                         group r by r.Topic
                into grp
                         select new { key = grp.Key, cnt = grp.Count() };
</code>```

答:
You can flatten the contained collection with another from:

```<code>var result = from r in lineItems
             from t in r.Topic  // List<string>
             group t by t into grp
             orderby grp.Key
             select new { key = grp.Key, cnt = grp.Count() };
</code>```

Body:
I need to get topic name and number of times (count) a given topic occurs.

Example:

Name: John
Topic: X, Y, Z => these are List<string>

Name: Bob
Topic: Y

Name: Suzy
Topic: Y, Z

Should generate output:
X: 1
Y: 3
Z: 2

I've tried this but it doesn't return correct result:

var result = from r in items
                         orderby r.Topic
                         group r by r.Topic
                into grp
                         select new { key = grp.Key, cnt = grp.Count() };

Body:
You can flatten the contained collection with another from:

var result = from r in lineItems
             from t in r.Topic  // List<string>
             group t by t into grp
             orderby grp.Key
             select new { key = grp.Key, cnt = grp.Count() };


问:
Where to apply for more "URL Fetch calls" quota from google
I use URL fetch calls in Adwords scripts to scrape various sources, most of all my own web pages. I find myself limited by the quota of 20 000 requests/24hours. https://script.google.com/dashboard . Where can I apply for a larger quota?

I have substantially large Adwords accounts.
My account managers and Adwords support didn't know the answer and finally sent me to the Adwords API support team. Adwords API support sent me here to stackoverflow. Thanks for any input.

答:
You may want to check this documentation which outlines various limits and limitations in AdWords scripts that you should be aware of. Also note that, Google Apps Script services impose daily quotas and hard limits on some features.

And as commented by @rckrd, to get a higher quota, you may want to sign up for G Suite. See this page for more information on quota limits for Google Services.


问:
Does the number of users ( not logged out ) on app equal no of simultaneous connections on firebase?
I have an android app developed and I am expecting more than a 100 users.The app does have a logout button but I doubt any user would logout,they would instead push it to background.
So my question is if I have 150 users ( logged in ,but in background) mean that I have 150 simultaneous connections ? I did read a few questions on simultaneous connections , but can someone be more accurate on what is a concurrent connection.
150 users  - logged in (background) - open app at different times - ?
If this is going to exceed the free plan on firebase , how do i prevent it?.I use email/password for login.</p>

答:
When you start an app that uses the Firebase Database, it creates a persistent connection to the Firebase server. This counts as one active connection on the back-end.

The connection can be broken when:

the user hasn't written any data and doesn't have any active listeners for a few minutes (currently 5 minutes, but that could change).

you call goOffline() in your code

Whether the app is in the foreground or background is irrelevant to the Firebase SDK. But you could use Android life-cycle events (such as onPause()) to detect such transitions and remove your listeners (to get to condition 1).

Also: when your app is backgrounded, the Android operating system might close the connection from the client to the Firebase back-end at any time. When it does this depends on the version and flavor of Android your device has.

A final option (as fellow Firebaser Doug pointed out in the comments) is to enable automatic resource management. If you enable automatic resource management, the client will essentially call goOffline() when the app goes into the background and goOnline() when it comes back to the foreground.


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
What's about just to silently convert string to numeric datatype on function startup?

You always can determine the datatype of 'string'. Can't you?

OwnerDisplayName: Pim Jager

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Thevs


问:
Android: Are there any benefits to using @id over @+id performance wise?
I know that the + in @+id tells the compiler to add the id to the (R.id.???) resources. However i was wondering if there were performance benefits to be gained by not putting the + ?

Perhaps for example when dealing with complex list view layouts?

答: There are no performance differences at all.  For IDs, the only reason to not use '+' is if you are declaring an ID explicitly and want to reference it, ensuring all references are to that particular ID.  For example, if you don't use '+' and have a typo in your ID name, you will get a compile-time error, while with a '+' a new entry for the typo'd ID will be created.</p>


问:
SendGrid email template style not applying
I'm using SendGrid PHP API to send Newsletter but when I use the template ID, the mail sended doesn't contain the CSS & image.

Here is my code :

```<code><?php
require("sendgrid-php/sendgrid-php.php");

$from = new SendGrid\Email(null, "contact@projet.com");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "me@icloud.com");
$content = new SendGrid\Content("text/plain", "hello");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$mail->setTemplateId("727274bc-XXXX-XXXX-XXXX-83a2b53597e5");

$apiKey = 'SG.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->headers();
echo $response->body();

?>
</code>```

Hope someone will help me
Thanks

答:
Solved ! Just change
$content = new SendGrid\Content("text/plain", "hello"); to
$content = new SendGrid\Content("text/html", "hello");

Body:
I'm using SendGrid PHP API to send Newsletter but when I use the template ID, the mail sended doesn't contain the CSS & image.

Here is my code :

<?php
require("sendgrid-php/sendgrid-php.php");

$from = new SendGrid\Email(null, "contact@projet.com");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "me@icloud.com");
$content = new SendGrid\Content("text/plain", "hello");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$mail->setTemplateId("727274bc-XXXX-XXXX-XXXX-83a2b53597e5");

$apiKey = 'SG.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->headers();
echo $response->body();

?>

Hope someone will help me
Thanks


问:
How do you insert a newline character within the RegularExpressionValidator ErrorMessage Field?
Consider this code below:

```<code><asp:RegularExpressionValidator
        ID="MyTestId"
        ValidationGroup="MyTestGroup"
        ErrorMessage="You are a silly user. You entered the wrong format for this problem. Please try again. Using this format! ELRLDKX##Z"
        ValidationExpression="some unrelated regex"
        runat="server"
        ControlToValidate="MyTestTextbox">
</asp:RegularExpressionValidator>
</code>```

Is there a way to insert an escape character of some sort into the ErrorMessage string to ensure that Please try again. Using this format! ELRLDKX##Z is on another line? I have tried, \n with no luck.

答:
The Validator is on a web page, so you can just add html code to the text, like a

```<code>ErrorMessage="You are a silly user. You entered the wrong format for this problem.<br />Please try again. Using this format! ELRLDKX##Z"
</code>```

Body:
Consider this code below:

<asp:RegularExpressionValidator
        ID="MyTestId"
        ValidationGroup="MyTestGroup"
        ErrorMessage="You are a silly user. You entered the wrong format for this problem. Please try again. Using this format! ELRLDKX##Z"
        ValidationExpression="some unrelated regex"
        runat="server"
        ControlToValidate="MyTestTextbox">
</asp:RegularExpressionValidator>

Is there a way to insert an escape character of some sort into the ErrorMessage string to ensure that Please try again. Using this format! ELRLDKX##Z is on another line? I have tried, \n with no luck.

Body:
The Validator is on a web page, so you can just add html code to the text, like a <br />

ErrorMessage="You are a silly user. You entered the wrong format for this problem.<br />Please try again. Using this format! ELRLDKX##Z"


问:
Check if values from two different colums and get value from next column
I think that we can do it with formula, but I cannot get how can skip some cases:

column A has values different from column C

column A and Column C have equal number of identical values

values from column D need to go to column B infront of the corresponding cell

Column A has repeatable values, also column C has the same repeatable values.[!

Here is a example of my problem.

答:
Try this formula in B1 and fill down.

```<code>=IF(LEN(A1), INDEX(D:D, AGGREGATE(15, 6, ROW(D$1:INDEX(D:D, MATCH("zzz", D:D)))/(C$1:INDEX(C:C, MATCH("zzz", D:D))=A1), COUNTIF(A$1:A1, A1))), TEXT(,))
</code>```

Body:
Try this formula in B1 and fill down.

=IF(LEN(A1), INDEX(D:D, AGGREGATE(15, 6, ROW(D$1:INDEX(D:D, MATCH("zzz", D:D)))/(C$1:INDEX(C:C, MATCH("zzz", D:D))=A1), COUNTIF(A$1:A1, A1))), TEXT(,))


问:
Wicket NumberTextField in Kotlin throws ClassCastException when submitted
I'm having some issues with a Wicket (8.0.0-M4) NumberTextField in Kotlin (1.1.0).

My stripped-down form looks like this:

```<code>class Test : AbstractWebPage() {

    val housenumberModel: Model<Int> = Model<Int>()
    val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel)

    val form: Form<Unit> = object : Form<Unit>("adressForm") {}

    override fun onInitialize() {
        super.onInitialize()

        form.add(housenumber.setRequired(false))
        form.add(object : SubmitLink("submit") {
            override fun onSubmit() {
                super.onSubmit()
                println(housenumberModel.`object`)  // this is line 28
            }

        })
        add(form)
    }

}
</code>```

After submitting the form I get the following stacktrace:

java.lang.ClassCastException: java.lang.String cannot be cast to
  java.lang.Number
       at com.mycompany.test.pages.Test$onInitialize$1.onSubmit(Test.kt:28)
       at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1312)
       at org.apache.wicket.markup.html.form.Form.process(Form.java:979)
       at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:802)
       at org.apache.wicket.markup.html.form.Form.onRequest(Form.java:715)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.internalInvoke(ListenerRequestHandler.java:301)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:250)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:210)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:203)
       at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912)
       at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
       at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283)
       at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253)
       at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221)
       at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262)
       at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204)
       at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:286)
  [...]

If I use

```<code>val housenumberModel: Model<Int> = Model.of(0)
</code>```

instead of

```<code>val housenumberModel: Model<Int> = Model<Int>()
</code>```

everything works fine. But since my NumberTextField is optional I don't want to have it pre-initialized with 0.

Me and my colleagues were trying to change the type signature of the Model in every way we could imagine but came to no solution. A co-worker suggested to write a custom Wicket converter since Kotlins Int is represendeted as a primitive type (From the docs: "On the JVM, non-nullable values of this type are represented as values of the primitive type int.") Even though I don't know yet if this would work it seems like an overkill for me.

Another hack I could think of: writing some JavaScript to delete the zero from the input field. Also not really something I would want to do.

Question: Is there a simple solution to my problem?

(And as a bonus-question: has already anyone written a larger Wicket application in Kotlin and could tell me if this combination is ready for prime time to develop a critical project with this stack or is my problem just the tip of the iceberg?)

[edit]

Solution as pointed out by svenmeier:

Using

```<code>val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel, Int::class.java)
</code>```

works.

Or as an alternative:

```<code>val housenumbervalue: Int?  = null
val housenumberModel: IModel<Int> = PropertyModel<Int>(this, "housenumbervalue")
val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel)
</code>```

答:
Because of type erasure your NumberTextField cannot detect the generic type parameter of your model. Since your model object is null, it cannot be used to derive the type either.

In this case Wicket assumes a String model object type :/.

Either provide the type to the NumberTextField explicitly, or use a model that keeps its generic information, e.g. a PropertyModel.

Body:
I'm having some issues with a Wicket (8.0.0-M4) NumberTextField in Kotlin (1.1.0).

My stripped-down form looks like this:

class Test : AbstractWebPage() {

    val housenumberModel: Model<Int> = Model<Int>()
    val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel)

    val form: Form<Unit> = object : Form<Unit>("adressForm") {}

    override fun onInitialize() {
        super.onInitialize()

        form.add(housenumber.setRequired(false))
        form.add(object : SubmitLink("submit") {
            override fun onSubmit() {
                super.onSubmit()
                println(housenumberModel.`object`)  // this is line 28
            }

        })
        add(form)
    }

}

After submitting the form I get the following stacktrace:

java.lang.ClassCastException: java.lang.String cannot be cast to
  java.lang.Number
       at com.mycompany.test.pages.Test$onInitialize$1.onSubmit(Test.kt:28)
       at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1312)
       at org.apache.wicket.markup.html.form.Form.process(Form.java:979)
       at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:802)
       at org.apache.wicket.markup.html.form.Form.onRequest(Form.java:715)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.internalInvoke(ListenerRequestHandler.java:301)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:250)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:210)
       at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:203)
       at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912)
       at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
       at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283)
       at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253)
       at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221)
       at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262)
       at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204)
       at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:286)
  [...]

If I use

val housenumberModel: Model<Int> = Model.of(0)

instead of

val housenumberModel: Model<Int> = Model<Int>()

everything works fine. But since my NumberTextField is optional I don't want to have it pre-initialized with 0.

Me and my colleagues were trying to change the type signature of the Model in every way we could imagine but came to no solution. A co-worker suggested to write a custom Wicket converter since Kotlins Int is represendeted as a primitive type (From the docs: "On the JVM, non-nullable values of this type are represented as values of the primitive type int.") Even though I don't know yet if this would work it seems like an overkill for me.

Another hack I could think of: writing some JavaScript to delete the zero from the input field. Also not really something I would want to do.

Question: Is there a simple solution to my problem?

(And as a bonus-question: has already anyone written a larger Wicket application in Kotlin and could tell me if this combination is ready for prime time to develop a critical project with this stack or is my problem just the tip of the iceberg?)

[edit]

Solution as pointed out by svenmeier:

Using

val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel, Int::class.java)

works.

Or as an alternative:

val housenumbervalue: Int?  = null
val housenumberModel: IModel<Int> = PropertyModel<Int>(this, "housenumbervalue")
val housenumber = NumberTextField<Int>("housenumberModel", housenumberModel)


问:
How to pass items to bash for loop on multiple lines?
I can do this in bash:

```<code>for n in a b c d e ; do
  echo $n
done
</code>```

If a, b, c, d, e turn out to be long lines, without using a separate variable, how do I put them each on a separate line in the for loop syntax?

答:
Split the line with \:

```<code>$ for i in a \
> b \
> c \
> d ; do echo $i ; done
a
b
c
d
</code>```

Body:
I can do this in bash:

for n in a b c d e ; do
  echo $n
done

If a, b, c, d, e turn out to be long lines, without using a separate variable, how do I put them each on a separate line in the for loop syntax?

Body:
Split the line with \:

$ for i in a \
> b \
> c \
> d ; do echo $i ; done
a
b
c
d


问:
How to tell if Safari is using HTTP2?
I tried all tabs in Web Inspector and didn't find anything useful. Google does not turn up any way either.</p>

答: If you switch to the Network tab in the inspector and then open the right details sidebar, you can see the Header information of request and response:

Title: How to tell if Safari is using HTTP2?


问:
Search and replace div content with another div content
I am trying to find a way to replace a DIV that has a few other divs inside with another div that also has a few other divs inside. Tried to do it with a few different programs: Atom, Sublime, Visual Studio Code, PhpStorm but it didn't work.

It could probably be done using regex since the first div starts with
 and ends with

```<code>...id="submitbtn_intakeFormShortAutofillSubmit"/>
    </form>
</div>
                    </div>
</code>```

but my problem is probably the number of tabs, spaces and newlines.

Just to mention, I don't have to make this active on a webpage, but inside hundreds of html pages on my hard drive, so if you can recommend some free software that can do it, it's also good.

答:
Yep, this is very possible!  Here's how you do it:

```<code><div class="short-form"[\s\S]*id="submitbtn_intakeFormShortAutofillSubmit"\/>\s*<\/form>\s*<\/div>\s*<\/div>
</code>```

Break it down!

<div class="short-form" match anything that starts with <div class="short-form"

[\s\S]* matech 0 or more of anything that is white space or is not whitespase (So bassically match anything)

id="submitbtn_intakeFormShortAutofillSubmit"\/> match anything that matches  id="submitbtn_intakeFormShortAutofillSubmit"/>

\s* match 0 or more whitespace

repeate the last two a few times!

Here's an example on regexr!

Body:
I am trying to find a way to replace a DIV that has a few other divs inside with another div that also has a few other divs inside. Tried to do it with a few different programs: Atom, Sublime, Visual Studio Code, PhpStorm but it didn't work.

It could probably be done using regex since the first div starts with
 and ends with

...id="submitbtn_intakeFormShortAutofillSubmit"/>
    </form>

but my problem is probably the number of tabs, spaces and newlines.

Just to mention, I don't have to make this active on a webpage, but inside hundreds of html pages on my hard drive, so if you can recommend some free software that can do it, it's also good.

Body:
Yep, this is very possible!  Here's how you do it:

<div class="short-form"[\s\S]*id="submitbtn_intakeFormShortAutofillSubmit"\/>\s*<\/form>\s*<\/div>\s*<\/div>

Break it down!

<div class="short-form" match anything that starts with <div class="short-form"

[\s\S]* matech 0 or more of anything that is white space or is not whitespase (So bassically match anything)

id="submitbtn_intakeFormShortAutofillSubmit"\/> match anything that matches  id="submitbtn_intakeFormShortAutofillSubmit"/>

\s* match 0 or more whitespace

repeate the last two a few times!

Here's an example on regexr!