问:
How to hide view behind the view
I'm placing a textview over a line as textview have light color background the line behind the textview is visible, I want to hide that portion of line thats behind textview, how can i do that

Thanks in advance!

Like this

答:
You can do it in multiple ways using a RelativeLayout.

```<code> <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_height="2dp"/>
    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:background="#FFFFFF"
        android:paddingLeft="10dp"
        android:paddingRight="10sp"
        android:layout_centerInParent="true"
        android:text="Some Demo text"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
         />
</RelativeLayout>
</code>```

Other way can be as .

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_toLeftOf="@+id/txt"
        android:layout_height="2dp"/>
    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10sp"
        android:layout_centerInParent="true"
        android:text="Some Demo text"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
         />

    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_toRightOf="@+id/txt"
        android:layout_height="2dp"/>
</RelativeLayout>
</code>```

Title: How to hide view behind the view

Body:
You can do it in multiple ways using a RelativeLayout.

 <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_height="2dp"/>
    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:background="#FFFFFF"
        android:paddingLeft="10dp"
        android:paddingRight="10sp"
        android:layout_centerInParent="true"
        android:text="Some Demo text"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
         />
</RelativeLayout>

Other way can be as .

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_toLeftOf="@+id/txt"
        android:layout_height="2dp"/>
    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10sp"
        android:layout_centerInParent="true"
        android:text="Some Demo text"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
         />

    <View
        android:layout_width="match_parent"
        android:layout_centerVertical="true"
        android:background="#000000"
        android:layout_toRightOf="@+id/txt"
        android:layout_height="2dp"/>
</RelativeLayout>


来源: stackexchange

问:
MySql column names of a query
Am I able to write a stored procedure with a parameter, which is the mysql query and the stored procedure returns the column names of the query?

For example I call the procedure:

call selector('select * from users')

And the procedure returns the column names.
It would be easy with information.schema but if I have a more complicated query and alias in it?

答:
Found a solution

```<code>CREATE DEFINER=`admin`@`localhost` PROCEDURE `selector`(
    IN `sql_query` VARCHAR(50))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGiN
drop table if exists tmp111;
SET @sql = concat('create table tmp111 as ', sql_query);
PREPARE stmt FROM @sql;
Execute stmt;
describe tmp111;
END
</code>```

Then call it like:

```<code>call selector('select name as n, email as e from users')
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySql column names of a query

Body:
Found a solution

CREATE DEFINER=`admin`@`localhost` PROCEDURE `selector`(
    IN `sql_query` VARCHAR(50))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGiN
drop table if exists tmp111;
SET @sql = concat('create table tmp111 as ', sql_query);
PREPARE stmt FROM @sql;
Execute stmt;
describe tmp111;
END

Then call it like:

call selector('select name as n, email as e from users')


答:
Try this

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_centerInParent="true"
                android:background="@color/colorAccent" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@color/colorPrimary"
                android:gravity="center"
                android:text="Nilesh" />
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:gravity="center"
        android:orientation="horizontal">

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerInParent="true"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:background="#FFFFFF"
            android:text="NILu" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerInParent="true"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

    </LinearLayout>

</LinearLayout>
</code>```

OUTPUT

Title: How to hide view behind the view

Body:
I'm placing a textview over a line as textview have light color background the line behind the textview is visible, I want to hide that portion of line thats behind textview, how can i do that

Thanks in advance!

Like this

Body:
Try this

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_centerInParent="true"
                android:background="@color/colorAccent" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@color/colorPrimary"
                android:gravity="center"
                android:text="Nilesh" />
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:gravity="center"
        android:orientation="horizontal">

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerInParent="true"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:background="#FFFFFF"
            android:text="NILu" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerInParent="true"
            android:layout_weight="1"
            android:background="@color/colorAccent" />

    </LinearLayout>

</LinearLayout>

OUTPUT


问:
Rails ActiveRecord Associations that include "owner" role
I’m creating a chore tracker app as my first Rails project and I’m wondering if the associations I've created make sense or could be improved.  Here are the details of the app:

A user makes a chore list and becomes the “owner”(i.e. “admin”) of
that list.

The owner can create/edit chores for the list.  They can also “approve" other users to complete tasks on the list.  These users can ONLY complete tasks.

The owner, along with the usual admin abilities, can also complete
tasks on a list that they own.

Owners can own multiple lists. Users can be approved to complete
tasks on multiple lists.

And here are the relationships I’ve roughed out that I’m looking for feedback on:

(Model)User

has_many :lists

has_many :owners, class_name: “List”, foreign_key: “list_id"

has_many :chores, through: :lists

(Model)List

has_many :users

has_many :chores

belongs_to :owner, class_name: “User”, foreign_key: “owner_id"

(Model)User_List

belongs_to :user

belongs_to :list

(Model)Chore

belongs_to :list

has_many :users, through: :lists

Any red flags?  Thank you in advance!

答:
I would do something like this:

```<code># user.rb
class User
  has_many :lists_users
  has_many :lists, through: :lists_users
  has_many :chores, through :lists
end

# list.rb
class List
  has_many :lists_users
  has_many :users, through: :lists_users
  has_many :chores
end

# lists_user.rb
class ListsUser
  belongs_to :user
  belongs_to :list

  # field (Representational, add it in database)
  :user_role
    - member (can view)
    - collaborator (can mark complete)
    - owner (can do everything)
end

# chore.rb
class Chore
  belongs_to :list
end
</code>```

NOTE: I changed the association model to ListsUser as per rails naming conventions.

Please let me know if i missed something.

Body:
I would do something like this:

# user.rb
class User
  has_many :lists_users
  has_many :lists, through: :lists_users
  has_many :chores, through :lists
end

# list.rb
class List
  has_many :lists_users
  has_many :users, through: :lists_users
  has_many :chores
end

# lists_user.rb
class ListsUser
  belongs_to :user
  belongs_to :list

  # field (Representational, add it in database)
  :user_role
    - member (can view)
    - collaborator (can mark complete)
    - owner (can do everything)
end

# chore.rb
class Chore
  belongs_to :list
end

NOTE: I changed the association model to ListsUser as per rails naming conventions.

Please let me know if i missed something.


问:
Task does not wait up-to the wait time
I have created a task and provided the wait time to the task.wait() method, but the task does not wait up to the provided time and return before the wait time with completed status false.

```<code>using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main(string[] args)
    {
        for(int i = 0 ; i < 10 ; i++)
        {
            int localValue = i;
            Task.Factory.StartNew(() => ProcessTask(localValue));
        }
        Console.ReadKey();
    }

    private static void ProcessTask(int thread)
    {
        var task = Task<int>.Factory.StartNew(() => GetSomeValue());
        task.Wait(2000);

        if(task.IsCompleted)
        {
            Console.WriteLine("Completed Thread: " + thread);
        }
        else
        {
            Console.WriteLine("Not Completed Thread " + thread);
        }
    }

    private static int GetSomeValue()
    {
        Thread.Sleep(400);
        return 5;
    }
}
</code>```

Update:

I have updated the code. When I have run this code I got the following output.

Only two tasks are completed out of 10. so I want to know what is the issue with this code?

Note: I am running this code in 4.5.2 frameworks.

答:
The problem isn't that Task.Wait isn't waiting long enough here - it's that you're assuming that as soon as you call Task.Factory.StartNew() (which you should almost never do, btw - use Task.Run instead), the task is started. That's not the case. Task scheduling is a complicated topic, and I don't claim to be an expert, but when you start a lot of tasks at the same time, the thread pool will wait a little while before creating a new thread, to see if it can reuse it.

You can see this if you add more logging to your code. I added logging before and after the Wait call, and before and after the Sleep call, identifying which original value of i was involved. (I followed your convention of calling that the thread, although that's not quite the case.) The log uses DateTime.UtcNow with a pattern of MM:ss.FFF to show a timestamp down to a millisecond.

Here's the output of the log for a single task that completed:

```<code>12:01.657: Before Wait in thread 7
12:03.219: Task for thread 7 started
12:03.623: Task for thread 7 completing
12:03.625: After Wait in thread 7
</code>```

Here the Wait call returns after less than 2 seconds, but that's fine because the task has completed.

And here's the output of the log for a single task that didn't complete:

```<code>12:01.644: Before Wait in thread 6
12:03.412: Task for thread 6 started
12:03.649: After Wait in thread 6
12:03.836: Task for thread 6 completing
</code>```

Here Wait really has waited for 2 seconds, but the task still hasn't completed, because it only properly started just before the Wait time was up.

Title: Task does not wait up-to the wait time

Body:
I have created a task and provided the wait time to the task.wait() method, but the task does not wait up to the provided time and return before the wait time with completed status false.

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main(string[] args)
    {
        for(int i = 0 ; i < 10 ; i++)
        {
            int localValue = i;
            Task.Factory.StartNew(() => ProcessTask(localValue));
        }
        Console.ReadKey();
    }

    private static void ProcessTask(int thread)
    {
        var task = Task<int>.Factory.StartNew(() => GetSomeValue());
        task.Wait(2000);

        if(task.IsCompleted)
        {
            Console.WriteLine("Completed Thread: " + thread);
        }
        else
        {
            Console.WriteLine("Not Completed Thread " + thread);
        }
    }

    private static int GetSomeValue()
    {
        Thread.Sleep(400);
        return 5;
    }
}

Update:

I have updated the code. When I have run this code I got the following output.

Only two tasks are completed out of 10. so I want to know what is the issue with this code?

Note: I am running this code in 4.5.2 frameworks.

Body:
The problem isn't that Task.Wait isn't waiting long enough here - it's that you're assuming that as soon as you call Task.Factory.StartNew() (which you should almost never do, btw - use Task.Run instead), the task is started. That's not the case. Task scheduling is a complicated topic, and I don't claim to be an expert, but when you start a lot of tasks at the same time, the thread pool will wait a little while before creating a new thread, to see if it can reuse it.

You can see this if you add more logging to your code. I added logging before and after the Wait call, and before and after the Sleep call, identifying which original value of i was involved. (I followed your convention of calling that the thread, although that's not quite the case.) The log uses DateTime.UtcNow with a pattern of MM:ss.FFF to show a timestamp down to a millisecond.

Here's the output of the log for a single task that completed:

12:01.657: Before Wait in thread 7
12:03.219: Task for thread 7 started
12:03.623: Task for thread 7 completing
12:03.625: After Wait in thread 7

Here the Wait call returns after less than 2 seconds, but that's fine because the task has completed.

And here's the output of the log for a single task that didn't complete:

12:01.644: Before Wait in thread 6
12:03.412: Task for thread 6 started
12:03.649: After Wait in thread 6
12:03.836: Task for thread 6 completing

Here Wait really has waited for 2 seconds, but the task still hasn't completed, because it only properly started just before the Wait time was up.


问:
SQL Performance: Using Union and Subqueries
Hi stackoverflow(My first question!),

We're doing something like an SNS, and got a question about optimizing queries.

Using mysql 5.1, the current table was created with:

```<code>CREATE TABLE friends(
 user_id BIGINT NOT NULL,
 friend_id BIGINT NOT NULL,
 PRIMARY KEY (user_id, friend_id)
) ENGINE INNODB;
</code>```

Sample data is populated like:

```<code>INSERT INTO friends VALUES
(1,2),
(1,3),
(1,4),
(1,5),
(2,1),
(2,3),
(2,4),
(3,1),
(3,2),
(4,1),
(4,2),
(5,1),
(5,6),
(6,5),
(7,8),
(8,7);
</code>```

The business logic: we need to figure out which users are friends or friends of friends for a given user.
The current query for this for a user with user_id=1 is:

```<code>SELECT friend_id FROM friends WHERE user_id = 1
 UNION
 SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
 SELECT friend_id FROM friends WHERE user_id = 1
);
</code>```

The expected result is(order doesn't matter):

```<code>2
3
4
5
1
6
</code>```

As you can see, the above query performs the subquery "SELECT friend_id FROM friends WHERE user_id = 1" twice.

So, here is the question. If performance is your primary concern, how would you change the above query or schema?

Thanks in advance.

答:
In this particular case, you can use a JOIN:

```<code>SELECT DISTINCT f2.friend_id
  FROM friends AS f1
    JOIN friends AS f2 ON f1.friend_id=f2.user_id OR f2.user_id=1
  WHERE f1.user_id=1;
