问:
Chrome app content security policy not leting to run eval() even after made changes in manifest.json
I'm developing a Chrome App with Google Blockly. In order to run JavaScript code dynamically I want to use eval() function.

Chrome app relaxing the default policy using manifest

I tried the above link. I used this manifest as suggested by chrome docs.

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "Blockly",
  "version": "1.0.0",
  "icons": {
    "128": "icon_128.png"
  },
  "permissions": [],
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "minimum_chrome_version": "46",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
</code>```

inject.js

```<code>window.addEventListener("load", function() {
 document.getElementById("myBtn").addEventListener("click", function() {
  let code = 'initiate();';
  try {
    eval(code);
   } catch (e) {
     console.log(e);
  }
 });
});
</code>```

I am still getting this error :

EvalError: Refused to evaluate a string as JavaScript because
'unsafe-eval' is not an allowed source of script in the following
Content Security Policy directive: "script-src 'self' blob:
filesystem: 'wasm-eval'".

at HTMLButtonElement. (inject.js:40)

答:
I found answer

Content Security Policy in Chrome App

Chrome extensions will let you relax the default Content Security Policy; Chrome Apps won’t.

Body:
I'm developing a Chrome App with Google Blockly. In order to run JavaScript code dynamically I want to use eval() function.

Chrome app relaxing the default policy using manifest

I tried the above link. I used this manifest as suggested by chrome docs.

manifest.json

{
  "manifest_version": 2,
  "name": "Blockly",
  "version": "1.0.0",
  "icons": {
    "128": "icon_128.png"
  },
  "permissions": [],
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "minimum_chrome_version": "46",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

inject.js

window.addEventListener("load", function() {
 document.getElementById("myBtn").addEventListener("click", function() {
  let code = 'initiate();';
  try {
    eval(code);
   } catch (e) {
     console.log(e);
  }
 });
});

I am still getting this error :

EvalError: Refused to evaluate a string as JavaScript because
'unsafe-eval' is not an allowed source of script in the following
Content Security Policy directive: "script-src 'self' blob:
filesystem: 'wasm-eval'".

at HTMLButtonElement. (inject.js:40)


来源: stackexchange

问:
The intended purpose of MvvmCross CreateBindingSet
So I recently came across an interesting scenario from one of my teammates.

They are currently working in a Xamarin project and leveraging MvvmCross. They have decided that they would like to use CreateBindingSet exclusively over bindings directly in xaml.

To me this seems like an anti-pattern for Mvvm. It's tightly coupling the behind code to the view model and it adds extra complexity to a platform that is designed to be bound in xaml.

I'm trying to understand if using this function in behind code is a good idea or not but I can't make heads or tails of it from the documentation.

Can someone tell me what the intended use case is for CreateBindingSet?

答:
In addition to providing text-format binding statement which can be easily included in xml layout files, MvvmCross also provides a C# based syntax to enable bindings to be easily constructed using code.

This binding syntax is referred to as Fluent bindings.

For example

MvvmCross creates the relationship between the View and the ViewModel by the following  code:

```<code>var set = this.CreateBindingSet<MyView, MyViewModel>();
</code>```

Then you can set the data-binding by For and To methods:

```<code>set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName);
</code>```

With the fluent syntax we can continue to specify the binding type, such as OneWay, and TwoWay, etc, like this:

```<code>set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName).TwoWay();
</code>```

Fluent binding is especially useful in the iOS and OSX platforms where the Xml layout formats are not easily human-editable(in iOS and MACOS platform there is no such a xml file so we need to set binding in code behind).

For more details you could check https://www.mvvmcross.com/documentation/fundamentals/data-binding.

ContentLicense: CC BY-SA 4.0

Body:
In addition to providing text-format binding statement which can be easily included in xml layout files, MvvmCross also provides a C# based syntax to enable bindings to be easily constructed using code.

This binding syntax is referred to as Fluent bindings.

For example

MvvmCross creates the relationship between the View and the ViewModel by the following  code:

var set = this.CreateBindingSet<MyView, MyViewModel>();

Then you can set the data-binding by For and To methods:

set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName);

With the fluent syntax we can continue to specify the binding type, such as OneWay, and TwoWay, etc, like this:

set.Bind(LabelUserName).For(x => x.Text).To(vm => vm.UserName).TwoWay();

Fluent binding is especially useful in the iOS and OSX platforms where the Xml layout formats are not easily human-editable(in iOS and MACOS platform there is no such a xml file so we need to set binding in code behind).

For more details you could check https://www.mvvmcross.com/documentation/fundamentals/data-binding.


问:
C# How can I communicate between winfirms app and unity android app?
I'm working on a project for my friend and I need to implement communication between windows forms app and unity android app but I don't know how. Example of my code:

Unity:

```<code>Class program
{

   Public InputField password;

   Public static void Loggin ()
   {

      String localpass = password.text;

      String winpass = //passS from WinForm code

      If (localpass == winpass)
         Mytextbox.text = "success";
      Else
         Mytextbox.text = "wrong password";

   }

}
</code>```

WinForm:

```<code>Public static void myVoid ()
{

   String passS = File.ReadLines(App domain.CurrentDomain.BaseDirectory + @"\\mytextfile.txt").ElementAtOrDefault(3);

}
</code>```

答:
There are many ways to do this. If you are only communicating locally. Try socket programming, Use TCP/IP for communication between the two programs.

Try this link for a start

Or if you want to connect over a network try WCF can also work out

Try this link for a WCF fresh start (this is Slower)

or you can use SignalR web sockets

Try this link for ASP NET CORE SignalR

Another way is to use RabbitMQ

Try this link for RabbitMQ documentation

And there many more ways.

Body:
I'm working on a project for my friend and I need to implement communication between windows forms app and unity android app but I don't know how. Example of my code:

Unity:

Class program
{

   Public InputField password;

   Public static void Loggin ()
   {

      String localpass = password.text;

      String winpass = //passS from WinForm code

      If (localpass == winpass)
         Mytextbox.text = "success";
      Else
         Mytextbox.text = "wrong password";

   }

}

WinForm:

Public static void myVoid ()
{

   String passS = File.ReadLines(App domain.CurrentDomain.BaseDirectory + @"\\mytextfile.txt").ElementAtOrDefault(3);

}


问:
notify user if he dont have flash player in android phone apps is build using phone gap
i have build my android apps using phone gap in this i wanted to add one more feature when my apps gets install it also check for flash player if flash player is not there ask to install through showing link how can i do this ??

i am new for phone gap

Please help me if possible share code with me

答:
Detect if Flash is installed on Android and embed a Flash video in an Activity

from above: It will throw an exception of such a package doesn't exist.

```<code>boolean flashInstalled = false;
try {
  PackageManager pm = getPackageManager();
  ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0);
  if (ai != null)
    flashInstalled = true;
} catch (NameNotFoundException e) {
  flashInstalled = false;
}
</code>```

as for installing it you could just provide a link to flash on the marketplace.

ContentLicense: CC BY-SA 3.0

Body:
Detect if Flash is installed on Android and embed a Flash video in an Activity

from above: It will throw an exception of such a package doesn't exist.

boolean flashInstalled = false;
try {
  PackageManager pm = getPackageManager();
  ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0);
  if (ai != null)
    flashInstalled = true;
} catch (NameNotFoundException e) {
  flashInstalled = false;
}

as for installing it you could just provide a link to flash on the marketplace.


问:
How to insert big data on the laravel?
I am using laravel 5.6

My script to insert big data is like this :

```<code>...
$insert_data = [];
foreach ($json['value'] as $value) {
    $posting_date = Carbon::parse($value['Posting_Date']);
    $posting_date = $posting_date->format('Y-m-d');
    $data = [
        'item_no'                   => $value['Item_No'],
        'entry_no'                  => $value['Entry_No'],
        'document_no'               => $value['Document_No'],
        'posting_date'              => $posting_date,
        ....
    ];
    $insert_data[] = $data;
}
\DB::table('items_details')->insert($insert_data);
</code>```

I have tried to insert 100 record with the script, it works. It successfully insert data

But if I try to insert 50000 record with the script, it becomes very slow. I've waited about 10 minutes and it did not work. There exist error like this :

```<code>504 Gateway Time-out
</code>```

How can I solve this problem?

答:
Here is very good and very Fast Insert data solution</p>

```<code>$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
    $test_data[$i]['number'] = "1234567890";
    $test_data[$i]['message'] = "Test Data";
    $test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
   foreach ($chunk_data as $chunk_data_val) {
    DB::table('messages')->insert($chunk_data_val);
  }
}
</code>```

Title: How to insert big data on the laravel?

Body:
I am using laravel 5.6

My script to insert big data is like this :

...
$insert_data = [];
foreach ($json['value'] as $value) {
    $posting_date = Carbon::parse($value['Posting_Date']);
    $posting_date = $posting_date->format('Y-m-d');
    $data = [
        'item_no'                   => $value['Item_No'],
        'entry_no'                  => $value['Entry_No'],
        'document_no'               => $value['Document_No'],
        'posting_date'              => $posting_date,
        ....
    ];
    $insert_data[] = $data;
}
\DB::table('items_details')->insert($insert_data);

I have tried to insert 100 record with the script, it works. It successfully insert data

But if I try to insert 50000 record with the script, it becomes very slow. I've waited about 10 minutes and it did not work. There exist error like this :

504 Gateway Time-out

How can I solve this problem?

Body:
Here is very good and very Fast Insert data solution

$no_of_data = 1000000;
$test_data = array();
for ($i = 0; $i < $no_of_data; $i++){
    $test_data[$i]['number'] = "1234567890";
    $test_data[$i]['message'] = "Test Data";
    $test_data[$i]['status'] = "Delivered";
}
$chunk_data = array_chunk($test_data, 1000);
if (isset($chunk_data) && !empty($chunk_data)) {
   foreach ($chunk_data as $chunk_data_val) {
    DB::table('messages')->insert($chunk_data_val);
  }
}


问:
I need to get text from 2 different span tags with BeautifulSoup
I am trying to get these values from the following code, the text in span under Developer and Genres

```<code><div _ngcontent-sc18="" class="col-xl-6">
  <!-- -->
  <p _ngcontent-sc18="" class="mb-2">
    <strong _ngcontent-sc18="">
     Developer:
    </strong>
  <!-- -->
  <span _ngcontent-sc18="">
     Capy Games
  </span>
  </p>
  <!-- -->
  <!-- -->
  <p _ngcontent-sc18="" class="mb-2">
    <strong _ngcontent-sc18="">
     Genres:
    </strong>
    <!-- -->
    <span _ngcontent-sc18="">
     Action,
    </span>
    <span _ngcontent-sc18="">
     Platformer
    </span>
  </p>
