答:
You can use a scope in your User class, something like this:

```<code>public function scopeIsAdmin($query)
{
    return $query->whereHas('roles', function ($q) {
        $q->where('name', "ADMIN");
    });
}
</code>```

Then you can add it to your query like so:

User::isAdmin();

You will have to make sure that you include your OR statements correctly:

```<code>   return User::isAdmin()
        ->where(function ($q) use ($query, $sortColumn, $sortMethod) {
            $q->where('email', 'LIKE', '%' . $query . '%')
                ->orWhere('id', 'LIKE', '%' . $query . '%')
                ->orWhere('name', 'LIKE', '%' . $query . '%')
                ->orWhere('surname', 'LIKE', '%' . $query . '%')
                ->orderBy($sortColumn, $sortMethod)->paginate(25);
        })->paginate(25);
</code>```

I have not tested the above code so you may need to alter it slightly.

In response to your second question, you can probably use a different scope:

```<code>public function scopeOfRoleType($query, $types)
{
    return $query->whereHas('roles', function ($q) use ($types) {
        $q->whereIn('name', $types);
    });
}
</code>```

and then do User::ofRoleType(['admin', 'receptionist])....

Title: Filter users after the role

Body:
I am very beginner in Laravel.

I have this code:

    class User extends Authenticatable implements MustVerifyEmail
    {
        use Notifiable;

        public static $roles = [];

        protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

        protected $hidden = [
            'password', 'remember_token',
        ];

        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }

        public function mainRole()
        {
            return $this->hasOne('App\Role');
        }

        public function hasRole(array $roles)
        {

            foreach($roles as $role)
            {

                if(isset(self::$roles[$role]))
                {
                    if(self::$roles[$role])  return true;

                }
                else
                {
                    self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                    if(self::$roles[$role]) return true;
                }

            }
            return false;
        }

    }
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

and seed:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

    }

I would like to display a list of users who have the ADMIN role.

I have this code:

