问:
Skipping to "catch" instantly after changing PHP code in Java Android application
So I've been toying around in my mobile app that's supposed to let me register accounts and log in while getting some data from a database I've created. All was fine and dandy until I've changed my register.php file to check if the login is already taken and act accordingly to that. I tought I had a problem with my JSONObject and response, so I've tried using a string instead of boolean but still the program only goes into the try section to JSONObject jsonResponse = new JSONObject(response); and then in instantly goes into the catch part of the code. I didn't change much, honestly i'd say that the code I've written now is cleaner than the one before but it doesn't work properly.

When I click the "Zarejestruj" button (polish for Register) data should be sent to database (which happens, but I can add an infinite amount of same logins for some reason) and the activity should go back to LoginActivity.java but it doesnt, it just sends the credentials into the database and stays there for infinity while allowing me to spam the hell out of the bRegister.

Here's the java code:

```<code>public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Log.d("RA", "Zmienne");
    final EditText etName = (EditText) findViewById(R.id.etName);
    final EditText etSurame = (EditText) findViewById(R.id.etSurname);
    final EditText etLogin = (EditText) findViewById(R.id.etLogin);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final EditText etGroupNumber = (EditText) findViewById(R.id.etGroupNumber);
    final EditText etIndexNumber = (EditText) findViewById(R.id.etIndexNumber);

    final Button bRegister = (Button) findViewById(R.id.bRegister);
    Log.d("RA", "Po zmienncyh");

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String name = etName.getText().toString().trim();
            final String surname = etSurame.getText().toString().trim();
            final String login = etLogin.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            final String groupNumber = etGroupNumber.getText().toString().trim();
            final String indexNumber = etIndexNumber.getText().toString().trim();

            Log.d("RA", "Przed wywołąniem responseListener");
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("RA", "Response");
                    Log.d("RA", response);
                    Log.d("RA", "onResponse");
                    try {
                        Log.d("RA", "Try");
                        JSONObject jsonResponse = new JSONObject(response);
                        Log.d("RA", "ObiektResponse");
                        String success = jsonResponse.getString(response);
                        if (success == "success") {
                            Log.d("RA", "Success");
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);

                        } else {
                            Log.d("RA", "Error");
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        Log.d("RA", "catch");
                        e.printStackTrace();
                    }
                }
            };
            Log.d("RA", "Wykonało się");
            RegisterRequest registerRequest = new RegisterRequest(name, surname, login, password, groupNumber, indexNumber, responseListener);
            Log.d("RA", "queue");
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            Log.d("RA", "registerRequest");
            queue.add(registerRequest);
            Log.d("RA", "Koniec");
        }
    });
}}
</code>```

And here is my Register.php file:

```<code>require("Password.php");

ini_set('display_errors', 'On');
$mysqli = new mysqli("localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt");

if($mysqli->connect_errno){
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if(isset($_POST["name"]) && isset($_POST["surname"]) && isset($_POST["login"]) && isset($_POST["password"]) && isset($_POST["groupNumber"]) && isset($_POST["indexNumber"]))
{
$name = $_POST["name"];
$surname= $_POST["surname"];
$login = $_POST["login"];
$password = $_POST["password"];
$groupNumber = $_POST["groupNumber"];
$indexNumber = $_POST["indexNumber"];
}

function registerUser(){
    global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $mysqli->prepare("INSERT INTO user (name, surname, login, password, groupNumber, indexNumber) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber);
    $stmt->execute();
    $stmt->close();
}

function usernameAvailable(){
    global $mysqli, $login, $count;
    $sql = "SELECT * FROM users WHERE login = ?";
    if($stmt = $mysqli->prepare($sql)){
    $stmt->bind_param("s", $login);
    $stmt->execute();
    $stmt->store_result();
    $count = $stmt->num_rows;
    $stmt->close();
    }
    if($count < 1){
        return true;
    }
    else
        return false;
}
    $response = "false";

if(usernameAvailable()){
    registerUser();
    $response = "true";
}echo json_encode($response);
$mysqli->close();
</code>```

答:
The problem is in this line:

```<code>String success = jsonResponse.getString(response);
</code>```

Your JSON string is this:

```<code>{"success":true}
</code>```

Parsing this will create a JSONObject with one key/value pair: "success" = boolean true

What you're trying to do here, is get the String value of the key response (which is the full {"success":true} string, which does NOT exist as a key in the JSONObject). Instead, you should use jsonResponse.getString("success") because "success" is actually the key you're interested in.

However, since it's actually a boolean value and not a String, you should not use getString() but use getBoolean() instead:

```<code>boolean success = jsonResponse.getBoolean("success");
</code>```

This will have an impact on your following if-statement as well:

```<code>if (success == "success") {
</code>```

should become:

```<code>if (success) {
</code>```

(because success is now a boolean true or false).

Body:
So I've been toying around in my mobile app that's supposed to let me register accounts and log in while getting some data from a database I've created. All was fine and dandy until I've changed my register.php file to check if the login is already taken and act accordingly to that. I tought I had a problem with my JSONObject and response, so I've tried using a string instead of boolean but still the program only goes into the try section to JSONObject jsonResponse = new JSONObject(response); and then in instantly goes into the catch part of the code. I didn't change much, honestly i'd say that the code I've written now is cleaner than the one before but it doesn't work properly.

When I click the "Zarejestruj" button (polish for Register) data should be sent to database (which happens, but I can add an infinite amount of same logins for some reason) and the activity should go back to LoginActivity.java but it doesnt, it just sends the credentials into the database and stays there for infinity while allowing me to spam the hell out of the bRegister.

Here's the java code:

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Log.d("RA", "Zmienne");
    final EditText etName = (EditText) findViewById(R.id.etName);
    final EditText etSurame = (EditText) findViewById(R.id.etSurname);
    final EditText etLogin = (EditText) findViewById(R.id.etLogin);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final EditText etGroupNumber = (EditText) findViewById(R.id.etGroupNumber);
    final EditText etIndexNumber = (EditText) findViewById(R.id.etIndexNumber);

    final Button bRegister = (Button) findViewById(R.id.bRegister);
    Log.d("RA", "Po zmienncyh");

    bRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String name = etName.getText().toString().trim();
            final String surname = etSurame.getText().toString().trim();
            final String login = etLogin.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            final String groupNumber = etGroupNumber.getText().toString().trim();
            final String indexNumber = etIndexNumber.getText().toString().trim();

            Log.d("RA", "Przed wywołąniem responseListener");
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("RA", "Response");
                    Log.d("RA", response);
                    Log.d("RA", "onResponse");
                    try {
                        Log.d("RA", "Try");
                        JSONObject jsonResponse = new JSONObject(response);
                        Log.d("RA", "ObiektResponse");
                        String success = jsonResponse.getString(response);
                        if (success == "success") {
                            Log.d("RA", "Success");
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);

                        } else {
                            Log.d("RA", "Error");
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        Log.d("RA", "catch");
                        e.printStackTrace();
                    }
                }
            };
            Log.d("RA", "Wykonało się");
            RegisterRequest registerRequest = new RegisterRequest(name, surname, login, password, groupNumber, indexNumber, responseListener);
            Log.d("RA", "queue");
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            Log.d("RA", "registerRequest");
            queue.add(registerRequest);
            Log.d("RA", "Koniec");
        }
    });
}}

And here is my Register.php file:

require("Password.php");

ini_set('display_errors', 'On');
$mysqli = new mysqli("localhost", "id2147309_javaprojekt123", "javaprojekt321", "id2147309_javaprojekt");