</div>
</code>```

I'm able to pull the values fine if there is only one Genre, but if there are two, I can only figure out how to pull the first one. This is what I have so far

```<code>for y in gamesoup.find_all('p', class_= 'mb-2'):
    if y.strong.text == "Developer: ":
        devs.append(y.span.text)
    if "Genre" in y.strong.text:
        genres.append(y.span.text)
</code>```

What can I do to pull both of the values under Genre?

Thank you!

答:
Use find_all('span') inside if statement of Genre.

```<code>for y in gamesoup.find_all('p', class_= 'mb-2'):
    if y.strong.text == "Developer: ":
        devs.append(y.span.text)
    if "Genre" in y.strong.text:
        for genre in y.find_all('span'):
            genres.append(genre.text)
</code>```

Body:
I am trying to get these values from the following code, the text in span under Developer and Genres

     Developer:

     Capy Games

     Genres:

     Action,

     Platformer

I'm able to pull the values fine if there is only one Genre, but if there are two, I can only figure out how to pull the first one. This is what I have so far

for y in gamesoup.find_all('p', class_= 'mb-2'):
    if y.strong.text == "Developer: ":
        devs.append(y.span.text)
    if "Genre" in y.strong.text:
        genres.append(y.span.text)

What can I do to pull both of the values under Genre?

Thank you!

Body:
Use find_all('span') inside if statement of Genre.

for y in gamesoup.find_all('p', class_= 'mb-2'):
    if y.strong.text == "Developer: ":
        devs.append(y.span.text)
    if "Genre" in y.strong.text:
        for genre in y.find_all('span'):
            genres.append(genre.text)


问:
insert content of a file while changing values inside
```<code>$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}
</code>```

abc.php

```<code><div class='title'><?php echo $title; ?></div>
</code>```

So I need to insert abc.php while changing variables inside.

In the above (simplified) example I'm expecting lorem ipsum as the result, but I'm getting empty div .title

答:
```<code><?php
$template = "<div class='title'>%s</div>";

echo sprintf($template, 'this is title1');
echo sprintf($template, 'this is title2');
</code>```

Or more readable HTML template, using preg_replace:

PHP code:

```<code>$body = file_get_contents('template.html');
$patterns = array(
  '/{title}/'
);
$replacements = array(
  'this is title',
);
$body = preg_replace($patterns, $replacements, $body);
</code>```

template.html:

```<code><div class='title'>{title}</div>
</code>```

Body:
$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}

abc.php

<?php echo $title; ?>

So I need to insert abc.php while changing variables inside.

In the above (simplified) example I'm expecting lorem ipsum as the result, but I'm getting empty div .title

Body:
<?php
$template = "<div class='title'>%s</div>";

echo sprintf($template, 'this is title1');
echo sprintf($template, 'this is title2');

Or more readable HTML template, using preg_replace:

PHP code:

$body = file_get_contents('template.html');
$patterns = array(
  '/{title}/'
);
$replacements = array(
  'this is title',
);
$body = preg_replace($patterns, $replacements, $body);

template.html:

<div class='title'>{title}</div>


问:
Querying a list based on a string input
I'm trying to accomplish what I feel like should be a straightforward task, but have found it much more complicated than I expected.

Essentially, given:

```<code>public class MyObject
{
    public int A;
    public float B;
    public string C;
}

List<MyObject> objectList;
</code>```

I would like to be able to read in strings something like:

```<code>"A < 1"
"B > 0.5"
"C = \"text\""
</code>```

and for each of those get a List of items in objectList satisfying the requirement.

I've been working with LINQ queries like:

```<code>objectList.Where(obj => obj.A < 1)
</code>```

so far, but am unable to figure out how to create queries like that with the field name.

Is there something straightforward that I am missing? Or is my whole approach here flawed?

答:
I thinks you can use Expression tree, which you may be create own lambda expression and pass the it Where function.

For example please check these link:

Dynamically generate LINQ queries

Or you can use System.Linq.Dynamic namespace.:

https://docs.telerik.com/data-access/developers-guide/linq-support/data-access-feature-ref-linq-support-dynamic-linq

Title: Querying a list based on a string input

Body:
I'm trying to accomplish what I feel like should be a straightforward task, but have found it much more complicated than I expected.

Essentially, given:

public class MyObject
{
    public int A;
    public float B;
    public string C;
}

List<MyObject> objectList;

I would like to be able to read in strings something like:

"A < 1"
"B > 0.5"
"C = \"text\""

and for each of those get a List of items in objectList satisfying the requirement.

I've been working with LINQ queries like:

objectList.Where(obj => obj.A < 1)

so far, but am unable to figure out how to create queries like that with the field name.

Is there something straightforward that I am missing? Or is my whole approach here flawed?


问:
Trying to get property of non-object from blade view in laravel
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

```<code>  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}
</code>```

My controller

```<code>public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}
</code>```

my blade table that i want to display

```<code>    <tbody>
             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

              <tr>

       <td>{{ $user->ID }}</td>
       <td>{{ $user->NICK_NAME }}</td>
       <td>{{ $user->PWD_INVALID_HIT }}</td>

        </tr>