public function showAdminList(string $query, string $sortColumn, string $sortMethod) {

    return User::where('email', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('name', 'LIKE', '%' . $query . '%')->orWhere('surname', 'LIKE', '%' . $query . '%')->orderBy($sortColumn, $sortMethod)->paginate(25);

}

The above code shows me all the users I have in the database. How can I display only those users who have the ADMIN role?

Body:
You can use a scope in your User class, something like this:

public function scopeIsAdmin($query)
{
    return $query->whereHas('roles', function ($q) {
        $q->where('name', "ADMIN");
    });
}

Then you can add it to your query like so:

User::isAdmin();

You will have to make sure that you include your OR statements correctly:

   return User::isAdmin()
        ->where(function ($q) use ($query, $sortColumn, $sortMethod) {
            $q->where('email', 'LIKE', '%' . $query . '%')
                ->orWhere('id', 'LIKE', '%' . $query . '%')
                ->orWhere('name', 'LIKE', '%' . $query . '%')
                ->orWhere('surname', 'LIKE', '%' . $query . '%')
                ->orderBy($sortColumn, $sortMethod)->paginate(25);
        })->paginate(25);

I have not tested the above code so you may need to alter it slightly.

In response to your second question, you can probably use a different scope:

public function scopeOfRoleType($query, $types)
{
    return $query->whereHas('roles', function ($q) use ($types) {
        $q->whereIn('name', $types);
    });
}

and then do User::ofRoleType(['admin', 'receptionist])....


来源: stackexchange

问:
Stylesheets in external SVG - are they loaded from cache or twice?
I have the following code to export an external SVG image (I can't use it inline for a number of reasons):

```<code><head>
  <link rel="stylesheet" href="theme.css">
</head>

...

<object data="image.svg" type="image/svg+xml"></object>
</code>```

The image itself:

```<code><?xml-stylesheet href="theme.css" type="text/css"?>
<svg viewBox="0 0 100 100">...</svg>
</code>```

So for the image I am loading the same theme.css I am loading for the page to use some classes from it. It works fine, however I wonder if the page loading speed is affected by that? I checked the console and it looks like the second theme.css is loaded 10x times faster. Anybody can clarify how it works?

答:
If you use your browsers developer tools by pressing F12, view the Network tab, and then reload the page you can see whether a resource was loaded from memory cache or disk cache.

You can also test doing a refresh by using Shift+F5 for a refresh without cache to see if the speeds slow down again.

ContentLicense: CC BY-SA 4.0

Body:
I have the following code to export an external SVG image (I can't use it inline for a number of reasons):

  <link rel="stylesheet" href="theme.css">

...

<object data="image.svg" type="image/svg+xml"></object>

The image itself:

<?xml-stylesheet href="theme.css" type="text/css"?>
<svg viewBox="0 0 100 100">...</svg>

So for the image I am loading the same theme.css I am loading for the page to use some classes from it. It works fine, however I wonder if the page loading speed is affected by that? I checked the console and it looks like the second theme.css is loaded 10x times faster. Anybody can clarify how it works?


问:
How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

答:
So far here's where I've come.

After some research I've laned how to use the basic app script custom function, succeding in reproducing the if statement as below.
but I still don't see how to store the "PENDING" status once it has been verified by the  B1<=A1 argument. As is, the script below reverts back to "VALID" status when B1 value turns back to B1>A1.

How to formulate this missing storing argument in app script?

```<code>/**
* Stores Status 'PENDING' As soon as B1>A1 changes to B1<=A1
*
* @param arg1: The "PENDING" status that will be stored as soon as B1>A1 changes to B1<=A1
* @customfunction
*/

function STATUSPENDING(arg1) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if(changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING");
  } else {
    activeSheet.getRange(1, 4).setValue("VALID");
  }

  var result = arg1;

  return result;

}
</code>```

Body:
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

Body:
So far here's where I've come.

After some research I've laned how to use the basic app script custom function, succeding in reproducing the if statement as below.
but I still don't see how to store the "PENDING" status once it has been verified by the  B1<=A1 argument. As is, the script below reverts back to "VALID" status when B1 value turns back to B1>A1.

How to formulate this missing storing argument in app script?

/**
* Stores Status 'PENDING' As soon as B1>A1 changes to B1<=A1
*
* @param arg1: The "PENDING" status that will be stored as soon as B1>A1 changes to B1<=A1
* @customfunction
*/

function STATUSPENDING(arg1) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if(changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING");
  } else {
    activeSheet.getRange(1, 4).setValue("VALID");
  }

  var result = arg1;

  return result;

}


问:
Android on scroll up stop autoscroll
I have to edit a ListView so that the autoscroll stop when I scroll up and restart when I scroll completely down as it works in Android Studio's window Logcat for example. How can I implement it?

The ListView is set with android: transcriptMode = "alwaysScroll".

答: implement OnScrollListener and look on the firstVisibleItem. Store it somewhere, then when onScroll is called again compare firstVisibleItem with what you got stored. If it's greater => The user is scrolling down otherwise the user is scrolling up.

Title: Android on scroll up stop autoscroll


问:
Singleton initialization
I implemented the Singleton design pattern in my code.

Suppose it is:

```<code>class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};
</code>```

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

```<code>SingletonPointer* SingletonClass::s (0);
</code>```

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

答: It is accessed from the outside via Get (if you give that the appropriate type). The fact that it is private doesn't prevent that method from returning a pointer to it. A member being private just prevents access to it by name.

ContentLicense: CC BY-SA 3.0

Title: Singleton initialization

Body:
I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir


问:
SQL Check if value in Table is in range of 2 columns in another Table
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

```<code>mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)
</code>```

TABLE_2:

```<code>mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+
</code>```

Query:

```<code>SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);
</code>```

Output:

```<code>+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)
</code>```

答:
The not exists is likely the best performing version, but you can try the left join equivalent:

```<code>select table1.*
from Table1
left join table2
on table1.fruit = table2.fruit
and table1.count between table2.start_range and table2.end_range
where table2.id is null
</code>```

Body:
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)

TABLE_2:

mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+

Query:

SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);

Output:

+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)

Body:
The not exists is likely the best performing version, but you can try the left join equivalent:

select table1.*
from Table1
left join table2
on table1.fruit = table2.fruit
and table1.count between table2.start_range and table2.end_range
where table2.id is null


问:
How to connect from windows command prompt to mysql command line
I'm trying to connect to mysql server command line from my windows prompt

I write the next line in cmd but i get an error.

```<code>cd C:\MYSQL\bin\
</code>```

And then i execute

```<code>mysql.exe -u=root -p=admin
</code>```

but i getting this error

```<code>ERROR 1045: <28000>: Access denied for user 'root'@'localhost' <using password:YES>
</code>```

Thanks,

答:
Please perform the following steps

First, open your command prompt with Administrator.

Go to MySQL installed directory and copy path and past on command prompt
like:- C:\Program Files\MySQL\MySQL Server 5.7\bin>

C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -uroot -p  [-u for username -p for password]

C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -uroot -p
Enter password: **** [enter your password here]

Body:
I'm trying to connect to mysql server command line from my windows prompt

I write the next line in cmd but i get an error.

cd C:\MYSQL\bin\

And then i execute

mysql.exe -u=root -p=admin

but i getting this error

ERROR 1045: <28000>: Access denied for user 'root'@'localhost' <using password:YES>

Thanks,


问:
Why we use Lifecycle aware components & What is the purpose of Lifecycle Observer in Android?
We already have a Lifecycle in our Activity/Fragment then why will we use Lifecycle aware component & kindly guide me the main purpose of it.
And if we use lifecycle aware then why we use lifecycle that we knew already</p>

答:
Yes the Android Activity has a so called lifecycle

But that has nothing to do with a Lifecycle aware component

Lifecycle-aware components perform actions in response to a change in
the lifecycle status of another component, such as activities and
fragments. These components help you produce better-organized, and
often lighter-weight code, that is easier to maintain.

A common pattern is to implement the actions of the dependent
components in the lifecycle methods of activities and fragments.
However, this pattern leads to a poor organization of the code and to
the proliferation of errors. By using lifecycle-aware components, you
can move the code of dependent components out of the lifecycle methods
and into the components themselves.

Here´s a tutorial hands-on to make it more easy to understand

So why did Google Android devs come up with this technique and others in the Android jetpack? Yes Lifecycle aware component discussed here comes from Android jetpack from 2018. . They did it to make it easier for us to make robust Android apps. They are doing it to get us closer to the SOLID principles. Before that, developers were coming up with their own styles using homemade MVC,MVVC or MVP. Big discussions on Singletons technique for years and of course how we best do the separation of concern and Single responsibility principle

Now all of that is solved for us with Android jetpack

In object-oriented computer programming, SOLID is a mnemonic acronym
for five design principles intended to make software designs more
understandable, flexible and maintainable

WIKI


问:
How can I "associate" two variables to a position in a bi-dimensional array in C?
I have a bi-dimensional array with 8 elements in each dimension and I have two variables (x, y) with values from 0 to 7 each. I need to "associate" each value of those variables to the array position. Im positive that I must use pointers for this but I just can't figure it out by myself.

As an example, I have these two variables with 2 random values from 0 to 7.

```<code>int x = 3;
int y= 4;

int a [8][8];
</code>```

I need to assign the x=3 and the y=4 to the array as the element position:
a[3][4].

I will need to do this for every case, meaning, from x=0 to x=7 and y=0 to y=7, all the array position elements must be associated with the possible x and y variables values.

答:
Use 2 loops, 1 nested in other</p>

```<code>for (x = 0; x <= 7; x++) {
    for (y = 0; y <= 7; y++) {
        a[x][y] = something;
    }
}
</code>```

Body:
I have a bi-dimensional array with 8 elements in each dimension and I have two variables (x, y) with values from 0 to 7 each. I need to "associate" each value of those variables to the array position. Im positive that I must use pointers for this but I just can't figure it out by myself.

As an example, I have these two variables with 2 random values from 0 to 7.

int x = 3;
int y= 4;

int a [8][8];

I need to assign the x=3 and the y=4 to the array as the element position:
a[3][4].

I will need to do this for every case, meaning, from x=0 to x=7 and y=0 to y=7, all the array position elements must be associated with the possible x and y variables values.

Body:
Use 2 loops, 1 nested in other

for (x = 0; x <= 7; x++) {
    for (y = 0; y <= 7; y++) {
        a[x][y] = something;
    }
}


问:
IE8 CSS Hack - best method?
Can anyone recommend the best way to hack IE8 styling via CSS, I've recently been making IE8 render as IE7 for ease -  but wondered if it was best to add IE8 hacks?</p>

答:
As other answers posted,you could use Conditional Comments,but that would add one HTTP request when user is using IE8.
You can use the \0 hack in the css file</p>

```<code>img{
width:200px;//other broswers
width:100px\0;//only IE8
}
</code>```

Title: IE8 CSS Hack - best method?

Body:
As other answers posted,you could use Conditional Comments,but that would add one HTTP request when user is using IE8.
You can use the \0 hack in the css file

img{
width:200px;//other broswers
width:100px\0;//only IE8
}


问:
How to update table in MS Access 2007
I'm trying to update records in a table in MS Access 2007 from a temporary table. The temporary table gets new data from an external tool. The new data (2 columns) is supposed to go into the persistent table.

I tried the 2 following queries, but both show empty records when I look at the Datasheet view of the Query. (btw is there a better way to debug SQL in access?) The second Query also shows as many rows as there are in table1 instead of only the amount of rows edited by the external tool. (in both cases, the results are empty for every row)

the version that has at least the right amount of records:

```<code>UPDATE (table1 INNER JOIN table2 ON table1.key = table2.key)
SET table1.value1 = table2.value1, table1.datevalue = table2.datevalue
WHERE ((table1.value1) IS NULL);
</code>```

the version with as many records as result as there are records in table1:

```<code>UPDATE table1
SET table1.value1 = (SELECT value1
FROM table2
WHERE ((table1.value1 IS NULL)
AND (table1.key = table2.key))),
table1.datevalue = (SELECT datevalue
FROM table2
WHERE ((table1.key = table2.key)
AND (table1.value1 IS NULL)))
</code>```

In my test the tool manipulated 1 record so I expected to see one row as Output of the query with value1 and datevalue from table2, yet the output shows value1 and datevalue with empty entries (1 or (amount of records in table1)).

答:
To fully answer your questions, action queries including UPDATE and INSERT in the MS Access .exe program will raise a message prompt by default to inform the user how many rows will be updated or inserted and if user wants to continue with the action. Other views of action queries may not inform affected records.

This message will pop up if action query is called from:

Query Design window using the run action ! icon

Macro using OpenQuery action

Module using DoCmd.OpenQuery command

If not using MS Access .exe (since Access is both an application program and a database), you can still see how many records are affecting via code using DAO's Database.RecordsAffected property which is part of the MS Access object library. Any COM-interfaced language can run the same process including VBA, Python, PHP, Java, etc.

VBA Example (note: VBA is a separate component to MS Access and other Office apps)

Sub RunUpdate()
   Dim db as DAO.Database

   Set db = CurrentDb()
   db.Execute "mySavedUpdateQuery"

   MsgBox CStr(db.RecordsAffected) & " records were affected."

   Set db = Nothing
End Sub
```

<p><strong>Python Example</strong></p>

<pre class="lang-py prettyprint-override"><code>import os
import win32com.client

access_file = r'C:\Path\To\MyDatabase.accdb'

try:
    oApp = win32com.client.Dispatch("Access.Application")
    oApp.OpenCurrentDatabase(access_file)

    db = oApp.Currentdb()
    db.Execute("EmployeesUpdateQ")
    print("{} records were affected.".format(db.RecordsAffected))

except Exception as e:
    print(e)

finally:
    oApp.Quit()
    db = None; oApp = None
    del db; del oApp
</code>```

Number of Rows Question

Both your queries will update different number of records. First version maintains a JOIN and WHERE condition on outer level so will affect a filtered number of records in table1.

UPDATE (table1 t1 INNER JOIN table2 t2 ON t1.[key] = t2.[key])
SET t1.value1 = t2.value1,
    t1.datevalue = t2.datevalue
WHERE ((t1.value1) IS NULL);
```

<p>Second version uses subqueries with <code>JOIN</code> and <code>WHERE</code> conditions but nothing on outer level and so all records of <em>table1</em> will be affected but specific values may update to <code>NULL</code>. In fact, you may receive an exception error if subqueries return more than one value:</p>

<pre class="lang-sql prettyprint-override"><code>UPDATE table1
SET table1.value1 = (SELECT value1
                     FROM table2
                     WHERE ((table1.value1 IS NULL)
                       AND  (table1.[key] = table2.[key]))),

    table1.datevalue = (SELECT datevalue
                        FROM table2
                        WHERE ((table1.[key] = table2.[key])
                          AND  (table1.value1 IS NULL)))
</code>```

Title: How to update table in MS Access 2007

Body:
I'm trying to update records in a table in MS Access 2007 from a temporary table. The temporary table gets new data from an external tool. The new data (2 columns) is supposed to go into the persistent table.

I tried the 2 following queries, but both show empty records when I look at the Datasheet view of the Query. (btw is there a better way to debug SQL in access?) The second Query also shows as many rows as there are in table1 instead of only the amount of rows edited by the external tool. (in both cases, the results are empty for every row)

the version that has at least the right amount of records:

UPDATE (table1 INNER JOIN table2 ON table1.key = table2.key)
SET table1.value1 = table2.value1, table1.datevalue = table2.datevalue
WHERE ((table1.value1) IS NULL);

the version with as many records as result as there are records in table1:

UPDATE table1
SET table1.value1 = (SELECT value1
FROM table2
WHERE ((table1.value1 IS NULL)
AND (table1.key = table2.key))),
table1.datevalue = (SELECT datevalue
FROM table2
WHERE ((table1.key = table2.key)
AND (table1.value1 IS NULL)))

In my test the tool manipulated 1 record so I expected to see one row as Output of the query with value1 and datevalue from table2, yet the output shows value1 and datevalue with empty entries (1 or (amount of records in table1)).

Body:
To fully answer your questions, action queries including UPDATE and INSERT in the MS Access .exe program will raise a message prompt by default to inform the user how many rows will be updated or inserted and if user wants to continue with the action. Other views of action queries may not inform affected records.

This message will pop up if action query is called from:

Query Design window using the run action ! icon

Macro using OpenQuery action

Module using DoCmd.OpenQuery command

If not using MS Access .exe (since Access is both an application program and a database), you can still see how many records are affecting via code using DAO's Database.RecordsAffected property which is part of the MS Access object library. Any COM-interfaced language can run the same process including VBA, Python, PHP, Java, etc.

VBA Example (note: VBA is a separate component to MS Access and other Office apps)

Sub RunUpdate()
   Dim db as DAO.Database

   Set db = CurrentDb()
   db.Execute "mySavedUpdateQuery"

   MsgBox CStr(db.RecordsAffected) & " records were affected."

   Set db = Nothing
End Sub

Python Example

import os
import win32com.client

access_file = r'C:\Path\To\MyDatabase.accdb'

try:
    oApp = win32com.client.Dispatch("Access.Application")
    oApp.OpenCurrentDatabase(access_file)

    db = oApp.Currentdb()
    db.Execute("EmployeesUpdateQ")
    print("{} records were affected.".format(db.RecordsAffected))

except Exception as e:
    print(e)

finally:
    oApp.Quit()
    db = None; oApp = None
    del db; del oApp

Number of Rows Question

Both your queries will update different number of records. First version maintains a JOIN and WHERE condition on outer level so will affect a filtered number of records in table1.

UPDATE (table1 t1 INNER JOIN table2 t2 ON t1.[key] = t2.[key])
SET t1.value1 = t2.value1,
    t1.datevalue = t2.datevalue
WHERE ((t1.value1) IS NULL);

Second version uses subqueries with JOIN and WHERE conditions but nothing on outer level and so all records of table1 will be affected but specific values may update to NULL. In fact, you may receive an exception error if subqueries return more than one value:

UPDATE table1
SET table1.value1 = (SELECT value1
                     FROM table2
                     WHERE ((table1.value1 IS NULL)
                       AND  (table1.[key] = table2.[key]))),

    table1.datevalue = (SELECT datevalue
                        FROM table2
                        WHERE ((table1.[key] = table2.[key])
                          AND  (table1.value1 IS NULL)))


问:
Cannot add or update a child row: a foreign key constraint failss
The foreign key in the user table seems like don't allow me to input my data, the primary table is the company table.

I try to make companyid as not primary key in the users table but there is not much use

```<code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `webpage` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `webpage` ;

-- -----------------------------------------------------
-- Table `webpage`.`company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webpage`.`company` (
  `idcompany` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `user_id` INT NOT NULL,
  PRIMARY KEY (`idcompany`),
  INDEX `fk_company_user1_idx` (`user_id` ASC),
  CONSTRAINT `fk_company_user1`
    FOREIGN KEY (`user_id`)
    REFERENCES `webpage`.`user` (`iduser`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `webpage`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webpage`.`user` (
  `iduser` INT NOT NULL,
  `username` VARCHAR(45) NOT NULL,
  `password` VARCHAR(45) NOT NULL,
  `email` VARCHAR(45) NOT NULL,
  `first_name` TEXT NOT NULL,
  `last_name` TEXT NOT NULL,
  `gender` TEXT NOT NULL,
  `company_id` INT NOT NULL,
  PRIMARY KEY (`iduser`),
  INDEX `fk_user_company_idx` (`company_id` ASC),
  CONSTRAINT `fk_user_company`
    FOREIGN KEY (`company_id`)
    REFERENCES `webpage`.`company` (`idcompany`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code>```

This is the error messages that show

Cannot add or update a child row: a foreign key constraint fails (webpage.users, CONSTRAINT fk_users_company1 FOREIGN KEY (company_idcompany) REFERENCES company (idcompany) ON DELETE NO ACTION ON UPDATE NO ACTION)

答:
This looks like a circular reference to me.

You can't insert a company without a user, and can't insert a user without a company.  You also can't insert into two tables at once.

Decide if you really need this kind of relationship.  If there's a one to one relationship, you may be able to deal with just one table.  If a company has more than one user, you can remove the user_id from the company table.  If a user can belong to more than one company, you can create a membership table with company_id, user_id pairs as the records.

If you do, you may need to remove the foreign key and non-null constraints.

Body:
The foreign key in the user table seems like don't allow me to input my data, the primary table is the company table.

I try to make companyid as not primary key in the users table but there is not much use

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `webpage` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `webpage` ;

-- -----------------------------------------------------
-- Table `webpage`.`company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webpage`.`company` (
  `idcompany` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `user_id` INT NOT NULL,
  PRIMARY KEY (`idcompany`),
  INDEX `fk_company_user1_idx` (`user_id` ASC),
  CONSTRAINT `fk_company_user1`
    FOREIGN KEY (`user_id`)
    REFERENCES `webpage`.`user` (`iduser`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `webpage`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `webpage`.`user` (
  `iduser` INT NOT NULL,
  `username` VARCHAR(45) NOT NULL,
  `password` VARCHAR(45) NOT NULL,
  `email` VARCHAR(45) NOT NULL,
  `first_name` TEXT NOT NULL,
  `last_name` TEXT NOT NULL,
  `gender` TEXT NOT NULL,
  `company_id` INT NOT NULL,
  PRIMARY KEY (`iduser`),
  INDEX `fk_user_company_idx` (`company_id` ASC),
  CONSTRAINT `fk_user_company`
    FOREIGN KEY (`company_id`)
    REFERENCES `webpage`.`company` (`idcompany`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

This is the error messages that show

Cannot add or update a child row: a foreign key constraint fails (webpage.users, CONSTRAINT fk_users_company1 FOREIGN KEY (company_idcompany) REFERENCES company (idcompany) ON DELETE NO ACTION ON UPDATE NO ACTION)


问:
Pandas wide_to_long - keep rows with values in i or just one row with blank
I am trying to transform a dataframe into long format, and want to keep the records  following this rule:

(1) if the id has data in the stub - keep all the non-empty "long" records, drop the empty ones
(2) if the id does not have data in any of the stubs, keep only 1 "long" record of it

In other words, for each id I need to keep at least one record:
-exactly one record if the id does not have data in the stub,
-or as many rows as the id has filled in the stub

I am using wide_to_long because it allows the use of stubnames, which melt does not (or at least I could not figure out how to use). This is the sample code (inspired by the official pandas doc on wide_to_long):

```<code>import numpy as np
import pandas as pd

np.random.seed(123)
df = pd.DataFrame({"A2001" : {0 : "a", 1 : "b", 2 : "c",3:""},
                    "A2002" : {0 : "d", 1 : "e", 2 : "",3:""},
                    "A2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "A2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                   })

df["id"] = df.index
pd.wide_to_long(df, ["A"], i="id", j="year")
</code>```

The output is:

```<code>         A
id year
0  2001  a
1  2001  b
2  2001  c
3  2001
0  2002  d
1  2002  e
2  2002
3  2002
0  2003  g
1  2003  h
2  2003  i
3  2003
0  2004  j
1  2004  k
2  2004  l
3  2004
</code>```

What I need to achieve:
for ids 0, 1 and 2 I need the rows gone where ["A"] is blank (or NaN);
for id 3 - I need to keep 1 row (any one row, does not matter which one):

```<code>         A
id year
0  2001  a
1  2001  b
2  2001  c
3  2001
0  2002  d
1  2002  e
0  2003  g
1  2003  h
2  2003  i
0  2004  j
1  2004  k
2  2004  l
</code>```

I tried this:

```<code>df.dropna(axis=0,how="all",subset=["A"])
</code>```

but it deletes all rows for id 3

Edit:

I am also looking for a general solution for this as well, with a list of stubnames:

```<code>df = pd.DataFrame({"A2001" : {0 : "a", 1 : "b", 2 : "",3:""},
                    "A2002" : {0 : "d", 1 : "e", 2 : "test",3:""},
                    "A2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "A2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                    "B2001" : {0 : "a", 1 : "b", 2 : "",3:""},
                    "B2002" : {0 : "d", 1 : "e", 2 : "",3:""},
                    "B2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "B2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                   })

pd.wide_to_long(df, ["A","B"], i="id", j="year")
</code>```

I need to delete rows where both A and B columns are empty, but still keep at least 1 record for each id (and exactly one record if A and B are both blanks)

答:
Follow your condition and logic </p>

```<code>df["id"] = df.index
s=pd.wide_to_long(df, ["A"], i="id", j="year")
s=s.groupby(level=0).A.apply(lambda x : x.head(1) if (x=='').all() else x[x!='']).reset_index(level=0,drop=True)
s.sort_index(level=1)

Out[137]:
id  year
0   2001    a
1   2001    b
2   2001    c
3   2001
0   2002    d
1   2002    e
0   2003    g
1   2003    h
2   2003    i
0   2004    j
1   2004    k
2   2004    l
Name: A, dtype: object
</code>```

Body:
I am trying to transform a dataframe into long format, and want to keep the records  following this rule:

(1) if the id has data in the stub - keep all the non-empty "long" records, drop the empty ones
(2) if the id does not have data in any of the stubs, keep only 1 "long" record of it

In other words, for each id I need to keep at least one record:
-exactly one record if the id does not have data in the stub,
-or as many rows as the id has filled in the stub

I am using wide_to_long because it allows the use of stubnames, which melt does not (or at least I could not figure out how to use). This is the sample code (inspired by the official pandas doc on wide_to_long):

import numpy as np
import pandas as pd

np.random.seed(123)
df = pd.DataFrame({"A2001" : {0 : "a", 1 : "b", 2 : "c",3:""},
                    "A2002" : {0 : "d", 1 : "e", 2 : "",3:""},
                    "A2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "A2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                   })

df["id"] = df.index
pd.wide_to_long(df, ["A"], i="id", j="year")

The output is:

         A
id year
0  2001  a
1  2001  b
2  2001  c
3  2001
0  2002  d
1  2002  e
2  2002
3  2002
0  2003  g
1  2003  h
2  2003  i
3  2003
0  2004  j
1  2004  k
2  2004  l
3  2004

What I need to achieve:
for ids 0, 1 and 2 I need the rows gone where ["A"] is blank (or NaN);
for id 3 - I need to keep 1 row (any one row, does not matter which one):

         A
id year
0  2001  a
1  2001  b
2  2001  c
3  2001
0  2002  d
1  2002  e
0  2003  g
1  2003  h
2  2003  i
0  2004  j
1  2004  k
2  2004  l

I tried this:

df.dropna(axis=0,how="all",subset=["A"])

but it deletes all rows for id 3

Edit:

I am also looking for a general solution for this as well, with a list of stubnames:

df = pd.DataFrame({"A2001" : {0 : "a", 1 : "b", 2 : "",3:""},
                    "A2002" : {0 : "d", 1 : "e", 2 : "test",3:""},
                    "A2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "A2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                    "B2001" : {0 : "a", 1 : "b", 2 : "",3:""},
                    "B2002" : {0 : "d", 1 : "e", 2 : "",3:""},
                    "B2003" : {0 : "g", 1 : "h", 2 : "i",3:""},
                    "B2004" : {0 : "j", 1 : "k", 2 : "l",3:""},
                   })

pd.wide_to_long(df, ["A","B"], i="id", j="year")

I need to delete rows where both A and B columns are empty, but still keep at least 1 record for each id (and exactly one record if A and B are both blanks)

Body:
Follow your condition and logic

df["id"] = df.index
s=pd.wide_to_long(df, ["A"], i="id", j="year")
s=s.groupby(level=0).A.apply(lambda x : x.head(1) if (x=='').all() else x[x!='']).reset_index(level=0,drop=True)
s.sort_index(level=1)

Out[137]:
id  year
0   2001    a
1   2001    b
2   2001    c
3   2001
0   2002    d
1   2002    e
0   2003    g
1   2003    h
2   2003    i
0   2004    j
1   2004    k
2   2004    l
Name: A, dtype: object


问:
Inconsistent scope of "use strict" on different web browsers (concerning arguments.callee and caller)

Situation:

I found something strange concerning strict mode in Javascript.

I am using an external, third-party Javascript library which

was minified,

has over 4000 lines of code,

is not using use strict at all, and

is using arguments.callee.

I am using use strict in my own code, scoped within a function.

When I call one of the functions provided by the library, it throws an error. However,

the error is thrown only if I am using use strict

the error is thrown in all browsers except Chrome

Code:

I've removed all the unrelated stuff and reduced the code into this (online demo on jsFiddle):

// This comes from the minified external JS library.
// It creates a global object "foo".
(function () {
    foo = {};
    foo.bar = function (e) {
        return function () {
            var a5 = arguments.callee;
            while (a5) {
                a5 = a5.caller      // Error on this line in all browsers except Chrome
            }
        }
    }("any value here");
})();

// Here's my code.
(function() {
    "use strict";   // I enable strict mode in my own function only.

    foo.bar();
    alert("done");
})();```
</div>
</div>
</p>

<hr>

<h3>Test result:</h3>

```+-----------------------+-----+--------------------------------------------------------------+
| Browser               | OS  | Error                                                        |
+-----------------------+-----+--------------------------------------------------------------+
| Chrome 27.0.1453.94 m | Win | <<NO ERROR!>>                                                |
| Opera 12.15           | Win | Unhandled Error: Illegal property access                     |
| Firefox 21.0          | Win | TypeError: access to strict mode caller function is censored |
| Safari 5.1.7          | Win | TypeError: Type error                                        |
| IE 10                 | Win | SCRIPT5043: Accessing the 'caller' property of a function or |
|                       |     |             arguments object is not allowed in strict mode   |
| Chrome 27.0.1543.93   | Mac | <<NO ERROR!>>                                                |
| Opera 12.15           | Mac | Unhandled Error: Illegal property access                     |
| Firefox 21.0          | Mac | TypeError: access to strict mode caller function is censored |
| Safari 6.0.4          | Mac | TypeError: Function.caller used to retrieve strict caller    |
+-----------------------+-----+--------------------------------------------------------------+
```

Note: for OS, Win = Windows 7, Mac = Mac OS 10.7.5

My understanding:

All modern desktop browsers support use strict (see Can I use).

The use strict is scoped within my function, so everything defined outside its scope is not affected (see this Stack Overflow question).

Question:

So, are all browsers except Chrome wrong? Or is it the other way round? Or is this undefined behaviour so the browsers may choose to implement it in either way?

答:
I have to use an older Telerik JS library that I cant't readily update and encountered this error this morning.  One possible workaround for some people might be to use the 'setTimeout' JS function to leave strict mode before calling the loose mode function.

e.g.  Change this:

```<code>function functionInStrictMode(){
  looseModeFunction();
}
</code>```

To something like this:

```<code>function functionInStrictMode(){
    setTimeout(looseModeFunction);
}
</code>```

I'm guessing this probably works because setTimeout reverts the context to the global namespace and/or leaves the scope of functionInStrictMode.  I don't fully understand all the particulars.  There might be better ways; I did not research this thoroughly, but I thought I'd post it here for discussion.

Body:
Situation:

I found something strange concerning strict mode in Javascript.

I am using an external, third-party Javascript library which

was minified,

has over 4000 lines of code,

is not using use strict at all, and

is using arguments.callee.

I am using use strict in my own code, scoped within a function.

When I call one of the functions provided by the library, it throws an error. However,

the error is thrown only if I am using use strict

the error is thrown in all browsers except Chrome

Code:

I've removed all the unrelated stuff and reduced the code into this (online demo on jsFiddle):

// This comes from the minified external JS library.
// It creates a global object "foo".
(function () {
    foo = {};
    foo.bar = function (e) {
        return function () {
            var a5 = arguments.callee;
            while (a5) {
                a5 = a5.caller      // Error on this line in all browsers except Chrome
            }
        }
    }("any value here");
})();

// Here's my code.
(function() {
    "use strict";   // I enable strict mode in my own function only.

    foo.bar();
    alert("done");
})();

Test result:

+-----------------------+-----+--------------------------------------------------------------+
| Browser               | OS  | Error                                                        |
+-----------------------+-----+--------------------------------------------------------------+
| Chrome 27.0.1453.94 m | Win | <<NO ERROR!>>                                                |
| Opera 12.15           | Win | Unhandled Error: Illegal property access                     |
| Firefox 21.0          | Win | TypeError: access to strict mode caller function is censored |
| Safari 5.1.7          | Win | TypeError: Type error                                        |
| IE 10                 | Win | SCRIPT5043: Accessing the 'caller' property of a function or |
|                       |     |             arguments object is not allowed in strict mode   |
| Chrome 27.0.1543.93   | Mac | <<NO ERROR!>>                                                |
| Opera 12.15           | Mac | Unhandled Error: Illegal property access                     |
| Firefox 21.0          | Mac | TypeError: access to strict mode caller function is censored |
| Safari 6.0.4          | Mac | TypeError: Function.caller used to retrieve strict caller    |
+-----------------------+-----+--------------------------------------------------------------+

Note: for OS, Win = Windows 7, Mac = Mac OS 10.7.5

My understanding:

All modern desktop browsers support use strict (see Can I use).

The use strict is scoped within my function, so everything defined outside its scope is not affected (see this Stack Overflow question).

Question:

So, are all browsers except Chrome wrong? Or is it the other way round? Or is this undefined behaviour so the browsers may choose to implement it in either way?

Body:
I have to use an older Telerik JS library that I cant't readily update and encountered this error this morning.  One possible workaround for some people might be to use the 'setTimeout' JS function to leave strict mode before calling the loose mode function.

e.g.  Change this:

function functionInStrictMode(){
  looseModeFunction();
}

To something like this:

function functionInStrictMode(){
    setTimeout(looseModeFunction);
}

I'm guessing this probably works because setTimeout reverts the context to the global namespace and/or leaves the scope of functionInStrictMode.  I don't fully understand all the particulars.  There might be better ways; I did not research this thoroughly, but I thought I'd post it here for discussion.


问:
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).

Google shows many hits for explanations on how to do this.

Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.

I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.

My specific use case is a command-line python program that needs to send emails.  I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).

I do not need it to work on windows or mac, just linux.

答:
You can try using the Python Prompt Toolkit, a library for building interactive command line applications in Python.

The library makes it easy to add interactive autocomplete functionality, allowing the user to use the Tab key to visually cycle through the available choices. The library is cross-platform (Linux, OS X, FreeBSD, OpenBSD, Windows). Example:

(Image source: pcgli)

OwnerDisplayName: Paul Eden

ContentLicense: CC BY-SA 2.5


答:
Mask to NaN before you wide_to_long then dropna using the threshold.

m checks if every stub column is empty for a row. Replace either all, or all but one, '' with NaN, based on m. This allows us to keep exactly one row in the result when all stubs are missing:

If you change the suffix or sep parameters in wide_to_long, you will need to adjust the creation of scols accordingly.

```<code>stubs = ['A', 'B']
scols = df.columns[df.columns.str.split('[0-9]+').str[0].isin(stubs)]  #Mimic stubs
m = df.loc[:, scols].eq('').all(1)

df.loc[~m, scols] = df.loc[~m, scols].replace('', np.NaN)
df.loc[m, scols[1:]] = np.NaN

(pd.wide_to_long(df.assign(id=df.index), stubnames=stubs, i="id", j="year")
   .dropna(thresh=1)
   .replace(np.NaN, '')  #Or perhaps the empty to NaN
)
</code>```

Output:

```<code>            A  B
id year
0  2001     a  a
1  2001     b  b
3  2001
0  2002     d  d
1  2002     e  e
2  2002  test
0  2003     g  g
1  2003     h  h
2  2003     i  i
0  2004     j  j
1  2004     k  k
2  2004     l  l
</code>```

Title: Pandas wide_to_long - keep rows with values in i or just one row with blank

Body:
Mask to NaN before you wide_to_long then dropna using the threshold.

m checks if every stub column is empty for a row. Replace either all, or all but one, '' with NaN, based on m. This allows us to keep exactly one row in the result when all stubs are missing:

If you change the suffix or sep parameters in wide_to_long, you will need to adjust the creation of scols accordingly.

stubs = ['A', 'B']
scols = df.columns[df.columns.str.split('[0-9]+').str[0].isin(stubs)]  #Mimic stubs
m = df.loc[:, scols].eq('').all(1)

df.loc[~m, scols] = df.loc[~m, scols].replace('', np.NaN)
df.loc[m, scols[1:]] = np.NaN

(pd.wide_to_long(df.assign(id=df.index), stubnames=stubs, i="id", j="year")
   .dropna(thresh=1)
   .replace(np.NaN, '')  #Or perhaps the empty to NaN
)

Output:

            A  B
id year
0  2001     a  a
1  2001     b  b
3  2001
0  2002     d  d
1  2002     e  e
2  2002  test
0  2003     g  g
1  2003     h  h
2  2003     i  i
0  2004     j  j
1  2004     k  k
2  2004     l  l


问:
Spring boot logbcak to file is not working on tomcat
I am running spring boot as War on tomcat with logback to console and file.

as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.

I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
</code>```

答:
Here is my logback-spring.xml which i have</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
</code>```

Body:
I am running spring boot as War on tomcat with logback to console and file.

as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.

I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

Body:
Here is my logback-spring.xml which i have

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>


问:
How do I change the value of a variable for a short time span?
I wanna change the value of a variable for a short time span only! If a user presses the up-key/down-key the value should be changed for 3 seconds. How could I implement this in Python?

I've tried some things such as time.sleep() but with this method the Tron is not moving in this time.

#Controls of Tron-Bike
#Up-Key increases the forward speed
def up():
      thread_sleep_time = 0.5
    # THIS code is ONLY for the POC (proof of concept)
    # normally in TRON, the "bike" moves with a constant speed
    # therefore you can use this hook
      print("heading P1:", t1.heading())
```

I wanna change the code that the thread_sleep_time is set to 0.5 and after 3 seconds it should change back to 1.

答:
Since you specifically tagged [turtle-graphics], here's an approach using turtle's timer mechanism.  The method write() runs continuously printing the current value of variable to the center of the screen.  When you press the up arrow key, another timed event kicks in that changes variable to a different value for three seconds, after which it's restored to its original value.  The write() method knows nothing of this, it just keeps displaying the current value:

```<code>from turtle import Screen, Turtle
from random import randint

FONT = ('Arial', 28, 'normal')

def up():
    global variable

    screen.onkey(None, "Up")  # disable handler inside handler

    screen.ontimer(lambda o=variable: reset_variable(o), 3000)  # in milliseconds

    variable = randint(1, 1000)

def reset_variable(original_value):
    global variable

    variable = original_value

    screen.onkey(up, "Up")  # restore event handler

def write():
    turtle.undo()
    turtle.write("variable = {}".format(variable), align='center', font=FONT)
    screen.ontimer(write, 250)

variable = randint(1, 1000)

screen = Screen()

turtle = Turtle(visible=False)
turtle.write("variable = {}".format(variable), align='center', font=FONT)

screen.onkey(up, "Up")
screen.listen()

write()

screen.mainloop()
</code>```

Body:
I wanna change the value of a variable for a short time span only! If a user presses the up-key/down-key the value should be changed for 3 seconds. How could I implement this in Python?

I've tried some things such as time.sleep() but with this method the Tron is not moving in this time.

#Controls of Tron-Bike
#Up-Key increases the forward speed
def up():
      thread_sleep_time = 0.5
    # THIS code is ONLY for the POC (proof of concept)
    # normally in TRON, the "bike" moves with a constant speed
    # therefore you can use this hook
      print("heading P1:", t1.heading())

I wanna change the code that the thread_sleep_time is set to 0.5 and after 3 seconds it should change back to 1.

Body:
Since you specifically tagged [turtle-graphics], here's an approach using turtle's timer mechanism.  The method write() runs continuously printing the current value of variable to the center of the screen.  When you press the up arrow key, another timed event kicks in that changes variable to a different value for three seconds, after which it's restored to its original value.  The write() method knows nothing of this, it just keeps displaying the current value:

from turtle import Screen, Turtle
from random import randint

FONT = ('Arial', 28, 'normal')

def up():
    global variable

    screen.onkey(None, "Up")  # disable handler inside handler

    screen.ontimer(lambda o=variable: reset_variable(o), 3000)  # in milliseconds

    variable = randint(1, 1000)

def reset_variable(original_value):
    global variable

    variable = original_value

    screen.onkey(up, "Up")  # restore event handler

def write():
    turtle.undo()
    turtle.write("variable = {}".format(variable), align='center', font=FONT)
    screen.ontimer(write, 250)

variable = randint(1, 1000)

screen = Screen()

turtle = Turtle(visible=False)
turtle.write("variable = {}".format(variable), align='center', font=FONT)

screen.onkey(up, "Up")
screen.listen()

write()

screen.mainloop()


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
Attributes are part of the meta-data of a type and so they are hardcoded in the compiled assembly (that's also why you are only allowed to use some primitive types and not arbitrary data at attributes).

The consequence is that you can't add any attributes to a type at runtime. But there are various alternative techniques. You could use simple dictionaries or something more powerful like attached dependency properties.

LastEditorDisplayName: Samuel

OwnerDisplayName: Thomas Danecker


问:
how to avoid memory wastage when storing UTF-8 characters (8 bit) in Java character (16 bit). two in one?
I'm afraid I have a question on a detail of a rather oversaturated topic, I searched aroudn a lot, but couldn't find a clear answer to that specific obvious -imho- important, problem:

When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8, but each UTF-8 character is saved as a 16 bit character in java. Is that correct?
If yes, this means, that each stupid java character only uses the first 8 bits, and consumes double the memory? Is that correct too? I wonder how this wasteful behaviour is acceptable..

Isn't there some trick to have a pseudo String that is 8 bit?  Would that actually result in less memory consumption?
Or maybe, is there a way to store >two< 8bit characters in one java 16bit character to avoid this memory waste?

thanks for any deconfusing answers...

EDIT:
hi, thanks everybody for answering. I was aware of the variable-length property of UTF-8. However, since my source is byte which is 8 bit, I understood (apparently wrongly) that it needs only 8-bit UTF-8 words. Is UTF-8 conversion actually saving the strange symbols that you see when on the CLI you do "cat somebinary" ? I thought UTF-8 was just somehow used to map each of the possible 8bit words of byte to one particular 8 bit word of UTF-8. Wrong? I thought about using Base64 but it's bad because it uses only 7 bit..

questions reformulated: is there a smarter way to convert byte to something String?
May favorite was to just cast byte[] to char[], but then I still have 16bit words.

additional use case info:

I'm adapting Jedis (java client for the NoSQL Redis) as the  "primitive storage layer" for hypergraphDB. So, jedis is a database for another "database".
My problem is that I have to feed jedis with byte[] data all the time, but internally, >Redis< (the actual server)  is dealing only with "binary safe" Strings. Since Redis is written in C, a char is 8 bit long, AFAIK not ASCIII which is 7 bit. In Jedis however, java world, every character is 16 bit long internally. I don't understand this code (yet), but I suppose jedis then converts this java 16 bit strings to a Redis conforming 8 bit string (([here][3]). It says it extends FilterOutputStream. My hope is to bypass the byte[] <-> string conversion altogether and use that Filteroutputstream...?  )

now I wonder: if I had to interconvert byte[] and String all the time, with datasizes ranging from very small to potentially very big, isn't there a huge waste of memory to have each 8 bit character passed around as 16bit within java?

答:
Isn't there some trick to have a pseudo String that is 8 bit?

yes, make sure you have an up to date version of Java. ;)

http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

-XX:+UseCompressedStrings     Use a byte[] for Strings which can be represented as pure ASCII. (Introduced in Java 6 Update 21 Performance Release)

EDIT: This option doesn't work in Java 6 update 22 and is not on by default in Java 6 update 24. Note: it appears this option may slow performance by about 10%.

The following program

```<code>public static void main(String... args) throws IOException {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; i++)
        sb.append(i);

    for (int j = 0; j < 10; j++)
        test(sb, j >= 2);
}

