问:
How to find a component that is not there on mount?
I have this component called "Paginator", but it's not available on mount:

```<code><Col xs='4'>
    {
        (() => {
            if (this.state.gridApi) {
                return <Paginator pages={this.state.gridApi.paginationGetTotalPages()} gridApi={this.state.gridApi} />
            }
            return <></>
        })()
    }
</Col>
</code>```

How can I test it if its not there on mount?

```<code>import React from 'react';
import RelatorioVendas from './RelatorioVendas';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { AgGridReact } from 'ag-grid-react/lib/agGridReact';
import Paginator from '../../components/General/Paginator';

import { Provider } from 'react-redux';
import { SnackbarProvider } from 'notistack';
import store from '../../store';

configure({ adapter: new Adapter() });

test('renders the "RelatorioVendas" component.', () => {
    const wrapper = mount(
        <Provider store={store}>
            <SnackbarProvider>
                <RelatorioVendas />
            </SnackbarProvider>
        </Provider>
    );
    expect(wrapper.find(Paginator)).toHaveLength(1);
});
</code>```

How can I "wait" for the state to change and finally render the component?

答:
you should be able to setState of a mounted/shallowed component like this:

```<code>it('should render pagination if gridApi exists', () => {
    const relatorioVendas = shallow(< RelatorioVendas />);
    relatorioVendas.setState({ gridApi: {} });
    expect(relatorioVendas.find(Paginator)).toHaveLength(1);
});
</code>```

Body:
I have this component called "Paginator", but it's not available on mount:

<Col xs='4'>
    {
        (() => {
            if (this.state.gridApi) {
                return <Paginator pages={this.state.gridApi.paginationGetTotalPages()} gridApi={this.state.gridApi} />
            }
            return <></>
        })()
    }
</Col>

How can I test it if its not there on mount?

import React from 'react';
import RelatorioVendas from './RelatorioVendas';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { AgGridReact } from 'ag-grid-react/lib/agGridReact';
import Paginator from '../../components/General/Paginator';

import { Provider } from 'react-redux';
import { SnackbarProvider } from 'notistack';
import store from '../../store';

configure({ adapter: new Adapter() });

test('renders the "RelatorioVendas" component.', () => {
    const wrapper = mount(
        <Provider store={store}>
            <SnackbarProvider>
                <RelatorioVendas />
            </SnackbarProvider>
        </Provider>
    );
    expect(wrapper.find(Paginator)).toHaveLength(1);
});

How can I "wait" for the state to change and finally render the component?

Body:
you should be able to setState of a mounted/shallowed component like this:

it('should render pagination if gridApi exists', () => {
    const relatorioVendas = shallow(< RelatorioVendas />);
    relatorioVendas.setState({ gridApi: {} });
    expect(relatorioVendas.find(Paginator)).toHaveLength(1);
});


来源: stackexchange

问:
Excluding multiple urls in Strpos- why doesn't it work?
I'm trying to exclude several urls from appending a nofollow rule using strpos but it only works with 1 url, I can't get it to exclude all the urls I need to include.

This is the code that I've tried:

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false && strpos( $href, 'https://www.examplelink2.com' ) === false && strpos( $href, 'https://www.examplelink3.com' ) === false && strpos( $href, 'https://examplelink4.to' ) === false) {
       $nofollow = '';
   }

   return $nofollow;
}
</code>```

I've tried it with == false and !== false as well and those don't seem to work.

This one DOES work, but it only excludes a single domain, I need to be able to exclude 5 in all.

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

    if ( strpos( $href, 'http://your-domain.here' ) !== false ) {
        $nofollow = 'rel="dofollow"';
    }

    return $nofollow;
}
</code>```

What is the correct strpos syntax to include multiple urls,

```<code>https://www.examplelink1.com AND/OR
https://www.examplelink2.com AND/OR
https://www.examplelink3.com AND/OR
https://www.examplelink4.com
</code>```

答:
Sorry, I want it to DOFOLLOW those 5 links and NOFOLLOW everything else.

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );

function my_custom_bbpress_nofollow( $nofollow, $href ) {
$nofollow = '';
if ( strpos( $href, 'https://www.link1.com' )!== false ||
     strpos( $href, 'https://www.link2.com' ) !== false ||
     strpos( $href, 'https://www.link3.com' ) !== false ||
     strpos( $href, 'https://www.link4.com' ) === false
    ) {
   $nofollow = 'rel="nofollow" target="_blank"';
}

return $nofollow;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to exclude several urls from appending a nofollow rule using strpos but it only works with 1 url, I can't get it to exclude all the urls I need to include.

This is the code that I've tried:

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false && strpos( $href, 'https://www.examplelink2.com' ) === false && strpos( $href, 'https://www.examplelink3.com' ) === false && strpos( $href, 'https://examplelink4.to' ) === false) {
       $nofollow = '';
   }

   return $nofollow;
}

I've tried it with == false and !== false as well and those don't seem to work.

This one DOES work, but it only excludes a single domain, I need to be able to exclude 5 in all.

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

    if ( strpos( $href, 'http://your-domain.here' ) !== false ) {
        $nofollow = 'rel="dofollow"';
    }

    return $nofollow;
}

What is the correct strpos syntax to include multiple urls,

https://www.examplelink1.com AND/OR
https://www.examplelink2.com AND/OR
https://www.examplelink3.com AND/OR
https://www.examplelink4.com

Body:
Sorry, I want it to DOFOLLOW those 5 links and NOFOLLOW everything else.

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );

function my_custom_bbpress_nofollow( $nofollow, $href ) {
$nofollow = '';
if ( strpos( $href, 'https://www.link1.com' )!== false ||
     strpos( $href, 'https://www.link2.com' ) !== false ||
     strpos( $href, 'https://www.link3.com' ) !== false ||
     strpos( $href, 'https://www.link4.com' ) === false
    ) {
   $nofollow = 'rel="nofollow" target="_blank"';
}

return $nofollow;
}


问:
How to combine two plots from two data frame in one plot in ggplot?
I have two separate datasets with the same variables and already created two separate plots. I want to combine them in one plot.

Here are the codes for each plot:

```<code>##For tb2 :
my_data2$Date<- as.Date(my_data2$Date) #factor to date
tb2 <- my_data2
str(tb2)
tb2 <- tb2 %>% mutate (Month = month(Date, label = TRUE), Year =
as.integer(year(Date)))

## plotting bar chart
tb2_plot <- tb2 %>% ggplot(aes(factor(Month), GWQ)) +
geom_bar(stat = "identity")+ facet_wrap(vars(Year), nrow = 1)+
theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 9))
</code>```

```<code>##For tb:
my_data$Date<- as.Date(my_data$Date) #factor to date
tb <- my_data
str(tb)
tb <- tb %>% mutate (Month = month(Date, label = TRUE), Year =
as.integer(year(Date)))
## plotting bar chart
tb_plot <- tb %>% ggplot(aes(factor(Month), GWQ))+ geom_bar(stat =
 "identity")+ facet_wrap(vars(Year), nrow = 1)+ theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 9))
</code>```

答:
You need to combine the data prior to plotting.

Try:

tb_all = bind_rows(tb %>% mutate(category = "A"), tb2 %>% mutate(category = "B"))

If you want to distinguish between the two groups of data in the plot, you can for instance add fill = category to your aes() call.

Body:
I have two separate datasets with the same variables and already created two separate plots. I want to combine them in one plot.

Here are the codes for each plot:

##For tb2 :
my_data2$Date<- as.Date(my_data2$Date) #factor to date
tb2 <- my_data2
str(tb2)
tb2 <- tb2 %>% mutate (Month = month(Date, label = TRUE), Year =
as.integer(year(Date)))

## plotting bar chart
tb2_plot <- tb2 %>% ggplot(aes(factor(Month), GWQ)) +
geom_bar(stat = "identity")+ facet_wrap(vars(Year), nrow = 1)+
theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 9))

##For tb:
my_data$Date<- as.Date(my_data$Date) #factor to date
tb <- my_data
str(tb)
tb <- tb %>% mutate (Month = month(Date, label = TRUE), Year =
as.integer(year(Date)))
## plotting bar chart
tb_plot <- tb %>% ggplot(aes(factor(Month), GWQ))+ geom_bar(stat =
 "identity")+ facet_wrap(vars(Year), nrow = 1)+ theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 9))


问:
How to navigate from fragment to activity when class Extends YouTubeBaseActivity
Cannot get my floating button to successfully navgiate from an Activity page to a fragment page. I believe it is because the activity page extends YoutubeBaseActivity and not AppCompat so the getSupportFragmentManager() method is not found.

Can someone please help me work around this?

```<code>public class ActivityDetailsActivity extends YouTubeBaseActivity {

@Override
        public void onClick(View v) {

            ActivitiesFragment fragment = new ActivitiesFragment();
            fragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragment).commit();
</code>```

答: You can use getFragmentManager() instead getSupportFragmentManager().

Body:
Cannot get my floating button to successfully navgiate from an Activity page to a fragment page. I believe it is because the activity page extends YoutubeBaseActivity and not AppCompat so the getSupportFragmentManager() method is not found.