@endforeach
</code>```

dd($user)

```<code>array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]
</code>```

How do i display data in table

答:
I think it's cause you have a collection in your $user variable. You need to loop over that $user var like this:

```<code><tbody>
@foreach($paginationRecord as $i=>$user)
   @php
     $currentRecordno = 1;
   @endphp
   @foreach($user as $i => $u)
   <tr>
       <td>{{ $u['ID'] }}</td>
       <td>{{ $u['NICK_NAME'] }}</td>
       <td>{{ $u['PWD_INVALID_HIT'] }}</td>
   </tr>
   @endforeach
@endforeach
</code>```

Also, do you need this:

```<code>@php
   $currentRecordno = 1;
@endphp
</code>```

The $i in your foreach loop should represent the index or $currentRecordno. But if you have good reason, then stick with it.

Body:
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

My controller

public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}

my blade table that i want to display

             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

       {{ $user->ID }}
       {{ $user->NICK_NAME }}
       {{ $user->PWD_INVALID_HIT }}

@endforeach

dd($user)

array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]

How do i display data in table

Body:
I think it's cause you have a collection in your $user variable. You need to loop over that $user var like this:

<tbody>
@foreach($paginationRecord as $i=>$user)
   @php
     $currentRecordno = 1;
   @endphp
   @foreach($user as $i => $u)
   <tr>
       <td>{{ $u['ID'] }}</td>
       <td>{{ $u['NICK_NAME'] }}</td>
       <td>{{ $u['PWD_INVALID_HIT'] }}</td>
   </tr>
   @endforeach
@endforeach

Also, do you need this:

@php
   $currentRecordno = 1;
@endphp

The $i in your foreach loop should represent the index or $currentRecordno. But if you have good reason, then stick with it.


问:
Remove focus of system window
I would like to print the document currently displayed in the control.
I use WebBrowser and Print() function to that.
But after using Print() function there is a system window which pops up and gets focus of my application.
In addition I can not go back to the form unless I close the system window.

Is there any chance to let me remove the focus of this system pop-up window?

答:
There is a ShowActivated property on Window object so you can set the main window not activated after you show a child window.

From MSDN:

When a window with its ShowActivated property set to false is opened, the window is not activated and its Activated event is not raised until a user manually activates the window by selecting it.

Title: Remove focus of system window


问:
Task :react-native-screens:compileDebugJavaWithJavac FAILED
Im using react navigation v5.. installed all the dependencies.. now Im getting above error..
FAILURE: Build failed with an exception.</p>

```<code>* What went wrong:
Execution failed for task ':react-native-screens:compileDebugJavaWithJavac'.
> java.lang.reflect.UndeclaredThrowableException

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings
</code>```

答:
I think this issue is still open on GitHub issues -> View

If your React Native Version < 0.60 then you can use Jetifier to solve this issue

How to use Jetifier to solve ?

yarn add --dev jetify

Then in your package.json scripts add:

"postinstall": "jetify"

yarn jetify

If your React Native Version 0.60 > then try this

```<code>cd android && ./gradlew clean
</code>```

Body:
Im using react navigation v5.. installed all the dependencies.. now Im getting above error..
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-screens:compileDebugJavaWithJavac'.
> java.lang.reflect.UndeclaredThrowableException

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

Body:
I think this issue is still open on GitHub issues -> View

If your React Native Version < 0.60 then you can use Jetifier to solve this issue

How to use Jetifier to solve ?

yarn add --dev jetify

Then in your package.json scripts add:

"postinstall": "jetify"

yarn jetify

If your React Native Version 0.60 > then try this

cd android && ./gradlew clean


问:
Change style depending on RouterURL in Angular 8
I have one component named 'NavigatorComponent'. There I have my 'routerLink'. All the urls are attached to different components. Now the scenario is I have to change the link color depending on url it is currently. I am new to Angular and so I have no idea how to do it. Any help will be greatly appreciated. Below is the code snippet for Navigator.html and app-routing.module.ts file.

```<code><ul>
   <li><a class="active" [routerLink] = "'/welcome-information'">Welcome Information</a></li>
   <li><a class="disable" [routerLink] = "'/your-plan'">Select Your Plan</a></li>
   <li><a class="disable" [routerLink] = "'/your-data'">Confirm Your Data</a></li>
   <li><a class="disable" [routerLink] = "'/bank-draft'">Bank Draft</a></li>
   <li><a class="disable" [routerLink] = "'/your-choice'">Finalize Your Choice</a></li>
</ul>

const routes: Routes = [
  {path: 'welcome-information' , component: WelcomeInformationComponent},
  {path: 'your-plan' , component: YourPlanComponent},
  {path: 'your-data' , component: YourDataComponent},
  {path: 'bank-draft' , component: BankDraftComponent},
  {path: 'your-choice' , component: YourChoiceComponent},
];
</code>```

答:
You can use RouterLinkActive to add CSS class to your active link, Exp :

```<code><li><a [routerLinkActive]="['class1', 'class2'] [routerLink] = "'/your-plan'">Select Your Plan</a></li>
</code>```

Or

```<code><li><a routerLinkActive="class1 class2" [routerLink] = "'/your-plan'">Select Your Plan</a></li>
</code>```

Body:
I have one component named 'NavigatorComponent'. There I have my 'routerLink'. All the urls are attached to different components. Now the scenario is I have to change the link color depending on url it is currently. I am new to Angular and so I have no idea how to do it. Any help will be greatly appreciated. Below is the code snippet for Navigator.html and app-routing.module.ts file.

Welcome Information

Select Your Plan

Confirm Your Data

Bank Draft

Finalize Your Choice

const routes: Routes = [
  {path: 'welcome-information' , component: WelcomeInformationComponent},
  {path: 'your-plan' , component: YourPlanComponent},
  {path: 'your-data' , component: YourDataComponent},
  {path: 'bank-draft' , component: BankDraftComponent},
  {path: 'your-choice' , component: YourChoiceComponent},
];

Body:
You can use RouterLinkActive to add CSS class to your active link, Exp :

<li><a [routerLinkActive]="['class1', 'class2'] [routerLink] = "'/your-plan'">Select Your Plan</a></li>

Or

<li><a routerLinkActive="class1 class2" [routerLink] = "'/your-plan'">Select Your Plan</a></li>


问:
ORA-31061: XDB error: special char to escaped char conversion failed
I'm completely new to Oracle's XDB, trying to breakfix a code in production environment which i am completely new to.

```<code>SELECT  DBMS_LOB.SubStr(RTRIM (XMLAGG (XMLELEMENT (E,XMLATTRIBUTES (ntx.nttx_str || '|' AS "Seg")) ORDER BY ntx.ref_id, ntx.ntnb_input_dtm desc)
                                   .EXTRACT ('./E[not(@Seg = preceding-sibling::E/@Seg)]/@Seg').GetClobVal(),','),1000,1)
    FROM
       (SELECT umum.ref_id,
               ntnb.ntnb_input_dtm,
               DBMS_LOB.SubStr(RTRIM (XMLAGG (XMLELEMENT (E,XMLATTRIBUTES (nttx.nttx_text || '' AS "Seg")) ORDER BY nttx.nttx_seq_no asc)
                                   .EXTRACT ('./E[not(@Seg = preceding-sibling::E/@Seg)]/@Seg').GetClobVal(),','),500,1) AS nttx_str
        FROM umum_util_mgt umum,
             ntnb_note_base ntnb,
             nttx_note_text nttx
        WHERE ntnb.ntnb_id = umum.ntnb_id
          AND ntnb.ntnb_id = nttx.ntnb_id
          AND ntnb.ntnb_input_dtm = nttx.ntnb_input_dtm
          GROUP BY umum.ref_id, ntnb.ntnb_input_dtm
        ) ntx,
        php_mdx_auth_ext_tbl paex
        WHERE ntx.ref_id = paex.ref_id*