if($mysqli->connect_errno){
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if(isset($_POST["name"]) && isset($_POST["surname"]) && isset($_POST["login"]) && isset($_POST["password"]) && isset($_POST["groupNumber"]) && isset($_POST["indexNumber"]))
{
$name = $_POST["name"];
$surname= $_POST["surname"];
$login = $_POST["login"];
$password = $_POST["password"];
$groupNumber = $_POST["groupNumber"];
$indexNumber = $_POST["indexNumber"];
}

function registerUser(){
    global $mysqli, $name, $surname, $login, $password, $groupNumber, $indexNumber;
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $mysqli->prepare("INSERT INTO user (name, surname, login, password, groupNumber, indexNumber) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss", $name, $surname, $login, $passwordHash, $groupNumber, $indexNumber);
    $stmt->execute();
    $stmt->close();
}

function usernameAvailable(){
    global $mysqli, $login, $count;
    $sql = "SELECT * FROM users WHERE login = ?";
    if($stmt = $mysqli->prepare($sql)){
    $stmt->bind_param("s", $login);
    $stmt->execute();
    $stmt->store_result();
    $count = $stmt->num_rows;
    $stmt->close();
    }
    if($count < 1){
        return true;
    }
    else
        return false;
}
    $response = "false";

if(usernameAvailable()){
    registerUser();
    $response = "true";
}echo json_encode($response);
$mysqli->close();

Body:
The problem is in this line:

String success = jsonResponse.getString(response);

Your JSON string is this:

{"success":true}

Parsing this will create a JSONObject with one key/value pair: "success" = boolean true

What you're trying to do here, is get the String value of the key response (which is the full {"success":true} string, which does NOT exist as a key in the JSONObject). Instead, you should use jsonResponse.getString("success") because "success" is actually the key you're interested in.

However, since it's actually a boolean value and not a String, you should not use getString() but use getBoolean() instead:

boolean success = jsonResponse.getBoolean("success");

This will have an impact on your following if-statement as well:

if (success == "success") {

should become:

if (success) {

(because success is now a boolean true or false).


来源: stackexchange

问:
Sqlx "missing destination name" for struct tag through pointer
I have a model like this:

```<code>type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group
</code>```

And when i try to do sqlx.Select for Groups with a query like this:

```<code>SELECT c.name as course_name FROM courses as c;
</code>```

I get

missing destination name course_name in *main.Groups

error.

What is the issue with this code?

答:
You need to use sqlx.Select when you are selecting multiple rows and you want to scan the result into a slice, as is the case for your query, otherwise use sqlx.Get for a single row.

In addition, you can't scan directly into a Group struct because none of its fields are tagged (unlike the Course struct), and the Course field isn't embedded.

Try:

```<code>course := Course{}
courses := []Course{}

db.Get(&course, "SELECT name AS course_name FROM courses LIMIT 1")
db.Select(&courses, "SELECT name AS course_name FROM courses")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a model like this:

type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group

And when i try to do sqlx.Select for Groups with a query like this:

SELECT c.name as course_name FROM courses as c;

I get

missing destination name course_name in *main.Groups

error.

What is the issue with this code?

Body:
You need to use sqlx.Select when you are selecting multiple rows and you want to scan the result into a slice, as is the case for your query, otherwise use sqlx.Get for a single row.

In addition, you can't scan directly into a Group struct because none of its fields are tagged (unlike the Course struct), and the Course field isn't embedded.

Try:

course := Course{}
courses := []Course{}

db.Get(&course, "SELECT name AS course_name FROM courses LIMIT 1")
db.Select(&courses, "SELECT name AS course_name FROM courses")


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答:
Functionally there is no difference.

However there is one reason for not doing this. Longer methods with several exit points are often more difficult to read and analyze. But that objection has more to do with return statements than catch and finally blocks.

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: Ifeanyi Echeruo

ContentLicense: CC BY-SA 2.5


问:
Upgrade WAMP to MySQL 5.5?
My dev team uses WAMP for the php/Mysql environment but i just learnt that uses MySQL 5.1 and MySQL is at 5.5 now. Can I get the mysql upgraded to 5.5 separately without any issue to make it work with WAMP or is there any patch for WAMP to get the latest mysql?

I want to ensure they work with the latest build of MySQL but i am not sure if it is as simple as download mySQL 5.5 and it gets auto-added to the WAMP server, or if there are compatible? I assume since WAMP never updated their MySQL something is not compatible?

答:
Found this for you:

STEP1: (x represents a number)

Download the latest version of MySQL
  first... Copy the new folder of
  mysqlx.x to wamp\bin\mysql\ Check if
  the folder of mysql and all database
  files exist in mysqlx.x\data folder.
  If the mysql folder doesn't exist,
  copy it from a working previous
  version of mysql.

Check if mysqlx.x\bin folder and all
  executable files in it exist. Check if
  the folder mysqlx.x\share exist. If
  they don't exist, then the extraction
  of the latest version of mysql isn't
  done properly.

Check if mysqlx.x\my.ini file exist.
  If it doesn't exist, copy the file
  from the previous wokring version of
  wamp mysql in wamp\bin\mysql\mysqlx.x
  Open the file from the latest mysql
  version, edit all occurrences of
  "mysqlx.x" in that file to the
  "mysqlx.x" as the latest version
  number.

For example, if you see the line
  "basedir=c:/wamp/bin/mysql/mysql4.1"
  in my.ini file, then edit it to
  "basedir=c:/wamp/bin/mysql/mysqlx.x"
  as mysqlx.x is the lastest version
  you've just downloaded. Normally there
  are only two occurrences you need to
  edit:
  basedir=c:/wamp/bin/mysql/mysqlx.x and
  datadir=c:'wamp/bin/mysql/mysqlx.x/data

STEP2:

Copy the wampserver.conf file in the
  previous version of wamp mysqlx.x
  folder to wamp\bin\mysql\mysqlx.x. You
  would need to open it with notepad and
  edit the line:
  $mysqlConf['mysqlExeFile'] =
  'mysqld-nt.exe'; to
  $mysqlConf['mysqlExeFile'] =
  'mysqld.exe';

Look at the mysqlx.x\bin directory and
  find out if there is a mysqld.exe or
  mysql-nt.exe file. If there is no
  mysql-nt.exe file, then change that
  line as mentioned.

STEP3:

Shutdown the wamp2 server (by right
  click on wamp tray icon and click
  exit). Then restart the wamp server.
  Restart all services. You should see
  the mysql newest version displayed in
  wamp mysql menu. Just click on the
  latest version to enable it, then you
  have the newest mysql version running
  with wamp server.

Title: Upgrade WAMP to MySQL 5.5?


问:
Username validation with regular expression in php
I am trying to validate a USERNAME in PHP using Regular Expression. But I am failed. My pattern is: /[^a-z0-9_]/

Rules:

username must start number or small letters

username support number, small letters and _

the end of username character is not be _

答:
You do not want username of two letters or username that has unlimited characters, do you? Consider this solution if you need to limit the number of characters in your username under your situation:

```<code>/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/
</code>```

https://www.tinywebhut.com/regex/4

The part [a-z0-9] exactly matches one character which can be only small letter or number. The middle part [a-z0-9_]{2,28} matches any small letter or number up to 2 or 28 characters including underscore. The final part [a-z0-9] exactly matches one character which can be only small letter or number. Therefore, this regular expression matches username that has at least 4 characters and 30 characters at the most. If you change your mind and want to include both small and capital letters, you'll have to add a modifier i:

```<code>/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/i
</code>```

https://www.tinywebhut.com/regex/5

Body:
You do not want username of two letters or username that has unlimited characters, do you? Consider this solution if you need to limit the number of characters in your username under your situation:

/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/

https://www.tinywebhut.com/regex/4

The part [a-z0-9] exactly matches one character which can be only small letter or number. The middle part [a-z0-9_]{2,28} matches any small letter or number up to 2 or 28 characters including underscore. The final part [a-z0-9] exactly matches one character which can be only small letter or number. Therefore, this regular expression matches username that has at least 4 characters and 30 characters at the most. If you change your mind and want to include both small and capital letters, you'll have to add a modifier i:

/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/i

https://www.tinywebhut.com/regex/5


问:
PHP / AJAX user last online displayed in real time
I have a good piece of code that shows how many users are online using sessions from a table named 'online_users'.

I'm using AJAX to return my data on to my home PHP page (this works; I just need the method to check each online client changed).

Here is a picture of my current styling using the first code method below

Here is a picture of my 'Online_users' table in my database

I need to use the same method of this code to check each users online time.

At the moment, it only counts how many users are online.

I also have another piece of code to check, but it doesn't run the same way as the second method (the method that gets online users count). This one shows offline if a timer has passed. I need to make it work the same way as the count online users method (Method 2 in the code below) so it checks sessions in my database.

I need to make it so the each individual user check does it the same way by checking the session in my table 'online_users'.

My 1st code (Working but changes to offline after a certain amount of time instead of checking if the session is still active) :

```<code>//First, define our client_is_online so we don't throw errors in the while loop
$client_is_online = "";

//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$last_online = strtotime($users_['lastonline']);

if(time() - $last_online < 30) {
    $client_is_online .= '
         <div class="chat-list-item sidebar-tab -available" data-target="#chat-view-tab" style="background: rgba(255,255,255,0.1); padding: 5px;">
            <img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
            <div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
            <div class="chat-list-excerpt">Online</div>
         </div>
    ';
} else {
    $client_is_online .= '
         <div class="chat-list-item sidebar-tab -away" data-target="#chat-view-tab" style="background: rgba(255,255,255,0.1); padding: 5px;">
            <img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
            <div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
            <div class="chat-list-excerpt">Offline</div>
         </div>
    ';
}
}
</code>```

My 2nd code (Get count of online users - Works perfectly but I need to use this sort of way for checking if each individual user is online) :

```<code>//Count online users
$session = session_id(); $time = time(); $time_check = $time - 30; //We have set a check of 30 seconds
$result = mysqli_query($con, "SELECT * FROM online_users WHERE session = '$session'");
$count  = mysqli_num_rows($result);

if($count == '0') { $result1 = mysqli_query($con, "INSERT INTO online_users(session, time) VALUES ('$session', '$time')"); }
else { $result2 = mysqli_query($con, "UPDATE online_users SET time = '$time' WHERE session = '$session'"); }

$result3     = mysqli_query($con, "SELECT * FROM online_users");
$totalOnline = mysqli_num_rows($result3);
$result4     = mysqli_query($con, "DELETE FROM online_users WHERE time < $time_check");
</code>```

答:
You should use WebSocket and Redis instead

Querying database like this can make your application slow and consume more data

Read more

Redis Link >> Redis

WebSocket Link>> Socket.IO

Body:
I have a good piece of code that shows how many users are online using sessions from a table named 'online_users'.

I'm using AJAX to return my data on to my home PHP page (this works; I just need the method to check each online client changed).

Here is a picture of my current styling using the first code method below

Here is a picture of my 'Online_users' table in my database

I need to use the same method of this code to check each users online time.

At the moment, it only counts how many users are online.

I also have another piece of code to check, but it doesn't run the same way as the second method (the method that gets online users count). This one shows offline if a timer has passed. I need to make it work the same way as the count online users method (Method 2 in the code below) so it checks sessions in my database.

I need to make it so the each individual user check does it the same way by checking the session in my table 'online_users'.

My 1st code (Working but changes to offline after a certain amount of time instead of checking if the session is still active) :

//First, define our client_is_online so we don't throw errors in the while loop
$client_is_online = "";

//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$last_online = strtotime($users_['lastonline']);

if(time() - $last_online < 30) {
    $client_is_online .= '

'.$users_['username'].' ('.get_users_level_all($users_['userLevel']).')

Online

    ';
} else {
    $client_is_online .= '

'.$users_['username'].' ('.get_users_level_all($users_['userLevel']).')

Offline

    ';
}
}

My 2nd code (Get count of online users - Works perfectly but I need to use this sort of way for checking if each individual user is online) :

//Count online users
$session = session_id(); $time = time(); $time_check = $time - 30; //We have set a check of 30 seconds
$result = mysqli_query($con, "SELECT * FROM online_users WHERE session = '$session'");
$count  = mysqli_num_rows($result);

if($count == '0') { $result1 = mysqli_query($con, "INSERT INTO online_users(session, time) VALUES ('$session', '$time')"); }
else { $result2 = mysqli_query($con, "UPDATE online_users SET time = '$time' WHERE session = '$session'"); }

$result3     = mysqli_query($con, "SELECT * FROM online_users");
$totalOnline = mysqli_num_rows($result3);
$result4     = mysqli_query($con, "DELETE FROM online_users WHERE time < $time_check");


问:
Bootstrap 4: Vertical align image in a circle button
I have a circle button that needs to have a plus image in the center of it. The thing is, I can't seem to vertical align that image without resorting to messing with margins.

Is there an easier, Bootstrap-y way of doing this?

Here's my code:

.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
}

/* the button is supposed to be a circle, but for some reason it's not showing up like that in this snippet */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<img src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" height="20"></code>```

答:
One way is to make the  display:flex using the included d-flex class.

```<code><a class="btn btn-circle mr-3 d-flex justify-content-center align-items-center" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"><img src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" class="" height="20"></a>
</code>```

The use the appropriate util classes to center:
justify-content-center align-items-center

https://www.codeply.com/go/BE0Jh6NqrL

Body:
I have a circle button that needs to have a plus image in the center of it. The thing is, I can't seem to vertical align that image without resorting to messing with margins.

Is there an easier, Bootstrap-y way of doing this?

Here's my code:

.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
}

/* the button is supposed to be a circle, but for some reason it's not showing up like that in this snippet */

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Body:
One way is to make the <a..></a> display:flex using the included d-flex class.

<a class="btn btn-circle mr-3 d-flex justify-content-center align-items-center" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"><img src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" class="" height="20"></a>

The use the appropriate util classes to center:
justify-content-center align-items-center

https://www.codeply.com/go/BE0Jh6NqrL


问:
PHP function to remove key from a query string
I have a query string, like:

n1=v1&n2=v2&n3=v3

etc

I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.

Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:

n1=v1&n2=&n3

I don’t know in advance how many keys there will be.

I am convinced that regexes are monsters that eat time.  Eventually all matter in the universe will end up in a regex.

答:
```<code>parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);
</code>```

NOTE: unset($gets['n3']); is just a show-case example

Body:
parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);

