问: Extracting contents inside

答:
You'll have to manipulate the string. Essentially it gives you a list of json structures:

```<code>import requests
from bs4 import BeautifulSoup
import json

url = 'https://www.broadwayinbound.com/shows/'
response = requests.get(url)
data = response.text     # a `bytes` object
soup = BeautifulSoup(data)
results = soup.findAll('script', {'type':'text/javascript'})
r = []

for result in results :
    if 'var shows = [' in result.text:
        jsonStr = result.text

        jsonStr = jsonStr.split('var shows = [')[1]
        jsonStr = jsonStr.rsplit('];',1)[0]

        jsonStr_list = jsonStr.split('{"Id":')[1:]

        for each in jsonStr_list:
            each = jsonStr_list[0]
            w=1
            if each[-1] == ',':
                each = each.rstrip(',')

            jsonTemp = '{"Id":' + each
            jsonObj = json.loads(jsonTemp)

            r.append(jsonObj)
</code>```

Output:

```<code>print (r)
[{'Id': '12680', 'ClientClassCode': 'default', 'ShowName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowCode': 'AINTPROUD', 'SortName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowLogo': '/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg', 'ShowLogoText': "Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway Inbound", 'ShowPromo': '', 'ShowPromoText': '', 'Description': "<em>Ain't Too Proud</em> is the electrifying new musical that follows The Temptations' extraordinary journey from the streets of Detroit to the Rock & Roll Hall of Fame.<br /><br />Five guys. One dream. And a sound that would make music history. With their signature dance moves and unmistakable harmonies, they rose to the top of the charts creating an amazing 42 Top Ten Hits with 14 reaching number one. The rest is history — how they met, the groundbreaking heights they hit, and how personal and political conflicts threatened to tear the group apart as the United States fell into civil unrest. This thrilling story of brotherhood, family, loyalty, and betrayal is set to the beat of the group's treasured hits, including “My Girl,” “Just My Imagination,” “Get Ready,” “Papa Was a Rolling Stone,” and so many more.<br /><br />After breaking house records at Berkeley Rep, The Kennedy Center, and at the Ahmanson Theater, <em>Ain't Too Proud</em>, written by three time Obie Award winner Dominique Morisseau, directed by two-time Tony Award® winner Des McAnuff (<em>Jersey Boys</em>), and featuring choreography by Tony nominee Sergio Trujillo (<em>Jersey Boys</em>, <em>On Your Feet</em>), now brings the untold story of this legendary quintet to irresistible life on Broadway.", 'Category': 'Broadway', 'CategoryCode': 'BW', 'ShowType': 'Musical', 'ShowTypeCode': 'MUSICAL', 'Rating': 'Might not be suitable for younger children', 'RatingCode': 'PT', 'City': 'New York', 'CityCode': 'NYCA', 'FirstPerformance': '2/28/2019', 'NextPerformance': '5/30/2019', 'NextPerformanceTime': '7:00 PM', 'OnSaleThrough': '6/7/2020', 'Weekdays': ['fr', 'mo', 'sa', 'su', 'th', 'tu', 'we'], 'MinPrice': '42.00', 'MaxPrice': '385.90', 'GroupMinimum': '10', 'MaximumTickets': '25', 'VenueName': 'Imperial Theatre', 'Url': '/shows/aint-too-proud-the-life-and-times-of-the-temptations/', 'BroadwayCollectionEN': 'http://www.broadwaycollection.com/shows/https://www.broadwaycollection.com/shows/aint-too-proud/', 'BroadwayCollectionES': 'http://www.broadwaycollection.com/es/shows/https://www.broadwaycollection.com/es/shows/aint-too-proud/', 'BroadwayCollectionDE': 'http://www.broadwaycollection.com/de/shows/https://www.broadwaycollection.com/de/shows/aint-too-proud/', 'BroadwayCollectionJA': 'http://www.broadwaycollection.com/ja/shows/https://www.broadwaycollection.com/ja/shows/aint-too-proud/', 'BroadwayCollectionPT': 'http://www.broadwaycollection.com/pt-br/shows/https://www.broadwaycollection.com/pt-br/shows/aint-too-proud/', 'BroadwayCollectionZH': 'http://www.broadwaycollection.com/zh-hans/shows/https://www.broadwaycollection.com/zh-hans/shows/aint-too-proud/', 'RunTime': '2 hours and 30 minutes, including intermission', 'ShowLetUsKnow': False}, {'Id': '12680', 'ClientClassCode': 'default', 'ShowName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowCode': 'AINTPROUD', 'SortName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowLogo': '/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg', 'ShowLogoText': "Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway Inbound", 'ShowPromo': '', 'ShowPromoText': '', 'Description': "<em>Ain't Too Proud</em> is the electrifying new musical that follows The Temptat ...
</code>```

Title: Extracting contents inside <script type="text/javascript"> and $(function ()

Body:
I am working on scraping data from websites. I was able to extract contents inside the tag . But it has '$(function () {' inside it. I want to extract contents inside it.

import urllib.request
from bs4 import BeautifulSoup
import json
url = 'https://www.broadwayinbound.com/shows/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
soup = BeautifulSoup(data)
results = soup.findAll('script', {'type':'text/javascript'})
r = []
for result in results :
    if 'var shows = [' in result.text:
        r.append(result.text)
print (r[0])

I want to extract the contents of 'var shows' alone.

{"Id":"12680","ClientClassCode":"default","ShowName":"Ain't Too Proud - The Life and Times of The Temptations","ShowCode":"AINTPROUD","SortName":"Ain't Too Proud - The Life and Times of The Temptations","ShowLogo":"/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg","ShowLogoText":"Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway......

Body:
You'll have to manipulate the string. Essentially it gives you a list of json structures:

import requests
from bs4 import BeautifulSoup
import json

url = 'https://www.broadwayinbound.com/shows/'
response = requests.get(url)
data = response.text     # a `bytes` object
soup = BeautifulSoup(data)
results = soup.findAll('script', {'type':'text/javascript'})
r = []

for result in results :
    if 'var shows = [' in result.text:
        jsonStr = result.text

        jsonStr = jsonStr.split('var shows = [')[1]
        jsonStr = jsonStr.rsplit('];',1)[0]

        jsonStr_list = jsonStr.split('{"Id":')[1:]

        for each in jsonStr_list:
            each = jsonStr_list[0]
            w=1
            if each[-1] == ',':
                each = each.rstrip(',')

            jsonTemp = '{"Id":' + each
            jsonObj = json.loads(jsonTemp)

            r.append(jsonObj)

Output:

print (r)
[{'Id': '12680', 'ClientClassCode': 'default', 'ShowName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowCode': 'AINTPROUD', 'SortName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowLogo': '/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg', 'ShowLogoText': "Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway Inbound", 'ShowPromo': '', 'ShowPromoText': '', 'Description': "<em>Ain't Too Proud</em> is the electrifying new musical that follows The Temptations' extraordinary journey from the streets of Detroit to the Rock & Roll Hall of Fame.<br /><br />Five guys. One dream. And a sound that would make music history. With their signature dance moves and unmistakable harmonies, they rose to the top of the charts creating an amazing 42 Top Ten Hits with 14 reaching number one. The rest is history — how they met, the groundbreaking heights they hit, and how personal and political conflicts threatened to tear the group apart as the United States fell into civil unrest. This thrilling story of brotherhood, family, loyalty, and betrayal is set to the beat of the group's treasured hits, including “My Girl,” “Just My Imagination,” “Get Ready,” “Papa Was a Rolling Stone,” and so many more.<br /><br />After breaking house records at Berkeley Rep, The Kennedy Center, and at the Ahmanson Theater, <em>Ain't Too Proud</em>, written by three time Obie Award winner Dominique Morisseau, directed by two-time Tony Award® winner Des McAnuff (<em>Jersey Boys</em>), and featuring choreography by Tony nominee Sergio Trujillo (<em>Jersey Boys</em>, <em>On Your Feet</em>), now brings the untold story of this legendary quintet to irresistible life on Broadway.", 'Category': 'Broadway', 'CategoryCode': 'BW', 'ShowType': 'Musical', 'ShowTypeCode': 'MUSICAL', 'Rating': 'Might not be suitable for younger children', 'RatingCode': 'PT', 'City': 'New York', 'CityCode': 'NYCA', 'FirstPerformance': '2/28/2019', 'NextPerformance': '5/30/2019', 'NextPerformanceTime': '7:00 PM', 'OnSaleThrough': '6/7/2020', 'Weekdays': ['fr', 'mo', 'sa', 'su', 'th', 'tu', 'we'], 'MinPrice': '42.00', 'MaxPrice': '385.90', 'GroupMinimum': '10', 'MaximumTickets': '25', 'VenueName': 'Imperial Theatre', 'Url': '/shows/aint-too-proud-the-life-and-times-of-the-temptations/', 'BroadwayCollectionEN': 'http://www.broadwaycollection.com/shows/https://www.broadwaycollection.com/shows/aint-too-proud/', 'BroadwayCollectionES': 'http://www.broadwaycollection.com/es/shows/https://www.broadwaycollection.com/es/shows/aint-too-proud/', 'BroadwayCollectionDE': 'http://www.broadwaycollection.com/de/shows/https://www.broadwaycollection.com/de/shows/aint-too-proud/', 'BroadwayCollectionJA': 'http://www.broadwaycollection.com/ja/shows/https://www.broadwaycollection.com/ja/shows/aint-too-proud/', 'BroadwayCollectionPT': 'http://www.broadwaycollection.com/pt-br/shows/https://www.broadwaycollection.com/pt-br/shows/aint-too-proud/', 'BroadwayCollectionZH': 'http://www.broadwaycollection.com/zh-hans/shows/https://www.broadwaycollection.com/zh-hans/shows/aint-too-proud/', 'RunTime': '2 hours and 30 minutes, including intermission', 'ShowLetUsKnow': False}, {'Id': '12680', 'ClientClassCode': 'default', 'ShowName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowCode': 'AINTPROUD', 'SortName': "Ain't Too Proud - The Life and Times of The Temptations", 'ShowLogo': '/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg', 'ShowLogoText': "Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway Inbound", 'ShowPromo': '', 'ShowPromoText': '', 'Description': "<em>Ain't Too Proud</em> is the electrifying new musical that follows The Temptat ...


来源: stackexchange

问:
Is there a way to pass existing view model as a data context to recently opened dialog window, when using autofac?
I have a project, using Autofac. There is created a BootStrapper file that is called on application run:

```<code>public class BootStrapper
    {
        public IContainer BootStrap()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<FileDataServices>()
              .As<IFileDataServices>().SingleInstance();

            builder.RegisterType<ScrapDataServices>()
              .As<IScrapDataServices>().SingleInstance();

            builder.RegisterType<MessageDialogService>()
              .As<IMessageDialogService>().SingleInstance();

            builder.RegisterType<MainWindow>().AsSelf();
            builder.RegisterType<MainViewModel>().AsSelf();

            return builder.Build();
        }
    }
</code>```

And the class is called by App.xaml.cs`

```<code>public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();
            var mainWindow = container.Resolve<MainWindow>();
            mainWindow.Show();
        }
    }
</code>```

When the MainWindow is created, constructor creates instance of MainViewModel, that I want to use later:

```<code>public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;
        public MainWindow(MainViewModel viewModel)
        {
            InitializeComponent();
            _viewModel = viewModel;
            DataContext = _viewModel;
        }
    }
</code>```

In MainViewModel there is created UpdateWindow via simple MessageDialogService:

var result = _messageDialogService.ShowUpdateWindow();

And the MessageDialogService by itself:

```<code>public class MessageDialogService : IMessageDialogService
    {
        public MessageDialogResult ShowUpdateWindow()
        {
            return new UpdateWindow()
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = App.Current.MainWindow
            }.ShowDialog().GetValueOrDefault()
              ? MessageDialogResult.Update //if DialogResult = true;
              : MessageDialogResult.Cancel; //if DialogResult = false;
        }
    }