</code>```

When i try to execute the above query, Oracle is returning the below error

ORA-31061: XDB error: special char to escaped char conversion failed.

This used to work in older version of Oracle, after moving to oracle 12c we are facing this issue.

答:
This error generally occurs when there is a control character (Bad data) present in the XML data.

I am able to reproduce the error with bad XML data but yes, error code is different, I am not sure why.

```<code>SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT xmlelement("a", test) AS TEST
  7    FROM DATAA;
ERROR:
ORA-64451: Conversion of special character to escaped character failed.
</code>```

To resolve this error,

You need to find out the records with bad XML data and correct those data. You can use REGEXP_LIKE as following to find the bad XML data and correct those data:

```<code>SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT *
  7  FROM DATAA
  8  WHERE REGEXP_LIKE ( TEST, '[[:cntrl:]]' );

TEST
-------
SObad

SQL>
</code>```

-- OR --

You can use REGEXP_REPLACE to skip the control characters preent in the XML data from processing as follows:

```<code>SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT xmlelement("a", REGEXP_REPLACE(TEST, '[[:cntrl:]]', '')) AS TEST
  7    FROM DATAA;

TEST
--------------------------------------------------------------------------------
<a>SObad</a>
<a>SO«good</a>

SQL>
</code>```

Cheers!!

Body:
I'm completely new to Oracle's XDB, trying to breakfix a code in production environment which i am completely new to.

SELECT  DBMS_LOB.SubStr(RTRIM (XMLAGG (XMLELEMENT (E,XMLATTRIBUTES (ntx.nttx_str || '|' AS "Seg")) ORDER BY ntx.ref_id, ntx.ntnb_input_dtm desc)
                                   .EXTRACT ('./E[not(@Seg = preceding-sibling::E/@Seg)]/@Seg').GetClobVal(),','),1000,1)
    FROM
       (SELECT umum.ref_id,
               ntnb.ntnb_input_dtm,
               DBMS_LOB.SubStr(RTRIM (XMLAGG (XMLELEMENT (E,XMLATTRIBUTES (nttx.nttx_text || '' AS "Seg")) ORDER BY nttx.nttx_seq_no asc)
                                   .EXTRACT ('./E[not(@Seg = preceding-sibling::E/@Seg)]/@Seg').GetClobVal(),','),500,1) AS nttx_str
        FROM umum_util_mgt umum,
             ntnb_note_base ntnb,
             nttx_note_text nttx
        WHERE ntnb.ntnb_id = umum.ntnb_id
          AND ntnb.ntnb_id = nttx.ntnb_id
          AND ntnb.ntnb_input_dtm = nttx.ntnb_input_dtm
          GROUP BY umum.ref_id, ntnb.ntnb_input_dtm
        ) ntx,
        php_mdx_auth_ext_tbl paex
        WHERE ntx.ref_id = paex.ref_id*

When i try to execute the above query, Oracle is returning the below error

ORA-31061: XDB error: special char to escaped char conversion failed.

This used to work in older version of Oracle, after moving to oracle 12c we are facing this issue.

Body:
This error generally occurs when there is a control character (Bad data) present in the XML data.

I am able to reproduce the error with bad XML data but yes, error code is different, I am not sure why.

SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT xmlelement("a", test) AS TEST
  7    FROM DATAA;
ERROR:
ORA-64451: Conversion of special character to escaped character failed.

To resolve this error,

You need to find out the records with bad XML data and correct those data. You can use REGEXP_LIKE as following to find the bad XML data and correct those data:

SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT *
  7  FROM DATAA
  8  WHERE REGEXP_LIKE ( TEST, '[[:cntrl:]]' );

TEST
-------
SObad

SQL>

-- OR --

You can use REGEXP_REPLACE to skip the control characters preent in the XML data from processing as follows:

SQL> WITH DATAA AS (
  2      SELECT UNISTR('SO\0013bad') TEST FROM DUAL
  3      UNION ALL
  4      SELECT UNISTR('SO\00aegood') TEST FROM DUAL
  5  )
  6  SELECT xmlelement("a", REGEXP_REPLACE(TEST, '[[:cntrl:]]', '')) AS TEST
  7    FROM DATAA;

TEST
--------------------------------------------------------------------------------
<a>SObad</a>
<a>SO«good</a>

SQL>

Cheers!!


问:
WPF Reset Focus on Button Click
I have a TextBox and a ToolBar with a Button.  If I'm typing in the TextBox and I click the Button I want the TextBox to lose Focus so the binding gets updated. I don't want to add a UpdateSourceTrigger=PropertyChanged to my TextBox. But instead when I click on the Button I reset Focus to the main window so what ever I'm on loses Focus and updates the bindings.

I've tried adding a OnClick to the button with the following, but it doesn't seem to work:

```<code>    private void Button_Click(object sender, RoutedEventArgs e) {
        FocusManager.SetFocusedElement(this, null);
    }
</code>```

Any tips would be appreciated.

Thanks,
Raul

答:
I encountered a similar issue. I need to unfocus a textbox when enter is pressed. I end up with this code:

```<code>var scope = FocusManager.GetFocusScope(elem); // elem is the UIElement to unfocus
FocusManager.SetFocusedElement(scope, null); // remove logical focus
Keyboard.ClearFocus(); // remove keyboard focus
</code>```

I think it is cleaner than creating dummy controls and it is reusable. I'm not confident with this solution though. But it seems work well.

Title: WPF Reset Focus on Button Click

Body:
I have a TextBox and a ToolBar with a Button.  If I'm typing in the TextBox and I click the Button I want the TextBox to lose Focus so the binding gets updated. I don't want to add a UpdateSourceTrigger=PropertyChanged to my TextBox. But instead when I click on the Button I reset Focus to the main window so what ever I'm on loses Focus and updates the bindings.

I've tried adding a OnClick to the button with the following, but it doesn't seem to work:

    private void Button_Click(object sender, RoutedEventArgs e) {
        FocusManager.SetFocusedElement(this, null);
    }

Any tips would be appreciated.

Thanks,
Raul

Body:
I encountered a similar issue. I need to unfocus a textbox when enter is pressed. I end up with this code:

var scope = FocusManager.GetFocusScope(elem); // elem is the UIElement to unfocus
FocusManager.SetFocusedElement(scope, null); // remove logical focus
Keyboard.ClearFocus(); // remove keyboard focus

I think it is cleaner than creating dummy controls and it is reusable. I'm not confident with this solution though. But it seems work well.


问:
Number of bytes used for Unicode characters in varchar

A common misconception is to think that CHAR(n) and VARCHAR(n), the n defines the number of characters. But in CHAR(n) and VARCHAR(n) the n defines the string length in bytes (0-8,000). n never defines numbers of characters that can be stored

According to this statement from Microsoft, I assume, n is the data length of a string and when we store unicode characters in varchar, a single character should take 2 bytes. But, when I try with a sample as below, I see varchar data taking 1 byte instead of 2 bytes.

```<code>declare @varchar varchar(6), @nvarchar nvarchar(6)