private static void test(StringBuilder sb, boolean print) {
    List<String> strings = new ArrayList<String>();
    forceGC();
    long free = Runtime.getRuntime().freeMemory();

    long size = 0;
    for (int i = 0; i < 100; i++) {
        final String s = "" + sb + i;
        strings.add(s);
        size += s.length();
    }
    forceGC();
    long used = free - Runtime.getRuntime().freeMemory();
    if (print)
        System.out.println("Bytes per character is " + (double) used / size);
}

private static void forceGC() {
    try {
        System.gc();
        Thread.sleep(250);
        System.gc();
        Thread.sleep(250);
    } catch (InterruptedException e) {
        throw new AssertionError(e);
    }
}
</code>```

Prints this by default

```<code>Bytes per character is 2.0013668655941212
Bytes per character is 2.0013668655941212
Bytes per character is 2.0013606946433575
Bytes per character is 2.0013668655941212
</code>```

with the option -XX:+UseCompressedStrings

```<code>Bytes per character is 1.0014671435440285
Bytes per character is 1.0014671435440285
Bytes per character is 1.0014609725932648
Bytes per character is 1.0014671435440285
</code>```

Body:
Isn't there some trick to have a pseudo String that is 8 bit?

yes, make sure you have an up to date version of Java. ;)

http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

-XX:+UseCompressedStrings     Use a byte[] for Strings which can be represented as pure ASCII. (Introduced in Java 6 Update 21 Performance Release)

EDIT: This option doesn't work in Java 6 update 22 and is not on by default in Java 6 update 24. Note: it appears this option may slow performance by about 10%.

The following program

public static void main(String... args) throws IOException {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; i++)
        sb.append(i);

    for (int j = 0; j < 10; j++)
        test(sb, j >= 2);
}

private static void test(StringBuilder sb, boolean print) {
    List<String> strings = new ArrayList<String>();
    forceGC();
    long free = Runtime.getRuntime().freeMemory();

    long size = 0;
    for (int i = 0; i < 100; i++) {
        final String s = "" + sb + i;
        strings.add(s);
        size += s.length();
    }
    forceGC();
    long used = free - Runtime.getRuntime().freeMemory();
    if (print)
        System.out.println("Bytes per character is " + (double) used / size);
}

private static void forceGC() {
    try {
        System.gc();
        Thread.sleep(250);
        System.gc();
        Thread.sleep(250);
    } catch (InterruptedException e) {
        throw new AssertionError(e);
    }
}

Prints this by default

Bytes per character is 2.0013668655941212
Bytes per character is 2.0013668655941212
Bytes per character is 2.0013606946433575
Bytes per character is 2.0013668655941212

with the option -XX:+UseCompressedStrings

Bytes per character is 1.0014671435440285
Bytes per character is 1.0014671435440285
Bytes per character is 1.0014609725932648
Bytes per character is 1.0014671435440285


问:
Hyperledger cost of peers for an organization
I'm researching the cost of an application that relies on the Hyperledger blockchain, but I don't understand if maintaining a node (peer) is expensive or not.
I find conflicting information, anyone can have an active node on their PC, but reading some documentation I find that having a peer is very expensive and there is support for services like this.

So I would like to understand, for an organization how much it costs to have nodes on Hyperledger? Do they require specific hardware specifications?

Can anyone help me shed some light on the subject?
Thank you!

答:
Hardware: Fabric docs didn't specifies minimum hardware requirements it will depend on the number and complexity of transactions, endorsement policies and your business, performance and security requirements.

License: Free

Technical Support: In my experience it's the most expensive side of use fabric. Fabric is a complex system, with complex configs and architecture. It demands skilled human resource in order to set up and maintain it working. The cost can vary by region and your requirements but its do uses to be cheap.


问:
Knockout single observable with multiple subscriptions
I have inherited an application written using Knockout for the UI and I am curious as to what the effect is of having multiple subscriptions against a single observable property?

I have an observable that has 2 subscriptions. By logging to the console I can see that both subscriptions get fired, one after the other.

Using the following example: (this is very stripped down for brevity in the full code there is lots of logic, some of which is duplicated)

```<code>self.VisitDate = ko.observable();