</code>```

On creation I need to pass the existing instance of MainViewModel to the UpdateWindow as a DataContext. And I do not know how. Right now I only managed to create a new instance of the MainViewModel on creation of UpdateWindow, but it is not my goal, because in this window I am having controls that I need them to have binded with ViewModel created by MainWindow. Is there any way or approach to do that?

Currently I have only this:

```<code>public partial class UpdateWindow : Window
    {
        public UpdateWindow()
        {
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();
            var vm = container.Resolve<MainViewModel>();
            InitializeComponent();
            DataContext = vm;
        }

        private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }
    }
</code>```

答:
You need to make sure you're resolving MainWindowViewModel.

Register MainwindowViewModel as a singleton using

```<code>builder.RegisterType<MainViewModel>().AsSelf().SingleInstance();
</code>```

Then add a variable of type MainWindowViewModel to the ctor of wherever you want to use it.

Resolve that - UpdateWindow is it?

The container should provide the same instance of MainWindowViewmodel it gave you for mainwindow.

ContentLicense: CC BY-SA 4.0

Body:
I have a project, using Autofac. There is created a BootStrapper file that is called on application run:

public class BootStrapper
    {
        public IContainer BootStrap()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<FileDataServices>()
              .As<IFileDataServices>().SingleInstance();

            builder.RegisterType<ScrapDataServices>()
              .As<IScrapDataServices>().SingleInstance();

            builder.RegisterType<MessageDialogService>()
              .As<IMessageDialogService>().SingleInstance();

            builder.RegisterType<MainWindow>().AsSelf();
            builder.RegisterType<MainViewModel>().AsSelf();

            return builder.Build();
        }
    }

And the class is called by App.xaml.cs`

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();
            var mainWindow = container.Resolve<MainWindow>();
            mainWindow.Show();
        }
    }

When the MainWindow is created, constructor creates instance of MainViewModel, that I want to use later:

public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;
        public MainWindow(MainViewModel viewModel)
        {
            InitializeComponent();
            _viewModel = viewModel;
            DataContext = _viewModel;
        }
    }

In MainViewModel there is created UpdateWindow via simple MessageDialogService:

var result = _messageDialogService.ShowUpdateWindow();

And the MessageDialogService by itself:

public class MessageDialogService : IMessageDialogService
    {
        public MessageDialogResult ShowUpdateWindow()
        {
            return new UpdateWindow()
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = App.Current.MainWindow
            }.ShowDialog().GetValueOrDefault()
              ? MessageDialogResult.Update //if DialogResult = true;
              : MessageDialogResult.Cancel; //if DialogResult = false;
        }
    }

On creation I need to pass the existing instance of MainViewModel to the UpdateWindow as a DataContext. And I do not know how. Right now I only managed to create a new instance of the MainViewModel on creation of UpdateWindow, but it is not my goal, because in this window I am having controls that I need them to have binded with ViewModel created by MainWindow. Is there any way or approach to do that?

Currently I have only this:

public partial class UpdateWindow : Window
    {
        public UpdateWindow()
        {
            var bootStrapper = new BootStrapper();
            var container = bootStrapper.BootStrap();
            var vm = container.Resolve<MainViewModel>();
            InitializeComponent();
            DataContext = vm;
        }

        private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }
    }

Body:
You need to make sure you're resolving MainWindowViewModel.

Register MainwindowViewModel as a singleton using

builder.RegisterType<MainViewModel>().AsSelf().SingleInstance();

Then add a variable of type MainWindowViewModel to the ctor of wherever you want to use it.

Resolve that - UpdateWindow is it?

The container should provide the same instance of MainWindowViewmodel it gave you for mainwindow.


问:
Sqlite keep in memory database open until jvm exit
I'd like to keep an in memory sqlite database, but without attached connections.

I'm unit testing a web app, so in the @BeforeAll method I do some initialization and then, in the various test methods, do some DDL manipulation.

Of course, when the last open connection is closed, sqlite in memory db is teared down, breaking my tests.

I achieved to keep a H2 in memory database open till the JVM lives, doing this

```<code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</code>```

But I can't find an alternative for sqlite.
I tried with

```<code>jdbc:sqlite::memory:&cache=shared
</code>```

But doesn't seem to work.

Is it possible?

答:
As unit-tests are supposed to be independent one another, I would advise against proceeding this way. Depending on the underlying framework you're using you might want to use annotations to drive the execution of initialisation and teardown SQL. For Spring, for example, you can use the following:

https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#spring-testing-annotation-sql

If you can't use annotations or are really determined to proceed down this path (context is everything: you might totally have good reasons) one possibility would be to open an additional connection in your @BeforeAll method, which you would then manually close in an @AfterAll method. As this would be an additional connection separately managed by your code, sqlite would be tricked into NOT performing its cleanup up until the @AfterAll method executes.

If you want this to be at JVM level, you can use a class' static initialiser...

Body:
I'd like to keep an in memory sqlite database, but without attached connections.

I'm unit testing a web app, so in the @BeforeAll method I do some initialization and then, in the various test methods, do some DDL manipulation.

Of course, when the last open connection is closed, sqlite in memory db is teared down, breaking my tests.

I achieved to keep a H2 in memory database open till the JVM lives, doing this

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

But I can't find an alternative for sqlite.
I tried with

jdbc:sqlite::memory:&cache=shared

But doesn't seem to work.

Is it possible?


问:
how to handle xml data in javascript
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

```<code>$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

the returned xml data looks like:

```<code><DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...
</code>```

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

```<code>success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}
</code>```

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

答:
Use the following snippet in your function to put the XML result string in a wrapped jQuery set.</p>

```<code>var xmlString = data;

//IE XML parser needs to use an ActiveXObject
if ($.browser.msie) {
    unwrappedXml = new ActiveXObject("Microsoft.XMLDOM");
    unwrappedXml.async = false;
    unwrappedXml.loadXML(xmlString);
    }
else {
    unwrappedXml = xmlString;
}

var xml = $(unwrappedXml);
xml.find(selector);
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to handle xml data in javascript

Body:
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

the returned xml data looks like:

<DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

Body:
Use the following snippet in your function to put the XML result string in a wrapped jQuery set.

var xmlString = data;

//IE XML parser needs to use an ActiveXObject
if ($.browser.msie) {
    unwrappedXml = new ActiveXObject("Microsoft.XMLDOM");
    unwrappedXml.async = false;
    unwrappedXml.loadXML(xmlString);
    }
else {
    unwrappedXml = xmlString;
}

var xml = $(unwrappedXml);
xml.find(selector);