Can someone please help me work around this?

public class ActivityDetailsActivity extends YouTubeBaseActivity {

@Override
        public void onClick(View v) {

            ActivitiesFragment fragment = new ActivitiesFragment();
            fragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragment).commit();


问:
How to enable tracing profiling in jvisualvm?
I've read that jvisualVm can do tracing profile.

So I ran jvisualVm on my local pc and I see following:

According the materials I read that jvisualVm allows to use tracing profiling on Profiler tab and it must look like:

But as you can see I don't have it. I tried to find button to show that tab but I was not successful.

How can I enable it?

P.S.

According the @Alexandar Petrov answer I tried to add plugun manually so I visited https://visualvm.github.io/uc/release14/updates.html and downloaded Tracer-JVM Probes The next step was to add file I downloaded:

but when I select file and click open - nothing happens - neither error nor anything else.

答:
Go to https://visualvm.github.io/plugins.html you will find the Tracer plugin there.

Here is a download link with all plugins for Java 8. What you need to download is under Tracer probes. The one that you 100% need is Tracer-JVM Probes the rest is optional.

https://visualvm.github.io/uc/8u131/updates.html

After you donwload you need to go to Tools->Plugins->Downloaded->Add Plugin and select the nbm file with the tracer plugin. When you do that you will get a screen where it gives you the list of the dependencies. You need to download all the dependencies and select them together with the plugin for installation as it is showed on this screenshot:

After you have installed it the java visual VM will get restarted and you will be able to see the tracer in a separate tab. Here is my screen notice tha tracer tab besides the Sampler tab:


问:
pandas: taking the diff of every second row
I have a dataframe that looks like this

```<code>                       price    signal
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell
</code>```

I want to create a profit column populated with the difference of the previous buy/sell pair

```<code>                       price    signal   profit
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell     -7.88
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell      7.99
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell      2.29
</code>```

How might I best go about this?

Alternative or more efficient approaches to calculating profit also welcome

答:
IIUC using cumsum create the group key , then diff

```<code>df.groupby(df.signal.eq('buy').cumsum())['price'].diff()
</code>```

Body:
I have a dataframe that looks like this

                       price    signal
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell

I want to create a profit column populated with the difference of the previous buy/sell pair

