问:
Not getting the first value when using "array_search"
Here, I have two multi-dimensional array. As I want to find the value from first array if the value is there in second array or not.

First array:

```<code>$abc = array(
    array("fld_channel_selected_item_track_id" => 627905217),
    array("fld_channel_selected_item_track_id" => 616557954)
);
</code>```

Second array:

```<code>$pqr = array(
    array(
        "fld_channel_item_track" => 627905217,
        "fld_channel_item_title" => "Tropical Fantasy"
    ),
    array(
        "fld_channel_item_track" => 616557954,
        "fld_channel_item_title" => "Bday Boys"
    )
);
</code>```

So, I am searching if the first array value is there in second array value or not:

```<code>for($i = 0;$i < count($abc); $i++)
{
    $pos = array_search($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "```";print_r($pqr[$pos]);
    }
}
exit;
```

<p>The outout is:</p>

``````Array
(
    [fld_channel_item_track] => 616557954
    [fld_channel_item_title] => Bday Boys
)
</code>```

Here, I am not getting the first value in my output.

Where I am wrong in that?

答:
As already pointed by other answers that,

we know that array_search() returns index value so for first loop it returns 0 and for second  it's 1 so when if($pos) is 0 it fails. But you can modify your exiting code with in_array() to achieve what you want. Let's try like below-