答:
You can use parse_dates in your call to read_csv

```<code>df = pd.read_csv("blabla.csv",parse_dates=True)
</code>```

This will result in datetime objects instead of strings. Then you could use the .isin method to see if the elements of one column are in the other.

```<code>df['time'].isin(dates)
</code>```

This will return a series of True and False for each value in df['time']

Title: How to search list elements in a data frame?

Body:
I have a list dates with dates as string objects with all dates from 2003-01-01 to 2017-06-30:

['2003-01-01', '2003-01-02', '2003-01-03', '2003-01-04', '2003-01-05', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-11', '2003-01-12', '2003-01-13', '2003-01-14', '2003-01-15', '2003-01-16', '2003-01-17', '2003-01-18', '2003-01-19', '2003-01-20', '2003-01-21',...]

And I have a dataframe with date time objects:

0       2013-01-09 09:07:49
1       2013-01-09 09:16:25
2       2013-01-09 11:14:28
3       2013-01-09 11:25:51
4       2013-01-09 11:25:51
5       2013-01-09 11:33:35
6       2013-01-09 11:35:31
7       2013-01-09 18:11:03
8       2013-03-13 21:04:58
9       2013-03-13 21:05:57
10      2013-03-15 14:07:27
11      2013-03-26 21:53:35
12      2013-03-26 22:19:20
13      2013-04-09 14:21:48
14      2013-04-09 14:22:29
15      2013-04-09 14:22:45
16      2013-04-22 12:10:47
...

Then I want to check if the dates in the list dates exist in the dataframe. So I want to do something like this:

df = pd.read_csv("blabla.csv")
df['time'] = pd.to_datetime(df['time'])
for j in dates:
  if j in df['time']:
       return(yes)

How can I compare a string object with a datetime object in a dataframe?

This is my full code:

dates=[]
start = date(2003, 1, 1)
end = date(2017, 6, 30)

delta = end - start

for i in range(delta.days + 1):
    newdate = start + timedelta(days=i)
    dates.append(newdate.strftime("%Y-%m-%d"))

df = pd.read_csv("blabla.csv",parse_dates=True)
df['time'] = pd.to_datetime(df['time'])

Body:
You can use parse_dates in your call to read_csv

df = pd.read_csv("blabla.csv",parse_dates=True)

This will result in datetime objects instead of strings. Then you could use the .isin method to see if the elements of one column are in the other.

df['time'].isin(dates)

This will return a series of True and False for each value in df['time']


问:
How to calculate month with fraction in Access VBA
I need to write a function that receives two arguments startdate and enddate where it returns the difference between these two dates.

Say that function is monthfractiondiff(startdate,enddate)

e.g. monthfractiondiff(15/01/2016,15/02/2016) will return
((31-15)/31)+(15/29) = 1.0333704116

monthfractiondiff(15/11/2018,15/02/2019) will return
((30-15)/30)+1+1+(15/28) = 3.0357142857

I vainly tried https://access-programmers.co.uk/forums/showthread.php?t=113589

答:
UPDATED thanks to other answer WeeBee

```<code>Function HowManyMonths(startdate As Date, Enddate As Date) As Double
Dim pctSTARTmonth As Double, pctENDmonth As Double, M As Long

'caputues percentage of month
pctSTARTmonth = Day(startdate) / Day(DateSerial(Year(startdate), Month(startdate) + 1, 1) - 1)
pctENDmonth = Day(Enddate) / Day(DateSerial(Year(Enddate), Month(Enddate) + 1, 1) - 1)

'Use Date difference function to get whole number and then combine perc
HowManyMonths = DateDiff("M", startdate, Enddate) + pctENDmonth - pctSTARTmonth

End Function
</code>```

Body:
UPDATED thanks to other answer WeeBee

Function HowManyMonths(startdate As Date, Enddate As Date) As Double
Dim pctSTARTmonth As Double, pctENDmonth As Double, M As Long

'caputues percentage of month
pctSTARTmonth = Day(startdate) / Day(DateSerial(Year(startdate), Month(startdate) + 1, 1) - 1)
pctENDmonth = Day(Enddate) / Day(DateSerial(Year(Enddate), Month(Enddate) + 1, 1) - 1)

'Use Date difference function to get whole number and then combine perc
HowManyMonths = DateDiff("M", startdate, Enddate) + pctENDmonth - pctSTARTmonth

End Function


问:
how to perform "dry-run" authorization check in .NET Core?
Consider that I have .NET Controller with Policy-based authorization:

```<code>public class ImportantController: Controller {
    [HttpGet]
    [Authorize(Policy = "CanAccessVIPArea")]
    public IActionResult ShowInformation() {
        ...
        return OK(VipData);
    }

    [HttpPost]
    [Authorize(Policy = "CanChangeVIPData")]
    public IActionResult SaveInformation([FromBody] VipData) {
        ...
        return CreatedAtAction(...);
    }
}
</code>```

Obviously, the real example is much more complex; I apologize if my simplification leads to too much make-believe in it. Also, real application is SPA with Angular front end; but I don't think it makes any difference for the purposes of this question.

When the user calls ShowInformation() I show a lot of data. On that page I have Save button that calls SaveInformation(). Authorization middleware checks for the right policy and it all works fine.

The problem is that by the time the user presses Save, she entered a lot of data, only to find out that she doesn't have the permissions to save. Obviously, leading to bad experience. I want to check for permissions on SaveInformation in the middleware that gets invoked when the user calls ShowInformation. I would prefer not to check for the hardcoded policy because it is on the server and it can change (we have pretty sophisticated permission management system that manipulates permissions at runtime). Invocation of SaveInformation is in the same Angular service as ShowInformation, and it is very easy to check...

I would like to invoke something like /api/SaveInformation?dryrun that will short-circuit the pipeline after authorization middleware with success or failure.

答:
You can inject an IAuthorizationService and ask to evaluate a policy by name:</p>

```<code>public class ImportantController: Controller
{
    private readonly IAuthorizationService authorization;

    public ImportantController(IAuthorizationService authorization)
    {
        this.authorization = authorization;
    }

    public async Task<IActionResult> ShowInformation()
    {
        // ...
        var result = await authorizationService.AuthorizeAsync(User, "IsLucky");

        return OK(VipData);
    }
}
</code>```

Body:
Consider that I have .NET Controller with Policy-based authorization:

public class ImportantController: Controller {
    [HttpGet]
    [Authorize(Policy = "CanAccessVIPArea")]
    public IActionResult ShowInformation() {
        ...
        return OK(VipData);
    }

    [HttpPost]
    [Authorize(Policy = "CanChangeVIPData")]
    public IActionResult SaveInformation([FromBody] VipData) {
        ...
        return CreatedAtAction(...);
    }
}

Obviously, the real example is much more complex; I apologize if my simplification leads to too much make-believe in it. Also, real application is SPA with Angular front end; but I don't think it makes any difference for the purposes of this question.

When the user calls ShowInformation() I show a lot of data. On that page I have Save button that calls SaveInformation(). Authorization middleware checks for the right policy and it all works fine.

The problem is that by the time the user presses Save, she entered a lot of data, only to find out that she doesn't have the permissions to save. Obviously, leading to bad experience. I want to check for permissions on SaveInformation in the middleware that gets invoked when the user calls ShowInformation. I would prefer not to check for the hardcoded policy because it is on the server and it can change (we have pretty sophisticated permission management system that manipulates permissions at runtime). Invocation of SaveInformation is in the same Angular service as ShowInformation, and it is very easy to check...

I would like to invoke something like /api/SaveInformation?dryrun that will short-circuit the pipeline after authorization middleware with success or failure.

Body:
You can inject an IAuthorizationService and ask to evaluate a policy by name:

public class ImportantController: Controller
{
    private readonly IAuthorizationService authorization;

    public ImportantController(IAuthorizationService authorization)
    {
        this.authorization = authorization;
    }

    public async Task<IActionResult> ShowInformation()
    {
        // ...
        var result = await authorizationService.AuthorizeAsync(User, "IsLucky");

        return OK(VipData);
    }
}


问:
Import AndroidStudio project in a new PC keeping the SQLite database
I have to work in my project from 2 PC, and share it with some partners. In this project we hace a database (SQLite) and when we import the project in a new PC, the database doesn't exist and we have to import it manually. Is there any way to keep the database in the project and if we import it in a new PC, the database will be imported in the project automatically?</p>

答: I depends on how your app initially creates the database.  If the database is created in code, then when opened on a new PC, or new AVD, or new device, it will recognize that the database is not in the Apps data folders, and will create a new empty database.  If you pre-design and perhaps pre-fill a database, then typically this is added to the project in the Apps Assets folder.  Then, on start-up, the App looks for the database in the data folders, and if not found, it copies it from the Assets folder to the data folder.  In that way, at least you can have a pre-designed database and pre-filled (for lookup tables etc), and since the SQLite database is part of the project structure, it can be copied to different development computers, just by copying the project directory.</p>


问:
How to parse a string using a string specification?
I wish to write a method to parse strings containing the names of people and their ages. For example:

```<code>Manuel 8
Mustafa 16
Zhihao 12
Itsuki 12
Louis 11
Farah 11
</code>```

i.e. the specification of the strings is %N %A, where %N represents the name, and %A represents the age.

However, the specification of the strings is not fixed (e.g. it could be %N age:%A or %N (%A) in another document), so the parsing method should be able to take the specification as one of its arguments.

In other words, the parsing method should work like this:

```<code>Data d1 = Parser.parse("Indira 15", "%N %A");
Data d2 = Parser.parse("12 Shu-chen", "%A %N");
Data d3 = Parser.parse("Hana (12)", "%N (%A)");
Data d4 = Parser.parse("Name: Sophia [12]", "Name: %N [%A]");
</code>```

where Data and Parser are defined like this:

```<code>public class Data {
    private String name;
    private int age;

    public Data(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // + getter and setter methods.
}

public class Parser {
    public static Data parse(String s, String specification) {
        // --- What to do here? ---
        return (new Data(name, age));
    }
}
</code>```

How can Parser.parse be written? In other words, how can a string be parsed using a string specification?

答:
Here, we can have an expression and collect our desired outputs in two groups, such as:

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

where our desired names are in this ([a-z-]+) group, and the age info are in this (\d+) and the rest can be simply scripted.

TEST

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "((?:\\s+)?([a-z-]+)(?:\\s+)?)|(\\d+)";
final String string = "Indira 15\n"
     + "12 Shu-chen\n"
     + "Hana (12)\n"
     + "Sophia [12]\n"
     + "  Manuel 8\n"
     + "Mustafa  16\n"
     + "Zhihao    12\n"
     + "Itsuki 12\n"
     + "Louis 11\n"
     + "Farah 11";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

DEMO 2

Advices

Based on zdim's advice:

(1) I think that (?:\s+)? (at least one space, but the whole thing is
  optional) is the same as \s* (optional spaces)

(2) In the second group of spaces I think that you want to require at
  least a space, so just \s+.

We can much simplify and modify our initial expression to something similar to:

```<code>(\s*([a-z-]+)\s+)|(\d+)
</code>```

DEMO

Body:
I wish to write a method to parse strings containing the names of people and their ages. For example:

Manuel 8
Mustafa 16
Zhihao 12
Itsuki 12
Louis 11
Farah 11

i.e. the specification of the strings is %N %A, where %N represents the name, and %A represents the age.

However, the specification of the strings is not fixed (e.g. it could be %N age:%A or %N (%A) in another document), so the parsing method should be able to take the specification as one of its arguments.

In other words, the parsing method should work like this:

Data d1 = Parser.parse("Indira 15", "%N %A");
Data d2 = Parser.parse("12 Shu-chen", "%A %N");
Data d3 = Parser.parse("Hana (12)", "%N (%A)");
Data d4 = Parser.parse("Name: Sophia [12]", "Name: %N [%A]");

where Data and Parser are defined like this:

public class Data {
    private String name;
    private int age;

    public Data(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // + getter and setter methods.
}

public class Parser {
    public static Data parse(String s, String specification) {
        // --- What to do here? ---
        return (new Data(name, age));
    }
}

How can Parser.parse be written? In other words, how can a string be parsed using a string specification?

Body:
Here, we can have an expression and collect our desired outputs in two groups, such as:

((?:\s+)?([a-z-]+)(?:\s+)?)|(\d+)

where our desired names are in this ([a-z-]+) group, and the age info are in this (\d+) and the rest can be simply scripted.

TEST

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "((?:\\s+)?([a-z-]+)(?:\\s+)?)|(\\d+)";
final String string = "Indira 15\n"
     + "12 Shu-chen\n"
     + "Hana (12)\n"
     + "Sophia [12]\n"
     + "  Manuel 8\n"
     + "Mustafa  16\n"
     + "Zhihao    12\n"
     + "Itsuki 12\n"
     + "Louis 11\n"
     + "Farah 11";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

DEMO 2

Advices

Based on zdim's advice:

(1) I think that (?:\s+)? (at least one space, but the whole thing is
  optional) is the same as \s* (optional spaces)

(2) In the second group of spaces I think that you want to require at
  least a space, so just \s+.

We can much simplify and modify our initial expression to something similar to:

(\s*([a-z-]+)\s+)|(\d+)

DEMO


问:
How can I use Stripe to delay charging a customer until a physical item is shipped?
I'm in the process of building an online marketplace which sells shippable goods. The site will be similar to Etsy, which will connect merchants with buyers.

I'd like to be able to charge a customer's card ONLY when an item is shipped by a merchant to avoid chargebacks and provide an Amazon-like payment experience. This will also help us avoid chargebacks and payment disputes in case a merchant is slow to ship or flakes out. In some cases, the goods will take more than 7 days to be custom manufactured and shipped out

Here's an example timeline:

1/1/2014 - Customer adds $75 worth of items to their cart and clicks "buy". Enters credit card info.

1/1/2014 - Customer's card is verified and a $75 temporary hold is placed on their card. Order is sent to merchant for fulfillment.

1/14/2014 - Merchant ships goods to customer and adds shipping tracking info

1/14/2014 - Customer's card is charged for the full amount and merchant receives $75 minus fees.

I plan to use Stripe Connect for payment processing, but am not sure how to delay capturing a payment for more than 7 days. Any thoughts? I don't want to aggregate the funds under my own account and use payouts since this will likely run afoul of money transmission laws. Any help would be appreciated!

EDIT: It looks like Quora has a similar question here , but the answers don't seem to deal with the case where a merchant ships out the item but the payment fails.

答: Stripe release a delay method to place a hold without charging. https://stripe.com/docs/payments/capture-later</p>


问:
How to install PHP 7.2.18 via asdf-php Plugin on MacOS
I'm trying to install PHP 7.2 via the asdf-php plugin.

I see a lot of error messages for missing libs (openssl, readline, zlib, ...).

答:
After lots of researches, trail and error and digging through GitHub issues, I found that this plugin is abandoned due to huge differences in the PHP build process. However I found a solution by doing the following:

xcode-select --install

sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /

brew tap magrathealabs/homebrew-mlabs
brew install pkg-config freetype bison bison27 gettext icu4c icu4c@58.1 jpeg libiconv libpng openssl readline zlib libedit

ln -s /usr/local/Cellar/openssl/1.0.2r/include/openssl /usr/local/include/openssl

export PHP_CONFIGURE_OPTIONS="--with-zlib-dir=$(brew --prefix zlib) --with-bz2=$(brew --prefix bzip2) --with-iconv=$(brew --prefix libiconv) --with-readline=$(brew --prefix readline) --with-libedit=$(brew --prefix libedit) --with-tidy=$(brew --prefix tidy-html5)"

export PKG_CONFIG_PATH="/usr/local/opt/openssl/lib/pkgconfig:/usr/local/opt/readline/lib/pkgconfig:/usr/local/opt/icu4c@58.1/lib/pkgconfig"

export CPPFLAGS="$CPPFLAGS -I/usr/local/opt/openssl/include -I/usr/local/opt/libedit/include -I/usr/local/opt/readline/include -I/usr/local/opt/icu4c@58.1/include"

export LDFLAGS="$LDFLAGS -L/usr/local/opt/openssl/lib -L/usr/local/opt/bison/lib -L/usr/local/opt/libedit/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/icu4c@58.1/lib"

export PATH="$(brew --prefix bison)/bin:$(brew --prefix icu4c@58.1)/bin:$(brew --prefix icu4c)/sbin:$PATH"

asdf install 7.2.18
```


问:
How to launch win32 executable desktop with 4 arguments from UWP project
I'm using UWP project to launch an win32 apps developed with Qt, but I need to pass some parameters (args). If I launch (.exe) without parameters it works.
I'm a beginner in UWP

Thanks for your help.

I've tried to use this code but was not succesful.

```<code>ApplicationData.Current.LocalSettings.Values["Parameters"] = tbParameters.Text;
           await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Parameters"); //Parameters
</code>```

答:
Assuming I understand your question correctly, please have a look at the following.

You can not pass parameters from UWP directly to your Win32 app. What you have to do is store the parameters in your packages LocalSettings first and then retrieve them within your Win32 app.

This is my code for saving four strings to the LocalSettings so that we can retrieve them later in our Win32 app. Again, note that we're not passing them directly, we're just saving them in the LocalSettings which our Win32 app can also access as long as it is included in our Package.

```<code>public static async void PrintFile(String string1, String, string2 String, string3 String string4 )
{

    ApplicationData.Current.LocalSettings.Values["param1"] = string1;
    ApplicationData.Current.LocalSettings.Values["param2"] = string2;
    ApplicationData.Current.LocalSettings.Values["param3"] = string3;
    ApplicationData.Current.LocalSettings.Values["param4"] = string4;

    if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
    {
        try
        {
            await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }

        catch (Exception Ex)
        {
            Debug.WriteLine(Ex.ToString());
        }
    }
}
</code>```

And then in the Win32 app, simply add something like the following in order to retrieve the parameters from the LocalSettings.

```<code>static void Main(string[] args)
{
    string string1 = ApplicationData.Current.LocalSettings.Values[@"param1"] as string;
    string string2 = ApplicationData.Current.LocalSettings.Values[@"param2"] as string;
    string string3 = ApplicationData.Current.LocalSettings.Values[@"param3"] as string;
    string string4 = ApplicationData.Current.LocalSettings.Values[@"param4"] as string;
}
</code>```

EDIT

If for whatever reason this is an unworkable solution (maybe the Win32 app is 3rd party and therefor you cannot modify the code), then you can still use the above code to achieve the same result.

1) Create a new Win32 app (My example uses a console app)

2) Pass your parameters from UWP to LocalSettings like above.

3) Pull the parameters from LocalSettings into the Win32 app when it has launched, like above.

4) Launch your 3rd party .exe file from your Win32 app with the specified parameters with something like the following...

```<code>private static Process CreateProcess(string exePath, string parameter)
{
    return new Process
    {
        StartInfo =
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = $@"""{exePath}""",
                Arguments = $@"""{parameter}""",
                UseShellExecute = false,
                CreateNoWindow = true
            }
    };
}
</code>```

EDIT 2

For completeness, the LocalSettings are stored inside your app package folder and can be retrieved here: C:\Users\"UserName"\AppData\Local\Packages\"PackageName"\Settings\settings.DAT

Body:
I'm using UWP project to launch an win32 apps developed with Qt, but I need to pass some parameters (args). If I launch (.exe) without parameters it works.
I'm a beginner in UWP

Thanks for your help.

I've tried to use this code but was not succesful.

ApplicationData.Current.LocalSettings.Values["Parameters"] = tbParameters.Text;
           await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Parameters"); //Parameters

Body:
Assuming I understand your question correctly, please have a look at the following.

You can not pass parameters from UWP directly to your Win32 app. What you have to do is store the parameters in your packages LocalSettings first and then retrieve them within your Win32 app.

This is my code for saving four strings to the LocalSettings so that we can retrieve them later in our Win32 app. Again, note that we're not passing them directly, we're just saving them in the LocalSettings which our Win32 app can also access as long as it is included in our Package.

public static async void PrintFile(String string1, String, string2 String, string3 String string4 )
{

    ApplicationData.Current.LocalSettings.Values["param1"] = string1;
    ApplicationData.Current.LocalSettings.Values["param2"] = string2;
    ApplicationData.Current.LocalSettings.Values["param3"] = string3;
    ApplicationData.Current.LocalSettings.Values["param4"] = string4;

    if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
    {
        try
        {
            await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }

        catch (Exception Ex)
        {
            Debug.WriteLine(Ex.ToString());
        }
    }
}

And then in the Win32 app, simply add something like the following in order to retrieve the parameters from the LocalSettings.

static void Main(string[] args)
{
    string string1 = ApplicationData.Current.LocalSettings.Values[@"param1"] as string;
    string string2 = ApplicationData.Current.LocalSettings.Values[@"param2"] as string;
    string string3 = ApplicationData.Current.LocalSettings.Values[@"param3"] as string;
    string string4 = ApplicationData.Current.LocalSettings.Values[@"param4"] as string;
}

EDIT

If for whatever reason this is an unworkable solution (maybe the Win32 app is 3rd party and therefor you cannot modify the code), then you can still use the above code to achieve the same result.

1) Create a new Win32 app (My example uses a console app)

2) Pass your parameters from UWP to LocalSettings like above.

3) Pull the parameters from LocalSettings into the Win32 app when it has launched, like above.

4) Launch your 3rd party .exe file from your Win32 app with the specified parameters with something like the following...

private static Process CreateProcess(string exePath, string parameter)
{
    return new Process
    {
        StartInfo =
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = $@"""{exePath}""",
                Arguments = $@"""{parameter}""",
                UseShellExecute = false,
                CreateNoWindow = true
            }
    };
}

EDIT 2

For completeness, the LocalSettings are stored inside your app package folder and can be retrieved here: C:\Users\"UserName"\AppData\Local\Packages\"PackageName"\Settings\settings.DAT


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答: Learn elisp so you can extend Emacs.</p>

OwnerDisplayName: Gregg Lind

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

Body: Learn elisp so you can extend Emacs.

OwnerDisplayName: TheProkrammer

ContentLicense: CC BY-SA 2.5


问:
To run ant commands through batch file
Please tell me how to call a command "ant deploy-hibernate" through batch file located in c: and i want to run the above command on trunk folder located in d: drive.The pupose is i want to run this command every time before i call a start-up for tomcat.Thanks in advance</p>

答:
```<code>cd /d d:\trunk
call c:\path\to\ant\bin\ant.bat deploy-hibernate
</code>```

Title: To run ant commands through batch file


问:
Refactoring long statement into a reusable function
Currently learning Selenium, using C# and Visual Studio, often you have to wait for a web element to become enabled before it can be interacted with, and as such you use a wait statement similar to:

```<code>using ec = SeleniumExtras.WaitHelpers.ExpectedConditions;
            IWebElement submitPassword = wait.Until(ec.ElementToBeClickable(By.Id("submitPassword")));
            submitPassword.Click();
</code>```

It's a lot to type out every single time, so I've tried to shorten it all to a simpler function, so far I have gotten as far as this:

```<code>        private static IWebElement waitById(WebDriverWait wait, String ElementId)
        {
        return wait.Until(ec.ElementToBeClickable(By.Id(ElementId)));
        }
</code>```

This lets me shorten the above to:

```<code> IWebElement passwordField= waitById(wait, "submitPassword");
 passwordField.Click();
</code>```

The method By. can be followed by several search types, e.g By.Name,By.ClassName,By.XPath etc.

I'd like my function to accept the search type, so I could do:

```<code>IWebElement passwordField= waitById(wait,ClassName, "submitPassword");
</code>```

And have it search by ClassName instead of Id, but I can't seem to get my function to accept this as a argument. When I look at the definition of By, it looks like each type is its own sub function (apologies if using incorrect terminology), I've tried just putting:

```<code>        private static IWebElement waitById(WebDriverWait wait,String SearchType, String ElementId)
        {
        return wait.Until(ec.ElementToBeClickable(By.SearchType(ElementId)));
        }
</code>```

But I just get an error saying By doesn't contain a definition for SearchType, so I'm not understanding how I pass this argument to that particular method. Googling has gotten me this close but I'm still a bit to green to fully get my head around how to solve this, any help appreciated.

答:
You should pass a By instance instead of a string. With your approach, you will have to write a method for each of the locator methods (id, xpath, css selector, name, etc.) and then yet another for each wait type (present, visible, clickable) which is going to turn into a LOT of methods. With a By, you can have just three methods, one for each wait type. Here's what I would use...

```<code>public IWebElement WaitForPresence(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(locator));
}