set @varchar = 'Ø'

select @varchar as VarcharString, len(@varchar) as VarcharStringLength, DATALENGTH(@varchar) as VarcharStringDataLength

</code>```

Could someone explain the reason behind it?

答:
I thought the original quote was a bit confusion, as it continues

The misconception happens because when using single-byte encoding, the
  storage size of CHAR and VARCHAR is n bytes and the number of
  characters is also n.

but since it mentions encodings, my guess is that the statement refers to the  UTF encodings supported in SQL Server 2019 and higher which seem to allow (I haven't tried yet) to store Unicode in VARCHAR columns.

Body:
A common misconception is to think that CHAR(n) and VARCHAR(n), the n defines the number of characters. But in CHAR(n) and VARCHAR(n) the n defines the string length in bytes (0-8,000). n never defines numbers of characters that can be stored

According to this statement from Microsoft, I assume, n is the data length of a string and when we store unicode characters in varchar, a single character should take 2 bytes. But, when I try with a sample as below, I see varchar data taking 1 byte instead of 2 bytes.

declare @varchar varchar(6), @nvarchar nvarchar(6)

set @varchar = 'Ø'

select @varchar as VarcharString, len(@varchar) as VarcharStringLength, DATALENGTH(@varchar) as VarcharStringDataLength

Could someone explain the reason behind it?


问:
Laravel and MySQL understanding Index and composite/compound index
In Laravel (v 6.8) I have created below migration for the users table.

User Migration

```<code>public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('username')->unique()->index();
        $table->string('email')->unique()->index();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password')->nullable();
        $table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
        $table->boolean('is_root')->default(FALSE);
        $table->rememberToken();
        $table->timestamps();

        $table->unique(['username', 'email'], 'user_unique_credentials');
        $table->index(['username', 'email'], 'user_index_columns');
    });
}
</code>```

Explaination

I know basics of index and how it works but I a having not so clear understanding about index on individual column and composite/compound index.

The App may have query by only username or email or I may have a query for both tables together. Therefore as you can see in my migration code, I have set index for each column as well as both columns using $this->index() that creates a compound index.

Question

I want to know if I have set all the indexes correctly or it is a bad idea to set up the way I did?

If it is not correct then may I know the correct way to do it?

答:
@danblack thanks for your help.

Okay so trying with EXPLAINquery with various way setting up unique and index finally, I found the final version as below.

```<code>public function up()
{
    Schema::create(
        'users',
        function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
            $table->boolean('is_root')->default(FALSE);
            $table->rememberToken();
            $table->timestamps();

            $table->unique(['username', 'email'], 'users_unique_credentials');
        }
    );
}
</code>```

This way when we query on individual column, it will use own unique index. When we search with both columns with multiple WHERE clause it will use the compound unique index.

Body:
In Laravel (v 6.8) I have created below migration for the users table.

User Migration

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('username')->unique()->index();
        $table->string('email')->unique()->index();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password')->nullable();
        $table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
        $table->boolean('is_root')->default(FALSE);
        $table->rememberToken();
        $table->timestamps();

        $table->unique(['username', 'email'], 'user_unique_credentials');
        $table->index(['username', 'email'], 'user_index_columns');
    });
}

Explaination

I know basics of index and how it works but I a having not so clear understanding about index on individual column and composite/compound index.

The App may have query by only username or email or I may have a query for both tables together. Therefore as you can see in my migration code, I have set index for each column as well as both columns using $this->index() that creates a compound index.

Question

I want to know if I have set all the indexes correctly or it is a bad idea to set up the way I did?

If it is not correct then may I know the correct way to do it?

Body:
@danblack thanks for your help.

Okay so trying with EXPLAINquery with various way setting up unique and index finally, I found the final version as below.

public function up()
{
    Schema::create(
        'users',
        function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
            $table->boolean('is_root')->default(FALSE);
            $table->rememberToken();
            $table->timestamps();

            $table->unique(['username', 'email'], 'users_unique_credentials');
        }
    );
}

This way when we query on individual column, it will use own unique index. When we search with both columns with multiple WHERE clause it will use the compound unique index.


问:
What is a node in Javascript?
I was wondering what exactly a node is in JavaScript?

As in the functions:

```<code>element.nodeType
row.parentNode.removeChild(row);
</code>```

答: A node (of DOM) is an element, from your HTML page, rendered by the browser to said “node tree” and on screen. It is to be accessible and manipulated by web-client programs, like JavaScript.</p>

Title: What is a node in Javascript?

Body:
I was wondering what exactly a node is in JavaScript?

As in the functions:

element.nodeType
row.parentNode.removeChild(row);


问:
Attribute Error during countplot in Python?
I have Pandas DataFrame like this: data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
And I want to make seaborn countplot which will count amount of "good" and "bad", so I have a code:

```<code>ax = sns.countplot(x="Risk", data=data)
ax
</code>```

But when I want to use above code I have error: AttributeError: 'list' object has no attribute 'get'

I want to achieve plot like this:

答:
May be check your data again?

data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
ax = sns.countplot(x="Risk", data=data)
ax
```

Running this shows the plot perfectly:

Body:
I have Pandas DataFrame like this: data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
And I want to make seaborn countplot which will count amount of "good" and "bad", so I have a code:

ax = sns.countplot(x="Risk", data=data)
ax

But when I want to use above code I have error: AttributeError: 'list' object has no attribute 'get'

I want to achieve plot like this:

Body:
May be check your data again?

data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
ax = sns.countplot(x="Risk", data=data)
ax

Running this shows the plot perfectly:


问:
Python Find the words in the set have word pairs on dataframe
I have set of words

```<code>{'DNA',
 'pada',
 'yang',...}
</code>```

I am trying to find whether the words in the set have word pairs on the following bigram dataframe

```<code>                bigramf    freq
0           (DNA, yang)      15
1          (DNA, dalam)       6
2            (DNA, ini)       5
3       (DNA, memiliki)       4
4         (DNA, unting)       4
5           (pada, DNA)       4
6        (pada, urutan)       3
7     (yang, diperoleh)       3
8         (yang, lebih)       3
9      (pada, sejumlah)       2
10          (pada, RNA)       2
11          (pada, satu)      2
12       (yang, berbeda)      2
13          (yang, sama)      2
14       (yang, tumpang)      2
</code>```

If so, then the expected output will be like this:

```<code>yang [('lebih', 3), ('diperoleh', 3), ('berbeda', 2), ('tumpang', 2), ('sama', 2)]

DNA [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)]

pada [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)]
</code>```

How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

答:
What I did is for matching words

I looped through the data frame and took each element and passed it to a def like this

```<code>def match_words(actual_word, word):
    return set(actual_word.split()).intersection(word.split())
</code>```

Body:
I have set of words

{'DNA',
 'pada',
 'yang',...}

I am trying to find whether the words in the set have word pairs on the following bigram dataframe

                bigramf    freq
0           (DNA, yang)      15
1          (DNA, dalam)       6
2            (DNA, ini)       5
3       (DNA, memiliki)       4
4         (DNA, unting)       4
5           (pada, DNA)       4
6        (pada, urutan)       3
7     (yang, diperoleh)       3
8         (yang, lebih)       3
9      (pada, sejumlah)       2
10          (pada, RNA)       2
11          (pada, satu)      2
12       (yang, berbeda)      2
13          (yang, sama)      2
14       (yang, tumpang)      2

If so, then the expected output will be like this:

yang [('lebih', 3), ('diperoleh', 3), ('berbeda', 2), ('tumpang', 2), ('sama', 2)]

DNA [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)]