NOTE: unset($gets['n3']); is just a show-case example


问:
subscribed value returns undefined in component.ts but value exists in service.ts
Here are the contents of my component.ts file

```<code>import { Component, OnInit } from '@angular/core';
import { GoogleSheetsService } from '../shared/services/googlesheets.service';

@Component({
selector: 'home-component',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {

  apiPortfolioListEndPoint: string;
  portfolioList: Array<string>;

  constructor (
    private googleSheetsService: GoogleSheetsService
  ) {}

  ngOnInit() {
    this.apiPortfolioListEndPoint = '/home/portfolio';
    this.getImagesFromSheets(this.apiPortfolioListEndPoint);
  }

  getImagesFromSheets(sheetName) {
    this.googleSheetsService.getImages(sheetName)
      .subscribe(photos => {
        console.log(photos);
      });
  }
}
</code>```

and contents of my service.ts file

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GoogleSheetsService {

  constructor(
    private http: Http
  ) { }

  getImages(sheetName) {
    const apiServerEndPoint = '/api' + sheetName;
    return this.http.get(apiServerEndPoint)
      .map((res: Response) => {
        console.log(res.json());
        res.json();
      });
  }
}
</code>```

res in google sheets service returns an array of values and gets printed out on console but returns undefined when subscribed in my component (i.e. photos returns undefined on console).

getImages() calls an API that retrieves data from google spreadsheets.

When I tried to assign photos to the portfolioList variable, atom highlights the following error "Type 'void' is not assignable to type 'string[]' ". it makes sense since they are of different types, photos cannot be assigned to the variable but I cant seem to wrap my head around this problem and how I can go about fixing this.

Any suggestions or directions is greatly appreciated.

答:
You should return the results in the map

```<code>  getImages(sheetName) {
        const apiServerEndPoint = '/api' + sheetName;
        return this.http.get(apiServerEndPoint)
          .map((res: Response) => {
            console.log(res.json());
            /* You need to return the data here*/
            return res.json();
          });
      }
</code>```

Even better

```<code>/* import these first*/
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

      getImages(sheetName) {
            const apiServerEndPoint = '/api' + sheetName;
            return this.http.get(apiServerEndPoint)
              .map(this.extractData)
              .catch(this.catchError);
          }

      private extractData(res: Response) {
        return res.json();
      }

      private catchError(error: Response | any) {
        return Observable.throw(error.json().error || "Server Error");

      }