public IWebElement WaitForVisible(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(locator));
}

public IWebElement WaitForClickable(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(locator));
}
</code>```

I removed the static keyword because you should generally avoid it if you plan to run your automation in parallel. You can get yourself into trouble and have threads stepping on each other if you aren't careful.

I would avoid passing around an instance of a WebDriverWait because it is related to a specific driver instance and will cause problems if you plan to run in parallel.

Body:
Currently learning Selenium, using C# and Visual Studio, often you have to wait for a web element to become enabled before it can be interacted with, and as such you use a wait statement similar to:

using ec = SeleniumExtras.WaitHelpers.ExpectedConditions;
            IWebElement submitPassword = wait.Until(ec.ElementToBeClickable(By.Id("submitPassword")));
            submitPassword.Click();

It's a lot to type out every single time, so I've tried to shorten it all to a simpler function, so far I have gotten as far as this:

        private static IWebElement waitById(WebDriverWait wait, String ElementId)
        {
        return wait.Until(ec.ElementToBeClickable(By.Id(ElementId)));
        }

This lets me shorten the above to:

 IWebElement passwordField= waitById(wait, "submitPassword");
 passwordField.Click();

The method By. can be followed by several search types, e.g By.Name,By.ClassName,By.XPath etc.

I'd like my function to accept the search type, so I could do:

IWebElement passwordField= waitById(wait,ClassName, "submitPassword");

And have it search by ClassName instead of Id, but I can't seem to get my function to accept this as a argument. When I look at the definition of By, it looks like each type is its own sub function (apologies if using incorrect terminology), I've tried just putting:

        private static IWebElement waitById(WebDriverWait wait,String SearchType, String ElementId)
        {
        return wait.Until(ec.ElementToBeClickable(By.SearchType(ElementId)));
        }

But I just get an error saying By doesn't contain a definition for SearchType, so I'm not understanding how I pass this argument to that particular method. Googling has gotten me this close but I'm still a bit to green to fully get my head around how to solve this, any help appreciated.

Body:
You should pass a By instance instead of a string. With your approach, you will have to write a method for each of the locator methods (id, xpath, css selector, name, etc.) and then yet another for each wait type (present, visible, clickable) which is going to turn into a LOT of methods. With a By, you can have just three methods, one for each wait type. Here's what I would use...

public IWebElement WaitForPresence(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(locator));
}

public IWebElement WaitForVisible(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(locator));
}

public IWebElement WaitForClickable(By locator)
{
    return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(locator));
}

I removed the static keyword because you should generally avoid it if you plan to run your automation in parallel. You can get yourself into trouble and have threads stepping on each other if you aren't careful.

I would avoid passing around an instance of a WebDriverWait because it is related to a specific driver instance and will cause problems if you plan to run in parallel.


问:
Cannot resolve symbol 'logger' on DuplicateKeyException
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

```<code>@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}
</code>```

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

答:
Indeed, I didn't managed properly my imports:

I added:

```<code>    private final Log logger = LogFactory.getLog(TicketDaoImpl.class);
</code>```

from

org.apache.commons.logging.Log;

Stupid lack of attention.

I am having a look also at the doc from log4j/ sl4j on Baeldung. Thanks ^^

Body:
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

Body:
Indeed, I didn't managed properly my imports:

I added:

    private final Log logger = LogFactory.getLog(TicketDaoImpl.class);

from

org.apache.commons.logging.Log;

Stupid lack of attention.

I am having a look also at the doc from log4j/ sl4j on Baeldung. Thanks ^^


问:
Devise issues with soft-deleted Records. Any idea, how to fix it?
I'm using discard gem for Soft deletion. Once user gets Soft-Deleted, user can still receive forget password emails. Because Devise password controller does not care either its soft-deleted or not ?

I'm using following Devise modules, it seems, i may need to fix for all modules:-

:confirmable,

:recoverable,

:timeoutable,

:trackable

:lockable

:authenticatable

Though I'm able to fix login issue with authenticatable by overriding find_for_authentication method in user model, but it doesn't seem to be working with other Devise modules.

Any Idea, how i can fix soft-deletion issues with Devise ?

I'm using devise(4.6.2), discard (1.0.0), Rails 5.1.6.2

答:
You could use a default scope, ex:

```<code>class User
  ...
  default_scope -> { kept }
  ...