pada [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)]

How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

Body:
What I did is for matching words

I looped through the data frame and took each element and passed it to a def like this

def match_words(actual_word, word):
    return set(actual_word.split()).intersection(word.split())


问:
How to Search and Hide on Blogger Posting
I have Table on my blogger post.

I give it an Input form to it. Reader can search data quickly.

I get code from W3school.

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table

W3school
This code run well. But I need some improvement.

The Question:

How to show the Table just when user click "Enter Key" on Input/Button Form.

And when Input Form is empty, the Table automatically Hide.

答:
This will trigger search only when you hit "Enter Key" on Input.

Table automatically hides when search text is removed.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

My Customers

<input type="text" id="myInput"  placeholder="Search for names.." title="Type in a name">

    Name
    Country

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

    Laughing Bacchus Winecellars
    Canada

    Magazzini Alimentari Riuniti
    Italy

    North/South
    UK

    Paris specialites
    France

```

Body:
This will trigger search only when you hit "Enter Key" on Input.

Table automatically hides when search text is removed.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<h2>My Customers</h2>

<input type="text" id="myInput"  placeholder="Search for names.." title="Type in a name">

<table id="myTable" style="display:none;">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
</table>

<script>
var input = document.getElementById("myInput");

input.addEventListener("keyup", function(event) {

 input = document.getElementById("myInput");
   if(input.value.length <1){
     document.getElementById("myTable").style.display = 'none';
        return;
    }
  else if (event.keyCode === 13) {
     // Cancel the default action, if needed
     event.preventDefault();
     myFunction();
    }
});

function myFunction() {

  var input, filter, table, tr, td, i, txtValue;

  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;

      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
  document.getElementById("myTable").style.display = 'block';
}
</script>

</body>
</html>


问:
HTML Bootstrap Carousel (carousel-control)
About the issue that currently facing is that for Bootstrap Carousel (from w3school) , there is a problem for carousel-control.

Problem that i am facing is that when i have enter hyperlink for the image , the carousel-control are larger then the image itself (screenshot below).

Screenshot: https://prnt.sc/r4wh2f

Codes for my bootstrap carousel

```<code><div class="row">
<div class="col-12 col-md-12 banner-section">
<div class="container">
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
                <a href="facebook.com"><picture>
            <source media="(max-width: 900px)" srcset="image/banner01small.jpg">
            <img src="image/banner01" alt="banner" style="z-index:1" class="img-fluid">
        </picture></a>
      </div>

      <div class="item">
                <a href="instagram.com"><picture>
            <source media="(max-width: 900px)" srcset="image/banner02small.jpg">
            <img src="image/banner02" alt="banner" style="z-index:1" class="img-fluid">
        </picture></a>
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</div>
</div>
</code>```

答:
This is because the controls are also using the anchor tag and is conflicting with the same.you can add additional css to control anchor tags of the carousal and it will work fine.

All the best :)

Body:
About the issue that currently facing is that for Bootstrap Carousel (from w3school) , there is a problem for carousel-control.

Problem that i am facing is that when i have enter hyperlink for the image , the carousel-control are larger then the image itself (screenshot below).

Screenshot: https://prnt.sc/r4wh2f

Codes for my bootstrap carousel

                <picture>
            <source media="(max-width: 900px)" srcset="image/banner01small.jpg">

        </picture>

                <picture>
            <source media="(max-width: 900px)" srcset="image/banner02small.jpg">

        </picture>

      Previous

      Next


问:
Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists
I am still getting this error message, when I try to move my project tree on to git repo.

I checked the permissions of my directory with this project and these are set on 777. In terminal in the directory with my_project I set:

git init

and then if I try

git add .

or

git commit -m "first upload"

so I'll get the error

```<code>fatal: Unable to create '/path/my_proj/.git/index.lock': File exists.

If no other git process is currently running, this probably means a git process crashed in this repository earlier.
Make sure no other git process is running and remove the file manually to continue.
</code>```

I tried also create a new repo and there to commit it, but unfortunately still the same error message.

What is the cause of problem?

答: I had this occur when I was in a subdirectory of the directory corresponding to the root folder of the repo (ie the directory in which .git was). Moving up to the root directory solved the problem - at the cost of making all file references a bit more inconvenient as you have to go path/to/folder/foo.ext instead of just foo.ext</p>

Body:
I am still getting this error message, when I try to move my project tree on to git repo.

I checked the permissions of my directory with this project and these are set on 777. In terminal in the directory with my_project I set:

git init

and then if I try

git add .

or

git commit -m "first upload"

so I'll get the error

fatal: Unable to create '/path/my_proj/.git/index.lock': File exists.

If no other git process is currently running, this probably means a git process crashed in this repository earlier.
Make sure no other git process is running and remove the file manually to continue.

I tried also create a new repo and there to commit it, but unfortunately still the same error message.

What is the cause of problem?


问:
Is Redux needed for every ReactJS project?
I have a question: Is Redux needed for every ReactJS project for development?</p>

答: No, it isn't required, you can check official react tutorial not using any redux.</p>


问:
Python encoding issue
i m working with some python script, got a raw string with UTF8 encoding. first of all i decoded it to utf8 then some processing is done and at the end i encode it back to utf8 and inserted to DB(mysql) but chars in DB are not presented in real format.

```<code>str = '<term>Beiträge</term>'
str = str.decode('utf8')
...
...
...
str = str.encode('utf8')
</code>```

after that string is found in txt file in its real form but in MYSQL_DB, i found it like this

```<code> <term>"BeitrÃ¤ge</term>
</code>```

any idea why this happened? :-(

答:
Assuming you are using the MySQLdb library, you need to create connections using the keyword arguments:

use_unicode
      If True, text-like columns are returned as unicode objects using the
  connection's character set. Otherwise,
  text-like columns are returned as
  strings. columns are returned as
  normal strings. Unicode objects will
  always be encoded to the connection's
  character set regardless of this
  setting.

&

charset
      If supplied, the connection character set will be changed to this
  character set (MySQL-4.1 and newer).
  This implies use_unicode=True.

You should also check the encoding of your db tables.

Title: Python encoding issue

Body:
i m working with some python script, got a raw string with UTF8 encoding. first of all i decoded it to utf8 then some processing is done and at the end i encode it back to utf8 and inserted to DB(mysql) but chars in DB are not presented in real format.

str = '<term>Beiträge</term>'
str = str.decode('utf8')
...
...
...
str = str.encode('utf8')

after that string is found in txt file in its real form but in MYSQL_DB, i found it like this

 <term>"BeitrÃ¤ge</term>

any idea why this happened? :-(


问:
How to stop busy javascript program?
I am trying to write a nodejs express server. In that, I need to set time for execution. let say I made a request to /endpoint1 in express from the postman and that endpoint will trigger a function that contains an infinite for loop. My doubt is it possible to set the time limit for a single request?</p>

```<code>....
app.get('/endpoint1',(req,res)=>{
    while(true){}
});
....
</code>```

答:
You cannot do anything about that within the same execution context of your application.

What you could try to do is to have a controlling/observing parent process that spawns your application. And that application sends regularly „heartbeat“ messages to the parent if those are missing the parent can restart the application.

In general, it is a good idea to write you express in such a way and in addition to this to use the cluster capability of node, so if one worker becomes unresponsive for whatever reason, that you only need to restart that one worker.

Title: How to stop busy javascript program?

Body:
I am trying to write a nodejs express server. In that, I need to set time for execution. let say I made a request to /endpoint1 in express from the postman and that endpoint will trigger a function that contains an infinite for loop. My doubt is it possible to set the time limit for a single request?

....
app.get('/endpoint1',(req,res)=>{
    while(true){}
});
....


问:
Not able to embed PDF blob in HTML in IE
I have adopted various approaches to embed PDF blob in html in IE in order to display it.

1) creating a object URL and passing it to the embed or iframe tag. This works fine in Chrome but not in IE.

```<code></head>
<body>
    <input type="file" onchange="previewFile()">
    <iframe id="test_iframe" style="width:100%;height:500px;"></iframe>
    <script>
        function previewFile() {
            var file = document.querySelector('input[type=file]').files[0];
            var downloadUrl = URL.createObjectURL(file);
            console.log(downloadUrl);
            var element = document.getElementById('test_iframe');
            element.setAttribute('src',downloadUrl);
        }
    </script>