                       price    signal   profit
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell     -7.88
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell      7.99
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell      2.29

How might I best go about this?

Alternative or more efficient approaches to calculating profit also welcome

Body:
IIUC using cumsum create the group key , then diff

df.groupby(df.signal.eq('buy').cumsum())['price'].diff()


问:
F# async function containing while loop with async calls fail to compile
Not really sure why my code fails to compile, the error I am having:
Incomplete structured construct at or before this point in expression

let resendErrorsAsync (bus: IBus) (errorQueueName: string) =
async {
    let! errorQueue = bus.Advanced.QueueDeclareAsync(errorQueueName) |> Async.AwaitTask
    let! message = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
    while message <> null do
        let utf8Body = Encoding.UTF8.GetString(message.Body)
        let error = JsonConvert.DeserializeObject<Error>(utf8Body)
        let errorBodyBytes = Encoding.UTF8.GetBytes(error.Message)
        let! exchange = bus.Advanced.ExchangeDeclareAsync(error.Exchange, "topic") |> Async.AwaitTask
        let! message = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
}
```

It seems to be related to my two async calls in the while loop, not really sure why though.

答:
You can't end a block with a let!, there has to be a body after it; that's the reason for the syntax error.

The message you're defining on the last line is a different variable to the one tested in the while condition. It seems you want to mutate the message; for that, you have to explicitly create a mutable variable:

```<code>let resendErrorsAsync (bus: IBus) (errorQueueName: string) =
    async {
        let! errorQueue = bus.Advanced.QueueDeclareAsync(errorQueueName) |> Async.AwaitTask
        let! msg = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
        let mutable message = msg
        while message <> null do
            let utf8Body = Encoding.UTF8.GetString(message.Body)
            let error = JsonConvert.DeserializeObject<Error>(utf8Body)
            let errorBodyBytes = Encoding.UTF8.GetBytes(error.Message)
            let! exchange = bus.Advanced.ExchangeDeclareAsync(error.Exchange, "topic") |> Async.AwaitTask
            let! msg = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
            message <- msg
    }
</code>```

Body:
Not really sure why my code fails to compile, the error I am having:
Incomplete structured construct at or before this point in expression

let resendErrorsAsync (bus: IBus) (errorQueueName: string) =
async {
    let! errorQueue = bus.Advanced.QueueDeclareAsync(errorQueueName) |> Async.AwaitTask
    let! message = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
    while message <> null do
        let utf8Body = Encoding.UTF8.GetString(message.Body)
        let error = JsonConvert.DeserializeObject<Error>(utf8Body)
        let errorBodyBytes = Encoding.UTF8.GetBytes(error.Message)
        let! exchange = bus.Advanced.ExchangeDeclareAsync(error.Exchange, "topic") |> Async.AwaitTask
        let! message = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
}

It seems to be related to my two async calls in the while loop, not really sure why though.

Body:
You can't end a block with a let!, there has to be a body after it; that's the reason for the syntax error.

The message you're defining on the last line is a different variable to the one tested in the while condition. It seems you want to mutate the message; for that, you have to explicitly create a mutable variable:

let resendErrorsAsync (bus: IBus) (errorQueueName: string) =
    async {
        let! errorQueue = bus.Advanced.QueueDeclareAsync(errorQueueName) |> Async.AwaitTask
        let! msg = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
        let mutable message = msg
        while message <> null do
            let utf8Body = Encoding.UTF8.GetString(message.Body)
            let error = JsonConvert.DeserializeObject<Error>(utf8Body)
            let errorBodyBytes = Encoding.UTF8.GetBytes(error.Message)
            let! exchange = bus.Advanced.ExchangeDeclareAsync(error.Exchange, "topic") |> Async.AwaitTask
            let! msg = bus.Advanced.GetMessageAsync(errorQueue) |> Async.AwaitTask
            message <- msg
    }


问:
matplotlib ylim & TypeError: 'float' object is not callable
I have this nested list:

```<code>acc = [[3, 0.95804195804195802], [4, 0.965034965034965], [5, 0.97202797202797198], [6, 0.97202797202797198]]
</code>```

and this code which is supposed to plot those values and set the boundaries of the y-axis to 95 and 100:

```<code>import matplotlib.pyplot as plt

x_ = [x[0] for x in acc]
y_ = [x[1] for x in acc]

plt.figure(figsize=(8,6))
plt.scatter(x_, y_)
plt.ylim((95, 100))
plt.show()
</code>```

But I get this error, and I can't figure out why:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-193-5a9016a37585> in <module>()
     19 plt.figure(figsize=(8,6))
     20 plt.scatter(x_, y_)
---> 21 plt.ylim((95, 98))
     22 plt.show()

TypeError: 'float' object is not callable
</code>```

答:
from importlib import reload
reload(plt)

My matplotlib plots ran successfully when I added the above code. I had in a prior section coded:
import matplotlib.pyplot as plt

However it was necessary to add the reload coded for the later piece of code to run.

ContentLicense: CC BY-SA 3.0

Body:
I have this nested list:

acc = [[3, 0.95804195804195802], [4, 0.965034965034965], [5, 0.97202797202797198], [6, 0.97202797202797198]]

and this code which is supposed to plot those values and set the boundaries of the y-axis to 95 and 100:

import matplotlib.pyplot as plt

x_ = [x[0] for x in acc]
y_ = [x[1] for x in acc]

plt.figure(figsize=(8,6))
plt.scatter(x_, y_)
plt.ylim((95, 100))
plt.show()

But I get this error, and I can't figure out why:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-193-5a9016a37585> in <module>()
     19 plt.figure(figsize=(8,6))
     20 plt.scatter(x_, y_)
---> 21 plt.ylim((95, 98))
     22 plt.show()

TypeError: 'float' object is not callable


问:
Not able to create a cluster in Elasticsearch
I have configured two nodes to create a cluster. Both these nodes are working fine separately. When We join them together to form a cluster, Only single node is appearing in cluster.
The elasticsearch.yml of both node is mentioned below:

```<code>========Node-1======================
cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["NODE1-IP","NODE2-IP"]

===============Node-2==============

cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["NODE1-IP","NODE2-IP"]
</code>```

My Requirement is to create a cluster of two nodes and if node1(Master node) fails anyhow, node2 automatically starts working as a Master node.
I have searched a lot but can't find anything wrong in my configuration.

Please help!!!

答:
i think you have ip issue. try:</p>

```<code>========Node-1======================
cluster.name: "docker-cluster"
network.host: <instance1-ip>
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["<instance1-ip>","<instance2-ip>"]

===============Node-2==============

cluster.name: "docker-cluster"
network.host: <instance2-ip>
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["<instance1-ip>","<instance2-ip>"]
</code>```

Body:
I have configured two nodes to create a cluster. Both these nodes are working fine separately. When We join them together to form a cluster, Only single node is appearing in cluster.
The elasticsearch.yml of both node is mentioned below:

========Node-1======================
cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["NODE1-IP","NODE2-IP"]

===============Node-2==============

cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["NODE1-IP","NODE2-IP"]

My Requirement is to create a cluster of two nodes and if node1(Master node) fails anyhow, node2 automatically starts working as a Master node.
I have searched a lot but can't find anything wrong in my configuration.

Please help!!!

Body:
i think you have ip issue. try:

========Node-1======================
cluster.name: "docker-cluster"
network.host: <instance1-ip>
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["<instance1-ip>","<instance2-ip>"]

===============Node-2==============

cluster.name: "docker-cluster"
network.host: <instance2-ip>
http.port: 9200
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
discovery.zen.ping.unicast.hosts: ["<instance1-ip>","<instance2-ip>"]


问:
How to place a small square box across every td element having text in css?
I am working on a table in html in which I want to place a square box across every td element in css

```<code><tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"> <?php echo basename($file, ".mp4"); ?></td>
</tr>
</code>```

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

答:
How about using CSS pseudo element ?

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

tr {
  position: relative;
}

tr td {
  min-width: 30%;
  display: inline-block;
  text-align: center;
  border: 1px solid black;
}

tr:after {
  height: 20px;
  width: 40px;
  content: 'Box';
  position: absolute;
  border: 1px solid red;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
</table></code>```

Body:
I am working on a table in html in which I want to place a square box across every td element in css

    <?php echo $program["series_title"]; ?>
    <?php echo $program["episode_title"]; ?>
    <?php echo $program["description"]; ?>
    <?php echo $program["series_title_fr"]; ?>
    <?php echo $program["episode_title_fr"]; ?>
    <?php echo $program["description_fr"]; ?>
     <?php echo basename($file, ".mp4"); ?>

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

Body:
How about using CSS pseudo element ?

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

tr {
  position: relative;
}

tr td {
  min-width: 30%;
  display: inline-block;
  text-align: center;
  border: 1px solid black;
}

tr:after {
  height: 20px;
  width: 40px;
  content: 'Box';
  position: absolute;
  border: 1px solid red;
  right: 0;
}

<table>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
  <tr>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
  </tr>
</table>


问:
Correct way to set html div position when inserting html via ajax
I am dynamically building html in javascript.  This will then be inserted into an element.  What is the correct way to set the top, left, width and height properties within the html that I am creating.  My current technique works in IE, but not Chrome or Safari.  This is how I'm currently doing it (controlgroup is an object containing my properties):

```<code>html += '<div id="' + controlgroup.id + '" class="controlgroup ui-widget-content"';
html += ' style="{';
html += 'top:' + controlgroup.top + '; left:' + controlgroup.left + ';';
html += 'width:' + controlgroup.width + '; height:' + controlgroup.height + ';';
html += '}">';
html += 'cg:' + controlgroup.id + ' ' + controlgroup.left + ',' + controlgroup.top;
html += '</div>';
</code>```

I then do this:

```<code>$('#formcontainer').html(html);
</code>```

I need the ability to specify exact coordinates, so I can't use 'predefined' css classes here.  Thanks very much.

答:
1) You'll want to make that you are using left, right, height, and width values that have px attached. So instead of setting width:50; set it to width:50px;.

2) You'll want to add position:relative; to your style.

3) The {} brackets are not needed

Working Demo: http://jsfiddle.net/Jaybles/6fbvT/2/

Body:
I am dynamically building html in javascript.  This will then be inserted into an element.  What is the correct way to set the top, left, width and height properties within the html that I am creating.  My current technique works in IE, but not Chrome or Safari.  This is how I'm currently doing it (controlgroup is an object containing my properties):

html += '
';
html += 'cg:' + controlgroup.id + ' ' + controlgroup.left + ',' + controlgroup.top;
html += '
';

I then do this:

$('#formcontainer').html(html);

I need the ability to specify exact coordinates, so I can't use 'predefined' css classes here.  Thanks very much.


问:
Question about IIS logging and time degradation
For years I always use IIS Looging always active on my sites. I currently use Windows Server 2008 R2 and Windows Server 2012. The official information I follow is this:

https://learn.microsoft.com/en-us/windows/desktop/http/iis-logging

I have looked for official information from Microsoft asking if it is recommended to always use this feature active or it is better to enable it only when you want to trace a problem.

Do you know if there is any official information?

Is there any study that says how much is the degradation of the
response times or general speed of the site to be active?

If I use an architecture with a Load Balancer F5 or A10 or Apache
that connect to my nodes, is it recommended to use Logging in the
Load Balancer always if it is deactivated in the nodes?

thanks!

答:
IIS logging is processed on separate threads from the gateway services and app pools. Which means that it will not degrade performance.

Don't just take my word for it.  If you want to confirm this, you can use a capacity testing tool (not recommended on your prod server, of course). Test your capacity with logging turned-on and logging turned-off. You will see that they are comparable.


问:
How can I select elements having specific siblings?
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

```<code><aside class="sidebar">
 <div id="leftside-navigation" class="nano">
  <ul class="nano-content">
   <li>
    <a href="index.html">
      <span>Home</span>
    </a>
   </li>
   <li class="sub-menu">
     <a href="javascript:void(0);">
       <span>Categories</span>
       <i class="arrow fa fa-angle-right pull-right"></i>
     </a>
     <ul>
       <li>
         <a href="index.html">
           <span>Home</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Lifestyles</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Technology</span>
         </a>
        </li>
      </ul>
    </li>
  </ul>
</div>
</code>```

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

答:
Another approach would be to not include the  tag in general. Just write the the text "Categories" within the
 and it will display in menu as normal.
Example:

```<code><li class="sub-menu">
       <span>Categories</span>
       <i class="arrow fa fa-angle-right pull-right"></i>
     <ul>
       <li>......
</code>```

Although you would need to add CSS if you want the cursor to change or if you want the text to be underlined for your  etc...

Body:
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

      Home

       Categories

           Home

           Lifestyles

           Technology

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

Body:
Another approach would be to not include the <a> tag in general. Just write the the text "Categories" within the <li class="sub-menu> and it will display in menu as normal.
Example:

<li class="sub-menu">
       <span>Categories</span>
       <i class="arrow fa fa-angle-right pull-right"></i>
     <ul>
       <li>......

Although you would need to add CSS if you want the cursor to change or if you want the text to be underlined for your <span> etc...


问:
Search all files in repository for pattern in Perforce
Is there a way to search a repository for a pattern that could be contained in one or more code files...

i.e I have the an application, that has a dev, UAT and Prod folders, under each of these there are multiple sub-folders for the code, resource [images, etc], binaries, etc. The program has maybe 100 different code file (.java, .cs, .net, .egl, etc). I would want to click on the application root and do a search for a specific string within each of these files, without having to click on each file.

Is this doable?

I have tried to do the suggestion at https://www.perforce.com/blog/vcs/how-add-grep-command-search-your-helix-core-depot but that only seems to look for file names not the content within a file.

TYIA

答:
I recommend you take a look at the silver searcher. https://github.com/ggreer/the_silver_searcher

It's a tool that lets your recursively walk over files and highlight matches. It's like grep, but works over a directory and provides line numbers of the results.


问:
Facebook bot messages not showing blank lines
I have created a chat bot using Microsoft bot framework and deployed it on Azure and linked it with my Facebook page. Everything is working fine but has a minor issue that, One of the messages send by the bot has a combination of 2-3 different lines, I want to show those 3 lines separated by blank lines  so I have added escape sequence "\n\n" between the lines.

```<code>"Line1\n\nLine2\n\nLine3"
</code>```

This works fine when I testes it in Azure web chat but Facebook chat window don't display the blank lines, Can any one help me with this?Thanks in Advance.

Currently face Display message like

```<code>Line1
Line2
Line3
</code>```

I want to show it as

```<code>Line 1

Line 2

Line 3
</code>```

答:
Your message text is being run through a rather aggressive Markdown parser that's stripping away extra line breaks. You have a few options for how to deal with this.

Option 1

If you set the text as channel data instead of the actual activity text, it won't be run through the Markdown parser:

var text = "Line1\n\nLine2\n\nLine3";
var activity = turnContext.Activity.CreateReply();
activity.ChannelData = new { text };
await turnContext.SendActivityAsync(activity);
```

<h2>Option 2</h2>

<p>If you set the text format to plain, the text won't be run through the Markdown parser:</p>

<pre class="lang-cs prettyprint-override"><code>var text = "Line1\n\nLine2\n\nLine3";
var activity = turnContext.Activity.CreateReply(text);
activity.TextFormat = TextFormatTypes.Plain;
await turnContext.SendActivityAsync(activity);
</code>```

Option 3

If you're using channel data for something else and you don't want to set the text format to plain, you can always use
 instead of \n:

var text = "Line1

Line2

Line3";
```

Body:
I have created a chat bot using Microsoft bot framework and deployed it on Azure and linked it with my Facebook page. Everything is working fine but has a minor issue that, One of the messages send by the bot has a combination of 2-3 different lines, I want to show those 3 lines separated by blank lines  so I have added escape sequence "\n\n" between the lines.

"Line1\n\nLine2\n\nLine3"

This works fine when I testes it in Azure web chat but Facebook chat window don't display the blank lines, Can any one help me with this?Thanks in Advance.

Currently face Display message like

Line1
Line2
Line3

I want to show it as

Line 1

Line 2

Line 3

Body:
Your message text is being run through a rather aggressive Markdown parser that's stripping away extra line breaks. You have a few options for how to deal with this.

Option 1

If you set the text as channel data instead of the actual activity text, it won't be run through the Markdown parser:

var text = "Line1\n\nLine2\n\nLine3";
var activity = turnContext.Activity.CreateReply();
activity.ChannelData = new { text };
await turnContext.SendActivityAsync(activity);

Option 2

If you set the text format to plain, the text won't be run through the Markdown parser:

var text = "Line1\n\nLine2\n\nLine3";
var activity = turnContext.Activity.CreateReply(text);
activity.TextFormat = TextFormatTypes.Plain;
await turnContext.SendActivityAsync(activity);

Option 3

If you're using channel data for something else and you don't want to set the text format to plain, you can always use <br/> instead of \n:

var text = "Line1<br/><br/>Line2<br/><br/>Line3";


问:
How to get the URI scheme of any app for AppLinks/universal linking?
I need to open a third-party app from my react native mobile app. I understand that this is called universal linking on iOS and AppLink on Android.

I have done a lot of research for this, and I have been able to set up a link to the third party app on the app store. Now I just need to get my app to open up the app if the user has it installed. That requires the URI scheme of the other app, though.

My question is, how do I get the URI scheme to this third party app? Rather, how do I get the URI scheme of any app? I know the URI scheme of the twitter app is 'twitter://app', but the app I am trying to link to is way more niche than twitter or other popular apps, so there is no help for this sort of thing online.

Any tips?

答:
Finding the URL scheme of an iOS app

Due to Apple's tendency for secrecy, it's not easy to find the URL scheme of an iOS app. But it can be done. Here's how I do it, using a Mac app called iMazing.

Launch iMazing, select a connected iOS device, click Apps:

In the footer of the window, click Manage Apps:

Select the app you're interested in , then select Export .IPA menu item. Note: You may need to download the app first.

The saved file will have the .ipa extension. Change the extension to .zip, and unzip the file. You now have a directory with the name matching the app's name.

Assuming "asana" is the app name, open the file "asana/Payload/asana.app/Info.plist" in a text editor, and search for a section that contains "CFBundleURLSchemes". Assuming the app contains CFBundleURLSchemes (they are optional), it should look something like this:

The URL scheme is in the <string>asana</string>, so the complete url scheme in this case is "asana://". Test that the URL launches the app by typing it into iOS Safari browser window. If it works, Safari should display an alert like this:

What About Apps Without CFBundleURLSchemes?

I haven't found a way to launch apps without CFBundleURLSchemes directly, but you can link to the app's page in the App Store, where the user can open the app with the Open button (or Get button if the app is not installed).

You will need to obtain the app page's URL from the App Store:

Open App Store, go to the app's page, click the share icon:

Click Copy Link:

The URL will look like this:

```<code>https://apps.apple.com/us/app/asana-organize-tasks-work/id489969512
</code>```

Clicking on that link in Safari will bring up the app page in the App Store.

Body:
Finding the URL scheme of an iOS app

Due to Apple's tendency for secrecy, it's not easy to find the URL scheme of an iOS app. But it can be done. Here's how I do it, using a Mac app called iMazing.

Launch iMazing, select a connected iOS device, click Apps:

In the footer of the window, click Manage Apps:

Select the app you're interested in , then select Export .IPA menu item. Note: You may need to download the app first.

The saved file will have the .ipa extension. Change the extension to .zip, and unzip the file. You now have a directory with the name matching the app's name.

Assuming "asana" is the app name, open the file "asana/Payload/asana.app/Info.plist" in a text editor, and search for a section that contains "CFBundleURLSchemes". Assuming the app contains CFBundleURLSchemes (they are optional), it should look something like this:

The URL scheme is in the <string>asana</string>, so the complete url scheme in this case is "asana://". Test that the URL launches the app by typing it into iOS Safari browser window. If it works, Safari should display an alert like this:

What About Apps Without CFBundleURLSchemes?

I haven't found a way to launch apps without CFBundleURLSchemes directly, but you can link to the app's page in the App Store, where the user can open the app with the Open button (or Get button if the app is not installed).

You will need to obtain the app page's URL from the App Store:

Open App Store, go to the app's page, click the share icon:

Click Copy Link:

The URL will look like this:

https://apps.apple.com/us/app/asana-organize-tasks-work/id489969512

Clicking on that link in Safari will bring up the app page in the App Store.


问:
How to use asyncio with ProcessPoolExecutor
I am searching for huge number of addresses on web, I want to use both asyncio and ProcessPoolExecutor in my task to quickly search the addresses.

```<code>    async def main():
        n_jobs = 3
        addresses = [list of addresses]
        _addresses = list_splitter(data=addresses, n=n_jobs)
        with ProcessPoolExecutor(max_workers=n_jobs) as executor:
             futures_list = []
             for _address in _addresses:
                futures_list +=[asyncio.get_event_loop().run_in_executor(executor, execute_parallel, _address)]

                for f in tqdm(as_completed(futures_list, loop=asyncio.get_event_loop()), total=len(_addresses)):
                results = await f

asyncio.get_event_loop().run_until_complete(main())
</code>```

expected:
I want to execute_parallel function should run in parallel.

error:

```<code>    Traceback (most recent call last):
  File "/home/awaish/danamica/scraping/skraafoto/aerial_photos_scraper.py", line 228, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "/home/awaish/danamica/scraping/skraafoto/aerial_photos_scraper.py", line 224, in main
    results = await f
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 533, in _wait_for_one
    return f.result()  # May raise f.exception().
TypeError: can't pickle coroutine objects
</code>```

答:
I'm not sure I'm answering the correct question, but it appears the intent of your code is to run your execute_parallel function across several processes using Asyncio. As opposed to using ProcessPoolExecutor, why not try something like using a normal multiprocessing Pool and setting up separate Asyncio loops to run in each. You might set up one process per core and let Asyncio work its magic within each process.

```<code>async def run_loop(addresses):
    loop = asyncio.get_event_loop()
    loops = [loop.create_task(execute_parallel, address) for address in addresses]
    loop.run_until_complete(asyncio.wait(loops))

def main():
    n_jobs = 3
    addresses = [list of addresses]
    _addresses = list_splitter(data=addresses, n=n_jobs)
    with multiprocessing.Pool(processes=n_jobs) as pool:
        pool.imap_unordered(run_loop, _addresses)
</code>```

I've used Pool.imap_unordered with great success, but depending on your needs you may prefer Pool.map or some other functionality. You can play around with chunksize or with the number of addresses in each list to achieve optimal results (ie, if you're getting a lot of timeouts you may want to reduce the number of addresses being processed concurrently)

Body:
I am searching for huge number of addresses on web, I want to use both asyncio and ProcessPoolExecutor in my task to quickly search the addresses.