end
</code>```

Other discard scopes like discarded and with_discarded should keep working since they operate on the same column (discard_column), so they would override the default scope. That way, there's no need to override any of devise methods

Body:
You could use a default scope, ex:

class User
  ...
  default_scope -> { kept }
  ...
end

Other discard scopes like discarded and with_discarded should keep working since they operate on the same column (discard_column), so they would override the default scope. That way, there's no need to override any of devise methods


问:
set focus to input box
I have the existing code:

```<code> <form action="page.php?id=<?= $_GET['id'] ?>" method="post">
            <fieldset>
                <p id="edit_name"><label for="name">Page Name:</label><input type="text" name="name" value="<?PHP echo htmlspecialchars_decode($s->name);?>" id="name"> <input type="submit" src="../img/button_save.jpg" name="btnSubmit" value="Save" id="btnSubmit" class="submit"></p>
                <div id="show_name"<?= $_GET['edit'] ? ' style=" display: none"' : '' ?>><p><label for="name">Page Name:</label> <?PHP echo $s->name;?>   <a href="?id=<?= $_GET['id'] ?>&edit_name=1" onClick="$('edit_name').show(); $('show_name').hide(); return false;"><img style="vertical-align: top;" src="../img/button_change.png" alt="Change Name"></a></p></div>
                <?
                // for non-JS browsers
                if(!$_GET['edit']) {
                    ?>
                <script type="text/javascript">
                    $('edit_name').hide();
                </script>
                    <?
                }
                ?>
            </fieldset>
        </form>