</body>
</code>```

2) I have also tried wrapping the URL Blob inside a encodeURIcomponent()

Any pointers on how I can approach to solve this?

答:
IE doesn't support iframe with data url as src attribute. You could check it in caniuse. It shows that the support is limited to images and linked resources like CSS or JS in IE. Please also check this documentation:

Data URIs are supported only for the following elements and/or
  attributes.

object (images only)

img

input type=image

link

CSS declarations that accept a URL, such as background,    backgroundImage, and so on.

Besides, IE doesn't have PDF viewer embeded, so you can't display PDFs directly in IE 11. You can only use msSaveOrOpenBlob to handle blobs in IE, then choose to open or save the PDF file:

```<code>if(window.navigator.msSaveOrOpenBlob) {
    //IE11
    window.navigator.msSaveOrOpenBlob(blobData, fileName);
}
else{
   //Other browsers
    window.URL.createObjectURL(blobData);
    ...
}
</code>```

Body:
I have adopted various approaches to embed PDF blob in html in IE in order to display it.

1) creating a object URL and passing it to the embed or iframe tag. This works fine in Chrome but not in IE.

    <input type="file" onchange="previewFile()">

2) I have also tried wrapping the URL Blob inside a encodeURIcomponent()

Any pointers on how I can approach to solve this?

Body:
IE doesn't support iframe with data url as src attribute. You could check it in caniuse. It shows that the support is limited to images and linked resources like CSS or JS in IE. Please also check this documentation:

Data URIs are supported only for the following elements and/or
  attributes.

object (images only)

img

input type=image

link

CSS declarations that accept a URL, such as background,    backgroundImage, and so on.

Besides, IE doesn't have PDF viewer embeded, so you can't display PDFs directly in IE 11. You can only use msSaveOrOpenBlob to handle blobs in IE, then choose to open or save the PDF file:

if(window.navigator.msSaveOrOpenBlob) {
    //IE11
    window.navigator.msSaveOrOpenBlob(blobData, fileName);
}
else{
   //Other browsers
    window.URL.createObjectURL(blobData);
    ...
}


问:
Change name of factor with dplyr
I have a variable in a data frame that contains integers and some "<31" values.  R recognizes this variable as a factor.

I'd like to set the <31 values to 30, but I've been unable to find an approach to do this.

```<code>#example my approach so far
a <- factor(c("31","32","43","36","35","46","<31"))
df <- as.data.frame(a)
str(df)
mutate(df, b = as.numeric(if_else(a == "<31", 30, a)))
Error: `false` must be a double vector, not a `factor` object
</code>```

Help would be appreciated.

答:
You can use fct_recode from forcats and then convert it to numeric.

```<code>library(dplyr)
df %>%
  mutate(b = forcats::fct_recode(a, `30` = "<31"),
         b = as.numeric(as.character(b)))

#    a  b
#1  31 31
#2  32 32
#3  43 43
#4  36 36
#5  35 35
#6  46 46
#7 <31 30
</code>```

Title: Change name of factor with dplyr

Body:
I have a variable in a data frame that contains integers and some "<31" values.  R recognizes this variable as a factor.

I'd like to set the <31 values to 30, but I've been unable to find an approach to do this.

#example my approach so far
a <- factor(c("31","32","43","36","35","46","<31"))
df <- as.data.frame(a)
str(df)
mutate(df, b = as.numeric(if_else(a == "<31", 30, a)))
Error: `false` must be a double vector, not a `factor` object

Help would be appreciated.

Body:
You can use fct_recode from forcats and then convert it to numeric.

library(dplyr)
df %>%
  mutate(b = forcats::fct_recode(a, `30` = "<31"),
         b = as.numeric(as.character(b)))

#    a  b
#1  31 31
#2  32 32
#3  43 43
#4  36 36
#5  35 35
#6  46 46
#7 <31 30


答:
I guess this will work,</p>

```<code>//type 1
var server = app.listen();
server.setTimeout(500000);

//type 2
app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

//type 3
app.post('/xxx', function (req, res) {
    res.setTimeout(3000, function () {
        console.log('here')
    });
});
</code>```

Title: How to stop busy javascript program?

Body:
I guess this will work,

//type 1
var server = app.listen();
server.setTimeout(500000);

//type 2
app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

//type 3
app.post('/xxx', function (req, res) {
    res.setTimeout(3000, function () {
        console.log('here')
    });
});


问:
The best way to store the following temporal data in DB
Imagine we have a set of entities each of which has its state: free, busy or broken. The state is specified for a day, for example, today on 2011-05-17 an entity E1 is free and tomorrow on 2011-05-18 it is busy.

There is a need to store ~10^5 entities for 1000 days. Which is the best way to do so?

I am thinking about 2 options:

represent each day as a character "0", "1" or "2" and store for every entity a string of 1000 characters

store each day with entity's state in a row, i.e. 1000 rows for an entity

The most important query for such data is: given start date and end date identify which entities are free.

Performance is of higher priority than storage.

All suggestions and comments are welcome.

答:
The best way is to try the simpler and more flexible option first (that is, store each day in its own row) and only devise a sophisticated alternative method if the performance is unsatisfactory. Avoid premature optimization.

10^8 rows isn't such a big deal for your average database on a commodity server nowadays. Put an index on the date, and I would bet that range queries ("given start date and end date...") will work just fine.

The reasons I claim that this is both simpler and more flexible than the idea of storing a string of 1000 characters are:

You'll have to process this in code, and that code would not be as straightforward to understand as code that queries DB records that contain date and status.

Depending on the database engine, 1000 character strings may be blobs that are stored outside of the record. That makes them less efficient.

What happens if you suddenly need 2,000 days instead of 1,000? Start updating all the rows and the code that processes them? That's much more work than just changing your query.

What happens when you're next asked to store some additional information per daily record, or need to change the granularity (move from days to hours for example)?


问:
MongoDB query on two collections to add/subtract a field in first collection with matched field from second collection
I've been stuck on this for a couple days and can't seem to figure it out.

Here's a couple example collections in my MongoDB database:
(just an example. sorry if they're not formatted correctly)

Products :

```<code>{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c3"
    },
    "name": "Acrylic Frame Magnetic",
    "units: "50",
    "fbasku": "AFM-CL-0507-FBA",
    "upc": "642709233954"
},
{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c4"
    },
    "name": "Apron Polka Dot",
    "units: "488",
    "fbasku": "APD-RD-03PC-FBA",
    "upc": "642709233961"
},
{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c5"
    },
    "name": "Acrylic Sign Holder - 5x7",
    "units: "632",
    "fbasku": "ASH-GD-0507-FBA",
    "upc": "642709233978"
}
</code>```

Transactions :

```<code>{
    "_id": {
        "$oid": "5e44e8ed8f4cd40bd09d5ce8"
    },
    "type": "adjust",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "25"
    },
    "comment": "example transaction"
},
{
    "_id": {
        "$oid": "5e4c9ab642c5a232042f4b67"
    },
    "type": "send",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "75"
    },
    "comment": ""
},
{
    "_id": {
        "$oid": "5e4c9ab642c5a232042f4b69"
    },
    "type": "send",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "5"
    },
    "comment": ""
}
</code>```

This is for a REST api I'm trying to build, so when I send a request to get all products, I want to:

Get an object containing all the products

Look through the transactions collection for each product in the object above, and add/subtract units from the listed unit quantity.

Give a response containing an object with the "fbasku", and a new calculated unit quantity for each product.

I got stuck when it came to all the async/await and Promise stuff, don't really understand it

答:
You can try below code - it is a sample of how to do your requirement using native nodejs-mongodb driver and node.js :

```<code>const MongoClient = require('mongodb').MongoClient;