</code>```

Examining each query suggests the JOIN will about as performant as the UNION in a big-O sense, though perhaps faster by a constant factor. Jasie's query looks like it might be big-O faster.

```<code>EXPLAIN SELECT friend_id FROM friends WHERE user_id = 1
  UNION
    SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
      SELECT friend_id FROM friends WHERE user_id = 1
    );
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
| id | select_type        | table      | type   | possible_keys | key     | key_len | ref        | rows | Extra                                     |
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
|  1 | PRIMARY            | friends    | ref    | PRIMARY       | PRIMARY | 8       | const      |    4 | Using index                               |
|  2 | UNION              | friends    | index  | NULL          | PRIMARY | 16      | NULL       |   16 | Using where; Using index; Using temporary |
|  3 | DEPENDENT SUBQUERY | friends    | eq_ref | PRIMARY       | PRIMARY | 16      | const,func |    1 | Using index                               |
| NULL | UNION RESULT       | <union1,2> | ALL    | NULL          | NULL    | NULL    | NULL       | NULL |                                           |
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+

EXPLAIN SELECT DISTINCT f2.friend_id
  FROM friends AS f1
    JOIN friends AS f2
      ON f1.friend_id=f2.user_id OR f2.user_id=1
  WHERE f1.user_id=1;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref   | rows | Extra                                       |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+
|  1 | SIMPLE      | f1    | ref   | PRIMARY       | PRIMARY | 8       | const |    4 | Using index; Using temporary                |
|  1 | SIMPLE      | f2    | index | PRIMARY       | PRIMARY | 16      | NULL  |   16 | Using where; Using index; Using join buffer |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+

EXPLAIN SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
    SELECT friend_id FROM friends WHERE user_id = 1
) OR user_id = 1;
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
| id | select_type        | table   | type   | possible_keys | key     | key_len | ref        | rows | Extra                                     |
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
|  1 | PRIMARY            | friends | index  | PRIMARY       | PRIMARY | 16      | NULL       |   16 | Using where; Using index; Using temporary |
|  2 | DEPENDENT SUBQUERY | friends | eq_ref | PRIMARY       | PRIMARY | 16      | const,func |    1 | Using index                               |
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi stackoverflow(My first question!),

We're doing something like an SNS, and got a question about optimizing queries.

Using mysql 5.1, the current table was created with:

CREATE TABLE friends(
 user_id BIGINT NOT NULL,
 friend_id BIGINT NOT NULL,
 PRIMARY KEY (user_id, friend_id)
) ENGINE INNODB;

Sample data is populated like:

INSERT INTO friends VALUES
(1,2),
(1,3),
(1,4),
(1,5),
(2,1),
(2,3),
(2,4),
(3,1),
(3,2),
(4,1),
(4,2),
(5,1),
(5,6),
(6,5),
(7,8),
(8,7);

The business logic: we need to figure out which users are friends or friends of friends for a given user.
The current query for this for a user with user_id=1 is:

SELECT friend_id FROM friends WHERE user_id = 1
 UNION
 SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
 SELECT friend_id FROM friends WHERE user_id = 1
);

The expected result is(order doesn't matter):

2
3
4
5
1
6

As you can see, the above query performs the subquery "SELECT friend_id FROM friends WHERE user_id = 1" twice.

So, here is the question. If performance is your primary concern, how would you change the above query or schema?

Thanks in advance.

Body:
In this particular case, you can use a JOIN:

SELECT DISTINCT f2.friend_id
  FROM friends AS f1
    JOIN friends AS f2 ON f1.friend_id=f2.user_id OR f2.user_id=1
  WHERE f1.user_id=1;

Examining each query suggests the JOIN will about as performant as the UNION in a big-O sense, though perhaps faster by a constant factor. Jasie's query looks like it might be big-O faster.

EXPLAIN SELECT friend_id FROM friends WHERE user_id = 1
  UNION
    SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
      SELECT friend_id FROM friends WHERE user_id = 1
    );
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
| id | select_type        | table      | type   | possible_keys | key     | key_len | ref        | rows | Extra                                     |
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
|  1 | PRIMARY            | friends    | ref    | PRIMARY       | PRIMARY | 8       | const      |    4 | Using index                               |
|  2 | UNION              | friends    | index  | NULL          | PRIMARY | 16      | NULL       |   16 | Using where; Using index; Using temporary |
|  3 | DEPENDENT SUBQUERY | friends    | eq_ref | PRIMARY       | PRIMARY | 16      | const,func |    1 | Using index                               |
| NULL | UNION RESULT       | <union1,2> | ALL    | NULL          | NULL    | NULL    | NULL       | NULL |                                           |
+----+--------------------+------------+--------+---------------+---------+---------+------------+------+-------------------------------------------+

EXPLAIN SELECT DISTINCT f2.friend_id
  FROM friends AS f1
    JOIN friends AS f2
      ON f1.friend_id=f2.user_id OR f2.user_id=1
  WHERE f1.user_id=1;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref   | rows | Extra                                       |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+
|  1 | SIMPLE      | f1    | ref   | PRIMARY       | PRIMARY | 8       | const |    4 | Using index; Using temporary                |
|  1 | SIMPLE      | f2    | index | PRIMARY       | PRIMARY | 16      | NULL  |   16 | Using where; Using index; Using join buffer |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+---------------------------------------------+

EXPLAIN SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
    SELECT friend_id FROM friends WHERE user_id = 1
) OR user_id = 1;
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
| id | select_type        | table   | type   | possible_keys | key     | key_len | ref        | rows | Extra                                     |
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+
|  1 | PRIMARY            | friends | index  | PRIMARY       | PRIMARY | 16      | NULL       |   16 | Using where; Using index; Using temporary |
|  2 | DEPENDENT SUBQUERY | friends | eq_ref | PRIMARY       | PRIMARY | 16      | const,func |    1 | Using index                               |
+----+--------------------+---------+--------+---------------+---------+---------+------------+------+-------------------------------------------+