    async def main():
        n_jobs = 3
        addresses = [list of addresses]
        _addresses = list_splitter(data=addresses, n=n_jobs)
        with ProcessPoolExecutor(max_workers=n_jobs) as executor:
             futures_list = []
             for _address in _addresses:
                futures_list +=[asyncio.get_event_loop().run_in_executor(executor, execute_parallel, _address)]

                for f in tqdm(as_completed(futures_list, loop=asyncio.get_event_loop()), total=len(_addresses)):
                results = await f

asyncio.get_event_loop().run_until_complete(main())

expected:
I want to execute_parallel function should run in parallel.

error:

    Traceback (most recent call last):
  File "/home/awaish/danamica/scraping/skraafoto/aerial_photos_scraper.py", line 228, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "/home/awaish/danamica/scraping/skraafoto/aerial_photos_scraper.py", line 224, in main
    results = await f
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 533, in _wait_for_one
    return f.result()  # May raise f.exception().
TypeError: can't pickle coroutine objects

Body:
I'm not sure I'm answering the correct question, but it appears the intent of your code is to run your execute_parallel function across several processes using Asyncio. As opposed to using ProcessPoolExecutor, why not try something like using a normal multiprocessing Pool and setting up separate Asyncio loops to run in each. You might set up one process per core and let Asyncio work its magic within each process.

async def run_loop(addresses):
    loop = asyncio.get_event_loop()
    loops = [loop.create_task(execute_parallel, address) for address in addresses]
    loop.run_until_complete(asyncio.wait(loops))

def main():
    n_jobs = 3
    addresses = [list of addresses]
    _addresses = list_splitter(data=addresses, n=n_jobs)
    with multiprocessing.Pool(processes=n_jobs) as pool:
        pool.imap_unordered(run_loop, _addresses)

I've used Pool.imap_unordered with great success, but depending on your needs you may prefer Pool.map or some other functionality. You can play around with chunksize or with the number of addresses in each list to achieve optimal results (ie, if you're getting a lot of timeouts you may want to reduce the number of addresses being processed concurrently)


问:
Entity Framework Core : Access parent from child
Might be a silly question but I'm a bit confused here.