self.VisitDate.subscribe(function (newValue) {
    self.ListItemRemoved(removed);
});

self.VisitDate.subscribe(function (newValue) {
    self.Basket.VisitDate(newValue);
});
</code>```

I was thinking that I should see some sort of error, because of the multiple subscriptions, but everything appears to work fine but I cannot find any clear explanation of why this is OK to do?

I am just trying to find out the following:

Is it normal and acceptable to have multiple subscriptions to a single observable?
Is there any underlying impact on doing this i.e. race conditions maybe?
Is there ever really any need to have multiple subscriptions to achieve something that cannot be achieved in a single subscription?

I appreciate this may be a little shy in detail but I am really just trying to get an understanding of how knockout is doing things under the covers to see whether I should be looking to refactor this code or not.

答:
The observer/observable design pattern does allow for multiple observers/subscriptions. The purpose of the design pattern in short is:

De-couple the change from the effects of the change.

Allow for any and arbitrary effects to stem from a change.

So, Knockout does that through its observables.

var observable = ko.observable("a");

observable.subscribe(function(newValue) {
  console.log("observer 1", newValue)
});

observable.subscribe(function(newValue) {
  console.log("observer 2", newValue)
});

observable.subscribe(function(newValue) {
  console.log("observer 3", newValue)
});

observable("b");
observable("c");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

There is no race condition to really worry about because your code will be run in a single thread, so it's pretty much guaranteed to be deterministic, unless you explicitly opt-into some sort of multi-threadedness.

An observer will usually also not inherently invoke multiple threads anyway, as the subsribers update functionality is generally going to take the form of something like:

```<code>for (subscriber of this.subscribers) {
  subscriber.update(this.value);
}
</code>```

With this said, you might run into problems but only if subscribers depend on a shared state and you cannot guarantee or know the order each subscription is added. In that case, you can get different results based on the order of the subscriptions. Simple demonstration:

var observable = ko.observable("a");

var sharedState = "";

observable.subscribe(function(newValue) {
  //append to the shared state
  sharedState += newValue;
  console.log("observer 1", sharedState);
});

observable.subscribe(function(newValue) {
  //double up the shared state
  sharedState += sharedState;
  console.log("observer 2", sharedState);
});

observable("b");
observable("c");
observable("d");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

var observable = ko.observable("a");

var sharedState = "";

observable.subscribe(function(newValue) {
  //double up the shared state
  sharedState += sharedState;
  console.log("observer 2", sharedState);
});

observable.subscribe(function(newValue) {
  //append to the shared state
  sharedState += newValue;
  console.log("observer 1", sharedState);
});

observable("b");
observable("c");
observable("d");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

So, this would be a bad practice. It would be best avoided if possible. Unless you can guarantee the order of subscriptions - in the example above, I add the subscriptions one after another which guarantees that they show up in the order they are added. But you might have code that adds subscriptions conditionally or in different parts of the application, in which case it's hard to keep that order under control.

Body:
I have inherited an application written using Knockout for the UI and I am curious as to what the effect is of having multiple subscriptions against a single observable property?

I have an observable that has 2 subscriptions. By logging to the console I can see that both subscriptions get fired, one after the other.

Using the following example: (this is very stripped down for brevity in the full code there is lots of logic, some of which is duplicated)

self.VisitDate = ko.observable();

self.VisitDate.subscribe(function (newValue) {
    self.ListItemRemoved(removed);
});

self.VisitDate.subscribe(function (newValue) {
    self.Basket.VisitDate(newValue);
});

I was thinking that I should see some sort of error, because of the multiple subscriptions, but everything appears to work fine but I cannot find any clear explanation of why this is OK to do?

I am just trying to find out the following:

Is it normal and acceptable to have multiple subscriptions to a single observable?
Is there any underlying impact on doing this i.e. race conditions maybe?
Is there ever really any need to have multiple subscriptions to achieve something that cannot be achieved in a single subscription?

I appreciate this may be a little shy in detail but I am really just trying to get an understanding of how knockout is doing things under the covers to see whether I should be looking to refactor this code or not.

Body:
The observer/observable design pattern does allow for multiple observers/subscriptions. The purpose of the design pattern in short is:

De-couple the change from the effects of the change.

Allow for any and arbitrary effects to stem from a change.

So, Knockout does that through its observables.

var observable = ko.observable("a");

observable.subscribe(function(newValue) {
  console.log("observer 1", newValue)
});

observable.subscribe(function(newValue) {
  console.log("observer 2", newValue)
});

observable.subscribe(function(newValue) {
  console.log("observer 3", newValue)
});

observable("b");
observable("c");

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

There is no race condition to really worry about because your code will be run in a single thread, so it's pretty much guaranteed to be deterministic, unless you explicitly opt-into some sort of multi-threadedness.

An observer will usually also not inherently invoke multiple threads anyway, as the subsribers update functionality is generally going to take the form of something like:

for (subscriber of this.subscribers) {
  subscriber.update(this.value);
}

With this said, you might run into problems but only if subscribers depend on a shared state and you cannot guarantee or know the order each subscription is added. In that case, you can get different results based on the order of the subscriptions. Simple demonstration:

var observable = ko.observable("a");

var sharedState = "";

observable.subscribe(function(newValue) {
  //append to the shared state
  sharedState += newValue;
  console.log("observer 1", sharedState);
});

observable.subscribe(function(newValue) {
  //double up the shared state
  sharedState += sharedState;
  console.log("observer 2", sharedState);
});

observable("b");
observable("c");
observable("d");

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

var observable = ko.observable("a");

var sharedState = "";

observable.subscribe(function(newValue) {
  //double up the shared state
  sharedState += sharedState;
  console.log("observer 2", sharedState);
});

observable.subscribe(function(newValue) {
  //append to the shared state
  sharedState += newValue;
  console.log("observer 1", sharedState);
});

observable("b");
observable("c");
observable("d");

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

So, this would be a bad practice. It would be best avoided if possible. Unless you can guarantee the order of subscriptions - in the example above, I add the subscriptions one after another which guarantees that they show up in the order they are added. But you might have code that adds subscriptions conditionally or in different parts of the application, in which case it's hard to keep that order under control.


问:
I need two consecutive lowercases for a password requirement
I am having problems checking 2 consecutives lower cases in a string.

I have tried this:

```<code>def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    for char in input:
        if re.search(checker, char):
            return True
        else:
            return False