问:
How to count the number of comparisons happening when organizing an array?
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

```<code>import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}
</code>```

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

答:
simply add a counter and place it after the compare:

import java.util.Scanner;

public class tst
{
  private static int comparisonCount = 0;

```<code>public static void main(String[] args)
{
    Scanner stdIn = new Scanner(System.in);
    final int Size = 10;
    double [] scores = new double[Size];
    // set all the scores to a random number [0 - 99]
    for (int s = 0; s < Size; ++s)
        scores[s] = (int)(Math.random() * 100);
    // print the scores - original order
    System.out.println("Scores - Original");
    System.out.println("------------------");
    printArray(scores, Size);
    System.out.println("\n");
    // sort the scores
    System.out.println("Sorting ...\n");
    // print the scores - sorted order
    sortArray(scores, Size);
    System.out.println("Size of array = " + Size);
    System.out.println("Comparisons needed =   " + comparisonCount + "\n");
    System.out.println("Scores - Sorted");
    System.out.println("----------------");
    printArray(scores, Size);
    System.out.println("\n");
    stdIn.close();
}
public static void printArray(double [] arr, int eSize)
{
    for (int i = 0; i < eSize; ++i)
        System.out.println(arr[i]);
}
public static int findMinLoc(double [] arr, int startInd, int     endInd)
{
    int minLoc = startInd;
    for (int i = startInd; i <= endInd; ++i)
    {
        if (arr[i] < arr[minLoc])
            minLoc = i;
        comparisonCount++;
    }
    return minLoc;
}
public static void swapInArray(double [] arr, int ind1, int ind2)
{
    double tmp = arr[ind1];
    arr[ind1] = arr[ind2];
    arr[ind2] = tmp;
}
public static void sortArray(double [] arr, int eSize)
{
    for (int i = 0; i < eSize; ++i)
    {
        int ind = findMinLoc(arr, i, eSize-1);
        swapInArray(arr, i, ind);
    }
}
</code>```

}

Body:
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

Body:
simply add a counter and place it after the compare:

import java.util.Scanner;

public class tst
{
  private static int comparisonCount = 0;

public static void main(String[] args)
{
    Scanner stdIn = new Scanner(System.in);
    final int Size = 10;
    double [] scores = new double[Size];
    // set all the scores to a random number [0 - 99]
    for (int s = 0; s < Size; ++s)
        scores[s] = (int)(Math.random() * 100);
    // print the scores - original order
    System.out.println("Scores - Original");
    System.out.println("------------------");
    printArray(scores, Size);
    System.out.println("\n");
    // sort the scores
    System.out.println("Sorting ...\n");
    // print the scores - sorted order
    sortArray(scores, Size);
    System.out.println("Size of array = " + Size);
    System.out.println("Comparisons needed =   " + comparisonCount + "\n");
    System.out.println("Scores - Sorted");
    System.out.println("----------------");
    printArray(scores, Size);
    System.out.println("\n");
    stdIn.close();
}
public static void printArray(double [] arr, int eSize)
{
    for (int i = 0; i < eSize; ++i)
        System.out.println(arr[i]);
}
public static int findMinLoc(double [] arr, int startInd, int     endInd)
{
    int minLoc = startInd;
    for (int i = startInd; i <= endInd; ++i)
    {
        if (arr[i] < arr[minLoc])
            minLoc = i;
        comparisonCount++;
    }
    return minLoc;
}
public static void swapInArray(double [] arr, int ind1, int ind2)
{
    double tmp = arr[ind1];
    arr[ind1] = arr[ind2];
    arr[ind2] = tmp;
}
public static void sortArray(double [] arr, int eSize)
{
    for (int i = 0; i < eSize; ++i)
    {
        int ind = findMinLoc(arr, i, eSize-1);
        swapInArray(arr, i, ind);
    }
}

}


问:
how to insert form data to mysql using sockets in PHP | jquery
i am new to web sockets and i want to to insert form data to mysql database using web sockets
Can anyone please help me to do that?
Thanks in advance</p>

答:
Sockets are used to for interprocess communication between server and clients or TCP,UDP Connections. But is a bad idea/usage to use to insert data to mysql.

Instead of scokets u can use php to insert data into mysql which is the most common and widely accepted method and very easy to use.

A sample code which shows u how this works .

```<code><?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $servername="localhost";
    $username="root";
    $password="";
    $db="login";
    //connection
    $conn=new mysqli($servername,$username,$password,$db);
    //fetch from form
    $myusername = mysqli_real_escape_string($conn,$_POST['usernam']);
    $mypassword = mysqli_real_escape_string($conn,$_POST['password']);
    $myemail=mysqli_real_escape_string($conn,$_POST['email']);
    $sql=$conn->query("INSERT INTO su values('$myusername','$mypassword','$myemail',0)");

    }
?>
</code>```

Hope this Post helped u!!!

Body:
Sockets are used to for interprocess communication between server and clients or TCP,UDP Connections. But is a bad idea/usage to use to insert data to mysql.

Instead of scokets u can use php to insert data into mysql which is the most common and widely accepted method and very easy to use.

A sample code which shows u how this works .

<?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $servername="localhost";
    $username="root";
    $password="";
    $db="login";
    //connection
    $conn=new mysqli($servername,$username,$password,$db);
    //fetch from form
    $myusername = mysqli_real_escape_string($conn,$_POST['usernam']);
    $mypassword = mysqli_real_escape_string($conn,$_POST['password']);
    $myemail=mysqli_real_escape_string($conn,$_POST['email']);
    $sql=$conn->query("INSERT INTO su values('$myusername','$mypassword','$myemail',0)");

    }
?>

Hope this Post helped u!!!


问:
rangeOfComposedCharacterSequenceAtIndex in Xamarin?
I'm trying to port the iosMath LaTeX library to C#. iosMath uses NSString's rangeOfComposedCharacterSequenceAtIndex in certain places. But I can't find any equivalent in Xamarin's NSString API. What am I missing? Is this functionality available some other way? If so, how?

Cross-posted on the Xamarin forums here.

答:
Is this functionality available some other way?

We have to implement it by ourselves using C# if the api can not be found in the Class.

For example :

rangeOfString in NSString also can't be found ,and we can create the method instead.

```<code>static NSRange CalcRangeFor (string source, string substring)
{
    var range = new NSRange {
        Location = source.IndexOf (substring),
        Length = substring.Length
    };
    return range;
}
</code>```

However, rangeOfComposedCharacterSequenceAtIndex is a bit of complex, you can search the source code and implement with your new method. But I'm afraid it is still hard to do the work, since it is related to CoreFoundtion and we know little about it.

So why didn't you try to create a binding project? You don't have to transform the code from objective-c to c# but need some extra works for binding.

Refer to Binding iOS Libraries

Body:
Is this functionality available some other way?

We have to implement it by ourselves using C# if the api can not be found in the Class.

For example :

rangeOfString in NSString also can't be found ,and we can create the method instead.

static NSRange CalcRangeFor (string source, string substring)
{
    var range = new NSRange {
        Location = source.IndexOf (substring),
        Length = substring.Length
    };
    return range;
}

However, rangeOfComposedCharacterSequenceAtIndex is a bit of complex, you can search the source code and implement with your new method. But I'm afraid it is still hard to do the work, since it is related to CoreFoundtion and we know little about it.

So why didn't you try to create a binding project? You don't have to transform the code from objective-c to c# but need some extra works for binding.

Refer to Binding iOS Libraries


问:
Do Loop and If Statement in Excel
In the WorkSheet, I'm trying to create the following logic in Excel Macro.

Logic:

```<code>Dub Test()

Dim rws as integer
Dim counter as integer

rws = 6
counter = 2

Do while rws <> 0
    IF 'Data Sheet with Space'!J`counter` = "Sample Data Row 1 Col 10" Then
        WorkSheet!A`counter` = 'Data Sheet with Space'!A`counter`
    end IF

    counter = counter + 1
    rws = rws - 1
</code>```

The Excel sheets are:

Data Sheet with Space

```<code>---------------------------------------------
Header 1                 Header 2                 Header 3                 Header 4                 Header 5                 Header 6                 Header 7                 Header 8                 Header 9                 Header 10
Sample Data Row 1 Col 1  Sample Data Row 1 Col 2  Sample Data Row 1 Col 3  Sample Data Row 1 Col 4  Sample Data Row 1 Col 5  Sample Data Row 1 Col 6  Sample Data Row 1 Col 7  Sample Data Row 1 Col 8  Sample Data Row 1 Col 9  Sample Data Row 1 Col 10
Sample Data Row 2 Col 1  Sample Data Row 2 Col 2  Sample Data Row 2 Col 3  Sample Data Row 2 Col 4  Sample Data Row 2 Col 5  Sample Data Row 2 Col 6  Sample Data Row 2 Col 7  Sample Data Row 2 Col 8  Sample Data Row 2 Col 9  Sample Data Row 2 Col 10
Sample Data Row 3 Col 1  Sample Data Row 3 Col 2  Sample Data Row 3 Col 3  Sample Data Row 3 Col 4  Sample Data Row 3 Col 5  Sample Data Row 3 Col 6  Sample Data Row 3 Col 7  Sample Data Row 3 Col 8  Sample Data Row 3 Col 9  Sample Data Row 3 Col 10
Sample Data Row 4 Col 1  Sample Data Row 4 Col 2  Sample Data Row 4 Col 3  Sample Data Row 4 Col 4  Sample Data Row 4 Col 5  Sample Data Row 4 Col 6  Sample Data Row 4 Col 7  Sample Data Row 4 Col 8  Sample Data Row 4 Col 9  Sample Data Row 4 Col 10
Sample Data Row 5 Col 1  Sample Data Row 5 Col 2  Sample Data Row 5 Col 3  Sample Data Row 5 Col 4  Sample Data Row 5 Col 5  Sample Data Row 5 Col 6  Sample Data Row 5 Col 7  Sample Data Row 5 Col 8  Sample Data Row 5 Col 9  Sample Data Row 5 Col 10
---------------------------------------------
</code>```