I have a parent entity which contains a list of children.

```<code>public class Parent
{
    public int Id { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}
</code>```

EFcore will create a ParentId as a foreign key in the table Child.

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The ParentId is not available in the Child object.

Therefore, I cannot do something like:

```<code>var result = model.Child.Where(child => child.ParentId == 3);
</code>```

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.

答:
I would recommend you have both the references (child-parent and parent-children) in the respective classes as provided in @ScotG answer.

However,since you dont want that, in EF using lazy loading you can do something like model.Parents.Find(3).Children since from the Parent class you have the references of its children.

Body:
Might be a silly question but I'm a bit confused here.

I have a parent entity which contains a list of children.

public class Parent
{
    public int Id { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}

EFcore will create a ParentId as a foreign key in the table Child.

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The ParentId is not available in the Child object.

Therefore, I cannot do something like:

var result = model.Child.Where(child => child.ParentId == 3);

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.


问:
How to assign a class to divs based on a calulcated number
Is there a way to assign a class to a div based on a variable?

My example code:

```<code><button id="prev-item">Calculate</button>
<div class="main">
  <div class="item"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
</div>
</code>```

Example JS:

```<code>$("#prev-item").on("click", function(){
  var firstcal = $('.main').children().length;
  var actual = firstcal - 7
});
</code>```

The code I provided counts how many divs there are in .main and stores the number in firstcal and then actual takes the number in firstcal and subtracts 7 from it. In this example, it's 3.

I'm looking for a way to assign a class called .scroll to .items based on the number in the variable actual. So in this example, assign .scroll to the first three items in .main (item 1, item 2, item 3).

JS fiddle: https://jsfiddle.net/openbayou/xfa34qup/

答:
I hope this is what you wished for. It takes the amount of divs with the class "Item" and subtracts 7 from that number. Then assigns class "scroll" to the first (totalNumberOfDivs-7) divs and leave the rest as they are</p>

```<code><script type="text/javascript">
        $(document).ready(function(){
            $("#prev-item").click(function(){ //On button click
                var numberOfDivs = 0; //Set total number of divs
                var thisDivNumber = 0; //Set current div

                $(".item").each(function(){ //Figure out how many divs there are
                    numberOfDivs = numberOfDivs+1 //Add them up one by one
                });
                var assignClassToThese = numberOfDivs-7 //Total number of divs minus 7
                $(".item").each(function(){ //Loop through the divs to see which ones to assign the class to
                    thisDivNumber = thisDivNumber+1
                    if(thisDivNumber<=assignClassToThese){ //If this div number is less than or equal to the number of divs minus 7, then add class
                        $(this).addClass("scroll");
                    }
                });
            });
        });
    </script>
<button id="prev-item">Calculate</button>
<div class="main">
  <div class="item"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
  <div class="item">item 11</div>
</div>
</code>```

Body:
Is there a way to assign a class to a div based on a variable?

My example code:

<button id="prev-item">Calculate</button>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

item 9

item 10

Example JS:

$("#prev-item").on("click", function(){
  var firstcal = $('.main').children().length;
  var actual = firstcal - 7
});

The code I provided counts how many divs there are in .main and stores the number in firstcal and then actual takes the number in firstcal and subtracts 7 from it. In this example, it's 3.

I'm looking for a way to assign a class called .scroll to .items based on the number in the variable actual. So in this example, assign .scroll to the first three items in .main (item 1, item 2, item 3).

JS fiddle: https://jsfiddle.net/openbayou/xfa34qup/

Body:
I hope this is what you wished for. It takes the amount of divs with the class "Item" and subtracts 7 from that number. Then assigns class "scroll" to the first (totalNumberOfDivs-7) divs and leave the rest as they are

<script type="text/javascript">
        $(document).ready(function(){
            $("#prev-item").click(function(){ //On button click
                var numberOfDivs = 0; //Set total number of divs
                var thisDivNumber = 0; //Set current div

                $(".item").each(function(){ //Figure out how many divs there are
                    numberOfDivs = numberOfDivs+1 //Add them up one by one
                });
                var assignClassToThese = numberOfDivs-7 //Total number of divs minus 7
                $(".item").each(function(){ //Loop through the divs to see which ones to assign the class to
                    thisDivNumber = thisDivNumber+1
                    if(thisDivNumber<=assignClassToThese){ //If this div number is less than or equal to the number of divs minus 7, then add class
                        $(this).addClass("scroll");
                    }
                });
            });
        });
    </script>
<button id="prev-item">Calculate</button>
<div class="main">
  <div class="item"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
  <div class="item">item 11</div>
</div>


问:
My webscraper is returning an empty list when im using the correct CSS selector
I am attempting to scrape some data off of this particular url by using selenium or scrapy.

ive scraped other pages without issue, however when it comes to these particular urls the info im trying to scrape into a list is returning empty. I've used scrapy then moved on to using selenium but the result is the same. I'm also using pycharm and chromedriver.

The info im looking for in particular is all the different phone models on 'https://shop.freedommobile.ca/devices'. I print the list only to find out nothing was scraped from the site or rather scrape is successful but nothing was returned.

The same occurs when i try to scrape anything from here as well:

https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786074&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB

```<code>from selenium import webdriver

#open chrome browser and navigate to the webpage
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

#extract the names of the phones
phones = driver.find_elements_by_css_selector('.jXeFbj')

#counts phone and its model
for element in range(len(phones)):
    numPhone = int(element) + 1
    print("phone "+ str(numPhone) +" : " + phones[element].text)

#number of phones in total
sizeOfList = len(phones)
print(sizeOfList)
</code>```

Whats supposed to happen is pull all the model names of the phones into a list.

phones = ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...]

答:
To to scrape the all the model names of the phones into a list in the form of ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...] using Selenium you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://shop.freedommobile.ca/devices")
#using CSS_SELECTOR
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "h3[class^='deviceListItem__DeviceModel-']")))])
#using XPATH
#print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[starts-with(@class, 'deviceListItem__DeviceModel-')]")))])
</code>```

Console Output:

```<code>['iPhone XS Max', 'iPhone XS', 'iPhone XR', 'iPhone 8 Plus', 'iPhone 8', 'Galaxy S10+', 'Galaxy S10', 'Galaxy S10e', 'Galaxy Tab A 8 LTE', 'Galaxy Note9', 'Galaxy S9', 'Galaxy A8', 'G7 Power', 'Moto E5 Play', 'Pixel 3a', 'Pixel 3', 'Pixel 3 XL', 'Z557', 'G7 ThinQ', 'P30 lite', 'Mate 20 Pro', 'X Power 3', 'G8 ThinQ', 'Q Stylo +', 'GoFLIP', 'Bring Your', 'Own Device']
</code>```

Body:
I am attempting to scrape some data off of this particular url by using selenium or scrapy.

ive scraped other pages without issue, however when it comes to these particular urls the info im trying to scrape into a list is returning empty. I've used scrapy then moved on to using selenium but the result is the same. I'm also using pycharm and chromedriver.

The info im looking for in particular is all the different phone models on 'https://shop.freedommobile.ca/devices'. I print the list only to find out nothing was scraped from the site or rather scrape is successful but nothing was returned.

The same occurs when i try to scrape anything from here as well:

https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786074&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB

from selenium import webdriver

#open chrome browser and navigate to the webpage
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

#extract the names of the phones
phones = driver.find_elements_by_css_selector('.jXeFbj')

#counts phone and its model
for element in range(len(phones)):
    numPhone = int(element) + 1
    print("phone "+ str(numPhone) +" : " + phones[element].text)

#number of phones in total
sizeOfList = len(phones)
print(sizeOfList)

Whats supposed to happen is pull all the model names of the phones into a list.

phones = ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...]

Body:
To to scrape the all the model names of the phones into a list in the form of ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...] using Selenium you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Code Block:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://shop.freedommobile.ca/devices")
#using CSS_SELECTOR
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "h3[class^='deviceListItem__DeviceModel-']")))])
#using XPATH
#print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[starts-with(@class, 'deviceListItem__DeviceModel-')]")))])

Console Output:

['iPhone XS Max', 'iPhone XS', 'iPhone XR', 'iPhone 8 Plus', 'iPhone 8', 'Galaxy S10+', 'Galaxy S10', 'Galaxy S10e', 'Galaxy Tab A 8 LTE', 'Galaxy Note9', 'Galaxy S9', 'Galaxy A8', 'G7 Power', 'Moto E5 Play', 'Pixel 3a', 'Pixel 3', 'Pixel 3 XL', 'Z557', 'G7 ThinQ', 'P30 lite', 'Mate 20 Pro', 'X Power 3', 'G8 ThinQ', 'Q Stylo +', 'GoFLIP', 'Bring Your', 'Own Device']


问:
A file or folder with the name already exists Visual Studio
I try to add a new file to my source controlled solution and receive this message:

A file or folder with the name 'xxx' already exists. Please give a unique
name to the item you are adding, or delete the existing item first.

I'm 100% sure that there is no file with the given name.

So how do I get VS to add items again?

答:
Visual Studio 2017 v 15.9.12 ... I ran into this problem, but with no actual folder conflict. In my case, I had solution folder named NewOrder, and I was trying  to create a child project with the same name, but encountered the above error. I tried closing and reopening the solution (didn't restart VS so not sure if that would have made a difference) but here's what worked for me.

renamed solution folder

created my project. At this point, I got a strange error about not being able to locate the .net standard 2.0... so then I did restart VS, which fixed that problem

renamed the folder back

Now everything works fine. I restarted VS again just for good measure and all works fine now.


问:
Simultaneous printing from two printers in C#
I do not know how to do it. There are two printers. They need to print documents at the same time. Actually the algorithm can be; If you are printing something on the system, the two printers reprint this document.</p>

```<code>foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    if (printer == "ZJ-58")
    {

    }

    if (printer == "ZJ-58-2")
    {

    }
}
</code>```

答:
If you want to trigger the printing at the same time you could fire tasks in parallel (here I'm assuming you have a print function which returns a task). Eg:</p>

```<code>var printers = new List<object>();
var printerTasks = printers.Select(printer =>
{
     if (printer == "ZJ-58")
     {
          return printer.print();
     }

     if (printer == "ZJ-58-2")
     {
          return printer.print();
     }
 });
 Task.WaitAll(printerTasks);