</code>```

I expect the outputs to be :

"TesT" gives True

"TEST" gives False

"test" gives False

答:
You don't want to use a loop. Assuming 'input' is a string. then for char in input: is going to check each individual character against the compiled expression, which will fail, because your regular expression is 2 characters long.

```<code>def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    return bool(re.search(checker, input))
</code>```

Body:
I am having problems checking 2 consecutives lower cases in a string.

I have tried this:

def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    for char in input:
        if re.search(checker, char):
            return True
        else:
            return False

I expect the outputs to be :

"TesT" gives True

"TEST" gives False

"test" gives False

Body:
You don't want to use a loop. Assuming 'input' is a string. then for char in input: is going to check each individual character against the compiled expression, which will fail, because your regular expression is 2 characters long.

def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    return bool(re.search(checker, input))


问:
Java 7zip compression of a String
I would like to compress an String manually defined to 7z in Java. So then I could convert it to base64. I found many examples compressing files to 7z and then saving into new File.

I just try the next code, and it takes correctly the file and compress it:

```<code>private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException {
        String name = dir + File.separator + file.getName();
        if (file.isFile()){
            SevenZArchiveEntry entry = out.createArchiveEntry(file, name);
            out.putArchiveEntry(entry);

            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = in.read(b)) > 0) {
                out.write(b, 0, count);
            }
            out.closeArchiveEntry();

        } else if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null){
                for (File child : children){
                    addToArchiveCompression(out, child, name);
                }
            }
        } else {
            System.out.println(file.getName() + " is not supported");
        }
    }