and the other Excel sheet called WorkSheet

When trying to run the macro I get an error the ' in the Data Sheet with Space name causes an error.

Secondly, I an having an error when trying to change the input and output cell number dynamically using the counter variable.

Any help is appreciate it.

答:
The problem lies in the way in which you address the cells.

If you want to refer to cell "B6" on the first sheet, there are basically 3 ways to refer to the sheet:

By CodeName (If you happen to know the codename of the sheet)

```<code>Sheet1.[B6]
</code>```

By Name (That is the name you see on the tab of the sheet)

```<code>Sheets("Data Sheet with Space").[B6]
</code>```

By Number (If you happen to know the order of the sheets)

```<code>Sheets(1).[B6]
</code>```

It is your code, you are going to maintain it, so use whichever looks best to you.
You might prefer to use a variable: wsData = Sheets("Data Sheet with Space"), so you could simply write wsOther.[A1]=wsData.[B6].

There are also several ways to refer to the cells on the sheet. Some usefull ones:

Directly using the Address:

```<code>Sheets("Data Sheet with Space").[B6]
</code>```

By using .Range (using the Address)

```<code>Sheets("Data Sheet with Space").Range("B6")
</code>```

By using .Cell (using the Coordinates)

```<code>Sheets("Data Sheet with Space").Cells(6, 2)
</code>```

A more reeadable way of using .Cell (as sugessted by YowE3K)

```<code>Sheets("Data Sheet with Space").Cells(6, "B")
</code>```

In your code, you are already using coordinates. So you might prefer to use .Cells(rws, counter). But it's up to you.

Title: Do Loop and If Statement in Excel

Body:
In the WorkSheet, I'm trying to create the following logic in Excel Macro.

Logic:

Dub Test()

Dim rws as integer
Dim counter as integer

rws = 6
counter = 2

Do while rws <> 0
    IF 'Data Sheet with Space'!J`counter` = "Sample Data Row 1 Col 10" Then
        WorkSheet!A`counter` = 'Data Sheet with Space'!A`counter`
    end IF

    counter = counter + 1
    rws = rws - 1

The Excel sheets are:

Data Sheet with Space

---------------------------------------------
Header 1                 Header 2                 Header 3                 Header 4                 Header 5                 Header 6                 Header 7                 Header 8                 Header 9                 Header 10
Sample Data Row 1 Col 1  Sample Data Row 1 Col 2  Sample Data Row 1 Col 3  Sample Data Row 1 Col 4  Sample Data Row 1 Col 5  Sample Data Row 1 Col 6  Sample Data Row 1 Col 7  Sample Data Row 1 Col 8  Sample Data Row 1 Col 9  Sample Data Row 1 Col 10
Sample Data Row 2 Col 1  Sample Data Row 2 Col 2  Sample Data Row 2 Col 3  Sample Data Row 2 Col 4  Sample Data Row 2 Col 5  Sample Data Row 2 Col 6  Sample Data Row 2 Col 7  Sample Data Row 2 Col 8  Sample Data Row 2 Col 9  Sample Data Row 2 Col 10
Sample Data Row 3 Col 1  Sample Data Row 3 Col 2  Sample Data Row 3 Col 3  Sample Data Row 3 Col 4  Sample Data Row 3 Col 5  Sample Data Row 3 Col 6  Sample Data Row 3 Col 7  Sample Data Row 3 Col 8  Sample Data Row 3 Col 9  Sample Data Row 3 Col 10
Sample Data Row 4 Col 1  Sample Data Row 4 Col 2  Sample Data Row 4 Col 3  Sample Data Row 4 Col 4  Sample Data Row 4 Col 5  Sample Data Row 4 Col 6  Sample Data Row 4 Col 7  Sample Data Row 4 Col 8  Sample Data Row 4 Col 9  Sample Data Row 4 Col 10
Sample Data Row 5 Col 1  Sample Data Row 5 Col 2  Sample Data Row 5 Col 3  Sample Data Row 5 Col 4  Sample Data Row 5 Col 5  Sample Data Row 5 Col 6  Sample Data Row 5 Col 7  Sample Data Row 5 Col 8  Sample Data Row 5 Col 9  Sample Data Row 5 Col 10
---------------------------------------------

and the other Excel sheet called WorkSheet

When trying to run the macro I get an error the ' in the Data Sheet with Space name causes an error.

Secondly, I an having an error when trying to change the input and output cell number dynamically using the counter variable.

Any help is appreciate it.

Body:
The problem lies in the way in which you address the cells.

If you want to refer to cell "B6" on the first sheet, there are basically 3 ways to refer to the sheet:

By CodeName (If you happen to know the codename of the sheet)

Sheet1.[B6]

By Name (That is the name you see on the tab of the sheet)

Sheets("Data Sheet with Space").[B6]

By Number (If you happen to know the order of the sheets)

Sheets(1).[B6]

It is your code, you are going to maintain it, so use whichever looks best to you.
You might prefer to use a variable: wsData = Sheets("Data Sheet with Space"), so you could simply write wsOther.[A1]=wsData.[B6].

There are also several ways to refer to the cells on the sheet. Some usefull ones:

Directly using the Address:

Sheets("Data Sheet with Space").[B6]

By using .Range (using the Address)

Sheets("Data Sheet with Space").Range("B6")

By using .Cell (using the Coordinates)

Sheets("Data Sheet with Space").Cells(6, 2)

A more reeadable way of using .Cell (as sugessted by YowE3K)

Sheets("Data Sheet with Space").Cells(6, "B")

In your code, you are already using coordinates. So you might prefer to use .Cells(rws, counter). But it's up to you.


答:
I think there are two options:

You use three views side-by-side to have line - text - line

You use two views in a FrameLayout: The first one will be the view for the line, and the second one the TextView, which will be drawn above the line. Make sure that the TextView has a non-transparent background and its layout_width is wrap_content. Depending on your desired result you might want to add some horizontal padding to the TextView, so that the line doesn't directly touch the text.

Title: How to hide view behind the view


问:
How to validate ant design formitems without using getFieldDecorator in reactjs?
In reactjs i am using ant design form. In that form i dont want default validation using getfielddecorator. I want to validate fields with my own validation.How it validate?
For example</p>

```<code> <Form onSubmit={this.handlesubmit.bind(this)}>                                                                                <FormItem>
    <input/>
</FormItem>
 <FormItem >
  <input/>
 </FormItem>
<ButtonAnt className="btng" type="primary" htmlType="submit">Save</ButtonAnt>
 </Form>
</code>```

答:
According to the docs,

We provide properties like validateStatus help hasFeedback to
  customize your own validate status and message, without using
  Form.create and getFieldDecorator.

Also, it seems there is a validator prop (amongst others) that you can use to write your own validator function.

Body:
In reactjs i am using ant design form. In that form i dont want default validation using getfielddecorator. I want to validate fields with my own validation.How it validate?
For example

 <Form onSubmit={this.handlesubmit.bind(this)}>                                                                                <FormItem>
    <input/>
</FormItem>
 <FormItem >
  <input/>
 </FormItem>
<ButtonAnt className="btng" type="primary" htmlType="submit">Save</ButtonAnt>
 </Form>


问:
Having a block of code wait to run at a certain time in iOS
Let's say I have a view controller with code that I want to execute at a certain time, say 2:00pm. What I want to happen is that if the user opens the view controller at 1:58pm, that the code will wait and continuously check the time, executing itself at exactly 2:00pm. Is there a way to do this in Swift 4, perhaps with a timer?</p>

答:
Read about DispatchQueue

Example:

```<code>// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
     // your code
}
</code>```

Note: Your application must be active.
Also you may have a look at Background modes tutorial

Body:
Read about DispatchQueue

Example:

// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
     // your code
}

Note: Your application must be active.
Also you may have a look at Background modes tutorial


问:
Help with a MySQL process list description/meaning
Can anyone tell me what the information below means or says? I'm not real familiar with MySQL. This info is coming from my hosting provider. I'm specifically interested in what the command and time comment means or is telling them.

Looking into the current mysql process list, we have noticed following threads related to your account:

```<code>| Id | User  | Host | db | Command | Time | State | Info |

| 4655267 | xyz | localhost | xyz | Sleep   | 111  |
| 4655961 | xyz | localhost | xyz | Sleep   | 8    |
| 4654241 | xyz | localhost | xyz | Sleep   | 126  |
| 4655961 | xyz | localhost | xyz | Sleep   | 38   |
</code>```

Here's some more detailed info on the situation:

I've recently run into a situation with my shared hosting provider regarding my MySQL usage. The page in reference has been up and running for nearly 2 years without issue until two days ago when they claimed it was utilizing excessive resources and putting load on server, making it unstable. Our site traffic and stats have been the same for the last 9 months and probably longer.

They've provide me with some information after dragging it out of them, but my questions are:

is this excessive resource usage?

why after 2 years would it be an issue all of a sudden?

even after the page was disabled for the last 2.5 days the resource usage on MySQL either remained the same or went up, so is the issue really related to my page or something else?

what does the process list tell me?

what might I do to resolve this issue?

Here's some info they have provided:

```<code>CPU: 0.06 %
Memory: 0.17 %
Mysql: 1.2 %

Top Process   %CPU 3.0   /usr/php4/bin/php / specific file name
Top Process   %CPU 1.5   /usr/php4/bin/php / specific file name
</code>```

The issue with your account is of high MySQL usage. The average usage of other account is 0.2% of MySQL whereas your account is consuming more than 1%.

Looking into the current mysql process list, we have noticed following threads related to your account:

```<code>+ Id | User  | Host | db | Command | Time | State | Info |

| 4655267 | xyz | localhost | xyz | Sleep   | 111  |
| 4655961 | xyz | localhost | xyz | Sleep   | 8    |
| 4654241 | xyz | localhost | xyz | Sleep   | 126  |
| 4655961 | xyz | localhost | xyz | Sleep   | 38   |
</code>```

Please make sure that your account is having not more than 2-3 simultaneous mysql connections at a single time and you continue to optimize your connection strings for connection pooling; also make sure that all of the connections are properly terminated after their utilization and no connections are left as "idle-open".

I've checked the resource usage over the last seven days and this is what it says for MySQL. Strange that the usage has gone up or remained the same since the page is no longer active and hasn't been for the last 2.5 days.

```<code>1/21/11 : Number of MySQL procs (average) - 1.19
1/20/11 : Number of MySQL procs (average) - 1.24
1/19/11 : Number of MySQL procs (average) - 1.20
1/18/11 : Number of MySQL procs (average) - 1.18
1/17/11 : Number of MySQL procs (average) - 1.13
1/16/11 : Number of MySQL procs (average) - 1.08
1/15/11 : Number of MySQL procs (average) - 1.09
</code>```

答:
Ok, to answer your questions:

Whether this is "excessive" resource usage would, I think, depend on your agreement with your hosting company. I'd review that. But honestly, if my host considered 1% CPU usage excessive, I'd find another host. Same with 4 sleeping connections. Of course, I'm more used to dedicated hosting (where I'd say excessive CPU usage is well over 200% for MySQL on the machines I use, and excessive idle connections would be more like several hundred). But even so, you're using less than 1% of one cheap machine, so. Consider that max CPU usage on a $1k i7 machine is either 400 or 800% (depending on hyperthreading).

For why it may have suddenly changed, the only thing that comes to mind is to check for proper indices. Maybe your data has been slowly growing? Its also possible that it hasn't suddenly changed, but your hosting company just noticed "hey, this server is overloaded, let's look into it".

Well, obviously, if turning off the page didn't change the load, then it wasn't causing the load. But I'm sure you already knew this.

The process list tells you you have 4 sleeping (idle) connections, and how long they've been idle for.

To decrease the number of idle connections, change your PHP/Apache configuration. I believe mysql_pconnect holds one connection per Apache process. Alternatively, switch to mysql_connect.

The only real programming answers are to check your indices, do EXPLAIN on your queries, etc., the normal MySQL optimization stuff. The real answer, I suspect, is to find a host that doesn't complain when you use 20¢/mo of computing power.

Body:
Can anyone tell me what the information below means or says? I'm not real familiar with MySQL. This info is coming from my hosting provider. I'm specifically interested in what the command and time comment means or is telling them.

Looking into the current mysql process list, we have noticed following threads related to your account:

| Id | User  | Host | db | Command | Time | State | Info |

| 4655267 | xyz | localhost | xyz | Sleep   | 111  |
| 4655961 | xyz | localhost | xyz | Sleep   | 8    |
| 4654241 | xyz | localhost | xyz | Sleep   | 126  |
| 4655961 | xyz | localhost | xyz | Sleep   | 38   |

Here's some more detailed info on the situation:

I've recently run into a situation with my shared hosting provider regarding my MySQL usage. The page in reference has been up and running for nearly 2 years without issue until two days ago when they claimed it was utilizing excessive resources and putting load on server, making it unstable. Our site traffic and stats have been the same for the last 9 months and probably longer.

They've provide me with some information after dragging it out of them, but my questions are:

is this excessive resource usage?

why after 2 years would it be an issue all of a sudden?

even after the page was disabled for the last 2.5 days the resource usage on MySQL either remained the same or went up, so is the issue really related to my page or something else?

what does the process list tell me?

what might I do to resolve this issue?

Here's some info they have provided:

CPU: 0.06 %
Memory: 0.17 %
Mysql: 1.2 %

Top Process   %CPU 3.0   /usr/php4/bin/php / specific file name
Top Process   %CPU 1.5   /usr/php4/bin/php / specific file name

The issue with your account is of high MySQL usage. The average usage of other account is 0.2% of MySQL whereas your account is consuming more than 1%.

Looking into the current mysql process list, we have noticed following threads related to your account:

+ Id | User  | Host | db | Command | Time | State | Info |

| 4655267 | xyz | localhost | xyz | Sleep   | 111  |
| 4655961 | xyz | localhost | xyz | Sleep   | 8    |
| 4654241 | xyz | localhost | xyz | Sleep   | 126  |
| 4655961 | xyz | localhost | xyz | Sleep   | 38   |

Please make sure that your account is having not more than 2-3 simultaneous mysql connections at a single time and you continue to optimize your connection strings for connection pooling; also make sure that all of the connections are properly terminated after their utilization and no connections are left as "idle-open".

I've checked the resource usage over the last seven days and this is what it says for MySQL. Strange that the usage has gone up or remained the same since the page is no longer active and hasn't been for the last 2.5 days.

1/21/11 : Number of MySQL procs (average) - 1.19
1/20/11 : Number of MySQL procs (average) - 1.24
1/19/11 : Number of MySQL procs (average) - 1.20
1/18/11 : Number of MySQL procs (average) - 1.18
1/17/11 : Number of MySQL procs (average) - 1.13
1/16/11 : Number of MySQL procs (average) - 1.08
1/15/11 : Number of MySQL procs (average) - 1.09


问:
Script to copy specific columns from one sheet to another, but not in the same order
I've got this script working, but I was just wondering if someone could explain how to make it more efficient. Right now I'm just repeating code and that's obviously not the right way to do it.

Basically I'm just trying to copy certain columns from one sheet to another. The catch is I don't want all the columns from the source sheet and they are also not in the same order on the destination sheet. For example: Column A on the source sheet goes in Column D on the destination sheet

```<code>function copy() {
    var sss = SpreadsheetApp.openById('myID');
    var ss = sss.getSheetByName('Inventory');
    var range1 = ss.getRange('A2:A');
    var data1 = range1.getValues();
    var range2 = ss.getRange('D2:D');
    var data2 = range2.getValues();
    var range3 = ss.getRange('F2:F');
    var data3 = range3.getValues();
    var tss = SpreadsheetApp.openById('myID');
    var ts = tss.getSheetByName('Inventory Report');
    ts.getRange(2, 4, data1.length, data1[0].length).setValues(data1);
    ts.getRange(2, 2, data2.length, data2[0].length).setValues(data2);
    ts.getRange(2, 1, data3.length, data3[0].length).setValues(data3);
}
</code>```

答:
How about this modification? Please think of this as one of several answers.

Modification points :

Retrieve all data from source sheet using getDataRange().

Create data for importing to the destination sheet.

Here, I used filter() and map().

e[5], e[3] and e[0]] is corresponding to F2:F, D2:D and A2:A, respectively.