</code>```

Edit

Arrow functions can have either a "concise body"

```<code>var fun = z => z + z; //In a concise body, only an expression is needed,and an implicit return is attached.
</code>```

or the usual "block body".

```<code>var fun = (x,y) => { return x + y;}; //  In a block body, you must use an explicit return statement.
</code>```

Since your function is "block body", you must use an explicit return statement.

Body:
Here are the contents of my component.ts file

import { Component, OnInit } from '@angular/core';
import { GoogleSheetsService } from '../shared/services/googlesheets.service';

@Component({
selector: 'home-component',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {

  apiPortfolioListEndPoint: string;
  portfolioList: Array<string>;

  constructor (
    private googleSheetsService: GoogleSheetsService
  ) {}

  ngOnInit() {
    this.apiPortfolioListEndPoint = '/home/portfolio';
    this.getImagesFromSheets(this.apiPortfolioListEndPoint);
  }

  getImagesFromSheets(sheetName) {
    this.googleSheetsService.getImages(sheetName)
      .subscribe(photos => {
        console.log(photos);
      });
  }
}

and contents of my service.ts file

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GoogleSheetsService {

  constructor(
    private http: Http
  ) { }

  getImages(sheetName) {
    const apiServerEndPoint = '/api' + sheetName;
    return this.http.get(apiServerEndPoint)
      .map((res: Response) => {
        console.log(res.json());
        res.json();
      });
  }
}

res in google sheets service returns an array of values and gets printed out on console but returns undefined when subscribed in my component (i.e. photos returns undefined on console).

getImages() calls an API that retrieves data from google spreadsheets.

When I tried to assign photos to the portfolioList variable, atom highlights the following error "Type 'void' is not assignable to type 'string[]' ". it makes sense since they are of different types, photos cannot be assigned to the variable but I cant seem to wrap my head around this problem and how I can go about fixing this.

Any suggestions or directions is greatly appreciated.

Body:
You should return the results in the map

  getImages(sheetName) {
        const apiServerEndPoint = '/api' + sheetName;
        return this.http.get(apiServerEndPoint)
          .map((res: Response) => {
            console.log(res.json());
            /* You need to return the data here*/
            return res.json();
          });
      }

Even better

/* import these first*/
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

      getImages(sheetName) {
            const apiServerEndPoint = '/api' + sheetName;
            return this.http.get(apiServerEndPoint)
              .map(this.extractData)
              .catch(this.catchError);
          }

      private extractData(res: Response) {
        return res.json();
      }

      private catchError(error: Response | any) {
        return Observable.throw(error.json().error || "Server Error");

      }

Edit

Arrow functions can have either a "concise body"

var fun = z => z + z; //In a concise body, only an expression is needed,and an implicit return is attached.

or the usual "block body".

var fun = (x,y) => { return x + y;}; //  In a block body, you must use an explicit return statement.

Since your function is "block body", you must use an explicit return statement.


问:
Dynamic Angular Js Not working via innerHTML
If I add a row with Dynamic Angular JS variable, it is not working.
Below is my code. Please help me let know the issue.

Also please note that the inner HTML in my original code is 600 lines long. In this example I have used simple div to simplify.

```<code><div data-ng-init="quantity_r=1;price_r=5">
   <h2>Cost Calculator Quantity:</h2>
   <input type="number" ng-model="quantity_r"> Price: <input type="number" ng-model="price_r">
 <div>
Total in dollar: {{quantity_r * price_r}}
 </div>
</code>```

<!DOCTYPE html>

<button onclick="replicateRegion()">insert Row</button>

Cost Calculator Quantity:

   <input type="number" ng-model="quantity_r"> Price: <input type="number" ng-model="price_r">

Total in dollar: {{quantity_r * price_r}}

```

Only the first row which is static has the correct output. The rows added after button-click "Insert Row" have the problematic Angular JS output. Please help.

答:
When you add markup manually, like

```<code>document.getElementById('idTableTD1').innerHTML= '<div dynamic></div>'
</code>```

you are bypassing all AngularJS code. You should do it rather as this:

```<code>angular.element("#idTableTD1").html('<div dynamic></div>');
</code>```

may be this will help.

ContentLicense: CC BY-SA 4.0

Body:
If I add a row with Dynamic Angular JS variable, it is not working.
Below is my code. Please help me let know the issue.

Also please note that the inner HTML in my original code is 600 lines long. In this example I have used simple div to simplify.

Cost Calculator Quantity:

   <input type="number" ng-model="quantity_r"> Price: <input type="number" ng-model="price_r">

Total in dollar: {{quantity_r * price_r}}

<!DOCTYPE html>

<button onclick="replicateRegion()">insert Row</button>

Cost Calculator Quantity:

   <input type="number" ng-model="quantity_r"> Price: <input type="number" ng-model="price_r">

Total in dollar: {{quantity_r * price_r}}

Only the first row which is static has the correct output. The rows added after button-click "Insert Row" have the problematic Angular JS output. Please help.

Body:
When you add markup manually, like

document.getElementById('idTableTD1').innerHTML= '<div dynamic></div>'

you are bypassing all AngularJS code. You should do it rather as this:

angular.element("#idTableTD1").html('<div dynamic></div>');

may be this will help.


问:
Left right button for slider like Bootstrap carousel
I Want to slide my images right and left on click. I use jquery for that. but problem is that when I continue to click on right the div goes right and blank space display. I tried but it not fixes. I'm a newbie in jquery.</p>

```<code>    <!DOCTYPE html><html class=''>
<head>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<style class="cp-pen-styles">
.row_outer {
  *overflow-x: auto;
  width: 100%;
}
.row__inner {
  -webkit-transition: 450ms -webkit-transform;
  transition: 450ms -webkit-transform;
  transition: 450ms transform;
  transition: 450ms transform, 450ms -webkit-transform;
  font-size: 0;
  white-space: nowrap;
  margin: 70.3125px 0;
  padding-bottom: 10px;
}
.tile {
  position: relative;
  display: inline-block;
  width: 326px;
  height: 192px;
  margin-right: 10px;
  font-size: 20px;
  cursor: pointer;
  -webkit-transition: 450ms all;
  transition: 450ms all;
  -webkit-transform-origin: center left;
          transform-origin: center left;
}
.tile__img {
  width: 326px;
  height: 192px;
  -o-object-fit: cover;
     object-fit: cover;
}
.tile__details {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  font-size: 10px;
  opacity: 0;
  background: -webkit-linear-gradient(bottom, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 100%);
  background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 100%);
  -webkit-transition: 450ms opacity;
  transition: 450ms opacity;
}
.tile__details:after,
.tile__details:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  display: #000;
}
.tile__details:after {
  margin-top: -25px;
  margin-left: -25px;
  width: 50px;
  height: 50px;
  border: 3px solid #ecf0f1;
  line-height: 50px;
  text-align: center;
  border-radius: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 1;
}
.tile__details:before {
  content: '▶';
  left: 0;
  width: 100%;
  font-size: 30px;
  margin-left: 7px;
  margin-top: -18px;
  text-align: center;
  z-index: 2;
  color: #fff;
}
.tile:hover .tile__details {
  opacity: 1;
}
.tile__title {
  position: absolute;
  bottom: 0;
  padding: 10px;
  color: #fff;
}
.row__inner:hover {
  -webkit-transform: translate3d(-72.5px, 0, 0);
          transform: translate3d(-72.5px, 0, 0);
}
.row__inner:hover .tile {
  opacity: 0.3;
}
.row__inner:hover .tile:hover {
  -webkit-transform: scale(1.5);
          transform: scale(1.5);
  opacity: 1;
}
.tile:hover ~ .tile {
  -webkit-transform: translate3d(215px, 0, 0);
          transform: translate3d(215px, 0, 0);
}

    .buttons{
        position: absolute;
        width: 100%;
        margin-right: 10px;
        font-size: 20px;
        margin-top: -190px;
    }

    .buttons button{
        height: 100%;
        padding: 7px 20px;
        color: #fa8f33;
        border: 1px solid
    }

    .left{
    float: left;
    }

    .right{
        float: right;
    }

/* Sweep To Right */
.hvr-sweep-to-right {
  display: inline-block;
  vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px transparent;
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
}
.hvr-sweep-to-right:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fa8f33;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transform-origin: 0 50%;
  transform-origin: 0 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}
.hvr-sweep-to-right:hover, .hvr-sweep-to-right:focus, .hvr-sweep-to-right:active {
  color: white;
}
.hvr-sweep-to-right:hover:before, .hvr-sweep-to-right:focus:before, .hvr-sweep-to-right:active:before {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

/* Sweep To Left */
.hvr-sweep-to-left {
  display: inline-block;
  vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px transparent;
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
}
.hvr-sweep-to-left:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fa8f33;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transform-origin: 100% 50%;
  transform-origin: 100% 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}
.hvr-sweep-to-left:hover, .hvr-sweep-to-left:focus, .hvr-sweep-to-left:active {
  color: white;
}
.hvr-sweep-to-left:hover:before, .hvr-sweep-to-left:focus:before, .hvr-sweep-to-left:active:before {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

</style></head><body>
<div class="contain">

  <div class="row_outer">
    <div class="row__inner">

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-1.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img " src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-2.jpg" alt="" />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img " src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-3.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-4.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-5.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-6.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-7.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-8.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-9.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-10.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-11.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-12.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-13.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-14.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-15.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-16.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-17.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-18.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-19.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="buttons">
         <button class="left hvr-sweep-to-left " id="left"><span><i class="fa fa-angle-double-left" aria-hidden="true"></i>
</span></button>
         <button href="" class="right hvr-sweep-to-right " id="right"><span><i class="fa fa-angle-double-right" aria-hidden="true"></i>
</span></button>
     </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    $( "#right" ).click(function() {
      $( ".tile" ).animate({ "left": "+=365px" }, "1000" );
    });

    $( "#left" ).click(function(){
      $( ".tile" ).animate({ "left": "-=365px" }, "1000" );
    });
    </script>

</body></html>
</code>```