</code>```

But how can I compress an manually defined String to 7z and convert it to byte[]? So then I can convert the byte[] to base64 and print it, without generating or reading new Files?

答:
Since you are already using commons-compress for 7zip compression you can create SevenZOutputFile(SeekableByteChannel) instance with SeekableInMemoryByteChannel that wraps a byte array. As per javadoc:

A SeekableByteChannel implementation that wraps a byte[].

When this channel is used for writing an internal buffer grows to accommodate incoming data. A natural size limit is the value of Integer.MAX_VALUE. Internal buffer can be accessed via array().

Something like:

```<code>SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel(new byte[1024]);
SevenZOutputFile out = new SevenZOutputFile(channel);
// modified addToArchiveCompression(out, ...); for String
// encode channel.array() to Base64
</code>```

Title: Java 7zip compression of a String

Body:
I would like to compress an String manually defined to 7z in Java. So then I could convert it to base64. I found many examples compressing files to 7z and then saving into new File.

I just try the next code, and it takes correctly the file and compress it:

private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException {
        String name = dir + File.separator + file.getName();
        if (file.isFile()){
            SevenZArchiveEntry entry = out.createArchiveEntry(file, name);
            out.putArchiveEntry(entry);

            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = in.read(b)) > 0) {
                out.write(b, 0, count);
            }
            out.closeArchiveEntry();

        } else if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null){
                for (File child : children){
                    addToArchiveCompression(out, child, name);
                }
            }
        } else {
            System.out.println(file.getName() + " is not supported");
        }
    }

But how can I compress an manually defined String to 7z and convert it to byte[]? So then I can convert the byte[] to base64 and print it, without generating or reading new Files?

Body:
Since you are already using commons-compress for 7zip compression you can create SevenZOutputFile(SeekableByteChannel) instance with SeekableInMemoryByteChannel that wraps a byte array. As per javadoc:

A SeekableByteChannel implementation that wraps a byte[].

When this channel is used for writing an internal buffer grows to accommodate incoming data. A natural size limit is the value of Integer.MAX_VALUE. Internal buffer can be accessed via array().

Something like:

SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel(new byte[1024]);
SevenZOutputFile out = new SevenZOutputFile(channel);
// modified addToArchiveCompression(out, ...); for String
// encode channel.array() to Base64


问:
CodeIgniter cannot use session data after redirect()
I was trying to build an application but I faced a problem with the session data. So I downloaded a new fresh CodeIgniter project and tried to work with the session but still failed. Here's what I did:

application/config/autoload.php:

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

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

<p><strong>application/config/config.php:</strong></p>

<pre class="lang-php prettyprint-override"><code>$config['sess_save_path'] = 'D:\Projects\CodeIgnter-fresh\application\cache\session';
</code>```