[e[5], e[3], "", e[0]] is coresponding to getRange(2, 1,, getRange(2, 2, and getRange(2, 4,, respectively. There is no getRange(2, 3,. So I used "".

Import data to the destination sheet.

Modified script :

```<code>function copy() {
  var sss = SpreadsheetApp.openById('myID');
  var ss = sss.getSheetByName('Inventory');
  var data = ss.getDataRange().getValues();
  var d = data.filter(function(e, i){return i > 0 && e}).map(function(e){return [e[5], e[3], "", e[0]]});
  var tss = SpreadsheetApp.openById('myID');
  var ts = tss.getSheetByName('Inventory Report');
  ts.getRange(2, 1, d.length, d[0].length).setValues(d);
}
</code>```

Rererences :

getDataRange()

filter()

map()

If my understanding was wrong, I'm sorry.

Body:
I've got this script working, but I was just wondering if someone could explain how to make it more efficient. Right now I'm just repeating code and that's obviously not the right way to do it.

Basically I'm just trying to copy certain columns from one sheet to another. The catch is I don't want all the columns from the source sheet and they are also not in the same order on the destination sheet. For example: Column A on the source sheet goes in Column D on the destination sheet

function copy() {
    var sss = SpreadsheetApp.openById('myID');
    var ss = sss.getSheetByName('Inventory');
    var range1 = ss.getRange('A2:A');
    var data1 = range1.getValues();
    var range2 = ss.getRange('D2:D');
    var data2 = range2.getValues();
    var range3 = ss.getRange('F2:F');
    var data3 = range3.getValues();
    var tss = SpreadsheetApp.openById('myID');
    var ts = tss.getSheetByName('Inventory Report');
    ts.getRange(2, 4, data1.length, data1[0].length).setValues(data1);
    ts.getRange(2, 2, data2.length, data2[0].length).setValues(data2);
    ts.getRange(2, 1, data3.length, data3[0].length).setValues(data3);
}

Body:
How about this modification? Please think of this as one of several answers.

Modification points :

Retrieve all data from source sheet using getDataRange().

Create data for importing to the destination sheet.

Here, I used filter() and map().

e[5], e[3] and e[0]] is corresponding to F2:F, D2:D and A2:A, respectively.

[e[5], e[3], "", e[0]] is coresponding to getRange(2, 1,, getRange(2, 2, and getRange(2, 4,, respectively. There is no getRange(2, 3,. So I used "".

Import data to the destination sheet.

Modified script :

function copy() {
  var sss = SpreadsheetApp.openById('myID');
  var ss = sss.getSheetByName('Inventory');
  var data = ss.getDataRange().getValues();
  var d = data.filter(function(e, i){return i > 0 && e}).map(function(e){return [e[5], e[3], "", e[0]]});
  var tss = SpreadsheetApp.openById('myID');
  var ts = tss.getSheetByName('Inventory Report');
  ts.getRange(2, 1, d.length, d[0].length).setValues(d);
}

Rererences :

getDataRange()

filter()

map()

If my understanding was wrong, I'm sorry.


问:
holder.getSurface().isValid() is returning false
I am using  Surfaceview to change the background image. But I am getting false on holder.getSurface().isValid() and I don't know why. I looked at some of the similar questions here, but still could not solve it. Is there something missing on what I have done so far, or is there something else I should try

Thanks

```<code>import android.content.Context;

import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class BrickSmasherView extends SurfaceView {

    SurfaceHolder holder;

    Canvas canvas;
    Context context;

    Thread back = null;

    volatile boolean running = false;

    public BrickSmasherView(Context context) {
        super(context);
        this.context = context;
        holder = getHolder();

    }
    public void runbackThread(){
        back = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    draw();
                }
            }
        });
        back.start();
    }

    public  void resumegame(){
        running = true;
       runbackThread();

    }

    public void pausegame(){

        running = false;
        try
        {
            back.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public void  draw(){
    if(holder.getSurface().isValid()){
        canvas = holder.lockCanvas();
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.sky),0,0,null);
        holder.unlockCanvasAndPost(canvas);
    }
}

}
</code>```

答:
You had to add Callback in the SurfaceView to receive events about Surface availability and do drawing from a thread.

A Callback Example will look like this :

```<code>public class MyCallback implements SurfaceHolder.Callback {
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format,
        int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // you need to start your drawing thread here
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // and here you need to stop it
    }
}
</code>```

And than you need to set this callback to SurfaceHolder:

```<code>surface.getHolder().addCallback(new MyCallback());
</code>```

Try this please. I Think It will help you

Body:
I am using  Surfaceview to change the background image. But I am getting false on holder.getSurface().isValid() and I don't know why. I looked at some of the similar questions here, but still could not solve it. Is there something missing on what I have done so far, or is there something else I should try

Thanks

import android.content.Context;

import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class BrickSmasherView extends SurfaceView {

    SurfaceHolder holder;

    Canvas canvas;
    Context context;

    Thread back = null;

    volatile boolean running = false;

    public BrickSmasherView(Context context) {
        super(context);
        this.context = context;
        holder = getHolder();

    }
    public void runbackThread(){
        back = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    draw();
                }
            }
        });
        back.start();
    }

    public  void resumegame(){
        running = true;
       runbackThread();

    }

    public void pausegame(){

        running = false;
        try
        {
            back.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public void  draw(){
    if(holder.getSurface().isValid()){
        canvas = holder.lockCanvas();
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.sky),0,0,null);
        holder.unlockCanvasAndPost(canvas);
    }
}

}

Body:
You had to add Callback in the SurfaceView to receive events about Surface availability and do drawing from a thread.

A Callback Example will look like this :

public class MyCallback implements SurfaceHolder.Callback {
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format,
        int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // you need to start your drawing thread here
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // and here you need to stop it
    }
}

And than you need to set this callback to SurfaceHolder:

surface.getHolder().addCallback(new MyCallback());

Try this please. I Think It will help you


问:
Is SQL the assembly for databases?
Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.

I think is soon to assert this, but I guess can be true on a near future, not sure.

UPDATE: The analogy I was referring means SQL is to assembly what ORM is to C/Java/C#. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only ORM (or ORM like) instead of SQL.

答: this will never happen.  SQL is really a dsl which assembler is decidedly not.  Mapping a relational db to an object model is useful but not the only purpose of dbs, that is there orms are a small part of what databases are used for, and therefore sql will always remain the dialect of choice for dealing with dbs!</p>

OwnerDisplayName: FerranB

Title: Is SQL the assembly for databases?

LastEditorDisplayName: FerranB

OwnerDisplayName: klyde


问:
Why is it giving me active:failed error while installation of mongodb on my ubuntu 16.04 LTS?
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
2017-12-06T12:16:58.540+0530 W NETWORK  [main] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-12-06T12:16:58.540+0530 E QUERY    [main] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:234:13
@(connect):1:6
exception: connect failed</p>

答:
You need to first start mongo server at port 27017.

You can do it by executing following command:

```<code>mongod --port 27017 --dbpath [database_path]
</code>```

Body:
You need to first start mongo server at port 27017.

You can do it by executing following command:

mongod --port 27017 --dbpath [database_path]


问:
React Native components name with point parameter

Is it possible to create custom component in React Native with parameters, ex. : transform <PageHeader /> to <Page.Header /> or <PageContent /> to <Page.Content />.

I've see this syntaxe with Picker component in React Native.

<Picker
  selectedValue={this.state.lang}
  onValueChange={(itemValue, itemIndex) => this.switchLang(itemValue)}
  style={Styles.picker}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>
```

Thank you community :)

答:
I used to do it this way:

Pager.js

import React, { Component } from 'react';

export class Pager extends Component {
    ...
}

Pager.Header = class extends Component {
    ...
}
```

<p>Then you can use it in your app. For VSCode it will also show auto complete <code>Header</code> after <code>Pager.</code>.</p>

<h2>app.js</h2>

<pre class="lang-js prettyprint-override"><code>import { Pager } from './Pager';

<Pager>
    <Pager.Header />
</Pager>
</code>```

Body:
Is it possible to create custom component in React Native with parameters, ex. : transform <PageHeader /> to <Page.Header /> or <PageContent /> to <Page.Content />.

I've see this syntaxe with Picker component in React Native.

<Picker
  selectedValue={this.state.lang}
  onValueChange={(itemValue, itemIndex) => this.switchLang(itemValue)}
  style={Styles.picker}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>

Thank you community :)

Body:
I used to do it this way:

Pager.js

import React, { Component } from 'react';

export class Pager extends Component {
    ...
}

Pager.Header = class extends Component {
    ...
}

Then you can use it in your app. For VSCode it will also show auto complete Header after Pager..

app.js

import { Pager } from './Pager';

<Pager>
    <Pager.Header />
</Pager>


问:
Dictionary keys and strings
I'm just getting started with dictionaries in python and I got stumbled at the following code snippet:

```<code>for word in word_dict:
    print(word) # Obviously returns the key
print("draw" in word_dict) # returns False even though the key is existent
</code>```

I suppose the False is returned maybe due to the incompatibility of types like "draw" is a string and word in the loop is a some sort of string key type maybe.

But when I inspect the types I can see both are <class 'str'> type only !!

How do I convert the string key I provide like "draw" to be acceptable as a key and it returns True? I guess this is a simple oversight but I need to know what the problem here is !

答:
Thank you all for your time into this.

I actually split the words in a file to keys in the dictionary and while doing so the keys also had a trailing \n. That's the reason I get False when I give a string without newline. I found this out when I inspected by looping through keys of word_dict.keys()

Thanks to schwobaseggl for leading me into the solution.

Title: Dictionary keys and strings

Body:
I'm just getting started with dictionaries in python and I got stumbled at the following code snippet:

for word in word_dict:
    print(word) # Obviously returns the key
print("draw" in word_dict) # returns False even though the key is existent

I suppose the False is returned maybe due to the incompatibility of types like "draw" is a string and word in the loop is a some sort of string key type maybe.

But when I inspect the types I can see both are <class 'str'> type only !!

How do I convert the string key I provide like "draw" to be acceptable as a key and it returns True? I guess this is a simple oversight but I need to know what the problem here is !


问:
My page scrolls horizontally on mobile
I just found out that my website is scrolling horizontally on mobile. However, I am not able to find out why this is happening.

The containers and body seem to have the correct width when I check it in my browser.

Any idea?

https://www.urban-zweirad.de

Cheers,
Mark

答:
The problem is in your class named "main"

what you need to do is to add css property : overflow:hidden;

```<code>.main{
overflow:hidden
}
</code>```

think this might help you.

Title: My page scrolls horizontally on mobile

Body:
The problem is in your class named "main"

what you need to do is to add css property : overflow:hidden;

.main{
overflow:hidden
}

think this might help you.


问:
How can I destructure tuples into typed variables?
I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

```<code>fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}
</code>```

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

I tried it another way:

```<code>fn main() {
    let tup = (500, 6.4, 1);
    let mut x: bool = true;
    let mut y: f32 = true;
    let mut z: i16 = true;
    (x, y, z) = tup;
    println!("{}, {}, {}", x, y, z);
}
</code>```

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?

答:
When doing tuple assignment, you should first specify all your variables, then all the types:

```<code>let (x, y, z): (bool, f32, i16) = tup;
</code>```

gives the error you expect (playground)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

I tried it another way:

fn main() {
    let tup = (500, 6.4, 1);
    let mut x: bool = true;
    let mut y: f32 = true;
    let mut z: i16 = true;
    (x, y, z) = tup;
    println!("{}, {}, {}", x, y, z);
}

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?

Body:
When doing tuple assignment, you should first specify all your variables, then all the types:

let (x, y, z): (bool, f32, i16) = tup;

gives the error you expect (playground)


问:
Different usage between: getElementsBy..(..), not getElementBy
In Javascript, we have getElementById,getElementsByTagName. I want to understand is there something underneath the hood about using getElementsByTagName, rather than just getElementByTagName. Because it sometimes confuse me a little bit to write the code.

答:
As per standards, id should be used for one and only one element.
Therefore there is getElementById and not getElementsById.

On the other hand, multiple elements can have same tag. So, we have getElementsByTag. Similarly, getElementsByClassName.


问:
Google+ People Search API returns no items
Is google+ people search deprecated?

I'm using the Try this API from their page
https://developers.google.com/+/web/api/rest/latest/people/search

and keep getting no items for different queries

```<code>{
 "kind": "plus#peopleFeed",
 "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/K-_p8YwZl_F9FBOVSt8JEHLSg9Y\"",
 "selfLink": "https://content.googleapis.com/plus/v1/people?
     query=jane%20smith&key=[mykey]",
 "title": "Google+ People Search Results",
 "nextPageToken": "",
  "items": []
}
</code>```

答:
No its not, I have been using it for the past two weeks within a .Net code but since yesterday there has been some mishaps (as you have shown no items return in searches that normally would return items).
If this is not the first time you use the API then I would try to use another google account for authentication (if you are using Auth2 not an API key). it might be a quota limit.
If this is your first time testing the API, then Id wait, peoplesearch.execute works around once in 15 times now (returns results vs no items at all), with no specific error returned to understand the reason. so it might be a glitch. Will update the answer once I reach a more solid conclusion.</p>

Body:
Is google+ people search deprecated?

I'm using the Try this API from their page
https://developers.google.com/+/web/api/rest/latest/people/search

and keep getting no items for different queries

{
 "kind": "plus#peopleFeed",
 "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/K-_p8YwZl_F9FBOVSt8JEHLSg9Y\"",
 "selfLink": "https://content.googleapis.com/plus/v1/people?
     query=jane%20smith&key=[mykey]",
 "title": "Google+ People Search Results",
 "nextPageToken": "",
  "items": []
}


问:
MATLAB Environment Tweaks
How have you tweaked the MATLAB environment to better suit your needs?  One tweak per answer.</p>

答:
I set shortcuts for

open current directory

up 1 folder

an action to do 'close all; clear all; clc;'

Ref:
http://www.mathworks.com/matlabcentral/fileexchange/19097-custom-panzoom-icons

Title: MATLAB Environment Tweaks


问:
How can I change outgoing mail configuration in Laravel?
My email setting in env like this :

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=secret@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

It works. But, I want to change email sender. So I don't use email sender gmail

My boss gives me a new email setting like this :

Mail Client Manual Settings

Secure SSL/TLS Settings (Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

palasik.in-hell.com

IMAP Port: 9xx

POP3 Port: 9xx

Outgoing Server:

palasik.in-hell.com

SMTP Port: 465

IMAP, POP3, and SMTP require authentication.

Non-SSL Settings (NOT Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

mail.secretshop.id

IMAP Port: 1xx

POP3 Port: 1xx

Outgoing Server:

mail.secretshop.id

SMTP Port: 587

IMAP, POP3, and SMTP require authentication.

I want to ask some questions

What is the difference between Secure SSL / TLS Settings and Non-SSL Settings?

what is the difference between incoming Server and Outgoing Server?

What new setting is more suitable?

I tried like this:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=mail.secretshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

Is it the best choice?

答: You can setup the config on config/mail.php or on the .env of your app.

Body:
My email setting in env like this :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=secret@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

It works. But, I want to change email sender. So I don't use email sender gmail

My boss gives me a new email setting like this :

Mail Client Manual Settings

Secure SSL/TLS Settings (Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

palasik.in-hell.com

IMAP Port: 9xx

POP3 Port: 9xx

Outgoing Server:

palasik.in-hell.com

SMTP Port: 465

IMAP, POP3, and SMTP require authentication.

Non-SSL Settings (NOT Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

mail.secretshop.id

IMAP Port: 1xx

POP3 Port: 1xx

Outgoing Server:

mail.secretshop.id

SMTP Port: 587

IMAP, POP3, and SMTP require authentication.

I want to ask some questions

What is the difference between Secure SSL / TLS Settings and Non-SSL Settings?

what is the difference between incoming Server and Outgoing Server?

What new setting is more suitable?

I tried like this:

MAIL_DRIVER=smtp
MAIL_HOST=mail.secretshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

Is it the best choice?


问:
What is the difference between Bearer Token and Refresh Token?
In ServiceStack, I am using JwtAuthProvider, where I got Bearer Token and Refresh token so how do I verify the token and authorize the web api service?
Code:

```<code>var client = new JsvServiceClient(ListeningOn) { UserName = "tuser", Password = "password" };
            client.Send<AssignRolesResponse>(new AssignRoles
            {
                UserName = "tuser",
                Roles = new ArrayOfString("TestRole"),
                Permissions = new ArrayOfString("GetStatus")
            });

            var jwtToken = client.Send(new Authenticate()).BearerToken;
</code>```

Here, What is the use of 'jwtToken' value? user is already authorized and authenticated so I don't get the idea why the token needed here?

Could anyone suggest me how do I take advantage of that token?
JWT Config:

```<code>this.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                new IAuthProvider[]
                                    {
                                        new JwtAuthProvider(AppSettings) {
                                        RequireSecureConnection = false,
                                        AuthKey = AesUtils.CreateKey(),
                                        //CreatePayloadFilter = (payload,session) =>
                                       // payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString(),
                                        CreatePayloadFilter = (jwtPayload, session) =>
                jwtPayload["exp"] = DateTime.UtcNow.AddSeconds(-1).ToUnixTime().ToString()
        },
                                new CredentialsAuthProvider(AppSettings),
                                new BasicAuthProvider()
                    }));