答:
Thanks to Every one who looked into it. I Fix my problem.

This is my Solution :

```<code>var $par = $('.row_outer').scrollLeft(546) ;
$('.right, .left').click(function( e ) {
    e.preventDefault();
    var n = $(this).hasClass("left") ? "+=182" : "-=182";
    $par.animate({scrollLeft: n});
});
</code>```

Body:
I Want to slide my images right and left on click. I use jquery for that. but problem is that when I continue to click on right the div goes right and blank space display. I tried but it not fixes. I'm a newbie in jquery.

    <!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

         <button class="left hvr-sweep-to-left " id="left">
</button>
         <button href="" class="right hvr-sweep-to-right " id="right">
</button>

Body:
Thanks to Every one who looked into it. I Fix my problem.

This is my Solution :

var $par = $('.row_outer').scrollLeft(546) ;
$('.right, .left').click(function( e ) {
    e.preventDefault();
    var n = $(this).hasClass("left") ? "+=182" : "-=182";
    $par.animate({scrollLeft: n});
});


问:
Save textField value to cell textLabel (name) [SWIFT]
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

```<code>@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}
</code>```

And here is code from the VC file

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}
</code>```

So how to save it to the user's name?

答:
Use DidSelectRowAtIndexPath method to get cell textLable text in textField.

Below Sample Code for That:

```<code>import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var btnOK: UIButton!
    @IBOutlet var txtValue: UITextField!
    @IBOutlet var tblData: UITableView!
    let arrResult = NSMutableArray()

    override func viewDidLoad() {
        super.viewDidLoad()

        tblData.dataSource = self
        tblData.delegate = self
        btnOK.tag = 57775
        btnOK.addTarget(self, action: #selector(applyEdit(sender:)), for: .touchUpInside)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrResult.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = arrResult[indexPath.row] as? String ?? ""
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        btnOK.tag = indexPath.row
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath)!
        txtValue.text = cell.textLabel?.text
        setTitle()
    }

    func setTitle() {
        if btnOK.tag == 57775 {
            btnOK.setTitle("Add", for: .normal)
        }else{
            btnOK.setTitle("Update", for: .normal)
        }
    }

    func applyEdit(sender: UIButton) {
        if sender.tag == 57775 {
            arrResult.add(txtValue.text ?? "")
        }else{
            arrResult.removeObject(at: sender.tag)
            arrResult.insert(txtValue.text ?? "", at: sender.tag)
            sender.tag = 57775
            setTitle()
        }
        txtValue.text = ""
        tblData.reloadData()
    }

}
</code>```

output:

Body:
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}

And here is code from the VC file

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}

So how to save it to the user's name?

Body:
Use DidSelectRowAtIndexPath method to get cell textLable text in textField.

Below Sample Code for That:

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var btnOK: UIButton!
    @IBOutlet var txtValue: UITextField!
    @IBOutlet var tblData: UITableView!
    let arrResult = NSMutableArray()

    override func viewDidLoad() {
        super.viewDidLoad()

        tblData.dataSource = self
        tblData.delegate = self
        btnOK.tag = 57775
        btnOK.addTarget(self, action: #selector(applyEdit(sender:)), for: .touchUpInside)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrResult.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = arrResult[indexPath.row] as? String ?? ""
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        btnOK.tag = indexPath.row
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath)!
        txtValue.text = cell.textLabel?.text
        setTitle()
    }

    func setTitle() {
        if btnOK.tag == 57775 {
            btnOK.setTitle("Add", for: .normal)
        }else{
            btnOK.setTitle("Update", for: .normal)
        }
    }

    func applyEdit(sender: UIButton) {
        if sender.tag == 57775 {
            arrResult.add(txtValue.text ?? "")
        }else{
            arrResult.removeObject(at: sender.tag)
            arrResult.insert(txtValue.text ?? "", at: sender.tag)
            sender.tag = 57775
            setTitle()
        }
        txtValue.text = ""
        tblData.reloadData()
    }

}

output:


问:
AVAssetTrack totalSampleDataLength is 0
I'm programming an iPhone app which uses an AVAssetReader to read samples from an AVAssetTrack, I need to allocate some memory which depends on the number of samples in the AVAssetTrack, but for some reason totalSampleDataLength is returning 0.

Any ideas?

答:
< warning - guess! >

Perhaps it's something to do with the AVAsynchronousKeyValueLoading protocol - do you have to ask it to load the value for that key before it's populated?

Title: AVAssetTrack totalSampleDataLength is 0


问:
shruti font is not working proper
i need to print gujrati font fron string.xml file with Shruti.ttf font in textview but it is not printing right specially in case of vowels

e.g i want to print પિતા:

and in textview it find -->

答: You can do same thing using local. for more information you may prefer  this link </p>

Title: shruti font is not working proper


问:
Unable to run Python code
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

```<code>import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")
</code>```

When I try running this in Powershell, I get the output below - what am I doing    wrong?

```<code>PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
This type string formating start supported on 3.6 version.

Use function format
 for python3.5:

print('{two} {plus} {two} = 4'.format(two=2, plus='4'))
```

<p>Or other methods for string formating:</p>

<pre class="lang-py prettyprint-override"><code>print("%d %s %d = 4" % (2, '+', 2))
print("%(two)d %(plus)s %(two)d = 4" % {"two": 2, "plus": '+'})
</code>```

Title: Unable to run Python code

Body:
I have installed Python 3.5 in the directory c:\users\rshukla\desktop\python\python35

I have downloaded a simple Python code that I have saved in Atom.io also in the same folder c:\users\rshukla\desktop\python\happy_hour.py
And I am trying to it run through Powershell

import random

bars = ["Shoolbred's",
    "The Wren",
    "The Scratcher",
    "ACME",
    "Blind Barber"]

people = ["Mattan",
      "Chris",
      "Pooje",
      "that person you forgot to text back",
      "Kanye West",
      "Samuel L. Jackson"]

random_bar = random.choice(bars)
random_person_1 = random.choice(people)
random_person_2 = ramndon.choice(people)