After that I created a controller called User.php

User.php

<?php

class User extends CI_Controller {

    public function index() {
        $this->session->set_userdata('somedata', 'somevalue');
        redirect('user/dashboard', 'refresh');
    }

    public function dashboard() {
        var_dump($this->session->userdata);
    }
}
```

The controller contains two simple methods. The index method sets some user data and after that redirects to the other method, which dumps the userdata. Unfortunately here's what I see:

It seems the only data I am able to see is some CodeIgniter data, but for sure the data I am trying to set is gone. Interesting thing I noticed was that in application/cache/session folder I can see some files with my data in it. So I guess it has to be some permission problem, but I cannot figure it out. Any suggestions?

I'm using:

OS: Windows 10 Education

PHP version: 7.2.11

CodeIgniter version: 3.1.10

答:
Set The Driver to 'files' in config:

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

Further Information here Codeigniter Session User Manual

Body:
I was trying to build an application but I faced a problem with the session data. So I downloaded a new fresh CodeIgniter project and tried to work with the session but still failed. Here's what I did:

application/config/autoload.php:

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

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

application/config/config.php:

$config['sess_save_path'] = 'D:\Projects\CodeIgnter-fresh\application\cache\session';

After that I created a controller called User.php

User.php

<?php

class User extends CI_Controller {

    public function index() {
        $this->session->set_userdata('somedata', 'somevalue');
        redirect('user/dashboard', 'refresh');
    }

    public function dashboard() {
        var_dump($this->session->userdata);
    }
}

The controller contains two simple methods. The index method sets some user data and after that redirects to the other method, which dumps the userdata. Unfortunately here's what I see:

It seems the only data I am able to see is some CodeIgniter data, but for sure the data I am trying to set is gone. Interesting thing I noticed was that in application/cache/session folder I can see some files with my data in it. So I guess it has to be some permission problem, but I cannot figure it out. Any suggestions?

I'm using:

OS: Windows 10 Education

PHP version: 7.2.11

CodeIgniter version: 3.1.10

Body:
Set The Driver to 'files' in config:

$config['sess_driver'] = 'files';

Further Information here Codeigniter Session User Manual


问:
Parsing HTML in Delphi to find the addresses of all images
How can I extract the addresses of all images in an HTML file using Delphi, for example by using an HTML parser?</p>

答: You can use the IHTMLDocument2 interface to parse the HTML, check this sample Retrieving all image links from an HTML document


问:
Use of dollar sign in data frames with missing end of the name
Maybe this is not the place to ask this. I recently run into a weird
error that took hours to debug. Finally I saw that one of the column names
was outputing a wrong value. The issue can be simplified to this simple example.

dframe1 = data.frame(
  hello_a = "a",
  hello_b = "b"
)

dframe1$hello
#> NULL

dframe2 = data.frame(
  hello_a = "a",
  bye_b = "b"
)

dframe2$hello
#> [1] a
#> Levels: a
dframe2$bye
#> [1] b
#> Levels: b
dframe2[,"bye"]
#> Error in `[.data.frame`(dframe2, , "bye"): undefined columns selected
dframe2[,"bye_b"]
#> [1] b
#> Levels: b
```

Created on 2019-05-29 by the reprex package (v0.2.0).

This is weird to me, is there a way to enforce a "strict" mode for R so this does not happen? I understand data frames are some sort of lists in R but is there some documentation on the use of $?

答:
I found the docs regarding this issue,

x$name is equivalent to x[["name", exact = FALSE]]

So if we do

```<code>dframe2[["bye",exact = FALSE]]
[1] b
Levels: b
</code>```

we get the expected behavior. I still don't know if we can change that behavior without using [[ which needs string.

EDIT

As Ben Bolker suggests in the comments, this is more or less what I wanted to do.

options(warnPartialMatchDollar=TRUE)
options(warn=2)

dframe2 = data.frame(
  hello_a = "a",
  bye_b = "b"
)

dframe2$hello
#> Warning in `$.data.frame`(dframe2, hello): Partial match of 'hello' to
#> 'hello_a' in data frame
#> [1] a
#> Levels: a
```

Created on 2019-05-29 by the reprex package (v0.2.0).

Body:
Maybe this is not the place to ask this. I recently run into a weird
error that took hours to debug. Finally I saw that one of the column names
was outputing a wrong value. The issue can be simplified to this simple example.

dframe1 = data.frame(
  hello_a = "a",
  hello_b = "b"
)

dframe1$hello
#> NULL

dframe2 = data.frame(
  hello_a = "a",
  bye_b = "b"
)

dframe2$hello
#> [1] a
#> Levels: a
dframe2$bye
#> [1] b
#> Levels: b
dframe2[,"bye"]
#> Error in `[.data.frame`(dframe2, , "bye"): undefined columns selected
dframe2[,"bye_b"]
#> [1] b
#> Levels: b

Created on 2019-05-29 by the reprex package (v0.2.0).

This is weird to me, is there a way to enforce a "strict" mode for R so this does not happen? I understand data frames are some sort of lists in R but is there some documentation on the use of $?

Body:
I found the docs regarding this issue,

x$name is equivalent to x[["name", exact = FALSE]]

So if we do

dframe2[["bye",exact = FALSE]]
[1] b
Levels: b

we get the expected behavior. I still don't know if we can change that behavior without using [[ which needs string.

EDIT

As Ben Bolker suggests in the comments, this is more or less what I wanted to do.

options(warnPartialMatchDollar=TRUE)
options(warn=2)

dframe2 = data.frame(
  hello_a = "a",
  bye_b = "b"
)

dframe2$hello
#> Warning in `$.data.frame`(dframe2, hello): Partial match of 'hello' to
#> 'hello_a' in data frame
#> [1] a
#> Levels: a

Created on 2019-05-29 by the reprex package (v0.2.0).


问:
File upload endpoint need to close InputStream?
```<code>@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
    ...
    inputStream.close(); // necessary?
}
</code>```

For an API endpoint that accepts a file input, do we need to manually close the InputStream or does the framework do it for us?

I have checked the Jersey docs but could not find any information about it.

Looking for credible source or some way to validate it.

答:
I just wondered the same thing and tried it out in the debugger. Jersey does not close the stream for you.

I think the most elegant way is to use try-with-resources, which can take arbitrary expressions since Java 9 and calls close() for you.

```<code>@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
...
try (inputStream) {
   //...
} catch (IOException e) {
   //...
}
</code>```

Body:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
    ...
    inputStream.close(); // necessary?
}

For an API endpoint that accepts a file input, do we need to manually close the InputStream or does the framework do it for us?

I have checked the Jersey docs but could not find any information about it.

Looking for credible source or some way to validate it.

Body:
I just wondered the same thing and tried it out in the debugger. Jersey does not close the stream for you.

I think the most elegant way is to use try-with-resources, which can take arbitrary expressions since Java 9 and calls close() for you.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
...
try (inputStream) {
   //...
} catch (IOException e) {
   //...
}


问:
Does ADF Application Module support H2 or any other in memory database
Does ADF Application Module support H2 or any other in memory database?
i am getting java.lang.ClassCastException: org.h2.jdbc.JdbcConnection cannot be cast to oracle.jdbc.OracleConnection while creating the Application Module for testing</p>

答:
You have to follow below steps to use H2 database properly in your ADF application.

Create H2 db connection in your application

Run your integrated weblogic server

Create data source with same name as you have created connection in first step

Create AM, EO, VO and page of your add application

This way you will not get class cast exception.

Regards,
Bhavesh