```<code>for($i = 0;$i < count($abc); $i++)
{
    $pos = in_array($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "```";print_r($pqr[$i]); // see the index I changed here
    }
}
```

DEMO: https://3v4l.org/HA9tA

Body:
Here, I have two multi-dimensional array. As I want to find the value from first array if the value is there in second array or not.

First array:

$abc = array(
    array("fld_channel_selected_item_track_id" => 627905217),
    array("fld_channel_selected_item_track_id" => 616557954)
);

Second array:

$pqr = array(
    array(
        "fld_channel_item_track" => 627905217,
        "fld_channel_item_title" => "Tropical Fantasy"
    ),
    array(
        "fld_channel_item_track" => 616557954,
        "fld_channel_item_title" => "Bday Boys"
    )
);

So, I am searching if the first array value is there in second array value or not:

for($i = 0;$i < count($abc); $i++)
{
    $pos = array_search($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "
";print_r($pqr[$pos]);
    }
}
exit;

The outout is:

Array
(
    [fld_channel_item_track] => 616557954
    [fld_channel_item_title] => Bday Boys
)

Here, I am not getting the first value in my output.

Where I am wrong in that?

Body:
As already pointed by other answers that,

we know that array_search() returns index value so for first loop it returns 0 and for second  it's 1 so when if($pos) is 0 it fails. But you can modify your exiting code with in_array() to achieve what you want. Let's try like below-

for($i = 0;$i < count($abc); $i++)
{
    $pos = in_array($abc[$i]["fld_channel_selected_item_track_id"], array_column($pqr, 'fld_channel_item_track'));
    if($pos)
    {
        echo "<pre>";print_r($pqr[$i]); // see the index I changed here
    }
}

DEMO: https://3v4l.org/HA9tA


来源: stackexchange

问:
Is it possible to convert Image pdf in PDFTables package
I am trying to convert PDF using PDFtables package which is an image of text, that is when we open the PDF in a PDF viewer and we cannot select words or lines with the cursor.

Whether there is any solution for converting this type of file using PDFtables package??

答: No you cannot do this with PDFTables. You will need to run your PDF through an OCR converter first before running it through PDFTables.</p>

ContentLicense: CC BY-SA 4.0


问:
Merge two separate Angular project to one URL on apache server
I have two different projects in Angular (one is in version 6, other in 7) and each project has own routing module.

I must merge them into one domain url. To be clear I must do in that way:

my-domain.com -> go to first app.

my-domain.com/app2/ --> go to second app and also first app should have some button to redirect to second one.

If is easier to do my-domain.com can redirect for my-domain.com/app1.

That projects were already configured in AWS cloud with docker and apache. Right now I have two different domain and load balancer point to separate ECS.

I've tried to do some apache configuration:

```<code><VirtualHost *:80>
  ServerName my-domain.com

  LoadModule auth_openidc_module modules/mod_auth_openidc.so

  ####
  configuration for OIDC plugin
  ###

    DocumentRoot /var/www/html/my-app/www/

  Alias / "/var/www/html/my-app/www/"
    <Directory /var/www/html/my-app/www/>
        Options FollowSymLinks
        DirectoryIndex index.html
        AllowOverride FileInfo Options
        AllowOverride All
        Order allow,deny
    RewriteEngine On
    RewriteBase /

    RewriteRule ^manifest.json /base/manifest.json [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/* /index.html [L]
    </Directory>

    Alias /app2 "/var/www/html/my-app/www/app2/"
    <Directory /var/www/html/my-app/www/app2/>
        Options FollowSymLinks
        DirectoryIndex index.html
        AllowOverride FileInfo Options
        AllowOverride All
        Order allow,deny
    RewriteEngine On
    RewriteBase /

    RewriteRule ^manifest.json /base/manifest.json [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/* /index.html [L]
    </Directory>

</VirtualHost>
</code>```

But unfortunately is not working as expected.

Second tired was from that medium article: https://medium.com/disney-streaming/combining-multiple-angular-applications-into-a-single-one-e87d530d6527

Since new angular has ability to create sub-project:

```<code>ng generate application app1 –-routing
ng generate application app2 –-routing
</code>```

Since it was easy app, like in the tutorial, was working as expected but when migrate my apps I had an error for each modules:

```<code>ERROR in ./projects/app1/src/app/modules/contact-page-module/contact-page.module.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: my-app/projects/app1/src/app/modules/contact-page-module/contact-page.module.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (my-app/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:752:23)
at plugin.done.then (my-app/node_modules/@ngtools/webpack/src/loader.js:41:31)
at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

Already read that is problem with multiple modules in sub apps.

```<code>{
    path: 'home',
    loadChildren: '../modules/home-page-module/home-page.module#HomePageModule',
  }
</code>```

I couldn't find any solutions on the darkest side of internet and also didn't figure out by myself.

Of course I can merge the code from two applications into one but I'd love to keep separate it and repository each, though.

Thanks,

答:
I resolved that issue with Apache configuration. Maybe in some day you need that solutions.

The main problem was Angular routing. When url is pointed to domain.com/some_route_path, Apache thinks that user want to see files from folder named some_route_path but there index.html is missing so Apache show us page with nothing.

Let me explain more details, I used default Apache config so my main folder to put all generated files from Angular is /usr/local/apache2/htdocs. After put url domain.com in browser, apache point direct to htdocs and looking for index file. But after click on menu, routing redirect to domain.com/some_route_path and after refresh browser, apache by default looking folder some_route_path in htdocs so is bad behaviour for us thus to working angular application we need to inject special config e.x. How to configure apache for angular 2

After applied mentioned configuration angular application starting working fine. But in my case I'd like to work with two independent angular apps.

domain.com -> one apps with itself routing.

domain.com/second-app -> second angular app.

the latter app should have own routing so if user put url domain.com/second-app/some_other_router_page, that case should be handle by index.html in folder second-app. With configuration from the above link, the first app is working fine, but when go to second app, the whole routing is taking by the first one thus second is not working properly.

I figure out that configuration and now both apps working with theirs routing.

```<code><VirtualHost *:80>
    ServerName my-domain

    DocumentRoot /usr/local/apache2/htdocs
         <Directory /usr/local/apache2/htdocs>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted

              RewriteEngine On
              RewriteCond %{REQUEST_FILENAME} !-f
              RewriteCond %{REQUEST_FILENAME} !-d
              RewriteCond %{REQUEST_URI} second-app
              RewriteRule second-app/(.*)$ /second-app/index.html?path=$1 [L]

              RewriteCond %{REQUEST_FILENAME} !-f
              RewriteCond %{REQUEST_FILENAME} !-d
              RewriteCond %{REQUEST_URI} !/second-app/ [NC]
              RewriteRule (.*)$ /index.html?path=$1 [L]
             </Directory>

</VirtualHost>
</code>```

In my case I had some business case to do it. But in testing env is good to test couple of angular applications in one apache server. It can reduce cost of machines.

I can prepare github project if someone would like to see real life example with docker apache.

Body:
I have two different projects in Angular (one is in version 6, other in 7) and each project has own routing module.

I must merge them into one domain url. To be clear I must do in that way:

my-domain.com -> go to first app.

my-domain.com/app2/ --> go to second app and also first app should have some button to redirect to second one.

If is easier to do my-domain.com can redirect for my-domain.com/app1.

That projects were already configured in AWS cloud with docker and apache. Right now I have two different domain and load balancer point to separate ECS.

I've tried to do some apache configuration:

<VirtualHost *:80>
  ServerName my-domain.com

  LoadModule auth_openidc_module modules/mod_auth_openidc.so

  ####
  configuration for OIDC plugin
  ###

    DocumentRoot /var/www/html/my-app/www/

  Alias / "/var/www/html/my-app/www/"
    <Directory /var/www/html/my-app/www/>
        Options FollowSymLinks
        DirectoryIndex index.html
        AllowOverride FileInfo Options
        AllowOverride All
        Order allow,deny
    RewriteEngine On
    RewriteBase /

    RewriteRule ^manifest.json /base/manifest.json [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/* /index.html [L]
    </Directory>

    Alias /app2 "/var/www/html/my-app/www/app2/"
    <Directory /var/www/html/my-app/www/app2/>
        Options FollowSymLinks
        DirectoryIndex index.html
        AllowOverride FileInfo Options
        AllowOverride All
        Order allow,deny
    RewriteEngine On
    RewriteBase /

    RewriteRule ^manifest.json /base/manifest.json [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/* /index.html [L]
    </Directory>

</VirtualHost>

But unfortunately is not working as expected.

Second tired was from that medium article: https://medium.com/disney-streaming/combining-multiple-angular-applications-into-a-single-one-e87d530d6527

Since new angular has ability to create sub-project:

ng generate application app1 –-routing
ng generate application app2 –-routing

Since it was easy app, like in the tutorial, was working as expected but when migrate my apps I had an error for each modules:

ERROR in ./projects/app1/src/app/modules/contact-page-module/contact-page.module.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: my-app/projects/app1/src/app/modules/contact-page-module/contact-page.module.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (my-app/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:752:23)
at plugin.done.then (my-app/node_modules/@ngtools/webpack/src/loader.js:41:31)
at process._tickCallback (internal/process/next_tick.js:68:7)

Already read that is problem with multiple modules in sub apps.

{
    path: 'home',
    loadChildren: '../modules/home-page-module/home-page.module#HomePageModule',
  }

I couldn't find any solutions on the darkest side of internet and also didn't figure out by myself.

Of course I can merge the code from two applications into one but I'd love to keep separate it and repository each, though.

Thanks,

Body:
I resolved that issue with Apache configuration. Maybe in some day you need that solutions.

The main problem was Angular routing. When url is pointed to domain.com/some_route_path, Apache thinks that user want to see files from folder named some_route_path but there index.html is missing so Apache show us page with nothing.

Let me explain more details, I used default Apache config so my main folder to put all generated files from Angular is /usr/local/apache2/htdocs. After put url domain.com in browser, apache point direct to htdocs and looking for index file. But after click on menu, routing redirect to domain.com/some_route_path and after refresh browser, apache by default looking folder some_route_path in htdocs so is bad behaviour for us thus to working angular application we need to inject special config e.x. How to configure apache for angular 2

After applied mentioned configuration angular application starting working fine. But in my case I'd like to work with two independent angular apps.

domain.com -> one apps with itself routing.

domain.com/second-app -> second angular app.

the latter app should have own routing so if user put url domain.com/second-app/some_other_router_page, that case should be handle by index.html in folder second-app. With configuration from the above link, the first app is working fine, but when go to second app, the whole routing is taking by the first one thus second is not working properly.

I figure out that configuration and now both apps working with theirs routing.

<VirtualHost *:80>
    ServerName my-domain

    DocumentRoot /usr/local/apache2/htdocs
         <Directory /usr/local/apache2/htdocs>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted

              RewriteEngine On
              RewriteCond %{REQUEST_FILENAME} !-f
              RewriteCond %{REQUEST_FILENAME} !-d
              RewriteCond %{REQUEST_URI} second-app
              RewriteRule second-app/(.*)$ /second-app/index.html?path=$1 [L]

              RewriteCond %{REQUEST_FILENAME} !-f
              RewriteCond %{REQUEST_FILENAME} !-d
              RewriteCond %{REQUEST_URI} !/second-app/ [NC]
              RewriteRule (.*)$ /index.html?path=$1 [L]
             </Directory>

</VirtualHost>

In my case I had some business case to do it. But in testing env is good to test couple of angular applications in one apache server. It can reduce cost of machines.

I can prepare github project if someone would like to see real life example with docker apache.


问:
Data Visualization & HBase
Greetings,

I have been looking through the questions on this site and I haven't found any related questions.

I have currently built a Flex/PHP/MySQL app where I take an extract from my Hadoop cluster and dump to a MySQL table. There are several problems with this as my data set continues to grow.

I am looking for a much more robust open-source solution, and therefore have started to examine HBase and how to leverage PHP or Java to extract my data to a visualization app.

Have any of you built any visualization platforms on top of Hadoop or HBase?

Thank you!

答: Check out metatron discovery: https://github.com/metatron-app/metatron-discovery. They use Druid and Hive for their OLAP & data store. It's an open source so that you can check their code. It might be helpful.</p>

ContentLicense: CC BY-SA 2.5

Title: Data Visualization & HBase


问:
Change colour of UIPickerView selection indicators
Our UIPickerView has a dark background and the selection lines are incredibly hard to see. Is there anyway to change them to a colour of my choosing?

Update: I'm talking about the --- above and below the "Panda" item.

```<code>    Cat
    Dog
  Elephant
-----------
   Panda
-----------
   Bear
  Giraffe
</code>```

答:
Add this to your UIPickerView's viewForRow, titleForRow or attributedTitleForRow:

```<code>for lineSubview in pickerView.subviews {
  if lineSubview.frame.height < 1 {
    lineSubview.backgroundColor = UIColor.white.withAlphaComponent(0.15)
  }
}
</code>```

This should be a little bit safer to use because we are looking for subviews that should be very short in height. If Apple changes the view hierarchy it most probably won't mess up anything :)

ContentLicense: CC BY-SA 3.0

Body:
Our UIPickerView has a dark background and the selection lines are incredibly hard to see. Is there anyway to change them to a colour of my choosing?

Update: I'm talking about the --- above and below the "Panda" item.

    Cat
    Dog
  Elephant
-----------
   Panda
-----------
   Bear
  Giraffe

Body:
Add this to your UIPickerView's viewForRow, titleForRow or attributedTitleForRow:

for lineSubview in pickerView.subviews {
  if lineSubview.frame.height < 1 {
    lineSubview.backgroundColor = UIColor.white.withAlphaComponent(0.15)
  }
}

This should be a little bit safer to use because we are looking for subviews that should be very short in height. If Apple changes the view hierarchy it most probably won't mess up anything :)


问:
Get Start and End Days for a Given Week in PHP
I'm trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can't seem to figure it out.

For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):

```<code>function x_week_range(&$start_date, &$end_date, $date)
{
    $start_date = '';
    $end_date = '';
    $week = date('W', strtotime($date));
    $week = $week;

    $start_date = $date;

    $i = 0;
    while(date('W', strtotime("-$i day")) >= $week) {
        $start_date = date('Y-m-d', strtotime("-$i day"));
        $i++;
    }

    list($yr, $mo, $da) = explode('-', $start_date);

    $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}
</code>```

I realized all it did was add 7 days to the current date. How would you do this?

答:
A simple code to return the days from start DateTime and end DateTime. Using gmdate() method you can format date/time.</p>

```<code>$start_str_date = strtotime($start_date);
$end_str_date = strtotime($end_date);
$interval_days = $end_str_date - $start_str_date;
$days = gmdate('d',$interval_days);
echo $days;
</code>```

Body:
I'm trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can't seem to figure it out.

For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):

function x_week_range(&$start_date, &$end_date, $date)
{
    $start_date = '';
    $end_date = '';
    $week = date('W', strtotime($date));
    $week = $week;

    $start_date = $date;

    $i = 0;
    while(date('W', strtotime("-$i day")) >= $week) {
        $start_date = date('Y-m-d', strtotime("-$i day"));
        $i++;
    }

    list($yr, $mo, $da) = explode('-', $start_date);

    $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}

I realized all it did was add 7 days to the current date. How would you do this?

Body:
A simple code to return the days from start DateTime and end DateTime. Using gmdate() method you can format date/time.

$start_str_date = strtotime($start_date);
$end_str_date = strtotime($end_date);
$interval_days = $end_str_date - $start_str_date;
$days = gmdate('d',$interval_days);
echo $days;


问:
Excel - Add Custom Sort List in VBA
I have some code which first refreshes a set of data from ODBC, then refreshes several pivots linked to that data.

The pivots need to have a custom sort order in order to show the data in the "correct" order to the customer.

The sort order needs to be defined by the customer and can change at any point. To enable this, I have added a two tables containing the names of the groups and account codes on a settings worksheet. They can then order the rows in these tables into the order they wish.

I then need to add the data from these tables into a sort list that can be set on the pivots.

I am using Application.AddCustomList to add the custom list into Excel. This works fine if I just try to add one list, but when it try to add the second, it errors with:

"Method 'AddCustomList' of object '_Application' failed".

Below is the code:

```<code>    ' Deletes old sort orders
        On Error Resume Next
        Dim i As Long
        For i = 1 To Application.CustomListCount
           Application.DeleteCustomList (i)
        Next i

        On Error GoTo 0

    ' Adds custom sort for customers to appplication
        Application.AddCustomList ListArray:=Range("tblSortList[Account Code]")

    ' Gets the number of the custom sorts
        CustomerSortNo = Application.CustomListCount

    ' Adds custom sort for groups to appplication
         Application.AddCustomList ListArray:=Range("tblGroupSort[Group]")

    ' Gets the number of the categorysort
        CategorySortNo = Application.CustomListCount

    ' Sorts the pivots
        Pt.SortUsingCustomLists = True
        PTTotals.SortUsingCustomLists = True
        PTYearGroup.SortUsingCustomLists = True
        PTGroupAvg.SortUsingCustomLists = True

        Pt.PivotFields("Account Code").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CustomerSortNo + 1  ' +1 as No Calcualtion is number 1.
        PTTotals.PivotFields("Account Code").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CustomerSortNo + 1  ' +1 as No Calcualtion is number 1

        Pt.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1.
        PTTotals.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1
        PTYearGroup.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1
        PTGroupAvg.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1
</code>```

Current it will fail on the line: Application.AddCustomList ListArray:=Range("tblGroupSort[Group]")

If I re-order the code and add the Group sort list first, it will run fine and error on the Account Code list.

I have tried separating out the adding of the custom list into a sub for each, but it made no difference.

How can I add two range lists?

答:
Your code to assign and use the custom lists works, but the loop deleting them, not.

You have to step the list downwards to catch each element (numbering changes, if you deleted one):

```<code>For i = Application.CustomListCount To 1 Step -1
   Application.DeleteCustomList (i)
Next i
</code>```

Title: Excel - Add Custom Sort List in VBA

Body:
I have some code which first refreshes a set of data from ODBC, then refreshes several pivots linked to that data.

The pivots need to have a custom sort order in order to show the data in the "correct" order to the customer.

The sort order needs to be defined by the customer and can change at any point. To enable this, I have added a two tables containing the names of the groups and account codes on a settings worksheet. They can then order the rows in these tables into the order they wish.

I then need to add the data from these tables into a sort list that can be set on the pivots.

I am using Application.AddCustomList to add the custom list into Excel. This works fine if I just try to add one list, but when it try to add the second, it errors with:

"Method 'AddCustomList' of object '_Application' failed".

Below is the code:

    ' Deletes old sort orders
        On Error Resume Next
        Dim i As Long
        For i = 1 To Application.CustomListCount
           Application.DeleteCustomList (i)
        Next i

        On Error GoTo 0

    ' Adds custom sort for customers to appplication
        Application.AddCustomList ListArray:=Range("tblSortList[Account Code]")

    ' Gets the number of the custom sorts
        CustomerSortNo = Application.CustomListCount

    ' Adds custom sort for groups to appplication
         Application.AddCustomList ListArray:=Range("tblGroupSort[Group]")

    ' Gets the number of the categorysort
        CategorySortNo = Application.CustomListCount

    ' Sorts the pivots
        Pt.SortUsingCustomLists = True
        PTTotals.SortUsingCustomLists = True
        PTYearGroup.SortUsingCustomLists = True
        PTGroupAvg.SortUsingCustomLists = True

        Pt.PivotFields("Account Code").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CustomerSortNo + 1  ' +1 as No Calcualtion is number 1.
        PTTotals.PivotFields("Account Code").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CustomerSortNo + 1  ' +1 as No Calcualtion is number 1

        Pt.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1.
        PTTotals.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1
        PTYearGroup.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1
        PTGroupAvg.PivotFields("Group").DataRange.Sort Order1:=xlAscending, Type:=xlSortLabels, OrderCustom:=CategorySortNo + 1  ' +1 as No Calcualtion is number 1

Current it will fail on the line: Application.AddCustomList ListArray:=Range("tblGroupSort[Group]")

If I re-order the code and add the Group sort list first, it will run fine and error on the Account Code list.

I have tried separating out the adding of the custom list into a sub for each, but it made no difference.

How can I add two range lists?

Body:
Your code to assign and use the custom lists works, but the loop deleting them, not.

You have to step the list downwards to catch each element (numbering changes, if you deleted one):

For i = Application.CustomListCount To 1 Step -1
   Application.DeleteCustomList (i)
Next i


问:
JavaScript: Add space between Char and Number with Regex
Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).

I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.

```<code>var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK
</code>```

答:
You should alternate with the other possibility, that a number is followed by a non-number:

var str = 'BZ8345LK';
console.log(str.replace(/[^0-9](?=[0-9])|[0-9](?=[^0-9])/g, '$& '));```

Body:
Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).

I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.

var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK


问:
How to fill periods in columns?
There is a dataframe. The period column contains lists. These lists contain time spans.

```<code>#load data
df = pd.DataFrame(data, columns=['task_id', 'target_start_date', 'target_end_date'])

df['target_start_date'] = pd.to_datetime(df.target_start_date)
df['target_end_date'] = pd.to_datetime(df.target_end_date)
df['period'] = np.nan

#create period column
z = dict()
freq = 'M'

for i in range(0, len(df)):
    l = pd.period_range(df.target_start_date[i], df.target_end_date[i], freq=freq)
    l = l.to_native_types()
    z[i] = l

df.period = z.values()
</code>```

Output

```<code>    task_id  target_start_date  target_end_date     period

0   35851   2019-04-01 07:00:00 2019-04-01 07:00:00 [2019-04]
1   35852   2020-02-26 11:30:00 2020-02-26 11:30:00 [2020-02]
2   35854   2019-05-17 07:00:00 2019-06-01 17:30:00 [2019-05, 2019-06]
3   35855   2019-03-20 11:30:00 2019-04-07 15:00:00 [2019-03, 2019-04]
4   35856   2019-04-06 08:00:00 2019-04-26 19:00:00 [2019-04]
</code>```

enter image description here

Then I add columns which are called time slices.

```<code>#create slices
date_min = df.target_start_date.min()
date_max = df.target_end_date.max()
period = pd.period_range(date_min, date_max, freq=freq)

#add columns
for i in period:
    df[str(i)] = np.nan
</code>```

result

enter image description here

How can I fill Nan values for True, if this value is in the list in the period column?

enter image description here

答:
Apply a function across the dataframe rows</p>

```<code>def fillit(row):
    for i in row.period:
        row[i] = True

df.apply(fillit), axis=1)
</code>```

Title: How to fill periods in columns?

Body:
There is a dataframe. The period column contains lists. These lists contain time spans.

#load data
df = pd.DataFrame(data, columns=['task_id', 'target_start_date', 'target_end_date'])

df['target_start_date'] = pd.to_datetime(df.target_start_date)
df['target_end_date'] = pd.to_datetime(df.target_end_date)
df['period'] = np.nan

#create period column
z = dict()
freq = 'M'

for i in range(0, len(df)):
    l = pd.period_range(df.target_start_date[i], df.target_end_date[i], freq=freq)
    l = l.to_native_types()
    z[i] = l

df.period = z.values()

Output

    task_id  target_start_date  target_end_date     period

0   35851   2019-04-01 07:00:00 2019-04-01 07:00:00 [2019-04]
1   35852   2020-02-26 11:30:00 2020-02-26 11:30:00 [2020-02]
2   35854   2019-05-17 07:00:00 2019-06-01 17:30:00 [2019-05, 2019-06]
3   35855   2019-03-20 11:30:00 2019-04-07 15:00:00 [2019-03, 2019-04]
4   35856   2019-04-06 08:00:00 2019-04-26 19:00:00 [2019-04]

enter image description here

Then I add columns which are called time slices.

#create slices
date_min = df.target_start_date.min()
date_max = df.target_end_date.max()
period = pd.period_range(date_min, date_max, freq=freq)

#add columns
for i in period:
    df[str(i)] = np.nan

result

enter image description here

How can I fill Nan values for True, if this value is in the list in the period column?

enter image description here

Body:
Apply a function across the dataframe rows

def fillit(row):
    for i in row.period:
        row[i] = True

df.apply(fillit), axis=1)


答:
You can use this regex

```<code>[a-z](?=\d)|\d(?=[a-z])
</code>```

[a-z](?=\d) - Match any alphabet followed by digit

| - Alternation same as logical OR

\d(?=[a-z]) - Any digit followed by alphabet

let str = 'BZ8345LK'

let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')

console.log(op)```

Title: JavaScript: Add space between Char and Number with Regex

Body:
You can use this regex

[a-z](?=\d)|\d(?=[a-z])

[a-z](?=\d) - Match any alphabet followed by digit

| - Alternation same as logical OR

\d(?=[a-z]) - Any digit followed by alphabet

let str = 'BZ8345LK'

let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')

console.log(op)


问:
Can I use GetDataRow() on a view if the view's datasource is IQueryable?
I am implementing drag and drop functionality in a form and I'm running into a situation where I need to GetDataRow, but the view has been bound to an IQueryable, as such:

```<code>    private void stackOverFlow()
    {
        Func<int, IQueryable> query = i =>
                                      from p in _data.PERSON
                                      where p.FavoriteNumber == i
                                      select p;

        gc1.DataSource = query(17);

        var row = ((GridView) gc1.DefaultView).GetDataRow(0);
    }
</code>```

The row is always null due to the nature of the binding... Any help would be highly appreciated.

Thanks

答: The GetDataRow() method is designed to return a DataRow object.  This method can be used when the GridContol is bound to a DataView or DataTable object.  In your case, I would suggest that you use the View's GetRow() method, it will return a PERSON object in your case.</p>

Body:
I am implementing drag and drop functionality in a form and I'm running into a situation where I need to GetDataRow, but the view has been bound to an IQueryable, as such:

    private void stackOverFlow()
    {
        Func<int, IQueryable> query = i =>
                                      from p in _data.PERSON
                                      where p.FavoriteNumber == i
                                      select p;

        gc1.DataSource = query(17);

        var row = ((GridView) gc1.DefaultView).GetDataRow(0);
    }

The row is always null due to the nature of the binding... Any help would be highly appreciated.

Thanks


问:
Can source string be converted to destination string?
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

```<code>Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB
</code>```

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?

答:
It should return true if Both strings should having the same length and same chars(not the same as we are going to transform) occurrence counts.

Please check whether below approach works:

check the length of both strings is the same.

Get counts of all chars of source and destination strings.

Sort both counts data and iterate over both, return false if you find different count at the same index.

Else return true.

Body:
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?


问:
toLiveData not available from DataSource.Factory in Android's Paging
I am trying to use LiveData for paging data from my Room database. The sample code from Google indicates the use of a toLiveData function:

```<code>class ConcertViewModel(concertDao: ConcertDao) : ViewModel() {
    val concertList: LiveData<PagedList<Concert>> =
            concertDao.concertsByDate().toLiveData(pageSize = 50)
}
</code>```

https://developer.android.com/topic/libraries/architecture/paging

Here is the code I created that follows their example:

AppDao.kt

```<code>import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import com.example.model.UserConnection

@Dao
interface AppDao {
    @Query("SELECT * FROM UserConnection")
    fun getAll(): LiveData<List<UserConnection>>

    @Insert(onConflict = REPLACE)
    fun save(userConnection: UserConnection)

    @Query("SELECT * FROM UserConnection ORDER BY firstName DESC")
    fun connectionsByFirstName(): DataSource.Factory<Int, UserConnection>
}
</code>```

AppDatabase.kt

```<code>import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.model.UserConnection

@Database(entities = arrayOf(UserConnection::class), version = 1, exportSchema = true)
@TypeConverters(RoomConverters::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun appDao(): AppDao
}
</code>```

ConnectionsViewModel.kt

```<code>import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.DataSource
import androidx.paging.PagedList
import com.linkedintools.da.local.room.AppDao
import com.example.model.UserConnection
import javax.inject.Inject

class ConnectionsViewModel @Inject constructor(appDao: AppDao) : ViewModel() {

    val connectionsDataSource : DataSource.Factory<Int, UserConnection> = appDao.connectionsByFirstName()

    val concertList: LiveData<PagedList<UserConnection>> = connectionsDataSource.toLiveData(pageSize = 40)

}
</code>```

build.gradle

```<code>dependencies {
    def room_version = "2.1.0-rc01"
    def paging_version = "2.1.0"

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"

    // optional - RxJava support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // Paging
    implementation "androidx.paging:paging-runtime:$paging_version"

}
</code>```

The toLiveData is not available. Am I doing something wrong or is the sample code from Google out of date?

答:
toLiveData is an extention fun, import this library and it is all done :

 androidx.paging:paging-runtime-ktx:2.1.0-rc01

Addionaly check this  google samples project Paging With Network Sample

https://github.com/googlesamples/android-architecture-components/tree/master/PagingWithNetworkSample

Body:
I am trying to use LiveData for paging data from my Room database. The sample code from Google indicates the use of a toLiveData function:

class ConcertViewModel(concertDao: ConcertDao) : ViewModel() {
    val concertList: LiveData<PagedList<Concert>> =
            concertDao.concertsByDate().toLiveData(pageSize = 50)
}

https://developer.android.com/topic/libraries/architecture/paging

Here is the code I created that follows their example:

AppDao.kt

import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import com.example.model.UserConnection

@Dao
interface AppDao {
    @Query("SELECT * FROM UserConnection")
    fun getAll(): LiveData<List<UserConnection>>

    @Insert(onConflict = REPLACE)
    fun save(userConnection: UserConnection)

    @Query("SELECT * FROM UserConnection ORDER BY firstName DESC")
    fun connectionsByFirstName(): DataSource.Factory<Int, UserConnection>
}

AppDatabase.kt

import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.model.UserConnection

@Database(entities = arrayOf(UserConnection::class), version = 1, exportSchema = true)
@TypeConverters(RoomConverters::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun appDao(): AppDao
}

ConnectionsViewModel.kt

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.DataSource
import androidx.paging.PagedList
import com.linkedintools.da.local.room.AppDao
import com.example.model.UserConnection
import javax.inject.Inject

class ConnectionsViewModel @Inject constructor(appDao: AppDao) : ViewModel() {

    val connectionsDataSource : DataSource.Factory<Int, UserConnection> = appDao.connectionsByFirstName()

    val concertList: LiveData<PagedList<UserConnection>> = connectionsDataSource.toLiveData(pageSize = 40)

}

build.gradle

dependencies {
    def room_version = "2.1.0-rc01"
    def paging_version = "2.1.0"

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"

    // optional - RxJava support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // Paging
    implementation "androidx.paging:paging-runtime:$paging_version"

}

The toLiveData is not available. Am I doing something wrong or is the sample code from Google out of date?


问:
How to add font types on Quill js with toolbar options?
I have made a rich text area made with Quill js. I have the next options for the tool bar:

new Quill('#quilljs-container', {
    modules: {
        toolbar: [
           ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
           ['blockquote', 'code-block', 'link'],

           [{ 'header': 1 }, { 'header': 2 }],               // custom button values
           [{ 'list': 'ordered'}, { 'list': 'bullet' }],
           [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
           [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
           [{ 'direction': 'rtl' }],                         // text direction

           [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
           [{ 'font': [] }],
           [{ 'align': [] }],

           ['clean']                                         // remove formatting button
       ]
    },
    theme: 'snow'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Style -->
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">

<!-- quill js container -->
<div id="quilljs-container">  </div>

<!-- Add quill js on the project -->
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script></code>```

Currently, when I try to add more types editing the 'font' option on toolbar (e.g. 'font': ['arial']), the select options just display "Sans Serif" instead of display the "Arial" option. What I spect is see the default options ("Sans Serif", "Serif", "Monospace") plus custom options that I want to add.

Also, I have tried the customizing attributors shown on the documentation, but with my current configuration, it just display just the default options. Maybe I'm missing something.

I hope I was clear with my doubt and someone could help me.

UPDATE:

Just to be a little more clear, I am trying to add more fonts following the Quill Container configuration

Container: At the simplest level, toolbar controls can be specified by a simple array of format names.

答:
FWIW, I've copied the code from Steve B and made it more generic. This way you don't need to do all the copy pasting of css rules, etc... just specify the fonts you would like adding in your fonts array.</p>

```<code>// specify the fonts you would
var fonts = ['Arial', 'Courier', 'Garamond', 'Tahoma', 'Times New Roman', 'Verdana'];
// generate code friendly names
function getFontName(font) {
    return font.toLowerCase().replace(/\s/g, "-");
}
var fontNames = fonts.map(font => getFontName(font));
// add fonts to style
var fontStyles = "";
fonts.forEach(function(font) {
    var fontName = getFontName(font);
    fontStyles += ".ql-snow .ql-picker.ql-font .ql-picker-label[data-value=" + fontName + "]::before, .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=" + fontName + "]::before {" +
        "content: '" + font + "';" +
        "font-family: '" + font + "', sans-serif;" +
        "}" +
        ".ql-font-" + fontName + "{" +
        " font-family: '" + font + "', sans-serif;" +
        "}";
});
var node = document.createElement('style');
node.innerHTML = fontStyles;
document.body.appendChild(node);

var toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],

    [{ 'header': 1 }, { 'header': 2 }],               // custom button values
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
    [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
    [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
    [{ 'direction': 'rtl' }],                         // text direction

    [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

    [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
    [{ 'font': fontNames }],
    [{ 'align': [] }],

    ['clean']                                         // remove formatting button
];

// Add fonts to whitelist
var Font = Quill.import('formats/font');
Font.whitelist = fontNames;
Quill.register(Font, true);

var quill = new Quill('#editor', {
    modules: {
        toolbar: toolbarOptions
    },
    theme: 'snow'
});
</code>```

Body:
I have made a rich text area made with Quill js. I have the next options for the tool bar:

new Quill('#quilljs-container', {
    modules: {
        toolbar: [
           ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
           ['blockquote', 'code-block', 'link'],

           [{ 'header': 1 }, { 'header': 2 }],               // custom button values
           [{ 'list': 'ordered'}, { 'list': 'bullet' }],
           [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
           [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
           [{ 'direction': 'rtl' }],                         // text direction

           [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
           [{ 'font': [] }],
           [{ 'align': [] }],

           ['clean']                                         // remove formatting button
       ]
    },
    theme: 'snow'
});

<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">

Currently, when I try to add more types editing the 'font' option on toolbar (e.g. 'font': ['arial']), the select options just display "Sans Serif" instead of display the "Arial" option. What I spect is see the default options ("Sans Serif", "Serif", "Monospace") plus custom options that I want to add.

Also, I have tried the customizing attributors shown on the documentation, but with my current configuration, it just display just the default options. Maybe I'm missing something.

I hope I was clear with my doubt and someone could help me.

UPDATE:

Just to be a little more clear, I am trying to add more fonts following the Quill Container configuration

Container: At the simplest level, toolbar controls can be specified by a simple array of format names.

Body:
FWIW, I've copied the code from Steve B and made it more generic. This way you don't need to do all the copy pasting of css rules, etc... just specify the fonts you would like adding in your fonts array.

// specify the fonts you would
var fonts = ['Arial', 'Courier', 'Garamond', 'Tahoma', 'Times New Roman', 'Verdana'];
// generate code friendly names
function getFontName(font) {
    return font.toLowerCase().replace(/\s/g, "-");
}
var fontNames = fonts.map(font => getFontName(font));
// add fonts to style
var fontStyles = "";
fonts.forEach(function(font) {
    var fontName = getFontName(font);
    fontStyles += ".ql-snow .ql-picker.ql-font .ql-picker-label[data-value=" + fontName + "]::before, .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=" + fontName + "]::before {" +
        "content: '" + font + "';" +
        "font-family: '" + font + "', sans-serif;" +
        "}" +
        ".ql-font-" + fontName + "{" +
        " font-family: '" + font + "', sans-serif;" +
        "}";
});
var node = document.createElement('style');
node.innerHTML = fontStyles;
document.body.appendChild(node);

var toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],

    [{ 'header': 1 }, { 'header': 2 }],               // custom button values
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
    [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
    [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
    [{ 'direction': 'rtl' }],                         // text direction

    [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

    [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
    [{ 'font': fontNames }],
    [{ 'align': [] }],

    ['clean']                                         // remove formatting button
];

// Add fonts to whitelist
var Font = Quill.import('formats/font');
Font.whitelist = fontNames;
Quill.register(Font, true);

var quill = new Quill('#editor', {
    modules: {
        toolbar: toolbarOptions
    },
    theme: 'snow'
});


问:
splitting long long
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

```<code>long long long_type = 0xaaaabbbbccccdddd;
</code>```

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.

答:
I'd recommend using uint32_t and uint64_t or other fixed width types.

Then use bit operations to split it like:

```<code>uint64_t long_type = smthng;
uint32_t high = (long_type & 0xFFFFFFFF00000000ULL) >> 32;
uint32_t low = long_type & 0xFFFFFFFF;
</code>```

Title: splitting long long

Body:
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

long long long_type = 0xaaaabbbbccccdddd;

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.

Body:
I'd recommend using uint32_t and uint64_t or other fixed width types.

Then use bit operations to split it like:

uint64_t long_type = smthng;
uint32_t high = (long_type & 0xFFFFFFFF00000000ULL) >> 32;
uint32_t low = long_type & 0xFFFFFFFF;


答:
First, I would advise against producing the dummy variables yourself. Let R do it for you during the model estimation by using a factor for the variable from which you want the dummy variables to be derived: just use factor(ISOCode) in the formula. The manual way is error prone.

Then, use model.matrix after the model estimation to look at the data after the within transformation inherent to the fixed effects model:

```<code>mod <-plm(ROSLN ~ DOILN + GDPGROW + IRATE + factor(ISOCode),
                         data = dat, model = "within")
model.matrix(mod)

    DOILN    GDPGROW     IRATE factor(ISOCode)RUS
   0.224725  0.0412125 -0.000615                  0
   0.071525  0.0028125 -0.093915                  0
  -0.024175 -0.0253775  0.031765                  0
  -0.272075 -0.0186475  0.062765                  0
   1.626660  0.0546400 -0.052980                  0
   0.045960 -0.0119500 -0.020600                  0
  -0.622140 -0.0412500  0.015010                  0
  -0.538440 -0.0052200  0.010400                  0
  -0.512040  0.0037800  0.048170                  0
   0.000000  0.0000000  0.000000                  0
</code>```

Two issues become apparent: One row is all zeros as there was only one observation for the individual. This row will be dropped in the model estimation. The column for the ISO codes is all zeros and will be dropped as well.

This is why the model summary looks like it looks.

Title: Dummy variables are missing when I ran a panel regression. How to display the dummy variables?

Body:
I am trying to do a panel data regression with fixed effect estimator. The sample data can be seen below:

structure(list(DOILN = c(4.3207, 4.1675, 4.0718, 3.8239, 3.6247,
2.044, 1.3759, 1.4596, 1.486, 4.3136), ROSLN = c(-2.0178, -2.2647,
-4.0632, -3.9933, -3.441, -3.6077, -2.8291, -2.6271, -2.4051,
-1.7239), IRATE = c(-0.0295, -0.1228, 0.00288, 0.03388, -0.0295,
0.00288, 0.03849, 0.03388, 0.07165, 0.04809), GDPGROW = c(0.11731,
0.07891, 0.05072, 0.05745, 0.11731, 0.05072, 0.02142, 0.05745,
0.06645, -0.01765), ISOCode = structure(c(4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 3L), .Label = c("BRA", "CHN", "IND", "RUS"), class = "factor"),
    ISOCodeBRA = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ISOCodeRUS = c(1,
    1, 1, 1, 1, 1, 1, 1, 1, 0), ISOCodeIND = c(0, 0, 0, 0, 0,
    0, 0, 0, 0, 1), ISOCodeCHN = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
    0)), .Names = c("DOILN", "ROSLN", "IRATE", "GDPGROW", "ISOCode",
"ISOCodeBRA", "ISOCodeRUS", "ISOCodeIND", "ISOCodeCHN"), row.names = c("120453-2010",
"120453-2011", "120453-2012", "120453-2014", "133431-2010", "133431-2012",
"133431-2013", "133431-2014", "133431-2015", "200448-2009"), class = c("pdata.frame",
"data.frame"), index = structure(list(GCKey = structure(c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L), .Label = c("120453", "133431",
"200448"), class = "factor"), FiscalY = structure(c(2L, 3L, 4L,
6L, 2L, 4L, 5L, 6L, 7L, 1L), .Label = c("2009", "2010", "2011",
"2012", "2013", "2014", "2015"), class = "factor")), .Names = c("GCKey",
"FiscalY"), row.names = c(915L, 647L, 35L, 41L, 83L, 68L, 220L,
330L, 497L, 1219L), class = c("pindex", "data.frame")))

However, when I introduced dummy variables for the countries (ISOCode), they are missing from the summary. Also, I still got N dummy variables, instead of N-1.

I used model.matrix to create dummy variables. First I did this to create the dummy variable and include it to my dataframe

dBRICna <-cbind(dBRICna, model.matrix(~ -1+ISOCode, data = dBRICna))

then I create a panel dataframe based on my initial dataframe. The panel regression is as follows:

fix.cdum <-Plm(ROSLN~DOILN+GDPGROW+IRATE+ISOCodeBRA+ISOCodeRUS+ISOCodeIND+ISOCodeCHN,
data = pbric,model = "within")

The resulting regression is as follow:

Oneway (individual) effect Within Model

Call:
plm(formula = ROSLN ~ DOILN + IRATE + GDPGROW + ISOCodeBRA +
    ISOCodeCHN + ISOCodeIND + ISOCodeRUS, data = pbric, model = "within")

Unbalanced Panel: n = 308, T = 1-7, N = 1574

Residuals:
      Min.    1st Qu.     Median    3rd Qu.       Max.
-6.4169648 -0.1066602  0.0075008  0.1344821  2.7955477

Coefficients:
         Estimate Std. Error t-value Pr(>|t|)
DOILN    0.031935   0.055124  0.5793  0.56247
IRATE   -1.194691   0.486961 -2.4534  0.01429 *
GDPGROW -0.041300   0.767433 -0.0538  0.95709
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Total Sum of Squares:    240.19
Residual Sum of Squares: 238.52
R-Squared:      0.006922
Adj. R-Squared: -0.23683
F-statistic: 2.93449 on 3 and 1263 DF, p-value: 0.032416

As observed, the dummy variables are not shown on the regression result. Would be really thankful if anyone can advise me on this matter!

Body:
First, I would advise against producing the dummy variables yourself. Let R do it for you during the model estimation by using a factor for the variable from which you want the dummy variables to be derived: just use factor(ISOCode) in the formula. The manual way is error prone.

Then, use model.matrix after the model estimation to look at the data after the within transformation inherent to the fixed effects model:

mod <-plm(ROSLN ~ DOILN + GDPGROW + IRATE + factor(ISOCode),
                         data = dat, model = "within")
model.matrix(mod)

    DOILN    GDPGROW     IRATE factor(ISOCode)RUS
   0.224725  0.0412125 -0.000615                  0
   0.071525  0.0028125 -0.093915                  0
  -0.024175 -0.0253775  0.031765                  0
  -0.272075 -0.0186475  0.062765                  0
   1.626660  0.0546400 -0.052980                  0
   0.045960 -0.0119500 -0.020600                  0
  -0.622140 -0.0412500  0.015010                  0
  -0.538440 -0.0052200  0.010400                  0
  -0.512040  0.0037800  0.048170                  0
   0.000000  0.0000000  0.000000                  0

Two issues become apparent: One row is all zeros as there was only one observation for the individual. This row will be dropped in the model estimation. The column for the ISO codes is all zeros and will be dropped as well.

This is why the model summary looks like it looks.


问:
windows batch to split string on first occurrence of a delimiter
I have a parameter string read from a properties file. One of the properties is as below:

```<code>"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"
</code>```

I need to split this string on the first occurrence of "=" and set a parameter with the value:

```<code>-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

```<code>@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause
</code>```

The above does not seem to work, it produces:

```<code>Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=
</code>```

Expected result needs to be:

```<code> str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

答:
If the first character after the = character is always a -, then the following method may also work for you:

@Echo Off
Set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"
Set "REST=-%TESTSTR:*-=%"
Set "FIRST=%TESTSTR:-="&:"%"
Set "FIRST=%FIRST:~,-1%"
Echo [%FIRST%] [%REST%] & Pause
```

The bottom line is simply to show you the information.

Body:
I have a parameter string read from a properties file. One of the properties is as below:

"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"

I need to split this string on the first occurrence of "=" and set a parameter with the value:

-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause

The above does not seem to work, it produces:

Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=

Expected result needs to be:

 str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

Body:
If the first character after the = character is always a -, then the following method may also work for you:

@Echo Off
Set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"
Set "REST=-%TESTSTR:*-=%"
Set "FIRST=%TESTSTR:-="&:"%"
Set "FIRST=%FIRST:~,-1%"
Echo [%FIRST%] [%REST%] & Pause

The bottom line is simply to show you the information.


问:
Redirect the pages of a site with the question mark with the htaccess
I should redirect all links similar to this:

```<code>http://www.sitename.com/?918pae056d2bnnxpy
</code>```

The problem is that these links do not have a variable that can be taken with htaccess ... so I was looking for a solution that could take all these URLs and redirect them to the home of the site.
Can someone help me?

答:
It is unclear what you actually mean by "these links do not have a variable that can be taken with htaccess"... That question mark in the URL denotes request arguments ("GET arguments") that can very well be considered and modified on the level of the http server, so for example inside the apache http server's rewriting module.

Here is a simple example:

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^/?$ /home.php?arg=%1 [END]
</code>```

It internally rewrites every incoming request to / to /home.php if there is a query string present (so a GET argument specified). The argument itself will be handed over to the script as GET argument "arg".

There are other alternatives for most cases, but you did not tell us any details about your actual situation, so we cannot be more specific here.

The above is just an example, obviously you will need to adjust it to your needs. It is only meant as an explanation, to point you into the right direction.

Body:
I should redirect all links similar to this:

http://www.sitename.com/?918pae056d2bnnxpy

The problem is that these links do not have a variable that can be taken with htaccess ... so I was looking for a solution that could take all these URLs and redirect them to the home of the site.
Can someone help me?

Body:
It is unclear what you actually mean by "these links do not have a variable that can be taken with htaccess"... That question mark in the URL denotes request arguments ("GET arguments") that can very well be considered and modified on the level of the http server, so for example inside the apache http server's rewriting module.

Here is a simple example:

RewriteEngine on
RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^/?$ /home.php?arg=%1 [END]

It internally rewrites every incoming request to / to /home.php if there is a query string present (so a GET argument specified). The argument itself will be handed over to the script as GET argument "arg".

There are other alternatives for most cases, but you did not tell us any details about your actual situation, so we cannot be more specific here.

The above is just an example, obviously you will need to adjust it to your needs. It is only meant as an explanation, to point you into the right direction.


问:
filtering the keys and reducing into nested structure
I have a below data structure from it i need extract the columns which is an array an i need to build an object with key and actual label name.

Is there any better way to achieve this.

Any help appreciated

    let data = {
      "section1": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section2": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test5",
                "label": [
                  {
                    "actualLabel": "Test 5"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section3": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test 4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      }
    }

    let extractColumns = ['test1', 'test2', 'test7', 'test15']

   let result = Object.entries(data).reduce(
          (initial, [key, { forms }]) => {
            forms.forEach(({ fields }) => {
              fields.forEach(
                ({
                  columnName,
                  label: {
                    0: { actualLabel },
                  },
                }) => {
                  if (extractColumns.indexOf(columnName) > -1) {
                    initial[columnName] = {
                      actualLabel,
                    };
                  }
                },
              );
            });
            return initial;
          },
          {},
        );

console.log(result)```

答:
You can simplify and compact the code like so - using Object.values, includes, ternary operators, and simplified array destructuring.

let data={"section1":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section2":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test5","label":[{"actualLabel":"Test 5"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]},"section3":{"forms":[{"fields":[{"columnName":"test1","label":[{"actualLabel":"Test 1"}]},{"columnName":"test2","label":[{"actualLabel":"Test 2"}]},{"columnName":"test0","label":[{"actualLabel":"Test 0"}]}]},{"fields":[{"columnName":"test3","label":[{"actualLabel":"Test 3"}]},{"columnName":"test 4","label":[{"actualLabel":"Test 4"}]},{"columnName":"test10","label":[{"actualLabel":"Test 10"}]}]},{"fields":[{"columnName":"test15","label":[{"actualLabel":"Test 15"}]},{"columnName":"test6","label":[{"actualLabel":"Test 6"}]},{"columnName":"test7","label":[{"actualLabel":"Test 7"}]}]}]}};
let extractColumns = ['test1', 'test2', 'test7', 'test15'];

const result = Object.values(data).reduce((acc, { forms }) => {
  forms.forEach(({ fields }) => fields.forEach(({ columnName, label: [{ actualLabel }]}) => extractColumns.includes(columnName) ? acc[columnName] = { actualLabel } : null));
  return acc;
}, {});

console.log(result)```


问:
ReactJS Semantic UI dropdown onChange won't fire if the user selects the same item twice
I have a File menu that contains 3 options:

```<code>const fileOptions = [
  { key: 'open', icon: 'open folder outline', text: 'Open lesson', value: 'open' },
  { key: 'save', icon: 'save', text: 'Save lesson', value: 'save' },
  { key: 'delete', icon: 'delete', text: 'Delete lesson', value: 'delete' },
]
</code>```

Everything works fine but if I select for example "Save lesson" twice it will work the first time only (I'm using the onChange event). And that's because the value of the dropdown did not change. What event should I usr?

```<code>     <Button.Group color='teal'>
        <Dropdown

          className='button icon'
          floating
          options={fileOptions}
          trigger={<React.Fragment />}
          onChange={this.handleLessonMenu}
        />
      </Button.Group>
</code>```

答: Try using onClick event instead of onChange. So it will get triggered everytime you click the option.

Body:
I have a File menu that contains 3 options:

const fileOptions = [
  { key: 'open', icon: 'open folder outline', text: 'Open lesson', value: 'open' },
  { key: 'save', icon: 'save', text: 'Save lesson', value: 'save' },
  { key: 'delete', icon: 'delete', text: 'Delete lesson', value: 'delete' },
]

Everything works fine but if I select for example "Save lesson" twice it will work the first time only (I'm using the onChange event). And that's because the value of the dropdown did not change. What event should I usr?

     <Button.Group color='teal'>
        <Dropdown

          className='button icon'
          floating
          options={fileOptions}
          trigger={<React.Fragment />}
          onChange={this.handleLessonMenu}
        />
      </Button.Group>


问:
How can I apply CSS style changes just for one page?
I have two css files:

A main file (main.css)

A specific page file (page5.css). My page.css contains main.css (@import url(main.css));)

My main.css has this as one part of it that sets the height of the page

```<code>#content {
    background:url(../images/image.png) no-repeat;
    width:154px;
    height:356px;
    clear:both;
}
</code>```

This works fine for all the other pages, but at page 5, I need a little bit more height.

How would I go about doing it?

答:
Just re-define it somewhere after your @import directive:

```<code>#content { height: 456px }
</code>```

for identical CSS selectors, the latter rule overwrites the former.

Body:
I have two css files:

A main file (main.css)

A specific page file (page5.css). My page.css contains main.css (@import url(main.css));)

My main.css has this as one part of it that sets the height of the page

#content {
    background:url(../images/image.png) no-repeat;
    width:154px;
    height:356px;
    clear:both;
}

This works fine for all the other pages, but at page 5, I need a little bit more height.

How would I go about doing it?

Body:
Just re-define it somewhere after your @import directive:

#content { height: 456px }

for identical CSS selectors, the latter rule overwrites the former.


问:
Use NgClass with a custom Pipe
I'm trying to assign a custom class on a span based on a result given from a pipe trasform. Sadly, I'm not getting it to work.

Here's the scenario. I'm itering this object in a ngFor statement:

```<code>"documents": [
  {
    "document_ext": "pdf"
  } ,
  {
    "document_ext": "doc"
  }
]
</code>```

While itering I want to assign a custom class based on the document_ext. but this is causing me following error:

Error: Got interpolation ({{}}) where expression was expected at
  column 0 in [{{doc?.document_ext | documentaleType}}]

The html code:

```<code><ng-container *ngFor="let doc of documentList">
  <div class="row">
    <div class="doc-type">
      <span class="row-icon" [ngClass]="{{doc?.document_ext | documentaleType}}">
      </span>
     </div>
  </div>
</ng-container>
</code>```

And the simple pipe just return a standard value for now:

```<code>export class DocumentaleTypePipe {
    transform(ext: string): string {
        return "p3-018-dummy";
    }
}
</code>```

I don't want to call a function, that's why I've choose to use a pipe. What am I missing?

Any help is appreciated.

EDIT

Solved this way:

```<code><span class="row-icon" [ngClass]="[doc.document_ext ? (doc.document_ext | documentaleType) : 'p3-018-dummy']"></span>
</code>```

答:
You can't use a combination of [ngClass] and {{function()}} as in [ngClass]="{{doc?.document_ext | documentaleType}}", since both will make it an expression instead of just interpreting the text.

Try using [ngClass]="doc?.document_ext | documentaleType".

Title: Use NgClass with a custom Pipe

Body:
I'm trying to assign a custom class on a span based on a result given from a pipe trasform. Sadly, I'm not getting it to work.

Here's the scenario. I'm itering this object in a ngFor statement:

"documents": [
  {
    "document_ext": "pdf"
  } ,
  {
    "document_ext": "doc"
  }
]

While itering I want to assign a custom class based on the document_ext. but this is causing me following error:

Error: Got interpolation ({{}}) where expression was expected at
  column 0 in [{{doc?.document_ext | documentaleType}}]

The html code:

<ng-container *ngFor="let doc of documentList">

</ng-container>

And the simple pipe just return a standard value for now:

export class DocumentaleTypePipe {
    transform(ext: string): string {
        return "p3-018-dummy";
    }
}

I don't want to call a function, that's why I've choose to use a pipe. What am I missing?

Any help is appreciated.

EDIT

Solved this way:


问:
Get number of days balance was negative
I would like to get the number of days the account went to a negative balance.

I have the following Balance table.

```<code>|AccNo |    Amount      | Date
------------------------------------
|1     |    -8775.76    | 2019-05-31
|1     |    -697.05     | 2019-05-30
|1     |    -3504.52    | 2019-05-29
|1     |   +1783.67     | 2019-05-28
|1     |    -14204.55   | 2019-05-27

  SELECT DATEDIFF(DAY, AccountB.Date, GETDATE()) AS DaysInDebit
  FROM (SELECT TOP 1 Date
        FROM Balance WHERE AccNo = 1
        AND Amount > 0
        ORDER BY Date DESC
       ) AS AccountB
  ORDER BY AccountB.Date DESC
</code>```

I am expecting to get 3 days where the account was in debt.
Result set from 2019-05-28 to 2019-05-31. Date Difference = 3

答:
You can do it by finding max() for the last positive balance.

```<code>select
    count(*) as NumberOfDays
from Balance
where [Date] > (select max([Date]) from Balance where Amount > 0 and AccNo = 1)
and AccNo = 1
</code>```

Title: Get number of days balance was negative

Body:
I would like to get the number of days the account went to a negative balance.

I have the following Balance table.

|AccNo |    Amount      | Date
------------------------------------
|1     |    -8775.76    | 2019-05-31
|1     |    -697.05     | 2019-05-30
|1     |    -3504.52    | 2019-05-29
|1     |   +1783.67     | 2019-05-28
|1     |    -14204.55   | 2019-05-27

  SELECT DATEDIFF(DAY, AccountB.Date, GETDATE()) AS DaysInDebit
  FROM (SELECT TOP 1 Date
        FROM Balance WHERE AccNo = 1
        AND Amount > 0
        ORDER BY Date DESC
       ) AS AccountB
  ORDER BY AccountB.Date DESC

I am expecting to get 3 days where the account was in debt.
Result set from 2019-05-28 to 2019-05-31. Date Difference = 3

Body:
You can do it by finding max() for the last positive balance.

select
    count(*) as NumberOfDays
from Balance
where [Date] > (select max([Date]) from Balance where Amount > 0 and AccNo = 1)
and AccNo = 1


问:
How should i inject Autorest Client with TokenProvider using autofac in asp.net mvc 5?
I want to properly inject an autorest client dependency that uses an api(which users will have their own token to use after login but they can use api before login for some methods token is not required) by using autofac. I know it is not directly a autorest question it is more about autofac but i I want to give the exact example, so i can get a better recommendation(maybe i am doing all wrong it is a conceptual problem). I looked out for some examples i found some but in all of them they were implementation just for one user they didnt use tokenprovider they just passed a foreknown token(which is not a token for user it is for application).

What i tried is registering  autorest client with a wrapped parameter(already registered multiple dependencies take each other as constructor parameters) into container.

This is how I register my services :

```<code>protected void Application_Start()
{

    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    var sp = ServicePointManager.FindServicePoint(new Uri(ConfigurationManager.AppSettings["WebApiBaseUrl"]));
    sp.ConnectionLeaseTimeout = 60 * 1000; // 1 minute
    builder.Register(c => new HttpContextWrapper(HttpContext.Current))
        .As<HttpContextBase>()
        .InstancePerRequest();
    builder.RegisterType<TokenProvider>().As<ITokenProvider>().InstancePerLifetimeScope();
    builder.RegisterType<TokenCredentials>().Keyed<ServiceClientCredentials>("credentials").InstancePerLifetimeScope();
    builder.RegisterType<WebApiClient>()
           .As<IWebApiClient>()
           .WithParameter("baseUri", new Uri(ConfigurationManager.AppSettings["WebApiBaseUrl"])
           ).WithParameter("credentials",
              new ResolvedParameter(
   (pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
   (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name))
   ).SingleInstance();

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

}
</code>```

and my services :

```<code>public partial class WebApiClient : ServiceClient<WebApiClient>, IWebApiClient
{

    public WebApiClient(System.Uri baseUri, ServiceClientCredentials credentials = null, params DelegatingHandler[] handlers) : this(handlers)
    {
        if (baseUri == null)
        {
            throw new System.ArgumentNullException("baseUri");
        }

        BaseUri = baseUri;

        if (credentials != null)
        {
            Credentials = credentials;
            Credentials.InitializeServiceClient(this);
        }
    }
}
public class TokenProvider : ITokenProvider
{
    private readonly HttpContextBase _context;

    public TokenProvider(HttpContextBase context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
    {
        // this should be async i know(another topic to ask in mvc 5)
        var token =_context.Session["ServiceToken"]?.ToString();
        if (string.IsNullOrWhiteSpace(token))
        {
            throw new InvalidOperationException("Could not get an access token from HttpContext.");
        }

        return new AuthenticationHeaderValue("Bearer", token);
    }
}

public class TokenCredentials : ServiceClientCredentials
{
    //I want to use this constructor
    public TokenCredentials(ITokenProvider tokenProvider);
}
</code>```

This is the exception I get

Inner exception
  Unable to cast object of type Autofac.Core.ResolvedParameter to type Microsoft.Rest.ServiceClientCredentials.

答:
Unable to cast object of type Autofac.Core.ResolvedParameter to type Microsoft.Rest.ServiceClientCredentials.

means that you are using a ResolvedParameter object whereas a ServiceClientCredentials is expected.

In your code there is

```<code>.WithParameter("credentials",
     new ResolvedParameter(
       (pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
       (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name))
     )
</code>```

The WithParameter has 3 overloads :

WithParameter(string parameterName, object parameterValue) : when you know the name of the parameter and you can provide it at registration time. Autofac will create a NamedParameter object for you.

WithParameter(Func<ParameterInfo, IComponentContext, bool> parameterSelector, Func<ParameterInfo, IComponentContext, object> valueProvider) : When you don't know the name of the parameter and/or when you can't provide the value at registration time. Autofac will create a ResolvedParameter object for you.

WithParameter(Parameter parameter) : to provide a Parameter object that you create yourself.

In your case your are using the first option. Autofac will create a NamedParameter for you and you provide a ResolvedParameter as a value.

To fix the error you should not use the first overload this way but you can use the second one :

```<code>.WithParameter((pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
               (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name)))
</code>```

Body:
I want to properly inject an autorest client dependency that uses an api(which users will have their own token to use after login but they can use api before login for some methods token is not required) by using autofac. I know it is not directly a autorest question it is more about autofac but i I want to give the exact example, so i can get a better recommendation(maybe i am doing all wrong it is a conceptual problem). I looked out for some examples i found some but in all of them they were implementation just for one user they didnt use tokenprovider they just passed a foreknown token(which is not a token for user it is for application).

What i tried is registering  autorest client with a wrapped parameter(already registered multiple dependencies take each other as constructor parameters) into container.

This is how I register my services :

protected void Application_Start()
{

    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    var sp = ServicePointManager.FindServicePoint(new Uri(ConfigurationManager.AppSettings["WebApiBaseUrl"]));
    sp.ConnectionLeaseTimeout = 60 * 1000; // 1 minute
    builder.Register(c => new HttpContextWrapper(HttpContext.Current))
        .As<HttpContextBase>()
        .InstancePerRequest();
    builder.RegisterType<TokenProvider>().As<ITokenProvider>().InstancePerLifetimeScope();
    builder.RegisterType<TokenCredentials>().Keyed<ServiceClientCredentials>("credentials").InstancePerLifetimeScope();
    builder.RegisterType<WebApiClient>()
           .As<IWebApiClient>()
           .WithParameter("baseUri", new Uri(ConfigurationManager.AppSettings["WebApiBaseUrl"])
           ).WithParameter("credentials",
              new ResolvedParameter(
   (pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
   (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name))
   ).SingleInstance();

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

}

and my services :

public partial class WebApiClient : ServiceClient<WebApiClient>, IWebApiClient
{

    public WebApiClient(System.Uri baseUri, ServiceClientCredentials credentials = null, params DelegatingHandler[] handlers) : this(handlers)
    {
        if (baseUri == null)
        {
            throw new System.ArgumentNullException("baseUri");
        }

        BaseUri = baseUri;

        if (credentials != null)
        {
            Credentials = credentials;
            Credentials.InitializeServiceClient(this);
        }
    }
}
public class TokenProvider : ITokenProvider
{
    private readonly HttpContextBase _context;

    public TokenProvider(HttpContextBase context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
    {
        // this should be async i know(another topic to ask in mvc 5)
        var token =_context.Session["ServiceToken"]?.ToString();
        if (string.IsNullOrWhiteSpace(token))
        {
            throw new InvalidOperationException("Could not get an access token from HttpContext.");
        }

        return new AuthenticationHeaderValue("Bearer", token);
    }
}

public class TokenCredentials : ServiceClientCredentials
{
    //I want to use this constructor
    public TokenCredentials(ITokenProvider tokenProvider);
}

This is the exception I get

Inner exception
  Unable to cast object of type Autofac.Core.ResolvedParameter to type Microsoft.Rest.ServiceClientCredentials.

Body:
Unable to cast object of type Autofac.Core.ResolvedParameter to type Microsoft.Rest.ServiceClientCredentials.

means that you are using a ResolvedParameter object whereas a ServiceClientCredentials is expected.

In your code there is

.WithParameter("credentials",
     new ResolvedParameter(
       (pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
       (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name))
     )

The WithParameter has 3 overloads :

WithParameter(string parameterName, object parameterValue) : when you know the name of the parameter and you can provide it at registration time. Autofac will create a NamedParameter object for you.

WithParameter(Func<ParameterInfo, IComponentContext, bool> parameterSelector, Func<ParameterInfo, IComponentContext, object> valueProvider) : When you don't know the name of the parameter and/or when you can't provide the value at registration time. Autofac will create a ResolvedParameter object for you.

WithParameter(Parameter parameter) : to provide a Parameter object that you create yourself.

In your case your are using the first option. Autofac will create a NamedParameter for you and you provide a ResolvedParameter as a value.

To fix the error you should not use the first overload this way but you can use the second one :

.WithParameter((pi, ctx) => pi.ParameterType == typeof(ServiceClientCredentials),
               (pi, ctx) => ctx.ResolveKeyed<ServiceClientCredentials>(pi.Name)))


问:
angular 6 How to populate the values on ng select multiple option
I have used ng-select for multiple option and i want populate some values on ng-select.
 I have passed array values in ngmodel but its not working.
Please guide to achieve this

Here is my code

```<code>companyArr = [10];
companyList = array

<ng-select [items]="companyList" bindLabel="brand_name" bindValue="id"
           [multiple]="true"
           [(ngModel)]="companyArr" (change)="onSelectCompany($event)"
           name="companyArr"
           [ngClass]="{ 'is-invalid': f.submitted && companyArr.invalid }" required>
</ng-select>
</code>```

答:
if you want to get the values which you are selected with multiple options then you need to store the [value] in an obj, and then you can bind it in typescript...
In my situation I wanted firstname and lastname of an employee which are differnt fields. So I get the value in obj and then concatinate them in typescript so i got my selected employee name As 'Fistname Lastname'...</p>

Body:
I have used ng-select for multiple option and i want populate some values on ng-select.
 I have passed array values in ngmodel but its not working.
Please guide to achieve this

Here is my code

companyArr = [10];
companyList = array

<ng-select [items]="companyList" bindLabel="brand_name" bindValue="id"
           [multiple]="true"
           [(ngModel)]="companyArr" (change)="onSelectCompany($event)"
           name="companyArr"
           [ngClass]="{ 'is-invalid': f.submitted && companyArr.invalid }" required>
</ng-select>


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答: A token is a terminal in a grammar, a sequence of one or more symbol(s) that is defined by the sequence itself, ie it does not derive from any other production defined in the grammar.</p>

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}


问:
Entering additional rows in dataframe as mid points between values of adjacent existing rows
Say you have the following time series dataset in r:

```<code>n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2
</code>```

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

```<code>  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2
</code>```

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

```<code>  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2
</code>```

Body:
Say you have the following time series dataset in r:

n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2

Body:
Another solution:

library(tidyverse)

df %>%
  slice(rep(1:n(), each = 2)) %>%
  mutate_at(c("Time", "Temper"), function(x) {
    replace(x, seq(2, n(), 2),
            (x + (1 / 3) * (lead(x) - lag(x)))[seq(2, n(), 2)])
  }) %>%
  mutate_at(c("Time", "Temper"), round, 2) %>%
  slice(-n())
#>   Day Time Temper
#> 1 Mon 1.00   3.00
#> 2 Mon 1.33   3.33
#> 3 Mon 2.00   4.00
#> 4 Mon 2.33   3.33
#> 5 Mon 3.00   2.00