print(f"How about you go to {random_bar} with {random_person_1} and {random_person_2}")

When I try running this in Powershell, I get the output below - what am I doing    wrong?

PS C:\Users\rshukla\desktop\python> python happy_hour.py
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python happy_hour.py
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Body:
This type string formating start supported on 3.6 version.

Use function format
 for python3.5:

print('{two} {plus} {two} = 4'.format(two=2, plus='4'))

Or other methods for string formating:

print("%d %s %d = 4" % (2, '+', 2))
print("%(two)d %(plus)s %(two)d = 4" % {"two": 2, "plus": '+'})


问:
Center image in ul
Tried to google this but didn't find anything that helped me.
So I have button-text on the left and right but I want to center an image inside the top bar.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #f3f3f3;
    }

    li {
    float: left;
    }

    li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }

    li a:hover:not(.active) {
    background-color: #ddd;
    }

    li a.active {
    color: white;
    background-color: #3744a2;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>home</li>
    <li>news</li>
    <li>services</li>
    <li>prices</li>
    <li>contat</li>
    <li><img src="https://dummyimage.com/150X38/000/fff"></li>
    <li style="float:right"><i class="fa fa-envelope" aria-hidden="true"></i>  enter@email.here</li>
    <li style="float:right"><i class="fa fa-phone" aria-hidden="true"></i>  123 123 123</li>
    </ul></code>```

so what I basicly want is the image (class="image") to be centered, but the rest as it is.

Thanks alot!

答:
```<code>a.image {
    display: block;
    margin-left: auto;
    margin-right: auto
}
</code>```

<p>try adding that code in your css file . Also try have a look here
it has more info about centering things . </p>

Title: Center image in ul

Body:
Tried to google this but didn't find anything that helped me.
So I have button-text on the left and right but I want to center an image inside the top bar.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #f3f3f3;
    }

    li {
    float: left;
    }

    li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }

    li a:hover:not(.active) {
    background-color: #ddd;
    }

    li a.active {
    color: white;
    background-color: #3744a2;
    }

home

news

services

prices

contat

  enter@email.here

  123 123 123

so what I basicly want is the image (class="image") to be centered, but the rest as it is.

Thanks alot!

Body:
a.image {
    display: block;
    margin-left: auto;
    margin-right: auto
}

try adding that code in your css file . Also try have a look here
it has more info about centering things .


问:
MySQL update column value where else update another column value (single query)
I would like to link these two queries together rather than executing them both at different times.

```<code>UPDATE `table` SET `column_one` = @value WHERE `column_one_key` = @key LIMIT 1;
</code>```

and also this query;

```<code>UPDATE `table` SET `column_two` = @value WHERE `column_two_key` = @key LIMIT 1;
</code>```

Something like this but can't seem to get it to work

```<code>UPDATE `table` (SET `column_one` = @value WHERE `column_one_key` = @key) || (SET `column_two` = @value WHERE `column_two_key` = @key) LIMIT 1;
</code>```

Some additional information

column_one_key and column_two_key are never the same which is why you can use OR.

答:
If you don't need the limit (that is, one match per key), you can do:

```<code>UPDATE `table`
     SET column_one = (CASE WHEN @key = column_one_key THEN @value ELSE column_one END),
         column_two = (CASE WHEN @key = column_two_key THEN @value ELSE column_two END)
    WHERE @key IN (column_one_key, column_two_key);
</code>```

I think two updates are simpler.  And, if you do need the limit, then two updates are definitely a simpler approach.

Body:
I would like to link these two queries together rather than executing them both at different times.

UPDATE `table` SET `column_one` = @value WHERE `column_one_key` = @key LIMIT 1;

and also this query;

UPDATE `table` SET `column_two` = @value WHERE `column_two_key` = @key LIMIT 1;

Something like this but can't seem to get it to work

UPDATE `table` (SET `column_one` = @value WHERE `column_one_key` = @key) || (SET `column_two` = @value WHERE `column_two_key` = @key) LIMIT 1;

Some additional information

column_one_key and column_two_key are never the same which is why you can use OR.

Body:
If you don't need the limit (that is, one match per key), you can do:

UPDATE `table`
     SET column_one = (CASE WHEN @key = column_one_key THEN @value ELSE column_one END),
         column_two = (CASE WHEN @key = column_two_key THEN @value ELSE column_two END)
    WHERE @key IN (column_one_key, column_two_key);

I think two updates are simpler.  And, if you do need the limit, then two updates are definitely a simpler approach.


问:
How to label duplicate groups in pandas?
I have a DataFrame:

```<code>>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar
</code>```

I need to find all the duplicate groups and label them with sequential dgroup_id's:

```<code>>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2
</code>```

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
</code>```

This leads to:

```<code>>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0
</code>```

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

答:
You can make a list of duplicates by get_duplicates() then set the dgroup_id by A's index

```<code>def find_index(string):
    if string in duplicates:
        return duplicates.index(string)+1
    else:
        return 0

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})
duplicates = df.set_index('A').index.get_duplicates()
df['dgroup_id'] = df['A'].apply(find_index)
df
</code>```

Output:

```
     A  dgroup_id
0  foo          2
1  bar          1
2  foo          2
3  baz          0
4  foo          2
5  bar          1
```

Body:
I have a DataFrame:

>>> df
     A
0  foo
1  bar
2  foo
3  baz
4  foo
5  bar

I need to find all the duplicate groups and label them with sequential dgroup_id's:

>>> df
     A  dgroup_id
0  foo          1
1  bar          2
2  foo          1
3  baz
4  foo          1
5  bar          2

(This means that foo belongs to the first group of duplicates, bar to the second group of duplicates, and baz is not duplicated.)

I did this:

import pandas as pd

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})

duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))

This leads to:

>>> df
     A  dgroup_id
0  foo        1.0
1  bar        0.0
2  foo        1.0
3  baz        NaN
4  foo        1.0
5  bar        0.0

Is there a simpler/shorter way to achieve this in pandas? I read that maybe pandas.factorize could be of help here, but I don't know how to use it... (the pandas documentation on this function is of no help)

Also: I don't mind neither the 0-based group count, nor the weird sorting order; but I would like to have the dgroup_id's as ints, not floats.

Body:
You can make a list of duplicates by get_duplicates() then set the dgroup_id by A's index

def find_index(string):
    if string in duplicates:
        return duplicates.index(string)+1
    else:
        return 0

df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})
duplicates = df.set_index('A').index.get_duplicates()
df['dgroup_id'] = df['A'].apply(find_index)
df

Output:

     A  dgroup_id
0  foo          2
1  bar          1
2  foo          2
3  baz          0
4  foo          2
5  bar          1


问:
passing data from javascript to servlet
I have values of checkbox and as soon as I click delete the values and the type must be sent to a servlet called DeleteServlet. Please help me how to send the values?

```<code><html>
    <head>
    <script type="text/javascript">
     function get_check_value(chkbox){
           if(chkbox.checked){
          var Values=chkbox.value;
          //send this Values to servlet

             }

    }
    function doDelete(theClick){
    var type=theClick;
//send this type to servlet
    alert(type);

    }

    </script>
    </head>
    <%String user=request.getParameter("Users"); %>
    <body>
    <%

    String User[]=user.trim().split(" ");

    for(int i=0;i<User.length;i++){%>
     <center>
        <form name='list' action='AddUserServlet'>

     <%  out.println("<input type='checkbox' name='user" + i + "' value='"+ User[i] + "' onClick='return get_check_value(this)'>" + User[i]+ "</input>" ); %>

    </form>

    <%}%>

        <input type="submit" value="ADD" name="b1" >
        <input type="submit" value="MODIFY" name="b1">
     <input type="submit" value="DELETE" name="b1" onClick="return doDelete(value)" >

      </center>

    </body>
    </html>
</code>```

I tried this  "document.list.user.value" in an alert box it comes as undefined object. To send to a servlet I tried the following line but nothing is read

```<code>chk_val=chkbox.value;
document.add.action = "AddUserServlet?type=delete&name="+chk_val;
 document.add.submit();
</code>```