</code>```

I want to also set focus to the input box on clicking change. Currently it just shows/hides upon clicking change.

Thanks!

答:
You can use:

```
$("#inputid").focus();
```

If you add that to the event that handles the displaying of the form (or add it to a document ready function such as

```
$(function(){
  $("#inputid").focus();
});
```

) it will also work on page load instead.

Title: set focus to input box

Body:
I have the existing code:

 <form action="page.php?id=<?= $_GET['id'] ?>" method="post">
            <fieldset>

Page Name:<input type="text" name="name" value="<?PHP echo htmlspecialchars_decode($s->name);?>" id="name"> <input type="submit" src="../img/button_save.jpg" name="btnSubmit" value="Save" id="btnSubmit" class="submit">

                <div id="show_name"<?= $_GET['edit'] ? ' style=" display: none"' : '' ?>>
Page Name: <?PHP echo $s->name;?>   <a href="?id=<?= $_GET['id'] ?>&edit_name=1" onClick="$('edit_name').show(); $('show_name').hide(); return false;">

                <?
                // for non-JS browsers
                if(!$_GET['edit']) {
                    ?>

                    <?
                }
                ?>
            </fieldset>
        </form>

I want to also set focus to the input box on clicking change. Currently it just shows/hides upon clicking change.

Thanks!

Body:
You can use:

$("#inputid").focus();

If you add that to the event that handles the displaying of the form (or add it to a document ready function such as

$(function(){
  $("#inputid").focus();
});

) it will also work on page load instead.


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

I have tried this:

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

I expect the outputs to be :

"TesT" gives True

"TEST" gives False

"test" gives False

答:
iamchoosinganame did it by means of simpler form (good answer!). If you want to keep your structure:

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

In addition, if you want to know where your regular expression find the first match, I would:

```<code>    def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    a = checker.search(input)
    if a:
        print('first match: ' + a.group(1))
        return True
    else:
        return False
</code>```

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

I have tried this:

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

I expect the outputs to be :

"TesT" gives True

"TEST" gives False

"test" gives False

Body:
iamchoosinganame did it by means of simpler form (good answer!). If you want to keep your structure:

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

In addition, if you want to know where your regular expression find the first match, I would:

    def consecutivelowercases(input):
    checker = re.compile(r'([a-z][a-z])')
    a = checker.search(input)
    if a:
        print('first match: ' + a.group(1))
        return True
    else:
        return False


问:
Angular 7 reactive forms - select position in a Form Build array
I need to select the position in the controls for the form builder array.

I need to do this: testArray.controls[0] but get a console error.

It works fine for testArray.controls. But that doesnt allow me to select a specific index in the form array

Component HTML:

```<code>   <div formArrayName="formArray">

         <div *ngFor="let item of testArray.controls[0]; let i = index"
         [formGroupName]="i">

         </div>

    </div>
</code>```

Component TS:

```<code>  public item = {
    field: [ '', [ Validators.required ] ]
  };

  public createForm(): void
    this.form = this.fb.group({
      formArray:  this.fb.array([ this.createItem() ]),
    });
  }

  get testArray(): FormArray {
    return this.form.get('formArray') as FormArray;
  }

  public createItem(): FormGroup {
    return this.fb.group(this.item);
  }
</code>```

答:
Sure you can, you just can't do it from within that for loop. When you're within the loop, you are already at the individual item level.

Here's a working stackblitz that demonstrates the idea, but the concept is this:

```<code><div [formGroup]="form">
  <div formArrayName="formArray">
    <h2> As array</h2>
    <div *ngFor="let item of testArray.controls; let i = index">
      <input formControlName="{{i}}"> Item value: {{ item.value }}
    </div>
    <div>
      <h2>Individually, get the second item</h2>
      <input [formControl]="testArray.controls[1]"> Item value: {{ item.value }}
    </div>
  </div>
</div>
</code>```

Body:
I need to select the position in the controls for the form builder array.

I need to do this: testArray.controls[0] but get a console error.

It works fine for testArray.controls. But that doesnt allow me to select a specific index in the form array

Component HTML:

Component TS:

  public item = {
    field: [ '', [ Validators.required ] ]
  };

  public createForm(): void
    this.form = this.fb.group({
      formArray:  this.fb.array([ this.createItem() ]),
    });
  }

  get testArray(): FormArray {
    return this.form.get('formArray') as FormArray;
  }

  public createItem(): FormGroup {
    return this.fb.group(this.item);
  }

Body:
Sure you can, you just can't do it from within that for loop. When you're within the loop, you are already at the individual item level.

Here's a working stackblitz that demonstrates the idea, but the concept is this:

<div [formGroup]="form">
  <div formArrayName="formArray">
    <h2> As array</h2>
    <div *ngFor="let item of testArray.controls; let i = index">
      <input formControlName="{{i}}"> Item value: {{ item.value }}
    </div>
    <div>
      <h2>Individually, get the second item</h2>
      <input [formControl]="testArray.controls[1]"> Item value: {{ item.value }}
    </div>
  </div>
</div>


问:
Computed Binding Not Detecting Change in Iron List
Polymer 1, I have in iron-list:

```<code>  <iron-list
    id="ironList"
    scroll-target="[[ironListScrollTarget]]"
    items="[[itemCollectionCopy]]">

    ...

        <div class="text center-justified info-icon">
          <iron-icon
            hidden="[[!_isDirtyData(item.*, itemCollectionCopy)]]"
            role="img"
            aria-label="Check-out information has been modified"
            title="Check-out information has been modified"
            icon="icons:info-outline"></iron-icon>
          <iron-icon
            hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]"
            role="img"
            class="pristine-data"
            aria-label="Check-out information has been modified"
            title="Check-out information has been modified"
            icon="icons:info-outline"></iron-icon>
        </div>
</code>```

```<code>    _isDirtyData: function(item) {
      console.log(item);
      return item.base.preferences;
    },

    setCustomPreference: function(e) {
      const id = e.detail.data.clientId;
      const preferences = e.detail.data.preferences;

      const foo = this.itemCollectionCopy.map((item) => {
          if (item.client_id === Number(id)) {
            item.preferences = preferences;
          }
          return item;
      });

      this.itemCollectionCopy = [];
      this.itemCollectionCopy = [...foo];
    },