const dbConnection = async function () {
    /** Connection URL */
    const url = 'mongodb://localhost:27017/test'; // Check whether you're passing correct DB name & full formed connection string
    let client;

    try {
        /** Use connect method to connect to the Server */
        client = await MongoClient.connect(url);
        const db = client.db(); // MongoDB would return client and you need to call DB on it.
        let dbResp = await db.collection('Products').aggregate([
            {
                $lookup:
                {
                    from: "Transactions",
                    let: { fbasku: "$fbasku" },
                    pipeline: [
                        {
                            $match:
                            {
                                $expr:
                                    { $eq: ["$fbasku", "$$fbasku"] }
                            }
                        },
                        { $project: { units: 1, _id: 0 } }
                    ],
                    as: "transaction_docs"
                }
            }, {
                $project: {
                    _id: 0, fbasku: 1,
                    units: {
                        $add: [{ $toInt: '$units' }, {
                            $reduce: {
                                input: '$transaction_docs',
                                initialValue: 0,
                                in: { $add: ["$$value", "$$this.units"] }
                            }
                        }]
                    }
                }
            }
        ]).toArray();
        client.close();
        return dbResp;
    } catch (err) {
        (client) && client.close();
        console.log(err);
        throw err
    }
};

/** In general dbConnection() has to be in one config file & it needs to be imported where ever db transactions are done like below */

dbConnection().then(res => console.log('Printing at calling ::', res)).catch(err => console.log('Err at Calling ::', err));
</code>```

Note : This code has query which assumes units in products is a string, So we're converting it into int & adding that values to (sum of units of transactions => intOf(units of a products) + (sum of units of all matched transactions)).

Test Query : MongoDB-Playground

Body:
I've been stuck on this for a couple days and can't seem to figure it out.

Here's a couple example collections in my MongoDB database:
(just an example. sorry if they're not formatted correctly)

Products :

{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c3"
    },
    "name": "Acrylic Frame Magnetic",
    "units: "50",
    "fbasku": "AFM-CL-0507-FBA",
    "upc": "642709233954"
},
{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c4"
    },
    "name": "Apron Polka Dot",
    "units: "488",
    "fbasku": "APD-RD-03PC-FBA",
    "upc": "642709233961"
},
{
    "_id": {
        "$oid": "5e4633eaa7095f26d44a43c5"
    },
    "name": "Acrylic Sign Holder - 5x7",
    "units: "632",
    "fbasku": "ASH-GD-0507-FBA",
    "upc": "642709233978"
}

Transactions :

{
    "_id": {
        "$oid": "5e44e8ed8f4cd40bd09d5ce8"
    },
    "type": "adjust",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "25"
    },
    "comment": "example transaction"
},
{
    "_id": {
        "$oid": "5e4c9ab642c5a232042f4b67"
    },
    "type": "send",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "75"
    },
    "comment": ""
},
{
    "_id": {
        "$oid": "5e4c9ab642c5a232042f4b69"
    },
    "type": "send",
    "fbasku": "AFM-CL-0507-FBA",
    "units": {
        "$numberInt": "5"
    },
    "comment": ""
}

This is for a REST api I'm trying to build, so when I send a request to get all products, I want to:

Get an object containing all the products

Look through the transactions collection for each product in the object above, and add/subtract units from the listed unit quantity.

Give a response containing an object with the "fbasku", and a new calculated unit quantity for each product.

I got stuck when it came to all the async/await and Promise stuff, don't really understand it

Body:
You can try below code - it is a sample of how to do your requirement using native nodejs-mongodb driver and node.js :

const MongoClient = require('mongodb').MongoClient;

const dbConnection = async function () {
    /** Connection URL */
    const url = 'mongodb://localhost:27017/test'; // Check whether you're passing correct DB name & full formed connection string
    let client;

    try {
        /** Use connect method to connect to the Server */
        client = await MongoClient.connect(url);
        const db = client.db(); // MongoDB would return client and you need to call DB on it.
        let dbResp = await db.collection('Products').aggregate([
            {
                $lookup:
                {
                    from: "Transactions",
                    let: { fbasku: "$fbasku" },
                    pipeline: [
                        {
                            $match:
                            {
                                $expr:
                                    { $eq: ["$fbasku", "$$fbasku"] }
                            }
                        },
                        { $project: { units: 1, _id: 0 } }
                    ],
                    as: "transaction_docs"
                }
            }, {
                $project: {
                    _id: 0, fbasku: 1,
                    units: {
                        $add: [{ $toInt: '$units' }, {
                            $reduce: {
                                input: '$transaction_docs',
                                initialValue: 0,
                                in: { $add: ["$$value", "$$this.units"] }
                            }
                        }]
                    }
                }
            }
        ]).toArray();
        client.close();
        return dbResp;
    } catch (err) {
        (client) && client.close();
        console.log(err);
        throw err
    }
};

/** In general dbConnection() has to be in one config file & it needs to be imported where ever db transactions are done like below */

dbConnection().then(res => console.log('Printing at calling ::', res)).catch(err => console.log('Err at Calling ::', err));

Note : This code has query which assumes units in products is a string, So we're converting it into int & adding that values to (sum of units of transactions => intOf(units of a products) + (sum of units of all matched transactions)).

Test Query : MongoDB-Playground


问:
How to prevent memory leaks during design phase of a component?
I am working on a web based component that would be developed in Java. A part of it is based on webservices, while the other has Spring-MVC framework and Hibernate for persistence layer.

I am still in the design process - preparing Use Cases, Activity diagrams and Sequence diagrams.

I was just wondering - What are specific ways to ensure that the design inherently does not have something that may cause a memory leak. Following proper coding guidelines followed by code review would ensure that memory leaks  do not exist in the program, but what about design level. Do we have some ways of putting a cap so that developer does not have to run his imagination wild and there by protect against leaks.

Appreciate any suggestions.

Thanks,
Ujjwal

答:
Loading up the system is only one half of the challenge in uncovering the resource leaks.   The second challenge is having a proper system of monitors and diagnostic utilities in place to understand how resources are being used, and potentially impinged.

Ultimately the resource leaks really fall into four broad categories: Memory, Disk, Network and CPU.   Whether you are looking at your app code, a guest operating system like Java or a Database, or the core operating system, all of the metrics you can collect are subset of these items.

Because monitoring can have an overhead on the system performance engineering staff tend to go light at the top level stats until an issue is identified and then deploy deeper level monitoring in the class of the identified resource leak for both the core and guest OS's to find out the likely cause.

If you are looking for some lightweight deep diagnostics which can help in profiling all of the way back into the unit test and component assembly stages and then carry the same tools all the way through performance testing efforts then I can recommend solutions from this organization, http://www.rtiperformance.com/.

James Pulley

Moderator: SQAForums Loadrunner|WinRunner, GoogleGroups lr-loadrunner, YahooGroups LoadRunner|Advanced-LoadRunner, LinkedIn LoadRunner (owner)| LoadRunnerbyTheHour (owner)