</code>```

Body:
I do not know how to do it. There are two printers. They need to print documents at the same time. Actually the algorithm can be; If you are printing something on the system, the two printers reprint this document.

foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    if (printer == "ZJ-58")
    {

    }

    if (printer == "ZJ-58-2")
    {

    }
}

Body:
If you want to trigger the printing at the same time you could fire tasks in parallel (here I'm assuming you have a print function which returns a task). Eg:

var printers = new List<object>();
var printerTasks = printers.Select(printer =>
{
     if (printer == "ZJ-58")
     {
          return printer.print();
     }

     if (printer == "ZJ-58-2")
     {
          return printer.print();
     }
 });
 Task.WaitAll(printerTasks);


问:
How to import excel file from angular to asp.core, than read data and push it in List
I have found package like NPOI, but i dont know how to stream file, or how to convert it to bit before sending to asp.core. Curently i am using Angular 6</p>

答:
You need to use form data

HTML

<input  accept=".xlsx,.csv" (change)="uploadFile($event)" type="file" #file />
```

<p>TS</p>

```uploadFile(event) {
    const file = event.target.files[0];
    if (this.validateFile(file)) {
      this.isUploadInprogress = true;
      const formData: FormData = new FormData();
      formData.append('files', file, file.name);

      this.uploadService
        .uploadFile(formData)
        .subscribe(
          uploadResponse => this.uploadSuccess(uploadResponse, file),
          error => (this.isUploadInprogress = false)
        );
    } else {
      this.invitationsService.showError('Please upload valid file');
    }
  }
```

Body:
You need to use form data

HTML

<input  accept=".xlsx,.csv" (change)="uploadFile($event)" type="file" #file />

TS

uploadFile(event) {
    const file = event.target.files[0];
    if (this.validateFile(file)) {
      this.isUploadInprogress = true;
      const formData: FormData = new FormData();
      formData.append('files', file, file.name);

      this.uploadService
        .uploadFile(formData)
        .subscribe(
          uploadResponse => this.uploadSuccess(uploadResponse, file),
          error => (this.isUploadInprogress = false)
        );
    } else {
      this.invitationsService.showError('Please upload valid file');
    }
  }


问:
How to append the same parameter for multiple identical login pages if authentication fails?
I have the same login form on different endpoints: /welcome,
 /login

If I set failureUrl(/welcome?error) it will redirect the /login to /welcome?error as well if authentication fails instead of /login?error

I think I need to implement a failureHandler, but how can I extract the actual login endpoint from HttpServletRequest?

I would like to something like that:

response.sendRedirect(/[actual_login_endpoint]?error);

答:
I solved it. I had to send a hidden attribute with the login forms. I don't think there is an easier solution.</p>

```<code>@Override
public void onAuthenticationFailure(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final AuthenticationException exception) throws IOException, ServletException {
    if (request.getParameter("loginForm").equals("welcome")) {
        response.sendRedirect("/welcome?error");
    } else if (request.getParameter("loginForm").equals("login")) {
        response.sendRedirect("/login?error");
    }
}
</code>```

Body:
I solved it. I had to send a hidden attribute with the login forms. I don't think there is an easier solution.

@Override
public void onAuthenticationFailure(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final AuthenticationException exception) throws IOException, ServletException {
    if (request.getParameter("loginForm").equals("welcome")) {
        response.sendRedirect("/welcome?error");
    } else if (request.getParameter("loginForm").equals("login")) {
        response.sendRedirect("/login?error");
    }
}


问:
How to avoid calling malloc for each node in a linked list
This question was inspired by

Prevent malloc function wrapping

I have written a program that allocates memory for individual nodes in a linked list by calling malloc.

There are speed tests in which malloc is wrapped by a function that causes malloc calls to take more time than normal. This allows the tests to detect frequent usage of malloc.

How do I avoid calling malloc for each node?

答:
This is similar to the answer from @Brendan but has no fixed limit to the number of nodes. It is derived from code I already wrote.

When a node is released it is placed in a linked list pool. When a node is needed it is taken from the pool (if any) or from an array (if any) or the array is extended, not by just one node, but by a large number of them. This reduces the number of calls to realloc.

```<code>#include <stdio.h>
#include <stdlib.h>

#define CHUNK 8192

typedef struct Node {
    int data;
    struct Node *next;
} node;

node *array;
node *pool;
int nodes_avail;
int nodes_used;

node *getnode(void)
{
    node *newnode;
    if(pool) {                              // any in the recycled pool?
        newnode = pool;
        pool = pool->next;
    }
    else if(nodes_used < nodes_avail) {     // any in the array?
        newnode = &array[nodes_used];
        nodes_used++;
    }
    else {                                  // extend the array?
        nodes_avail += CHUNK;
        node *temp = realloc(array, nodes_avail * sizeof *temp);
        if(temp == NULL) {
            exit(1);                        // or recovery
        }
        array = temp;
        newnode = &array[nodes_used];
        nodes_used++;
    }
    return newnode;
}

void freenode(node *nptr)
{
    nptr->next = pool;                      // add to recycled pool
    pool = nptr;
}

int main() {
    const int node_count = 1000 * 1000;
    node *head = NULL;
    for (int index = 0; index < node_count; index++) {
        node *new = getnode();
        new->next = head;
        head = new;
        printf("address of head = %p\n", head);
    }
    while (head) {
        node *next = head->next;
        freenode(head);
        head = next;
    }
    for (int index = 0; index < node_count; index++) {
        node *new = getnode();
        new->next = head;
        head = new;
        printf("address of head = %p\n", head);
    }
    return 0;
}
</code>```

Output

```<code>address of head = 0x100bc7000
address of head = 0x100bc7010
address of head = 0x100bc7020
...
address of head = 0x101b2a3f0
</code>```

Verification

```<code>$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ diff xaa xab
</code>```

Body:
This is similar to the answer from @Brendan but has no fixed limit to the number of nodes. It is derived from code I already wrote.

When a node is released it is placed in a linked list pool. When a node is needed it is taken from the pool (if any) or from an array (if any) or the array is extended, not by just one node, but by a large number of them. This reduces the number of calls to realloc.

#include <stdio.h>
#include <stdlib.h>

#define CHUNK 8192

typedef struct Node {
    int data;
    struct Node *next;
} node;

node *array;
node *pool;
int nodes_avail;
int nodes_used;

node *getnode(void)
{
    node *newnode;
    if(pool) {                              // any in the recycled pool?
        newnode = pool;
        pool = pool->next;
    }
    else if(nodes_used < nodes_avail) {     // any in the array?
        newnode = &array[nodes_used];
        nodes_used++;
    }
    else {                                  // extend the array?
        nodes_avail += CHUNK;
        node *temp = realloc(array, nodes_avail * sizeof *temp);
        if(temp == NULL) {
            exit(1);                        // or recovery
        }
        array = temp;
        newnode = &array[nodes_used];
        nodes_used++;
    }
    return newnode;
}

void freenode(node *nptr)
{
    nptr->next = pool;                      // add to recycled pool
    pool = nptr;
}

int main() {
    const int node_count = 1000 * 1000;
    node *head = NULL;
    for (int index = 0; index < node_count; index++) {
        node *new = getnode();
        new->next = head;
        head = new;
        printf("address of head = %p\n", head);
    }
    while (head) {
        node *next = head->next;
        freenode(head);
        head = next;
    }
    for (int index = 0; index < node_count; index++) {
        node *new = getnode();
        new->next = head;
        head = new;
        printf("address of head = %p\n", head);
    }
    return 0;
}

Output

address of head = 0x100bc7000
address of head = 0x100bc7010
address of head = 0x100bc7020
...
address of head = 0x101b2a3f0

Verification

$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ diff xaa xab


问:
XSLT Failing to Rename Tag with Dash
I have the following XML and I want to rename ENTINFO_ACCT-TYPE to ENTINFO_ACCT_TYPE (along with many other transformations seen in my XSLT). However, the XSLT fails to rename ENTINFO_ACCT-TYPE. I've tried moving it before the NORMDOC root tag is added, and it doesn't make a difference. What am I doing wrong? I've been testing everything on this website.

XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
         <FITIN>987654321</FITIN>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-001">Refer to <ENAMEX type="BANKDIV" id="BAN-123456789-000">FCI</ENAMEX>
            <NUMEX type="CASENUM" id="CAS-123456789-001">Case # FRD-123</NUMEX>.</S>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
   <ENTINFO ID="ACC-123456789-027"
            TYPE="ACCOUNT"
            NORM="000111222333444"
            REFID="ACC-123456789-027"
            ACCT-TYPE="UNK"
            MENTION="debit card #s 000111222333444"/>
</NORMDOC>
</code>```

XSLT (code to rename in last section)

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFO>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFO>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="NORMDOC/ENTINFO/ENTINFO/ENTINFO_ACCT-TYPE">
        <ENTINFO_ACCT_TYPE><xsl:apply-templates/></ENTINFO_ACCT_TYPE>
</xsl:template>

</xsl:stylesheet>
</code>```

Expected (abbreviated)

```<code><NORMDOC>
   <DOC>
       ...
   </DOC>
   <ENTINFO>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-027</ENTINFO_ID>
         <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
         <ENTINFO_NORM>000111222333444</ENTINFO_NORM>
         <ENTINFO_REFID>ACC-123456789-027</ENTINFO_REFID>
         <ENTINFO_ACCT_TYPE>UNK</ENTINFO_ACCT-TYPE>
         <ENTINFO_MENTION>debit card #s 000111222333444</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFO>
</NORMDOC>
</code>```

答:
Couldn't you just change:

```<code><xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</code>```

to:

```<code><xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</code>```

Title: XSLT Failing to Rename Tag with Dash

Body:
I have the following XML and I want to rename ENTINFO_ACCT-TYPE to ENTINFO_ACCT_TYPE (along with many other transformations seen in my XSLT). However, the XSLT fails to rename ENTINFO_ACCT-TYPE. I've tried moving it before the NORMDOC root tag is added, and it doesn't make a difference. What am I doing wrong? I've been testing everything on this website.

XML

<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <FI fitype="B" xref="54815594127">
         <FIName>BANK OF FURY, N.A.</FIName>
         <FITIN>987654321</FITIN>
      </FI>
      <OIs>
         <OI xref="54815594128">
            <OIName>BANK OF FURY, N.A.</OIName>
         </OI>
      </OIs>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectFullName type="L">SMITH/JANE/C</SubjectFullName>
            <SubjectLastName type="L">SMITH</SubjectLastName>
            <SubjectFirstName type="L">JANE</SubjectFirstName>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-001">Refer to <ENAMEX type="BANKDIV" id="BAN-123456789-000">FCI</ENAMEX>
            <NUMEX type="CASENUM" id="CAS-123456789-001">Case # FRD-123</NUMEX>.</S>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            NORM="333222111000"
            REFID="ACC-123456789-013"
            ACCT-TYPE="CHK"
            MENTION="MI checking account # 333222111000"/>
   <ENTINFO ID="ACC-123456789-027"
            TYPE="ACCOUNT"
            NORM="000111222333444"
            REFID="ACC-123456789-027"
            ACCT-TYPE="UNK"
            MENTION="debit card #s 000111222333444"/>
</NORMDOC>

XSLT (code to rename in last section)

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFO>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFO>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="NORMDOC/ENTINFO/ENTINFO/ENTINFO_ACCT-TYPE">
        <ENTINFO_ACCT_TYPE><xsl:apply-templates/></ENTINFO_ACCT_TYPE>
</xsl:template>

</xsl:stylesheet>

Expected (abbreviated)

<NORMDOC>
   <DOC>
       ...
   </DOC>
   <ENTINFO>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-027</ENTINFO_ID>
         <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
         <ENTINFO_NORM>000111222333444</ENTINFO_NORM>
         <ENTINFO_REFID>ACC-123456789-027</ENTINFO_REFID>
         <ENTINFO_ACCT_TYPE>UNK</ENTINFO_ACCT-TYPE>
         <ENTINFO_MENTION>debit card #s 000111222333444</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFO>
</NORMDOC>

Body:
Couldn't you just change:

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{name()}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

to:

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>


问:
Count #tags in text fields (users' posts)
I have a table with posts from my users. Each post is just a text field and a post can include tags, for example:

```<code>"Hello this is my first post and I am in #japan enjoying #tokio How are you doing?"
</code>```

I would like to write MySQL query that would go through whole table and return most popular tags with nr of occurrences, sorted by count, for example:

```<code>#travel 53
#japan 14
#food 13
#tokio 6
#selfie 4
etc.
</code>```

Note that I don't have seperate table for tags. All I have is one table with posts and #tags are part of post text.

答:
We could do something like this:

```<code>SELECT v.tag
     , COUNT(1) AS cnt
  FROM ( SELECT CONCAT('#',IF(t.foo=SUBSTRING_INDEX(t.foo,'#',i.n*-1),NULL,SUBSTRING_INDEX(SUBSTRING_INDEX(t.foo,'#',i.n*-1),' ',1))) AS tag
           FROM ( SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
                  UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
                  UNION ALL SELECT 11 UNION ALL SELECT 12
                 ) i
           CROSS
            JOIN ( SELECT 'Hello this is my first post and I am in #japan enjoying #tokio How are you doing?' AS foo
                   UNION ALL SELECT '#japan #rocks'
                   UNION ALL SELECT 'a # b ## c ##'
                 ) t
         HAVING tag IS NOT NULL
       ) v
 GROUP BY v.tag
 ORDER BY cnt DESC, v.tag ASC
</code>```

Inline view i needs to be extended 13, 14, 15, ... up to the maximum possible number of tags that can appear in a post.

Inline view t is providing some sample rows as a demonstration. The inline view should be replaced with a table reference.

We also need to specify what should be returned when strings like #  and ### are encountered in the post. (Are those valid tags? Should those get counted?)

In SQL, a table reference can be replaced with an inline view.

For example, let's assume we have a table named user_posts that includes a character type column named post_text. And suppose we have this query:

```<code>  SELECT t.`post_text`
    FROM `user_posts` t
</code>```

We could replace the table reference (user_posts) with a query that returns a resultset, like this:

```<code>  SELECT t.`post_text`
    FROM (
           SELECT 'Hi I''m in #tokio #japan' AS `post_text`
           UNION ALL SELECT '#hanoi #rocks'
           UNION ALL SELECT 'a # b ## c ##'
           UNION ALL SELECT ''
         ) t
</code>```

Not that we can run that inner query standalong, separately, and have it return a resultset. When we wrapping it in parens and put it into the FROM clause of an outer query, the the result from that query are a row source for the outer query.

The query that replaces the table reference is called an "inline view". MySQL calls it a "derived table", mostly because of how the inline view gets processed in the MySQL query plan.

Body:
I have a table with posts from my users. Each post is just a text field and a post can include tags, for example:

"Hello this is my first post and I am in #japan enjoying #tokio How are you doing?"

I would like to write MySQL query that would go through whole table and return most popular tags with nr of occurrences, sorted by count, for example:

#travel 53
#japan 14
#food 13
#tokio 6
#selfie 4
etc.

Note that I don't have seperate table for tags. All I have is one table with posts and #tags are part of post text.

Body:
We could do something like this:

SELECT v.tag
     , COUNT(1) AS cnt
  FROM ( SELECT CONCAT('#',IF(t.foo=SUBSTRING_INDEX(t.foo,'#',i.n*-1),NULL,SUBSTRING_INDEX(SUBSTRING_INDEX(t.foo,'#',i.n*-1),' ',1))) AS tag
           FROM ( SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
                  UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
                  UNION ALL SELECT 11 UNION ALL SELECT 12
                 ) i
           CROSS
            JOIN ( SELECT 'Hello this is my first post and I am in #japan enjoying #tokio How are you doing?' AS foo
                   UNION ALL SELECT '#japan #rocks'
                   UNION ALL SELECT 'a # b ## c ##'
                 ) t
         HAVING tag IS NOT NULL
       ) v
 GROUP BY v.tag
 ORDER BY cnt DESC, v.tag ASC

Inline view i needs to be extended 13, 14, 15, ... up to the maximum possible number of tags that can appear in a post.

Inline view t is providing some sample rows as a demonstration. The inline view should be replaced with a table reference.

We also need to specify what should be returned when strings like #  and ### are encountered in the post. (Are those valid tags? Should those get counted?)

In SQL, a table reference can be replaced with an inline view.

For example, let's assume we have a table named user_posts that includes a character type column named post_text. And suppose we have this query:

  SELECT t.`post_text`
    FROM `user_posts` t

We could replace the table reference (user_posts) with a query that returns a resultset, like this:

  SELECT t.`post_text`
    FROM (
           SELECT 'Hi I''m in #tokio #japan' AS `post_text`
           UNION ALL SELECT '#hanoi #rocks'
           UNION ALL SELECT 'a # b ## c ##'
           UNION ALL SELECT ''
         ) t