</code>```

When adding a preferences object to item.preferences, I could not get the computed binding  hidden="[[_isDirtyData(item.*)]]" to detect a change. Instead, I had to add the whole array itemCollectionCopy in hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]" which seems excessive.

Why wouldn't the computed binding detect a change with just  hidden="[[_isDirtyData(item.*)]]"?

答:
The way polymer is observing changes in property is not perfect, and they added some array mutations methods to change array and notify templates of this changes.

You can use them if they work for your particular case.

https://polymer-library.polymer-project.org/1.0/docs/devguide/model-data#work-with-arrays

Sometime you want to perform operation in a JS way, or just there is no array mutation method adapted for your case.

There is a notifyPath method which can help also.

```<code>this.notifyPath('myarray.*');
</code>```

for example will trigger all corresponding observers.

Body:
Polymer 1, I have in iron-list:

  <iron-list
    id="ironList"
    scroll-target="[[ironListScrollTarget]]"
    items="[[itemCollectionCopy]]">

    ...

          <iron-icon
            hidden="[[!_isDirtyData(item.*, itemCollectionCopy)]]"
            role="img"
            aria-label="Check-out information has been modified"
            title="Check-out information has been modified"
            icon="icons:info-outline"></iron-icon>
          <iron-icon
            hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]"
            role="img"
            class="pristine-data"
            aria-label="Check-out information has been modified"
            title="Check-out information has been modified"
            icon="icons:info-outline"></iron-icon>

    _isDirtyData: function(item) {
      console.log(item);
      return item.base.preferences;
    },

    setCustomPreference: function(e) {
      const id = e.detail.data.clientId;
      const preferences = e.detail.data.preferences;

      const foo = this.itemCollectionCopy.map((item) => {
          if (item.client_id === Number(id)) {
            item.preferences = preferences;
          }
          return item;
      });

      this.itemCollectionCopy = [];
      this.itemCollectionCopy = [...foo];
    },

When adding a preferences object to item.preferences, I could not get the computed binding  hidden="[[_isDirtyData(item.*)]]" to detect a change. Instead, I had to add the whole array itemCollectionCopy in hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]" which seems excessive.

Why wouldn't the computed binding detect a change with just  hidden="[[_isDirtyData(item.*)]]"?

Body:
The way polymer is observing changes in property is not perfect, and they added some array mutations methods to change array and notify templates of this changes.

You can use them if they work for your particular case.

https://polymer-library.polymer-project.org/1.0/docs/devguide/model-data#work-with-arrays

Sometime you want to perform operation in a JS way, or just there is no array mutation method adapted for your case.

There is a notifyPath method which can help also.

this.notifyPath('myarray.*');

for example will trigger all corresponding observers.


问:
Finding memory leaks in a C++ application with Visual Studio
In Linux, I have been using valgrind for checking if there are memory leaks in an application. What is the equivalent in Windows? Can this be done with Visual Studio 2010?</p>

答:
Dr. Memory is a memory monitoring tool capable of identifying memory-related programming errors such as accesses of uninitialized memory, accesses to unaddressable memory (including outside of allocated heap units and heap underflow and overflow), accesses to freed memory, double frees, memory leaks, and (on Windows) handle leaks, GDI API usage errors, and accesses to un-reserved thread local storage slots.

Dr. Memory operates on unmodified application binaries running on Windows, Linux, Mac, or Android on commodity IA-32, AMD64, and ARM hardware.

Dr. Memory is built on the DynamoRIO dynamic instrumentation tool platform.


问:
Multiple criteria within a single SHOULD query block
I'm hooking into an API which I have no control over and would like to extract all recipe entries which match certain criteria. For the most part, this is a simple 'does value equal N', however for one of these criterion I also have to check if another value is greater than 0.

This code works absolutely fine:

should: [
  { match: { 'ItemResult.ItemAction.Type': 853 } },
  { match: { 'ItemResult.ItemAction.Type': 1013 } },
  { match: { 'ItemResult.ItemAction.Type': 1322 } },
  { match: { 'ItemResult.ItemAction.Type': 5845 } }
]
```

<p>It gives me all recipe entries whose <code>'ItemResult.ItemAction.Type</code> is either 853, 1013, 1322 or 5845 as expected. The problem comes with this new more complex condition to my <code>should</code> array:</p>

<pre class="lang-js prettyprint-override"><code>range: {
  'ItemResult.ItemAction.Type': { gte: 5100, lte: 5300 },
  'ItemResult.ItemAction.Data0': { gt: 0 }
}, ...
</code>```

Each individual range property works fine, but naturally I'm getting the following error when both are combined like they are above:

"reason":"[range] query doesn\'t support multiple fields

Is there a way I happily have both ranges considered within the same query without impacting the other ItemResult.ItemAction.Type values?

Obviously I can hook into the API a second time to perform the more complex criterion search, but I'm wondering if I can do it all in the one call.

答:
```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "range": {
                        "ItemResult.ItemAction.Type": {
                            "gte": 5100,
                            "lte": 5300
                        }
                    }
                },
                {
                    "range": {
                        "ItemResult.ItemAction.Data0": {
                            "gt": 0
                        }
                    }
                }
            ]
        }
    }
}

</code>```

Range from elasticsearch doesn't support multiple fields but you can use this query for having multiple range conditions.

Body:
I'm hooking into an API which I have no control over and would like to extract all recipe entries which match certain criteria. For the most part, this is a simple 'does value equal N', however for one of these criterion I also have to check if another value is greater than 0.

This code works absolutely fine:

should: [
  { match: { 'ItemResult.ItemAction.Type': 853 } },
  { match: { 'ItemResult.ItemAction.Type': 1013 } },
  { match: { 'ItemResult.ItemAction.Type': 1322 } },
  { match: { 'ItemResult.ItemAction.Type': 5845 } }
]

It gives me all recipe entries whose 'ItemResult.ItemAction.Type is either 853, 1013, 1322 or 5845 as expected. The problem comes with this new more complex condition to my should array:

range: {
  'ItemResult.ItemAction.Type': { gte: 5100, lte: 5300 },
  'ItemResult.ItemAction.Data0': { gt: 0 }
}, ...

Each individual range property works fine, but naturally I'm getting the following error when both are combined like they are above:

"reason":"[range] query doesn\'t support multiple fields

Is there a way I happily have both ranges considered within the same query without impacting the other ItemResult.ItemAction.Type values?

Obviously I can hook into the API a second time to perform the more complex criterion search, but I'm wondering if I can do it all in the one call.

Body:
{
    "query": {
        "bool": {
            "must": [
                {
                    "range": {
                        "ItemResult.ItemAction.Type": {
                            "gte": 5100,
                            "lte": 5300
                        }
                    }
                },
                {
                    "range": {
                        "ItemResult.ItemAction.Data0": {
                            "gt": 0
                        }
                    }
                }
            ]
        }
    }
}

Range from elasticsearch doesn't support multiple fields but you can use this query for having multiple range conditions.


问:
Read words from paragraph to paragraph, from line to line (C++)
I'm looking for a way to read and locate words (line number, paragraph number) from a file.

For example, I want to track the number of the word "you" in a file. Each time I find this word on a line, I will push the line number and the paragraph number to the two vectors

```<code>ifstream file;
file.open(input.txt)
vector<int> paragraph_number;
vector<int> line_number;
</code>```

What's the best way to read paragraph by paragraph and line by line? Thank you!

答:
Supposing

paragraphs are separated by at least one empty line, so a line just containing a newline

a line even with only spaces is not an empty line, but that has no real sense and I let you changing that ;-)

the program memorizes the number of paragraph line and column where the word appears, all these numbers start by 1, and the line number is global rather than the line rank into the paragraph

a word only contains alphanumeric character, so all other characters are considered to be a separator. That allows to find the word "isn" or "t" in "this isn't possible" even they are not separated by a space with the other words, or to find "jean" in "jean-luc" etc

the program does not check if the input word is a valid word

A proposal  :

```<code>#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main(int argc, char ** argv)
{
  if (argc != 3)
      std::cerr << "Usage: " << *argv << " <file path> <word>" << std::endl;
  else {
    std::ifstream f(argv[1]);

    if (! f.is_open())
      std::cerr << "Cannot open '" << argv[1] << '\'' << std::endl;
    else {
      std::string word = argv[2];
      std::string line;
      size_t line_num = 0;
      size_t paragraph_num = 0;
      std::vector<size_t> paragraph_number;
      std::vector<size_t> line_number;
      std::vector<size_t> column_number;
      bool afterEmptyLine = true;

      while (std::getline(f, line)) {
        line_num += 1;
        if (!line.empty()) {
          if (afterEmptyLine) {
            afterEmptyLine = false;
            paragraph_num += 1;
          }

          std::size_t p = 0;

          while ((p = line.find(word, p)) != std::string::npos) {
            // check it is not a subword, suppose a word is only alphanum
            if (((p == 0) || !isalnum(line[p - 1])) &&
                ((line.length() == (p + word.length())) || !isalnum(line[p + word.length()]))) {
              paragraph_number.push_back(paragraph_num);
              line_number.push_back(line_num);
              column_number.push_back(p + 1);
            }

            p += word.length();
          }
        }
        else
          afterEmptyLine = true;
      }

      /* debug */
      std::cout << '\'' << word << "' found " << paragraph_number.size() << " times :" << std::endl;

      for (size_t i = 0; i != paragraph_number.size(); ++i)
        std::cout << "\t paragraph " << paragraph_number[i]
          << " line " << line_number[i]
            << " column " << column_number[i] << std::endl;
    }
  }

  return 0;
}
</code>```

Compilation and execution :

```<code>bruno@bruno-XPS-8300:/tmp$ g++ -pedantic -Wextra -Wall c.cc
bruno@bruno-XPS-8300:/tmp$ cat fw
is it you or not you?
this is your decision and you are right