答:
Could you use jQuery javascript libary. It is easy to use and you will find lots of tutorials.
Here is good tutorial about get method(AJAX) http://api.jquery.com/jQuery.get/

Is it possible to do it without javascript?

Title: passing data from javascript to servlet

Body:
I have values of checkbox and as soon as I click delete the values and the type must be sent to a servlet called DeleteServlet. Please help me how to send the values?

    <%String user=request.getParameter("Users"); %>

    <%

    String User[]=user.trim().split(" ");

    for(int i=0;i<User.length;i++){%>

        <form name='list' action='AddUserServlet'>

     <%  out.println("<input type='checkbox' name='user" + i + "' value='"+ User[i] + "' onClick='return get_check_value(this)'>" + User[i]+ "</input>" ); %>

    </form>

    <%}%>

        <input type="submit" value="ADD" name="b1" >
        <input type="submit" value="MODIFY" name="b1">
     <input type="submit" value="DELETE" name="b1" onClick="return doDelete(value)" >

I tried this  "document.list.user.value" in an alert box it comes as undefined object. To send to a servlet I tried the following line but nothing is read

chk_val=chkbox.value;
document.add.action = "AddUserServlet?type=delete&name="+chk_val;
 document.add.submit();


问:
I am unable to change the directory in cmd
cmd is not able to change the directory using the command

```<code>C:\Windows\system32>CD I:
</code>```

It is going back to same C: directory

The screenshot

答:
The short answer

The correct commando to go from C:\Windows\system32 to I:\, is this :

```<code>cd /d i:\
</code>```

More details

If you're somewhere random on your I:\ drive, and you want to go to the root of your drive, you can use this command :

```<code>cd i:\
</code>```

If you're somewhere random on your I:\ drive, and you want to go to a specific folder on your drive, you can use this command :

```<code>cd i:\path\to\my\folder
</code>```

If you're on a different drive, and you want to go to the root of your I:\ drive, you can use this command :

```<code>cd /d i:\
</code>```

If you're on a different drive, and you want to go to a specific folder on your I: drive, you can use this command :

```<code>cd /d i:\path\to\my\folder
</code>```

If you're on a different drive, and you want to go to the last open folder of you I: drive, you can use this command :

```<code>cd /d i:
</code>```

As a shorthand for cd /d i:, you can also use this command :

```<code>i:
</code>```

Body:
cmd is not able to change the directory using the command

C:\Windows\system32>CD I:

It is going back to same C: directory

The screenshot

Body:
The short answer

The correct commando to go from C:\Windows\system32 to I:\, is this :

cd /d i:\

More details

If you're somewhere random on your I:\ drive, and you want to go to the root of your drive, you can use this command :

cd i:\

If you're somewhere random on your I:\ drive, and you want to go to a specific folder on your drive, you can use this command :

cd i:\path\to\my\folder

If you're on a different drive, and you want to go to the root of your I:\ drive, you can use this command :

cd /d i:\

If you're on a different drive, and you want to go to a specific folder on your I: drive, you can use this command :

cd /d i:\path\to\my\folder

If you're on a different drive, and you want to go to the last open folder of you I: drive, you can use this command :

cd /d i:

As a shorthand for cd /d i:, you can also use this command :

i:


问:
How to change a cell value periodically in libreoffice calc?
The title says it all...

For example, if I want to have a cell which displays the current time and auto updates minute by minute (well, I think we call that a clock), how do I do it?

Is there a simple function implemented already or should I create a macro and assign it to a specific event?

EDIT: Following the provided answer by @Jim K, I want to be more clear about what I want. The "clock" example above was here to make it simple to understand, but what I really want is in the title: a cell value which changes periodically, be it a string, a number, a date...

答:
tl;dr

Is there a simple function implemented already

No.

From LibreOffice and fairly recent:

(I don't know a 'clock' property applying to cells.)

There are simple ways to obtain the time, for example given suitable formatting, with date:

```<code>=NOW()
</code>```

or Ctrl+;

Or, for example, without date:

```<code>=MOD(NOW(),1)
</code>```

The first and last will update, but only when the sheet is recalculated.

For a cell that ticks away (eg second by second) I believe you will need a script.

Body:
tl;dr

Is there a simple function implemented already

No.

From LibreOffice and fairly recent:

(I don't know a 'clock' property applying to cells.)

There are simple ways to obtain the time, for example given suitable formatting, with date:

=NOW()

or Ctrl+;

Or, for example, without date:

=MOD(NOW(),1)

The first and last will update, but only when the sheet is recalculated.

For a cell that ticks away (eg second by second) I believe you will need a script.


问:
How to request all permission needed when the time user install the app in Google Play?
I have an Android app,but when user click "Install" button,the app install directly and it didn't prompt up to ask for permission for user to accept directly.So,I need to request permission during runtime.

But what I need to do,when user click "Install" button,request all the permission needed before the app start downloading from Google Play just like the image below:

So far my manifest is look like this

```<code><uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</code>```

So what I need to add in order to achieve this?

答:
You are welcome to have your targetSdkVersion below 23, which will force the request for permissions at install time.

Over time, seeing this permission dialog at install time will signal to prospective users that your app is obsolete and not being maintained. An increasing number of those prospective users will elect to not install your app as a result.

Also, bear in mind that users can still remove your requested permissions via the Settings app.

Body:
I have an Android app,but when user click "Install" button,the app install directly and it didn't prompt up to ask for permission for user to accept directly.So,I need to request permission during runtime.

But what I need to do,when user click "Install" button,request all the permission needed before the app start downloading from Google Play just like the image below:

So far my manifest is look like this

<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

So what I need to add in order to achieve this?


问:
Partition of tables in MySQL
I have read that in a case where a table has many columns, but most of the time only one of them is used (say a title column in a forum post), a way to increase performance would be a partition to two tables, where one will contain only the title and the other one will contain the other columns (such as the forum post body).

However, in case I use

```<code>select ForumTitle from Forum;
</code>```

won't that be good enough to prevent the load of all columns (such as the forum post's body) to the memory, and eliminate the need of partition?

Thanks,

Joel

答:
No. The idea of partitioning the table is that the resulting table is much smaller; it fits on fewer pages. Therefore if MySQL needs to access the data freqeuently the chances that requested data containting the ForumTitles are already in memory are much bigger.

If a table contains a lot of fields, much more pages need to be cached in memory to cache the same amount of ForumTitles.

MySQL stores all columns of a row sequentially on a page and cannot load nor cache only part of a row.

Title: Partition of tables in MySQL

Body:
I have read that in a case where a table has many columns, but most of the time only one of them is used (say a title column in a forum post), a way to increase performance would be a partition to two tables, where one will contain only the title and the other one will contain the other columns (such as the forum post body).

However, in case I use

select ForumTitle from Forum;

won't that be good enough to prevent the load of all columns (such as the forum post's body) to the memory, and eliminate the need of partition?

Thanks,

Joel


问:
Why can't I assign an array variable directly to another array variable with the '=' operator?
Why does the following assignment not work? I would like a low-level explanation if possible.  Also, here's the compiler error I get: incompatible types in assignment of 'char*' to 'char [20]'</p>

```<code>class UCSDStudent {

  char name[20];

  public:

    UCSDStudent( char name[] ) {
      //this-> name = name; does not work! Please explain why not
      strcopy( this -> copy, copy ); //works
    }

};
</code>```

答:
Let's take this example.

```<code>int arr1[10] = {1,2,3,4,5,6,7,8,9,10};
</code>```

In case of C++, the array name arr1 does not get a separate memory location. It's true that arr1 sort of holds the memory location of arr1[0] but that is more of an oversimplification. The way arrays are referenced in C++ is via the symbol table. When an array is created,  corresponding to arr1 an entry is created in the symbol table at compile time. This entry contains the information about the data-type of elements in  arr1 (which here is an integer-type array) and the address of arr1[0].
Now, here lies the interesting thing. Once an entry is created in the symbol table, C++ does not allow for it be changed.

If you do arr1=arr2, what you are essentially trying to do is reassign arr1 to the entry corresponding to arr2 in the symbol table. But arr1 has already been assigned some value in the symbol table.   So C++ will give you an error.