</code>```

答:
Please see this article on the purpose of JWT Refresh Tokens.

In summary, the BearerToken the actual JWT and what used to authenticate via JWT. It's contains a stateless snapshot of the Users Session and is typically a short-lived token, which after it expires needs to contact the Auth Server to fetch a new JWT Token.

The RefreshToken is a longer-lived token which can be used to request new JWT Tokens transparently (i.e without forcing the User to manually re-authenticate) and will be populated with the latest snapshot of the Users Session.

The shorter the lifetime of JWT BearerTokens the less stale the stateless Session information that's stored in the JWT but the more often the RefreshToken will need to be used to fetch an updated BearerToken. Only after a new BearerToken is requested will session information like the Roles and Permissions has or whether they're locked out.

The lifetime of each Token is configurable with the ExpireTokensIn and ExpireRefreshTokensIn JwtAuthProvider properties.

ServiceStack Clients built-in support for JWT and Refresh Tokens

ServiceStack's Service Clients automatically take care of transparently fetching new JWT Tokens using RefreshTokens. You would typically populate both the BearerToken and RefreshToken when initializing your Service Client, e.g:

```<code>var authResponse = authClient.Send(new Authenticate());

var client = new JsonServiceClient(baseUrl) {
    BearerToken = authResponse.BearerToken,
    RefreshToken = authResponse.RefreshToken,
};
</code>```

The BearerToken is needed to make the request although since the Service Client automatically fetches new JWT Tokens with the configured RefreshToken you only need to populate the RefreshToken:

```<code>var client = new JsonServiceClient(baseUrl) {
    RefreshToken = authResponse.RefreshToken,
};
</code>```

As ServiceStack will automatically fetch a new JWT Token on first use, but you can save a round-trip by populating both.

Body:
In ServiceStack, I am using JwtAuthProvider, where I got Bearer Token and Refresh token so how do I verify the token and authorize the web api service?
Code:

var client = new JsvServiceClient(ListeningOn) { UserName = "tuser", Password = "password" };
            client.Send<AssignRolesResponse>(new AssignRoles
            {
                UserName = "tuser",
                Roles = new ArrayOfString("TestRole"),
                Permissions = new ArrayOfString("GetStatus")
            });

            var jwtToken = client.Send(new Authenticate()).BearerToken;

Here, What is the use of 'jwtToken' value? user is already authorized and authenticated so I don't get the idea why the token needed here?

Could anyone suggest me how do I take advantage of that token?
JWT Config:

this.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                new IAuthProvider[]
                                    {
                                        new JwtAuthProvider(AppSettings) {
                                        RequireSecureConnection = false,
                                        AuthKey = AesUtils.CreateKey(),
                                        //CreatePayloadFilter = (payload,session) =>
                                       // payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString(),
                                        CreatePayloadFilter = (jwtPayload, session) =>
                jwtPayload["exp"] = DateTime.UtcNow.AddSeconds(-1).ToUnixTime().ToString()
        },
                                new CredentialsAuthProvider(AppSettings),
                                new BasicAuthProvider()
                    }));

Body:
Please see this article on the purpose of JWT Refresh Tokens.

In summary, the BearerToken the actual JWT and what used to authenticate via JWT. It's contains a stateless snapshot of the Users Session and is typically a short-lived token, which after it expires needs to contact the Auth Server to fetch a new JWT Token.

The RefreshToken is a longer-lived token which can be used to request new JWT Tokens transparently (i.e without forcing the User to manually re-authenticate) and will be populated with the latest snapshot of the Users Session.

The shorter the lifetime of JWT BearerTokens the less stale the stateless Session information that's stored in the JWT but the more often the RefreshToken will need to be used to fetch an updated BearerToken. Only after a new BearerToken is requested will session information like the Roles and Permissions has or whether they're locked out.

The lifetime of each Token is configurable with the ExpireTokensIn and ExpireRefreshTokensIn JwtAuthProvider properties.

ServiceStack Clients built-in support for JWT and Refresh Tokens

ServiceStack's Service Clients automatically take care of transparently fetching new JWT Tokens using RefreshTokens. You would typically populate both the BearerToken and RefreshToken when initializing your Service Client, e.g:

var authResponse = authClient.Send(new Authenticate());

var client = new JsonServiceClient(baseUrl) {
    BearerToken = authResponse.BearerToken,
    RefreshToken = authResponse.RefreshToken,
};

The BearerToken is needed to make the request although since the Service Client automatically fetches new JWT Tokens with the configured RefreshToken you only need to populate the RefreshToken:

var client = new JsonServiceClient(baseUrl) {
    RefreshToken = authResponse.RefreshToken,
};

As ServiceStack will automatically fetch a new JWT Token on first use, but you can save a round-trip by populating both.


问:
Find the longest array within an object (within another object) in javascript
I have an object of objects. Within those objects are arrays, that have more objects.
Below is the structure.

I want to find out what the longest array of objects is within the parent object.
So in my example below:

For ObjectOne - the longest array is B.

For ObjectTwo, the longest array is C.

```<code>mainobj = {
    ObjectOne: {
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 2}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'}
           ]
    },
    ObjectTwo:{
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ]
    }
}
</code>```

I can do this:

```<code>var size = Object.values(mainobj).length
</code>```

but I don't know how to get deeper than that. For instance, this doesn't work:

```<code>var size = Object.values(mainobj)[0].length
</code>```

This question is pretty similar, but I can't figure out how to apply it.
I appreciate the help!

答:
You could return an object for each outer key and get an array with the largest inner array's keys.

var object = { objectOne: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 2 }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }] }, objectTwo: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }] } },
    result = Object.keys(object).map(function (k) {
        var o = object[k];
        return {
            key: k,
            items: Object.keys(o).reduce(function (r, l, i) {
                if (!i || o[r[0]].length < o[l].length) {
                    return [l];
                }
                if (o[r[0]].length === o[l].length) {
                    r.push(l);
                }
                return r;
            }, [])
        };
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an object of objects. Within those objects are arrays, that have more objects.
Below is the structure.

I want to find out what the longest array of objects is within the parent object.
So in my example below:

For ObjectOne - the longest array is B.

For ObjectTwo, the longest array is C.

mainobj = {
    ObjectOne: {
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 2}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'}
           ]
    },
    ObjectTwo:{
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ]
    }
}

I can do this:

var size = Object.values(mainobj).length

but I don't know how to get deeper than that. For instance, this doesn't work:

var size = Object.values(mainobj)[0].length

This question is pretty similar, but I can't figure out how to apply it.
I appreciate the help!

Body:
You could return an object for each outer key and get an array with the largest inner array's keys.

var object = { objectOne: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 2 }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }] }, objectTwo: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }] } },
    result = Object.keys(object).map(function (k) {
        var o = object[k];
        return {
            key: k,
            items: Object.keys(o).reduce(function (r, l, i) {
                if (!i || o[r[0]].length < o[l].length) {
                    return [l];
                }
                if (o[r[0]].length === o[l].length) {
                    r.push(l);
                }
                return r;
            }, [])
        };
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Access Value From Object
I got the following results in a object after I did a var_dump on that object, how can I access the individual elements and put them into a variable?

I tried:

```<code>$content["ID"];
$content->ID;
</code>```

but no result :-(

```<code>  ["ID"]=>
  string(5) "31655"
  ["Reference"]=>
  string(7) "1899801"
  ["FullName"]=>
  string(18) "Lennie De Villiers"
  ["Username"]=>
  string(12) "lenniedg2000"