you and me

you
bruno@bruno-XPS-8300:/tmp$ ./a.out
Usage: ./a.out <file path> <word>
bruno@bruno-XPS-8300:/tmp$ ./a.out fw you
'you' found 5 times :
     paragraph 1 line 1 column 7
     paragraph 1 line 1 column 18
     paragraph 1 line 2 column 27
     paragraph 2 line 4 column 1
     paragraph 3 line 8 column 1
bruno@bruno-XPS-8300:/tmp$
</code>```

(in the file the empty lines are really empty)

Body:
I'm looking for a way to read and locate words (line number, paragraph number) from a file.

For example, I want to track the number of the word "you" in a file. Each time I find this word on a line, I will push the line number and the paragraph number to the two vectors

ifstream file;
file.open(input.txt)
vector<int> paragraph_number;
vector<int> line_number;

What's the best way to read paragraph by paragraph and line by line? Thank you!

Body:
Supposing

paragraphs are separated by at least one empty line, so a line just containing a newline

a line even with only spaces is not an empty line, but that has no real sense and I let you changing that ;-)

the program memorizes the number of paragraph line and column where the word appears, all these numbers start by 1, and the line number is global rather than the line rank into the paragraph

a word only contains alphanumeric character, so all other characters are considered to be a separator. That allows to find the word "isn" or "t" in "this isn't possible" even they are not separated by a space with the other words, or to find "jean" in "jean-luc" etc

the program does not check if the input word is a valid word

A proposal  :

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main(int argc, char ** argv)
{
  if (argc != 3)
      std::cerr << "Usage: " << *argv << " <file path> <word>" << std::endl;
  else {
    std::ifstream f(argv[1]);

    if (! f.is_open())
      std::cerr << "Cannot open '" << argv[1] << '\'' << std::endl;
    else {
      std::string word = argv[2];
      std::string line;
      size_t line_num = 0;
      size_t paragraph_num = 0;
      std::vector<size_t> paragraph_number;
      std::vector<size_t> line_number;
      std::vector<size_t> column_number;
      bool afterEmptyLine = true;

      while (std::getline(f, line)) {
        line_num += 1;
        if (!line.empty()) {
          if (afterEmptyLine) {
            afterEmptyLine = false;
            paragraph_num += 1;
          }

          std::size_t p = 0;

          while ((p = line.find(word, p)) != std::string::npos) {
            // check it is not a subword, suppose a word is only alphanum
            if (((p == 0) || !isalnum(line[p - 1])) &&
                ((line.length() == (p + word.length())) || !isalnum(line[p + word.length()]))) {
              paragraph_number.push_back(paragraph_num);
              line_number.push_back(line_num);
              column_number.push_back(p + 1);
            }

            p += word.length();
          }
        }
        else
          afterEmptyLine = true;
      }

      /* debug */
      std::cout << '\'' << word << "' found " << paragraph_number.size() << " times :" << std::endl;

      for (size_t i = 0; i != paragraph_number.size(); ++i)
        std::cout << "\t paragraph " << paragraph_number[i]
          << " line " << line_number[i]
            << " column " << column_number[i] << std::endl;
    }
  }

  return 0;
}

Compilation and execution :

bruno@bruno-XPS-8300:/tmp$ g++ -pedantic -Wextra -Wall c.cc
bruno@bruno-XPS-8300:/tmp$ cat fw
is it you or not you?
this is your decision and you are right

you and me

you
bruno@bruno-XPS-8300:/tmp$ ./a.out
Usage: ./a.out <file path> <word>
bruno@bruno-XPS-8300:/tmp$ ./a.out fw you
'you' found 5 times :
     paragraph 1 line 1 column 7
     paragraph 1 line 1 column 18
     paragraph 1 line 2 column 27
     paragraph 2 line 4 column 1
     paragraph 3 line 8 column 1
bruno@bruno-XPS-8300:/tmp$

(in the file the empty lines are really empty)


问:
Individual column searching filter for js sourced data using DataTable.js with filter at the top
I am unable to place the filter selects at the top. How do I achive?

I stuck to initComplete option as it is triggered just once upon DataTable fully initialized and API methods can be called safely.

Also where exactly would I make the column drop down values unnique

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing
 if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('

');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table></code>```

答:
You can replace the content of the column-headers by using .appendTo( $(column.header()).empty() ). You also can add the eventlisteners inside the initComplete-callback and attach them directly to the inputs.

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Lorem ipsum", "Accountant", "Edinburgh", "1562", "2011/07/25", "$86,000"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
    title: header
  })),
  initComplete: function () {
    this.api().columns().every( function () {
      let column = this;
      let select = $('<select><option value="">All</option></select>')
      .appendTo( $(column.header()).empty() )
      .on( 'change, click', function ( e ) {
        e.stopPropagation();
        let val = $.fn.dataTable.util.escapeRegex( $(this).val() );
        column.search( val ? '^'+val+'$' : '', true, false ).draw();
      });
      column.data().unique().sort().each( function ( d, j ) {
        select.append( '<option value="'+d+'">'+d+'</option>' )
      });
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table></code>```

Body:
I am unable to place the filter selects at the top. How do I achive?

I stuck to initComplete option as it is triggered just once upon DataTable fully initialized and API methods can be called safely.

Also where exactly would I make the column drop down values unnique

const dataSet = [
      ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
      ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
      ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
    ];

    const dataTable = $('#example').DataTable({
        data: dataSet,
        dom: 't',
        columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
            title: header
          })),
        initComplete: function () {
          //purge existing
 if exists
          $('#example tfoot').remove();
          //append new footer to the table
          $('#example').append('

');
          //iterate through table columns
          this.api().columns().every(function () {
            //append <select> node to each column footer inserting
            //current column().index() as a "colindex" attribute
            $('#example tfoot tr').append(`<th><select colindex="${this.index()}"></select></th>`);
            //grab unique sorted column entries and translate those into <option> nodes
            const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '<option value=""></option>');
            //append options to corresponding <select>
            $(`#example tfoot th:eq(${this.index()}) select`).append(options);
          });
        }
      });

    $('#example').on('change', 'tfoot select', function (event) {
      //use "colindex" attribute value to search corresponding column for selected option value
      dataTable.column($(event.target).attr('colindex')).search($(event.target).val()).draw();
    })

<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>

Body:
You can replace the content of the column-headers by using .appendTo( $(column.header()).empty() ). You also can add the eventlisteners inside the initComplete-callback and attach them directly to the inputs.

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Lorem ipsum", "Accountant", "Edinburgh", "1562", "2011/07/25", "$86,000"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
];

const dataTable = $('#example').DataTable({
  data: dataSet,
  dom: 't',
  columns: ['Name', 'Job Title', 'Location', 'Id', 'Hire Date', 'Salary'].map(header => ({
    title: header
  })),
  initComplete: function () {
    this.api().columns().every( function () {
      let column = this;
      let select = $('<select><option value="">All</option></select>')
      .appendTo( $(column.header()).empty() )
      .on( 'change, click', function ( e ) {
        e.stopPropagation();
        let val = $.fn.dataTable.util.escapeRegex( $(this).val() );
        column.search( val ? '^'+val+'$' : '', true, false ).draw();
      });
      column.data().unique().sort().each( function ( d, j ) {
        select.append( '<option value="'+d+'">'+d+'</option>' )
      });
    });
  }
});

<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example">
</table>


答:
Try something like this :</p>

```<code>ifstream file("input.txt");

vector<int> paragraph_number;
vector<int> line_number;
string line, word;
int curr_paragraph_num = 0;
int curr_line_num = 0;
bool in_paragraph = false;

while (getline(file, line))
{
    ++curr_line_num;
    if (line.empty())
    {
        in_paragraph = false;
    }
    else
    {
        if (!in_paragraph)
        {
            in_paragraph = true;
            ++curr_paragraph_num;
        }

        istringstream iss(line);
        while (iss >> word)
        {
            if (word == "you")
            {
                paragraph_number.push_back(curr_paragraph_num);
                line_number.push_back(curr_line_num);
            }
        }
    }
}
</code>```

Title: Read words from paragraph to paragraph, from line to line (C++)

Body:
Try something like this :

ifstream file("input.txt");

vector<int> paragraph_number;
vector<int> line_number;
string line, word;
int curr_paragraph_num = 0;
int curr_line_num = 0;
bool in_paragraph = false;

while (getline(file, line))
{
    ++curr_line_num;
    if (line.empty())
    {
        in_paragraph = false;
    }
    else
    {
        if (!in_paragraph)
        {
            in_paragraph = true;
            ++curr_paragraph_num;
        }

        istringstream iss(line);
        while (iss >> word)
        {
            if (word == "you")
            {
                paragraph_number.push_back(curr_paragraph_num);
                line_number.push_back(curr_line_num);
            }
        }
    }
}