Not that we can run that inner query standalong, separately, and have it return a resultset. When we wrapping it in parens and put it into the FROM clause of an outer query, the the result from that query are a row source for the outer query.

The query that replaces the table reference is called an "inline view". MySQL calls it a "derived table", mostly because of how the inline view gets processed in the MySQL query plan.


问:
EntityFrameworkCore SQLite in-memory db tables are not created
For integration tests I am using an EntityFrameworkCore SQLite in-memory db and creating its schema as per Microsoft docs, but when I attempt to seed data an exception is thrown that tables do not exist.

The mouse-over docs for DbContext.Database.EnsureCreated(); :

Ensure that the database for the context exists.  If it exists, no
  action is taken.  If it does not exist then the database and all its
  schema are created.  If the database exists, then no action is made to
  ensure it is compatible with the model for this context.

I've read that an EntityFrameworkCore in-memory db only exists as long as an open connection exists, and so I tried explicitly creating a var connection = new SqliteConnection("DataSource=:memory:"); instance and wrapping the below code in a using(connection) {} block and passing the connection instance options.UseSqlite(connection);, but DbContext.Database.EnsureCreated(); still doesn't create any db-objects

```<code>public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup<Startup>();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
      using (var connection = new SqliteConnection("DataSource=MySharedInMemoryDb;mode=memory;cache=shared"))
      {
          connection.Open();
          builder.ConfigureServices(services =>
          {
              var serviceProvider = new ServiceCollection()
                  .AddEntityFrameworkSqlite()
                  .BuildServiceProvider();

              services.AddDbContext<MyDbContext>(options =>
              {
                  options.UseSqlite(connection);
                  options.UseInternalServiceProvider(serviceProvider);
              });

              var contextServiceProvider = services.BuildServiceProvider();

              // we need a scope to obtain a reference to the database contexts
              using (var scope = contextServiceProvider.CreateScope())
              {
                  var scopedProvider = scope.ServiceProvider;

                  var logger = scopedProvider.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                  using (var myDb = scopedProvider.GetRequiredService<MyDbContext>())
                  {
                      // DEBUG CODE
                      // this returns script to create db objects as expected
                      // proving that MyDbContext is setup correctly
                      var script = myDb.Database.GenerateCreateScript();
                      // DEBUG CODE

                      // this does not create the db objects ( tables etc )
                      // this is not as expected and contrary to ms docs
                      var result = myDb.Database.EnsureCreated();

                      try
                      {
                          SeedData.PopulateTestData(myDb);
                      }
                      catch (Exception e)
                      {
                          // exception is thrown that tables don't exist
                          logger.LogError(e, $"SeedData.PopulateTestData(myDb) threw exception=[{e.Message}]");
                      }
                  }
              }
          });
        }
        builder.UseContentRoot(".");
        base.ConfigureWebHost(builder);
    }
</code>```

Please note that in this post I'm only asking the question why doesn't DbContext.Database.EnsureCreated(); create the schema as expected. I'm not presenting the above code as a general pattern for running integration-tests.

答:
Using a non-shared SQLite in-memory database

SQLite in-memory databases are by default transient. As the documentation states:

The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other.

EF Core's DbContext on the other hand, always opens and closes connections to the database automatically, unless you pass an already open connection.

Therefore, in order to use the same SQLite in-memory database across multiple calls in EF Core, you need to create a SqliteConnection object separately and then pass it to every DbContext.

For example:

  var keepAliveConnection = new SqliteConnection("DataSource=:memory:");
  keepAliveConnection.Open();

  services.AddDbContext<MyContext>(options =>
  {
    options.UseSqlite(keepAliveConnection);
  });
```

<p>Note that <code>SqliteConnection</code> isn't really thread-safe, so this approach is applicable only to single-threaded scenarios. Any time you want to have a shared database that can be accessed by multiple threads (e.g. in an ASP.NET Core application, servicing multiple requests), you should consider using an on-disk database.</p>

<p>By the way, this is the approach currently used in the EF Core documentation on how to use SQLite in-memory databases for testing.</p>

<h1>Using a shared SQLite in-memory database</h1>

<p>SQLite also supports named shared in-memory databases. By using the same connection string, multiple <code>SqliteConnection</code> objects can connect to the same database. However:</p>

<blockquote>
  <p>The database is automatically deleted and memory is reclaimed when the last connection to the database closes.</p>
</blockquote>

<p>So it is still necessary to maintain a separate open connection object for the database to be usable across multiple EF Core calls. For example:</p>

<pre class="lang-cs prettyprint-override"><code>  var connectionString = "DataSource=myshareddb;mode=memory;cache=shared";
  var keepAliveConnection = new SqliteConnection(connectionString);
  keepAliveConnection.Open();

  services.AddDbContext<MyContext>(options =>
  {
    options.UseSqlite(connectionString);
  });
</code>```

Note that this approach isn’t limited to a single thread, because each DbContext gets its own instance of SqliteConnection.

Body:
For integration tests I am using an EntityFrameworkCore SQLite in-memory db and creating its schema as per Microsoft docs, but when I attempt to seed data an exception is thrown that tables do not exist.

The mouse-over docs for DbContext.Database.EnsureCreated(); :

Ensure that the database for the context exists.  If it exists, no
  action is taken.  If it does not exist then the database and all its
  schema are created.  If the database exists, then no action is made to
  ensure it is compatible with the model for this context.

I've read that an EntityFrameworkCore in-memory db only exists as long as an open connection exists, and so I tried explicitly creating a var connection = new SqliteConnection("DataSource=:memory:"); instance and wrapping the below code in a using(connection) {} block and passing the connection instance options.UseSqlite(connection);, but DbContext.Database.EnsureCreated(); still doesn't create any db-objects

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup<Startup>();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
      using (var connection = new SqliteConnection("DataSource=MySharedInMemoryDb;mode=memory;cache=shared"))
      {
          connection.Open();
          builder.ConfigureServices(services =>
          {
              var serviceProvider = new ServiceCollection()
                  .AddEntityFrameworkSqlite()
                  .BuildServiceProvider();

              services.AddDbContext<MyDbContext>(options =>
              {
                  options.UseSqlite(connection);
                  options.UseInternalServiceProvider(serviceProvider);
              });

              var contextServiceProvider = services.BuildServiceProvider();

              // we need a scope to obtain a reference to the database contexts
              using (var scope = contextServiceProvider.CreateScope())
              {
                  var scopedProvider = scope.ServiceProvider;

                  var logger = scopedProvider.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                  using (var myDb = scopedProvider.GetRequiredService<MyDbContext>())
                  {
                      // DEBUG CODE
                      // this returns script to create db objects as expected
                      // proving that MyDbContext is setup correctly
                      var script = myDb.Database.GenerateCreateScript();
                      // DEBUG CODE

                      // this does not create the db objects ( tables etc )
                      // this is not as expected and contrary to ms docs
                      var result = myDb.Database.EnsureCreated();

                      try
                      {
                          SeedData.PopulateTestData(myDb);
                      }
                      catch (Exception e)
                      {
                          // exception is thrown that tables don't exist
                          logger.LogError(e, $"SeedData.PopulateTestData(myDb) threw exception=[{e.Message}]");
                      }
                  }
              }
          });
        }
        builder.UseContentRoot(".");
        base.ConfigureWebHost(builder);
    }

Please note that in this post I'm only asking the question why doesn't DbContext.Database.EnsureCreated(); create the schema as expected. I'm not presenting the above code as a general pattern for running integration-tests.

Body:
Using a non-shared SQLite in-memory database

SQLite in-memory databases are by default transient. As the documentation states:

The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other.

EF Core's DbContext on the other hand, always opens and closes connections to the database automatically, unless you pass an already open connection.

Therefore, in order to use the same SQLite in-memory database across multiple calls in EF Core, you need to create a SqliteConnection object separately and then pass it to every DbContext.

For example:

  var keepAliveConnection = new SqliteConnection("DataSource=:memory:");
  keepAliveConnection.Open();

  services.AddDbContext<MyContext>(options =>
  {
    options.UseSqlite(keepAliveConnection);
  });

Note that SqliteConnection isn't really thread-safe, so this approach is applicable only to single-threaded scenarios. Any time you want to have a shared database that can be accessed by multiple threads (e.g. in an ASP.NET Core application, servicing multiple requests), you should consider using an on-disk database.

By the way, this is the approach currently used in the EF Core documentation on how to use SQLite in-memory databases for testing.

Using a shared SQLite in-memory database

SQLite also supports named shared in-memory databases. By using the same connection string, multiple SqliteConnection objects can connect to the same database. However:

The database is automatically deleted and memory is reclaimed when the last connection to the database closes.

So it is still necessary to maintain a separate open connection object for the database to be usable across multiple EF Core calls. For example:

  var connectionString = "DataSource=myshareddb;mode=memory;cache=shared";
  var keepAliveConnection = new SqliteConnection(connectionString);
  keepAliveConnection.Open();

  services.AddDbContext<MyContext>(options =>
  {
    options.UseSqlite(connectionString);
  });

Note that this approach isn’t limited to a single thread, because each DbContext gets its own instance of SqliteConnection.