</code>```

答:
Try it on your end and see output

```<code> echo $content->ID;
 $var=$content->ID;
 echo $var;
</code>```

Just take a look here I created an example

http://codepad.org/KMDNCto3

Title: Access Value From Object

Body:
I got the following results in a object after I did a var_dump on that object, how can I access the individual elements and put them into a variable?

I tried:

$content["ID"];
$content->ID;

but no result :-(

  ["ID"]=>
  string(5) "31655"
  ["Reference"]=>
  string(7) "1899801"
  ["FullName"]=>
  string(18) "Lennie De Villiers"
  ["Username"]=>
  string(12) "lenniedg2000"

Body:
Try it on your end and see output

 echo $content->ID;
 $var=$content->ID;
 echo $var;

Just take a look here I created an example

http://codepad.org/KMDNCto3


问:
NSOutlineView doesn't Collapse Item
I have a NSOutlineView, and clicking on a row will expand/collapse the item if it's expandable.

```<code>    if ([self.outlineView isItemExpanded:item]) {
        NSLog("Will collapse item : %@", item);
        [[self.outlineView animator] collapseItem:item];
    }
    else {
        [[self.outlineView animator] expandItem:item];
    }
</code>```

Expanding the item works as expected, however collapsing the item is not working. I did get the log before executing collapseItem:, and the item is correct. The delegate method - (BOOL)outlineView:(NSOutlineView *)outlineView shouldCollapseItem:(id)item was not called too.

Have been on this problem for hours. Any ideas what causes this?

答:
In my case, my item is struct so those function didn't work. Then I need to change to class, and it worked. Because when I use this code "let item = outlineView.item(atRow: selectedIndex)" in struct it will copy value and create new object. So outlineView can't recognize the item => it won't work

```<code>    let selectedIndex = outlineView.selectedRow
    if let item = outlineView.item(atRow: selectedIndex) {
        if outlineView.isItemExpanded(item) {
            outlineView.collapseItem(item, collapseChildren: true)
        }else {
            outlineView.expandItem(item, expandChildren: true)
        }
    }
</code>```

Title: NSOutlineView doesn't Collapse Item

Body:
I have a NSOutlineView, and clicking on a row will expand/collapse the item if it's expandable.

    if ([self.outlineView isItemExpanded:item]) {
        NSLog("Will collapse item : %@", item);
        [[self.outlineView animator] collapseItem:item];
    }
    else {
        [[self.outlineView animator] expandItem:item];
    }

Expanding the item works as expected, however collapsing the item is not working. I did get the log before executing collapseItem:, and the item is correct. The delegate method - (BOOL)outlineView:(NSOutlineView *)outlineView shouldCollapseItem:(id)item was not called too.

Have been on this problem for hours. Any ideas what causes this?

Body:
In my case, my item is struct so those function didn't work. Then I need to change to class, and it worked. Because when I use this code "let item = outlineView.item(atRow: selectedIndex)" in struct it will copy value and create new object. So outlineView can't recognize the item => it won't work

    let selectedIndex = outlineView.selectedRow
    if let item = outlineView.item(atRow: selectedIndex) {
        if outlineView.isItemExpanded(item) {
            outlineView.collapseItem(item, collapseChildren: true)
        }else {
            outlineView.expandItem(item, expandChildren: true)
        }
    }