Body:
Why does the following assignment not work? I would like a low-level explanation if possible.  Also, here's the compiler error I get: incompatible types in assignment of 'char*' to 'char [20]'

class UCSDStudent {

  char name[20];

  public:

    UCSDStudent( char name[] ) {
      //this-> name = name; does not work! Please explain why not
      strcopy( this -> copy, copy ); //works
    }

};

Body:
Let's take this example.

int arr1[10] = {1,2,3,4,5,6,7,8,9,10};

In case of C++, the array name arr1 does not get a separate memory location. It's true that arr1 sort of holds the memory location of arr1[0] but that is more of an oversimplification. The way arrays are referenced in C++ is via the symbol table. When an array is created,  corresponding to arr1 an entry is created in the symbol table at compile time. This entry contains the information about the data-type of elements in  arr1 (which here is an integer-type array) and the address of arr1[0].
Now, here lies the interesting thing. Once an entry is created in the symbol table, C++ does not allow for it be changed.

If you do arr1=arr2, what you are essentially trying to do is reassign arr1 to the entry corresponding to arr2 in the symbol table. But arr1 has already been assigned some value in the symbol table.   So C++ will give you an error.


问:
Can't make 2 Player Tic Tac Toe game work JavaScript
HTML

```<code><div class="container"> <-- div container -->

<div id="div1" onclick="canvasClicked(1);"></div>
<div id="div2" onclick="canvasClicked(2);"></div>
<div id="div3" onclick="canvasClicked(3);"></div>
<div id="div4" onclick="canvasClicked(4);"></div>
<div id="div5" onclick="canvasClicked(5);"></div>
<div id="div6" onclick="canvasClicked(6);"></div>
<div id="div7" onclick="canvasClicked(7);"></div>
<div id="div8" onclick="canvasClicked(8);"></div>
<div id="div9" onclick="canvasClicked(9);"></div>

</div> <-- div container end -->
</code>```

Css

```<code>  .container{     /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}

.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}
</code>```

JavaScript

```<code>var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;

var turn = 0;
var squaresFilled = 0; //global variables end

window.onload = function(){               //instantiating variables
painted = new Array();   //to check if the canvas contains something already
content = new Array();  //to see what the canvas contains 'X' or 'O'

winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P

for(var i=0; i<=8; i++){
    painted[i] = false;
    content[i]=false;
}
}

function canvasClicked(number){

theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);

if(painted[number-1]==false){
    if(turn%2==0){               //use X here
        c.innerHTML = '<img src="cross image" alt="x" width=100%
height=100%>';
        content[number-1] = 'X'; //storing value in content array
    }else{                       // user O here
        c.innerHTML = '<img src=" O image" height="100%"
width="100%" alt="O">';
        content[number-1] = 'O'; //storing value in content array
    }
}
else{
    alert('This block is already occupied, try another block');
    turn--;
    squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);

if(squaresFilled == 9){
    alert('It is a TIE');
    playAgain();
}
}

function checkForWinner(symbol){  // This functions seems to be the problem

for(var a = 0; a < winningCombinations.length; a++){

    if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
        console.log(symbol + ' won!!');
    }

}
}
function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}
</code>```

It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks

答:
Check your indices.

Either content[0-8] or content[1-9]

winningCombination uses 1-9
but canvasClicked uses 0-8

That's why you getting some strange results

Body:
HTML

 <-- div container -->

 <-- div container end -->

Css

  .container{     /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}

.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}

JavaScript

var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;

var turn = 0;
var squaresFilled = 0; //global variables end

window.onload = function(){               //instantiating variables
painted = new Array();   //to check if the canvas contains something already
content = new Array();  //to see what the canvas contains 'X' or 'O'

winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P

for(var i=0; i<=8; i++){
    painted[i] = false;
    content[i]=false;
}
}

function canvasClicked(number){

theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);

if(painted[number-1]==false){
    if(turn%2==0){               //use X here
        c.innerHTML = '';
        content[number-1] = 'X'; //storing value in content array
    }else{                       // user O here
        c.innerHTML = '';
        content[number-1] = 'O'; //storing value in content array
    }
}
else{
    alert('This block is already occupied, try another block');
    turn--;
    squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);

if(squaresFilled == 9){
    alert('It is a TIE');
    playAgain();
}
}

function checkForWinner(symbol){  // This functions seems to be the problem

for(var a = 0; a < winningCombinations.length; a++){

    if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
        console.log(symbol + ' won!!');
    }

}
}
function playAgain(){ // just another function to reset the game
    y=confirm("PLAY AGAIN?");
    if(y==true){
        location.reload(true);
    }else{
        alert('Good Bye Then!!');
    }
}

It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks


问:
User Name is not taking from Dataabase
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.</p>

```<code><?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>
</code>```

答:
Use something like this : </p>

```<code><?php
session_start(); //This always need to be first line of code
include("header.php");
include("classes/db.php");

$username="";
if(isset($_GET['username']))
{
    $user = mysqli_real_escape_string($con,$_GET['username']);
    //get data from table using the passed user name in the url
    $checkUser = mysqli_query($con,"SELECT user_name FROM user_reg WHERE user_name='$user'") or die(mysqli_error($con));
    //return number of rows from the above query
    //if more than 0 means user exist in database table
    if(mysqli_num_rows($checkUser)>0)
    {
        $row = mysqli_fetch_array($checkUser);
        $username = $row['user_name'];
        //use like this to store in session using $_SESSION global variable
        $_SESSION["firstname"] = $row["firstname"]; //firstname - column name in table
        $_SESSION["lastname"] = $row["lastname"];
        $_SESSION["email"] = $row["email"];
    }
    else
    {
        echo "User does not exist";
    }
}
?>
</code>```

Title: User Name is not taking from Dataabase

Body:
I'm new to php. I've some problem. I get the value of username with ($_GET) variable. Let's suppose if some one enter (mehwish) in url. I want to check if the username entered by user is available or not in the database. My code below doesn't work. Correct my mistake if there's any. Thank you for your support.

<?php include("header.php");
    include("classes/db.php");
    session_start();
    $username="";
    if(isset($_GET['username']))
    {
        $user=$_GET['username'];
        if("SELECT user_name FROM user_reg WHERE user_name='$user'")
        {
            $username="SELECT user_name FROM user_reg WHERE user_name='$user'";
            $run_username=mysqli_query($con,$username);
            $row=mysqli_fetch_array($run_username);
            $username=$row['user_name'];
        }
        else
        {
            die("User does nto exist");
        }
    }
    ?>

Body:
Use something like this :

<?php
session_start(); //This always need to be first line of code
include("header.php");
include("classes/db.php");

$username="";
if(isset($_GET['username']))
{
    $user = mysqli_real_escape_string($con,$_GET['username']);
    //get data from table using the passed user name in the url
    $checkUser = mysqli_query($con,"SELECT user_name FROM user_reg WHERE user_name='$user'") or die(mysqli_error($con));
    //return number of rows from the above query
    //if more than 0 means user exist in database table
    if(mysqli_num_rows($checkUser)>0)
    {
        $row = mysqli_fetch_array($checkUser);
        $username = $row['user_name'];
        //use like this to store in session using $_SESSION global variable
        $_SESSION["firstname"] = $row["firstname"]; //firstname - column name in table
        $_SESSION["lastname"] = $row["lastname"];
        $_SESSION["email"] = $row["email"];
    }
    else
    {
        echo "User does not exist";
    }
}
?>


问:
Redirect url without changing root
I want change url like this

mysite.org/myhtml5/index.html.txt
 mysite.org/myhtml5/opera/index.html.txt

  mysite.org/myhtml5/clicker/index.html.txt

To

mysite.org/myhtml5/index.html
 mysite.org/myhtml5/opera/index.html

  mysite.org/myhtml5/clicker/index.html

so i tried like this

location ~ $/index.html.txt {

  return 302 $1/index.html;
}

But it's not working. Would you help me? T_T

and i'm a newbie so i don't know about rule or like something. let me know when i'm doing something wrong.

答:
i solved.

location ~ /index.html.txt {

  return 302 index.html
 }

Title: Redirect url without changing root