问:
Iteration problem with pairs of coordinates, python
I'm having a hard time figuring out, why I can't -

1) Iterate over the set of coordinates that's created from coords,

2) Finding the streets overall when the link pops up (usually with sets of 20 listings)

3) Find the exact vicinities that have only "road" written.

Please help.

My end goal is to yield a set of coordinates that provide me vicinities in a radius of 9000, and within those vicinities, I can find "road" and other keywords.

```<code>import requests
import json

APIKEY = "akakak"

import geopandas as gpd
pagetoken = akakakakakak
pagetoken = None
fp = "/Users/akakak/Documents/akakak/akakaka.shp"
data = gpd.read_file(fp)
enugu = data.loc[data['ADM1FIPSNA'] == 'Enugu']
coords=[]

for long, lat in zip(enugu.geometry.y, enugu.geometry.x):
    coords.append((long,lat))

def findPlaces(loc = ('x','y'), radius=9000, pagetoken = None):
    loc = coords.append((long,lat))
    type = "school"
    xtype = "vicinity"
    xxtype = "road"
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{long}&radius={radius}&type={type}&key={APIKEY}{pagetoken}".format(lat = lat, long = long, radius = radius, type = type,APIKEY = APIKEY, pagetoken = "&pagetoken="+pagetoken if pagetoken else "")
    print(url)
    response = requests.get(url)
    res = json.loads(response.text)
    print(res)
    print("here results ---->>> ", len(res["results"]))
    for result in res["results"]:
        if xxtype in res["results"]:
            if xtype in result["vicinity"]:
                info = ";".join(map(str,[result["name"],result["geometry"]["location"]["lat"],result["geometry"]["location"]["lng"],result["types"]]))
                print(info)
    '
</code>```

答:
Because the code is incomplete and not runnable, I can only guess what you want to do. But once you have an array/list, you can access elements of the list using indexes or by iterating through the list.

In your def findPlaces() func, change the first few lines, like so:

```<code>def findPlaces(loc, radius=9000, pagetoken = None):
    # loc = coords.append((long,lat))
    loc = long, lat
    type = 'school'
       :
</code>```

And after the func, try iterating through coords, with something like:

```<code>for loc in coords:
    findPlaces(loc)
</code>```

Hopefully this will help you make some progress. Beyond this, you would really need to post more complete code, along with data files. Ideally you would post something that we can run and see what happens. Stubbing data is a common practice when asking for help.

Body:
I'm having a hard time figuring out, why I can't -

1) Iterate over the set of coordinates that's created from coords,

2) Finding the streets overall when the link pops up (usually with sets of 20 listings)

3) Find the exact vicinities that have only "road" written.

Please help.

My end goal is to yield a set of coordinates that provide me vicinities in a radius of 9000, and within those vicinities, I can find "road" and other keywords.

import requests
import json

APIKEY = "akakak"

import geopandas as gpd
pagetoken = akakakakakak
pagetoken = None
fp = "/Users/akakak/Documents/akakak/akakaka.shp"
data = gpd.read_file(fp)
enugu = data.loc[data['ADM1FIPSNA'] == 'Enugu']
coords=[]

for long, lat in zip(enugu.geometry.y, enugu.geometry.x):
    coords.append((long,lat))

def findPlaces(loc = ('x','y'), radius=9000, pagetoken = None):
    loc = coords.append((long,lat))
    type = "school"
    xtype = "vicinity"
    xxtype = "road"
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{long}&radius={radius}&type={type}&key={APIKEY}{pagetoken}".format(lat = lat, long = long, radius = radius, type = type,APIKEY = APIKEY, pagetoken = "&pagetoken="+pagetoken if pagetoken else "")
    print(url)
    response = requests.get(url)
    res = json.loads(response.text)
    print(res)
    print("here results ---->>> ", len(res["results"]))
    for result in res["results"]:
        if xxtype in res["results"]:
            if xtype in result["vicinity"]:
                info = ";".join(map(str,[result["name"],result["geometry"]["location"]["lat"],result["geometry"]["location"]["lng"],result["types"]]))
                print(info)
    '

Body:
Because the code is incomplete and not runnable, I can only guess what you want to do. But once you have an array/list, you can access elements of the list using indexes or by iterating through the list.

In your def findPlaces() func, change the first few lines, like so:

def findPlaces(loc, radius=9000, pagetoken = None):
    # loc = coords.append((long,lat))
    loc = long, lat
    type = 'school'
       :

And after the func, try iterating through coords, with something like:

for loc in coords:
    findPlaces(loc)

Hopefully this will help you make some progress. Beyond this, you would really need to post more complete code, along with data files. Ideally you would post something that we can run and see what happens. Stubbing data is a common practice when asking for help.


来源: stackexchange

问:
how to access tag slider value in iphone sdk?
i have a question regarding slider tags. Lets assume i have a slider and its tag is "1", how can i get the .value of slider that has tag '1'? I saw examples of if(slider.tag ==1) but i want to access the value of it - how is this possible? thanks</p>

答:
Use the viewWithTag: method on the superview:

```<code>UISlider *slider1 = [slidersView viewWithTag:1];
if (slider1) {
    NSLog(@"Value of slider 1: %f", slider1.value);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use the viewWithTag: method on the superview:

UISlider *slider1 = [slidersView viewWithTag:1];
if (slider1) {
    NSLog(@"Value of slider 1: %f", slider1.value);
}


问:
Postman and Browser have different behavior with my middleware
I'm getting into the backend with Node and express , I wanted to create a middleware that show on the console that the route was not found if you try to do a request to a route that does not exist , so I did this way

```<code>server.get('/' , (req,res) => {
    res.render('index.html')
})

server.use((req,res,next) => {
    console.log('NOT FOUND')
})

</code>```

If i'm not wrong , this middleware should just execute if I do the request to a route that is not / since it is the only that exist , and when I try in postman it have exactly the behavior that it should , but when I try on the browser it execute the middleware even if the request is to / and my view is render and sometimes it even execute it two times and it show NOT FOUND two times on the console

I don't know why Postman and the Browser are doing different things , Am I doing something wrong?

Thanks for the help

答: If I do a console log on the middleware of req,originalUrl it shows /favicon.ico , but why does it try to load a favicon if I dont have any reference to it in my html ? , my html just have the basic structure and no more , how could I solve this ? Anyway thanks for the answer because I feel more close to solve the problem than before for sure</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm getting into the backend with Node and express , I wanted to create a middleware that show on the console that the route was not found if you try to do a request to a route that does not exist , so I did this way

server.get('/' , (req,res) => {
    res.render('index.html')
})

server.use((req,res,next) => {
    console.log('NOT FOUND')
})

If i'm not wrong , this middleware should just execute if I do the request to a route that is not / since it is the only that exist , and when I try in postman it have exactly the behavior that it should , but when I try on the browser it execute the middleware even if the request is to / and my view is render and sometimes it even execute it two times and it show NOT FOUND two times on the console

I don't know why Postman and the Browser are doing different things , Am I doing something wrong?

Thanks for the help


问:
Is there a function in R that can convert a "time" factor (00:00:00) into seconds
Is there a function in R that can convert a "time" factor into seconds?</p>

```<code>Time <- tibble(ID = 1:4, Time = c("00:03:36", "00:02:14", "01:10:25", "00:32:10"))
</code>```

答:
```<code>library(lubridate)
library(dplyr)
Time %>% mutate(secs = period_to_seconds(hms(Time)))
## A tibble: 4 x 3
#     ID Time      secs
#  <int> <chr>    <dbl>
#1     1 00:03:36   216
#2     2 00:02:14   134
#3     3 01:10:25  4225
#4     4 00:32:10  1930
</code>```

Body:
Is there a function in R that can convert a "time" factor into seconds?

Time <- tibble(ID = 1:4, Time = c("00:03:36", "00:02:14", "01:10:25", "00:32:10"))


问:
Unable to open LiClipse 6.1.0 on MacOS/Catalina (10.15.3)
I have downloaded LiClipse 6.1.0 from http://www.liclipse.com/download.html three times (to ensure that I don't have a corrupt/damaged file) and installed it on a MacPro Notebook with MacOS Catalina (10.15.3). I have followed the installation instructions at http://www.liclipse.com/download.html for Native Mac OS Install, but every time I get "“LiClipse.app” is damaged and can’t be opened. You should move it to the Trash."

Since it gets installed without any problem, I think that downloaded file is not corrupted/damaged, but when opening it I always get the warning about its being damaged even when I have run sudo spctl --master-disable to enable apps from "Anywhere" to run.
I would appreciate if anyone who had succeeded in opening it on a MacPro/Catalina would share his/her steps. Thanks.

答:
You can try removing the quarantine flag (when Mac downloads a file it marks it as quarantined and it won't run unless it has an Apple signature -- which LiClipse doesn't have, so, Apple is making it always a bit harder to run files you download).

To remove the quarantine flag, run:

xattr -d com.apple.quarantine <FILE>

(<FILE> being /Applications/LiClipse.app and maybe /Applications/LiClipse.app/MacOS/LiClipse too -- I don't really have Catalina to check).


问:
What should go inside a functional component
While writing a functional component in React, where do you keep the constants and utility functions? Inside the react component or outside?

import React from 'react';

// A global constant
const EARTH_RADIUS = 3959;

// A utility function
const volume = () => {
  return (4/3) * (22/7) * Math.pow(EARTH_RADIUS, 3);
}

const MyComponent = () => {
  return (

Earth's radius: {EARTH_RADIUS}

{volume()}

  )
}
```

Should EARTH_RADIUS and volume be inside MyComponent? Is there any rule when to include or exclude, what's the best practice for this?

答:
A good way to do it is creating a folder called config or utils to put this kind of code in order to reused it in others components.

I hope this help you

Body:
While writing a functional component in React, where do you keep the constants and utility functions? Inside the react component or outside?

import React from 'react';

// A global constant
const EARTH_RADIUS = 3959;

// A utility function
const volume = () => {
  return (4/3) * (22/7) * Math.pow(EARTH_RADIUS, 3);
}

const MyComponent = () => {
  return (

Earth's radius: {EARTH_RADIUS}

{volume()}

  )
}

Should EARTH_RADIUS and volume be inside MyComponent? Is there any rule when to include or exclude, what's the best practice for this?


问:
an array of datetime values
i have the following code where i try and populate an array with dates from 1988-2016

```<code>from datetime import datetime, timedelta
t = np.arange(datetime(1988,1,1), datetime(2016,1,1), timedelta(days=365)).astype(datetime)
</code>```

This gives me the following output:

```<code>array([datetime.datetime(1988, 1, 1, 0, 0),
       datetime.datetime(1988, 12, 31, 0, 0),
       datetime.datetime(1989, 12, 31, 0, 0),
                 ....
       datetime.datetime(2015, 12, 25, 0, 0)], dtype=object)
</code>```

However, for my output i just want to have the year and not the month or day and i dont want that datetime.datetime at the begining. So i am aming for something like this:

```<code>array([(1988)
      (1989),
      (1990),
        ...
      (2015)], dtype=object)
</code>```

How can i achieve this?

答:
This should give you an array of both the years as datetime objects. </p>

```<code>year_objects = []
num_years = 20
start_year = 1988
for i in range(num_years):
    x = datetime.datetime(start_year + i, 1, 1)
    year_objects.append(x)
</code>```

Title: an array of datetime values

Body:
i have the following code where i try and populate an array with dates from 1988-2016

from datetime import datetime, timedelta
t = np.arange(datetime(1988,1,1), datetime(2016,1,1), timedelta(days=365)).astype(datetime)

This gives me the following output:

array([datetime.datetime(1988, 1, 1, 0, 0),
       datetime.datetime(1988, 12, 31, 0, 0),
       datetime.datetime(1989, 12, 31, 0, 0),
                 ....
       datetime.datetime(2015, 12, 25, 0, 0)], dtype=object)

However, for my output i just want to have the year and not the month or day and i dont want that datetime.datetime at the begining. So i am aming for something like this:

array([(1988)
      (1989),
      (1990),
        ...
      (2015)], dtype=object)

How can i achieve this?

Body:
This should give you an array of both the years as datetime objects.

year_objects = []
num_years = 20
start_year = 1988
for i in range(num_years):
    x = datetime.datetime(start_year + i, 1, 1)
    year_objects.append(x)


问:
How to use python timedelta function
I am using the below logic to calculate the average timedelta inside a python list.

```<code>from datetime import datetime,timedelta

def entry_rate(entry_timestamps):
   entry_deltas = [d1-d2 for d1,
                d2 in zip(entry_timestamps[1:], entry_timestamps[:-1])]
   average_timedelta = (sum(entry_deltas, timedelta(
                0)) / len(entry_deltas)).total_seconds() if len(entry_deltas) != 0 else -1.0
   return average_timedelta
</code>```

Here is the input to the function:-

```<code>entry_timestamps = [datetime.datetime(2019, 11, 13, 7, 36, 21), datetime.datetime(2019, 11, 13, 7, 40, 53), datetime.datetime(2019, 11, 13, 7, 45, 25), datetime.datetime(2019, 11, 13, 7, 49, 58), datetime.datetime(2019, 11, 13, 7, 54, 30), datetime.datetime(2019, 11, 13, 7, 58, 32), datetime.datetime(2019, 11, 13, 8, 2, 34), datetime.datetime(2019, 11, 13, 8, 6, 36), datetime.datetime(2019, 11, 13, 8, 10, 38), datetime.datetime(2019, 11, 13, 8, 14, 40), datetime.datetime(2019, 11, 13, 8, 18, 42), datetime.datetime(2019, 11, 13, 8, 22, 44), datetime.datetime(2019, 11, 13, 8, 26, 46), datetime.datetime(2019, 11, 13, 8, 29, 18)]
</code>```

However, I am getting the below error.

 in prepare_llog(llog_pd)
      288
      289     result_df['entry_rate'] =\
  --> 290         result_df['entry_timestamps'].apply(lambda x: compute_entry_rate(x))
      291
      292

~/miniconda3/envs/jupyter_21f8c25de0/lib/python3.6/site-packages/pandas/core/series.py
  in apply(self, func, convert_dtype, args, **kwds)    4043

  else:    4044                 values = self.astype(object).values
  -> 4045                 mapped = lib.map_infer(values, f, convert=convert_dtype)    4046     4047         if len(mapped) and
  isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

 in (x)
      288
      289     result_df['entry_rate'] =\
  --> 290         result_df['entry_timestamps'].apply(lambda x: compute_entry_rate(x))
      291
      292

 in
  compute_entry_rate(entry_timestamps)
       49
       50     average_timedelta = (sum(entry_deltas, timedelta(
  ---> 51         0)) / len(entry_deltas)).total_seconds() if len(entry_deltas) != 0 else -1.0
       52     return average_timedelta
       53

TypeError: _() takes 1 positional argument but 2 were given

Can anyone please suggest how to fix this?

答:
You can do this with pandas like this:

```<code>S = pd.Series([datetime.datetime(2019, 11, 13, 7, 36, 21),
    datetime.datetime(2019, 11, 13, 7, 40, 53),
    datetime.datetime(2019, 11, 13, 7, 45, 25),
    datetime.datetime(2019, 11, 13, 7, 49, 58),
    datetime.datetime(2019, 11, 13, 7, 54, 30),
    datetime.datetime(2019, 11, 13, 7, 58, 32),
    datetime.datetime(2019, 11, 13, 8, 2, 34),
    datetime.datetime(2019, 11, 13, 8, 6, 36),
    datetime.datetime(2019, 11, 13, 8, 10, 38),
    datetime.datetime(2019, 11, 13, 8, 14, 40),
    datetime.datetime(2019, 11, 13, 8, 18, 42),
    datetime.datetime(2019, 11, 13, 8, 22, 44),
    datetime.datetime(2019, 11, 13, 8, 26, 46),
    datetime.datetime(2019, 11, 13, 8, 29, 18)])

S.diff().mean().total_seconds()
</code>```

Output:

```<code>244.384615384
</code>```

Where as your function, entry_rate returns, without errors.:

```<code> entry_rate(entry_timestamps)
</code>```

Output:

```<code> 244.384615
</code>```

Timings:

Using entry_rate:

5.16 µs ± 193 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Using pandas functions:

389 µs ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops
  each)

Title: How to use python timedelta function

Body:
I am using the below logic to calculate the average timedelta inside a python list.

from datetime import datetime,timedelta

def entry_rate(entry_timestamps):
   entry_deltas = [d1-d2 for d1,
                d2 in zip(entry_timestamps[1:], entry_timestamps[:-1])]
   average_timedelta = (sum(entry_deltas, timedelta(
                0)) / len(entry_deltas)).total_seconds() if len(entry_deltas) != 0 else -1.0
   return average_timedelta

Here is the input to the function:-

entry_timestamps = [datetime.datetime(2019, 11, 13, 7, 36, 21), datetime.datetime(2019, 11, 13, 7, 40, 53), datetime.datetime(2019, 11, 13, 7, 45, 25), datetime.datetime(2019, 11, 13, 7, 49, 58), datetime.datetime(2019, 11, 13, 7, 54, 30), datetime.datetime(2019, 11, 13, 7, 58, 32), datetime.datetime(2019, 11, 13, 8, 2, 34), datetime.datetime(2019, 11, 13, 8, 6, 36), datetime.datetime(2019, 11, 13, 8, 10, 38), datetime.datetime(2019, 11, 13, 8, 14, 40), datetime.datetime(2019, 11, 13, 8, 18, 42), datetime.datetime(2019, 11, 13, 8, 22, 44), datetime.datetime(2019, 11, 13, 8, 26, 46), datetime.datetime(2019, 11, 13, 8, 29, 18)]

However, I am getting the below error.

 in prepare_llog(llog_pd)
      288
      289     result_df['entry_rate'] =\
  --> 290         result_df['entry_timestamps'].apply(lambda x: compute_entry_rate(x))
      291
      292

~/miniconda3/envs/jupyter_21f8c25de0/lib/python3.6/site-packages/pandas/core/series.py
  in apply(self, func, convert_dtype, args, **kwds)    4043

  else:    4044                 values = self.astype(object).values
  -> 4045                 mapped = lib.map_infer(values, f, convert=convert_dtype)    4046     4047         if len(mapped) and
  isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

 in (x)
      288
      289     result_df['entry_rate'] =\
  --> 290         result_df['entry_timestamps'].apply(lambda x: compute_entry_rate(x))
      291
      292

 in
  compute_entry_rate(entry_timestamps)
       49
       50     average_timedelta = (sum(entry_deltas, timedelta(
  ---> 51         0)) / len(entry_deltas)).total_seconds() if len(entry_deltas) != 0 else -1.0
       52     return average_timedelta
       53

TypeError: _() takes 1 positional argument but 2 were given

Can anyone please suggest how to fix this?

Body:
You can do this with pandas like this:

S = pd.Series([datetime.datetime(2019, 11, 13, 7, 36, 21),
    datetime.datetime(2019, 11, 13, 7, 40, 53),
    datetime.datetime(2019, 11, 13, 7, 45, 25),
    datetime.datetime(2019, 11, 13, 7, 49, 58),
    datetime.datetime(2019, 11, 13, 7, 54, 30),
    datetime.datetime(2019, 11, 13, 7, 58, 32),
    datetime.datetime(2019, 11, 13, 8, 2, 34),
    datetime.datetime(2019, 11, 13, 8, 6, 36),
    datetime.datetime(2019, 11, 13, 8, 10, 38),
    datetime.datetime(2019, 11, 13, 8, 14, 40),
    datetime.datetime(2019, 11, 13, 8, 18, 42),
    datetime.datetime(2019, 11, 13, 8, 22, 44),
    datetime.datetime(2019, 11, 13, 8, 26, 46),
    datetime.datetime(2019, 11, 13, 8, 29, 18)])

S.diff().mean().total_seconds()

Output:

244.384615384

Where as your function, entry_rate returns, without errors.:

 entry_rate(entry_timestamps)

Output:

 244.384615

Timings:

Using entry_rate:

5.16 µs ± 193 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Using pandas functions:

389 µs ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops
  each)


问:
How can I remove the line endings from output
The command I'm running is:

```<code>locate -b '\java' | xargs -ri  find {} -prune -type f -executable | xargs bash -c '$0 -version'
</code>```

Below is the response

```<code>java version "1.6.0_41"
OpenJDK Runtime Environment (IcedTea6 1.13.13) (rhel-1.13.13.1.el6_8-x86_64)
OpenJDK 64-Bit Server VM (build 23.41-b41, mixed mode)
</code>```

What I'm hoping to do is place this all on 1 line.

I've tried various sed and awk but is always comes back as 3 lines.

答:
Add:

```<code>| awk '{printf "%s%s", sep, $0; sep=OFS} END{print ""}'
</code>```

to the end of your existing pipline. If that doesn't change the output then chances are it's going to stderr rather than stdout so then change the above to:

```<code>2>&1 | awk '{printf "%s%s", sep, $0; sep=OFS} END{print ""}'
</code>```

Body:
The command I'm running is:

locate -b '\java' | xargs -ri  find {} -prune -type f -executable | xargs bash -c '$0 -version'

Below is the response

java version "1.6.0_41"
OpenJDK Runtime Environment (IcedTea6 1.13.13) (rhel-1.13.13.1.el6_8-x86_64)
OpenJDK 64-Bit Server VM (build 23.41-b41, mixed mode)

What I'm hoping to do is place this all on 1 line.

I've tried various sed and awk but is always comes back as 3 lines.

Body:
Add:

| awk '{printf "%s%s", sep, $0; sep=OFS} END{print ""}'

to the end of your existing pipline. If that doesn't change the output then chances are it's going to stderr rather than stdout so then change the above to:

2>&1 | awk '{printf "%s%s", sep, $0; sep=OFS} END{print ""}'


问:
Swift equivalent to Objective-C FourCharCode single quote literals (e.g. 'TEXT')
I am trying replicate some Objective C cocoa in Swift. All is good until I come across the following:

```<code>// Set a new type and creator:
unsigned long type = 'TEXT';
unsigned long creator = 'pdos';
</code>```

How can I create Int64s (or the correct Swift equivalent) from single quote character literals like this?

Types:

```<code>public typealias AEKeyword = FourCharCode
public typealias OSType = FourCharCode
public typealias FourCharCode = UInt32
</code>```

答:
Swift 5 Update:</p>

```<code>extension String {
    func osType() -> OSType {
        return OSType(
            data(using: .macOSRoman)?
                .withUnsafeBytes {
                    $0.reduce(into: UInt(0)) { $0 = $0 << 8 + UInt($1) }
                } ?? 0
        )
    }
}
</code>```

Body:
I am trying replicate some Objective C cocoa in Swift. All is good until I come across the following:

// Set a new type and creator:
unsigned long type = 'TEXT';
unsigned long creator = 'pdos';

How can I create Int64s (or the correct Swift equivalent) from single quote character literals like this?

Types:

public typealias AEKeyword = FourCharCode
public typealias OSType = FourCharCode
public typealias FourCharCode = UInt32

Body:
Swift 5 Update:

extension String {
    func osType() -> OSType {
        return OSType(
            data(using: .macOSRoman)?
                .withUnsafeBytes {
                    $0.reduce(into: UInt(0)) { $0 = $0 << 8 + UInt($1) }
                } ?? 0
        )
    }
}


问:
How to get test value from CDATA in xml file using java
I'm trying to get the MethodName value from the CDATA node in xml file.

XML file looks like-

```<code><params>
            <param index="0">
              <value>
                <![CDATA[{PackageResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedPackageResponse.json, ProviderRequest=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderRequest.json, ParameterFilePath=./src/test/resources/TestData/RequestParameter/InstantCash/GetAnywherePayoutAgents.json, ProviderResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderResponse.json, MethodName=GetAnywherePayoutAgents}]]>
              </value>
            </param>
          </params>
</code>```

What i have tried is only giving me all text value of this-

JAVA Code-

```<code>public static String getCharacterDataFromElement(Element e) {

        NodeList list = e.getChildNodes();
        String data;

        for(int index = 0; index < list.getLength(); index++){
            if(list.item(index) instanceof CharacterData){
                CharacterData child = (CharacterData) list.item(index);
                data = child.getData();

                if(data != null && data.trim().length() > 0)
                    return child.getData();
            }
        }
        return "";
    }
</code>```

But i want only methodName value from CDATA. Please help!

答:
You already have method for retrieving CDATA content. To extract MethodName or other fields from this text there can be implemented custom parsing function, e.g.:

```<code>public static String getMethodName(String source, String fieldName) {
        if(source.startsWith("{") && source.endsWith("}")) {
            source = source.substring(1, source.length() - 1);
        }
        return Arrays.asList(source.split(",")).stream()
                .map(s -> s.trim().split("="))
                .filter(s -> fieldName.equals(s[0]))
                .map(s -> s[1])
                .findFirst()
                .orElse(null);
}
</code>```

It splits text by commas, than splits each token by equal signs, than searches for supplied field name and returns text after equal sign (or null if not found). It can be called as follows:

```<code>String cdata = getCharacterDataFromElement(element);
String methodName = getMethodName(cdata , "MethodName");
</code>```

Body:
I'm trying to get the MethodName value from the CDATA node in xml file.

XML file looks like-

<params>
            <param index="0">
              <value>
                <![CDATA[{PackageResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedPackageResponse.json, ProviderRequest=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderRequest.json, ParameterFilePath=./src/test/resources/TestData/RequestParameter/InstantCash/GetAnywherePayoutAgents.json, ProviderResponse=./src/test/resources/TestData/ExpectedData/InstantCash/GetAnywherePayoutAgents/ExpectedProviderResponse.json, MethodName=GetAnywherePayoutAgents}]]>
              </value>
            </param>
          </params>

What i have tried is only giving me all text value of this-

JAVA Code-

public static String getCharacterDataFromElement(Element e) {

        NodeList list = e.getChildNodes();
        String data;

        for(int index = 0; index < list.getLength(); index++){
            if(list.item(index) instanceof CharacterData){
                CharacterData child = (CharacterData) list.item(index);
                data = child.getData();

                if(data != null && data.trim().length() > 0)
                    return child.getData();
            }
        }
        return "";
    }

But i want only methodName value from CDATA. Please help!

Body:
You already have method for retrieving CDATA content. To extract MethodName or other fields from this text there can be implemented custom parsing function, e.g.:

public static String getMethodName(String source, String fieldName) {
        if(source.startsWith("{") && source.endsWith("}")) {
            source = source.substring(1, source.length() - 1);
        }
        return Arrays.asList(source.split(",")).stream()
                .map(s -> s.trim().split("="))
                .filter(s -> fieldName.equals(s[0]))
                .map(s -> s[1])
                .findFirst()
                .orElse(null);
}

It splits text by commas, than splits each token by equal signs, than searches for supplied field name and returns text after equal sign (or null if not found). It can be called as follows:

String cdata = getCharacterDataFromElement(element);
String methodName = getMethodName(cdata , "MethodName");


问:
React.StrictMode: SetState function in useEffect is run multiple times when effect is run once
The output of the code below when oldRunIn is undefined is as expected when the effect is triggered:

Effect is running

setState is running

However, the next time useEffect runs with the state variable runInArrow defined, which is referred to as oldRunInArrow in the setState function the output is:

Effect is running

setState is running

setState is running

setState is running

How is it possible that the effect runs only one time but the setState runs 3 times?

```<code>const [runInArrow, setRunInArrow] = useState<mapkit.PolylineOverlay[] | undefined>(undefined);

useEffect(() => {
      const trueRunIn = settings.magneticRunIn + magVar;

      const boundingRegion = region.toBoundingRegion();
      const style = new mapkit.Style({
        lineWidth: 5,
        lineJoin: 'round',
        strokeColor: settings.runInColor,
      });
      const newRunInArrow = createArrow(boundingRegion, trueRunIn, style);
      console.log('Effect is running');

      setRunInArrow(oldRunIn => {

        // This runs too many times when oldRunIn aka runInArrow is defined

        console.log('setState is running');
        if (oldRunIn) map.removeOverlays(oldRunIn);
        return newRunInArrow;
      });
      map.addOverlays(newRunInArrow);
  }, [magVar, map, mapkit, region, settings.magneticRunIn, settings.runInColor, settings.showRunIn]);
</code>```

To understand why I'm using a function to set state see this post

Edit:

This is strange. if I remove if (oldRunIn) map.removeOverlays(oldRunIn); it works as expected. However if I change it to if (oldRunIn) console.log('oldRunIn is defined'); it still runs multiple times. I'm thoroughly confused.

if (oldRunIn) map.addAnnotations([]); does not run multiple times.

if (oldRunIn) console.log('test'); does run multiple times.

This runs multiple times (6 times per use effect) always:

```<code>  setRunInArrow(oldRunIn => {
    console.log('setState is running');
    console.log('test');
    return newRunInArrow;
  });
</code>```

This does not run multiple times:

```<code>  setRunInArrow(oldRunIn => {
    console.log('setState is running');
    return newRunInArrow;
  });
</code>```

Edit 2:

Reproducible example. Click the button. You don't even need to have if (oldState) console.log('Old state'); you can just put in 2nd console.log and it will change the behavior.

```<code>import { FunctionComponent, useState, useEffect } from 'react';

export const Test: FunctionComponent<> = function Test() {
  const [state, setState] = useState<number | undefined>(undefined);
  const [triggerEffect, setTriggerEffect] = useState(0);

  useEffect(() => {
    console.log('effect is running');
    setState(oldState => {
      console.log('setState is runnning');
      if (oldState) console.log('Old state');
      return 1;
    });
  }, [triggerEffect]);

  return <>
    <button onClick={() => setTriggerEffect(triggerEffect + 1)} type="button">Trigger Effect</button>
  </>;
};
</code>```

Edit 3:

I've reproduced this by putting this code into another nextJS project. I'm guessing it has to do with nextJS.

Edit 4:

It's not NextJS. It's wrapping it in React.StrictMode. Here is a sandbox. Why?

Edit 5:

As the answer pointed out the issue is due to StrictMode intentionally running code twice. It should not run useReducer twice per the docs (this is an issue with "react-hooks/exhaustive-deps" from my other question). Here is a UseReducer demo, try with and without StrictMode. It also runs twice. Seems like it needs to be pure too:

CodeSandbox

```<code>import { useState, useEffect, useReducer } from 'react';

function reducer(state, data) {
  console.log('Reducer is running');
  if (state) console.log(state);
  return state + 1;
}

export const Test = function Test() {
  const [state, dispatch] = useReducer(reducer, 1);
  const [triggerEffect, setTriggerEffect] = useState(0);

  useEffect(() => {
    dispatch({});
  }, [triggerEffect]);

  return (
    <>
      <button onClick={() => setTriggerEffect(triggerEffect + 1)} type="button">
        Trigger Effect
      </button>
    </>
  );
};

const Home = () => (
  <React.StrictMode>
    <Test></Test>
  </React.StrictMode>
);

export default Home;
</code>```

答:
As you've figured out, this is happening when you use React strict mode, and it is intentional.

As noted in this article:

It runs code TWICE

Another thing that React Strict Mode does is run certain callbacks/methods twice (in DEV mode ONLY). You read that right! The following callbacks/methods will be run twice in Strict Mode (in DEV mode ONLY):

Class component constructor method

The render method (includes function components)

setState updater functions (the first argument)

The static getDerivedStateFromProps lifecycle

The React.useState state initializer callback function

The React.useMemo callback

Checkout this codesandbox which logs to the console in hook callbacks and class methods to show you that certain things happen twice.

React does this because it cannot reliably warn you against side-effects you do in those methods. But if those methods are idempotent, then calling them multiple times shouldn't cause any trouble. If they are not idempotent, then you should notice funny things which you should hopefully be able to notice and fix.

Note that useEffect and useLayoutEffect callbacks are not called twice even in dev mode + strict mode because the entire point of those callbacks is to perform side-effects.

Note that I also observed that the reducer you pass to React.useReducer is not called twice in dev mode. I'm not sure why this is because I feel like that could also benefit from this kind of warning.

As seen above, this behavior is included to help you find bugs in your code. Since the updater functions should be idempotent and pure, running them twice instead of once should have no effect on your app's functionality. If it does, then that's a bug in your code.

It sounds like the map.removeOverlays() method you're calling is an effectful function, so it should not be called within a state updater function. I can see why you've implemented it this way based on the answers to your other question, but I think using chitova263's answer would remedy this issue.

Body:
The output of the code below when oldRunIn is undefined is as expected when the effect is triggered:

Effect is running

setState is running

However, the next time useEffect runs with the state variable runInArrow defined, which is referred to as oldRunInArrow in the setState function the output is:

Effect is running

setState is running

setState is running

setState is running

How is it possible that the effect runs only one time but the setState runs 3 times?

const [runInArrow, setRunInArrow] = useState<mapkit.PolylineOverlay[] | undefined>(undefined);

useEffect(() => {
      const trueRunIn = settings.magneticRunIn + magVar;

      const boundingRegion = region.toBoundingRegion();
      const style = new mapkit.Style({
        lineWidth: 5,
        lineJoin: 'round',
        strokeColor: settings.runInColor,
      });
      const newRunInArrow = createArrow(boundingRegion, trueRunIn, style);
      console.log('Effect is running');

      setRunInArrow(oldRunIn => {

        // This runs too many times when oldRunIn aka runInArrow is defined

        console.log('setState is running');
        if (oldRunIn) map.removeOverlays(oldRunIn);
        return newRunInArrow;
      });
      map.addOverlays(newRunInArrow);
  }, [magVar, map, mapkit, region, settings.magneticRunIn, settings.runInColor, settings.showRunIn]);

To understand why I'm using a function to set state see this post

Edit:

This is strange. if I remove if (oldRunIn) map.removeOverlays(oldRunIn); it works as expected. However if I change it to if (oldRunIn) console.log('oldRunIn is defined'); it still runs multiple times. I'm thoroughly confused.

if (oldRunIn) map.addAnnotations([]); does not run multiple times.

if (oldRunIn) console.log('test'); does run multiple times.

This runs multiple times (6 times per use effect) always:

  setRunInArrow(oldRunIn => {
    console.log('setState is running');
    console.log('test');
    return newRunInArrow;
  });

This does not run multiple times:

  setRunInArrow(oldRunIn => {
    console.log('setState is running');
    return newRunInArrow;
  });

Edit 2:

Reproducible example. Click the button. You don't even need to have if (oldState) console.log('Old state'); you can just put in 2nd console.log and it will change the behavior.

import { FunctionComponent, useState, useEffect } from 'react';

export const Test: FunctionComponent<> = function Test() {
  const [state, setState] = useState<number | undefined>(undefined);
  const [triggerEffect, setTriggerEffect] = useState(0);

  useEffect(() => {
    console.log('effect is running');
    setState(oldState => {
      console.log('setState is runnning');
      if (oldState) console.log('Old state');
      return 1;
    });
  }, [triggerEffect]);

  return <>
    <button onClick={() => setTriggerEffect(triggerEffect + 1)} type="button">Trigger Effect</button>
  </>;
};

Edit 3:

I've reproduced this by putting this code into another nextJS project. I'm guessing it has to do with nextJS.

Edit 4:

It's not NextJS. It's wrapping it in React.StrictMode. Here is a sandbox. Why?

Edit 5:

As the answer pointed out the issue is due to StrictMode intentionally running code twice. It should not run useReducer twice per the docs (this is an issue with "react-hooks/exhaustive-deps" from my other question). Here is a UseReducer demo, try with and without StrictMode. It also runs twice. Seems like it needs to be pure too:

CodeSandbox

import { useState, useEffect, useReducer } from 'react';

function reducer(state, data) {
  console.log('Reducer is running');
  if (state) console.log(state);
  return state + 1;
}

export const Test = function Test() {
  const [state, dispatch] = useReducer(reducer, 1);
  const [triggerEffect, setTriggerEffect] = useState(0);

  useEffect(() => {
    dispatch({});
  }, [triggerEffect]);

  return (
    <>
      <button onClick={() => setTriggerEffect(triggerEffect + 1)} type="button">
        Trigger Effect
      </button>
    </>
  );
};

const Home = () => (
  <React.StrictMode>
    <Test></Test>
  </React.StrictMode>
);

export default Home;


问:
SonataAdmin child admin route visible in debug but not found
php bin/console debug:router |grep postboxmessage

```<code>  pt__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/list
  pl__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/list
  en__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/list
  pt__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/create
  pl__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/create
  en__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/create
  pt__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/batch
  pl__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/batch
  en__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/batch
  pt__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/{id}/edit
  pl__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/{id}/edit
  en__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/{id}/edit
  pt__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/{id}/delete
  pl__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/{id}/delete
  en__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/{id}/delete
  pt__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/export
  pl__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/export
  en__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/export
  pt__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/send
  pl__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/send
  en__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/send
  pt__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/list
  pl__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/list
  en__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/list
  pt__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/create
  pl__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/create
  en__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/create
  pt__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/batch
  pl__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/batch
  en__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/batch
  pt__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  pl__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  en__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  pt__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  pl__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  en__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  pt__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  pl__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  en__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  pt__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/export
  pl__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/export
  en__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/export
</code>```

php bin/console router:match  /en/admin/app/postboxthread/{id}/postboxmessage/list

[OK] Route "en__RG__admin_app_postboxthread_postboxmessage_list" matches

```<code>+--------------+-------------------------------------------------------------------------------------------+
| Property     | Value                                                                                |
+--------------+-------------------------------------------------------------------------------------------+
| Route Name   | en__RG__admin_app_postboxthread_postboxmessage_list                                       |
| Path         | /en/admin/app/postboxthread/{id}/postboxmessage/list                                      |
| Path Regex   | #^/en/admin/app/postboxthread/(?P<id>[^/]++)/postboxmessage/list$#sD                      |
| Host         | ANY                                                                                |
| Host Regex   |                                                                                |
| Scheme       | ANY                                                                                |
| Method       | ANY                                                                                |
| Requirements | NO CUSTOM                                                                                |
| Class        | Symfony\Component\Routing\Route                                                           |
| Defaults     | _controller: Mea\PostBoxBundle\Sonata\Controller\PostBoxMessageCrudController::listAction |
|              | _locale: en                                                                               |
|              | _sonata_admin: mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message           |
|              | _sonata_name: admin_app_postboxthread_postboxmessage_list                                 |
| Options      | compiler_class: Symfony\Component\Routing\RouteCompiler                                   |
+--------------+-------------------------------------------------------------------------------------------+
</code>```

This example partial work, but this route I guessed :)

PostBoxThreadAdmin

```<code> /**
     * {@inheritdoc}
     */
    protected function configureTabMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null): void
    {
        if (!$childAdmin && !in_array($action, ['edit'])) {
            return;
        }

        $admin = $this->isChild() ? $this->getParent() : $this;

        $id = $admin->getRequest()->get('id');

        if ($this->isGranted('EDIT')) {
            $menu->addChild('Edit Thread', [
                'uri' => $admin->generateUrl('edit', ['id' => $id])
            ]);
        }

        $menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.message.list', ['id' => $id])
        );

    }
</code>```

When i try

```<code>$menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.message', ['id' => $id])
        );
</code>```

get

```<code>An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message`").
</code>```

try

```<code>   $menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message', ['id' => $id])
        );
</code>```

get

```<code>An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message`").
</code>```

try

```<code>  $menu->addChild('Messages',
            $admin->generateMenuUrl('admin_app_postboxthread_postboxmessage_list', ['id' => $id])
        );
</code>```

get

```<code>An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread.admin_app_postboxthread_postboxmessage_list`").
</code>```

When i use

$menu->addChild('Messages',
                $admin->generateMenuUrl('mea.postbox.sonata.admin.message.list', ['id' => $id])
            );

child panel is shown but when i create new and save - i get

```<code>unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message.send`

RuntimeException
in vendor/sonata-project/admin-bundle/src/Route/DefaultRouteGenerator.php (line 109)
in vendor/sonata-project/admin-bundle/src/Route/DefaultRouteGenerator.php->generateMenuUrl (line 60)
in vendor/Mea/PostBoxBundle/Sonata/Admin/PostBoxMessageAdmin.php->generateUrl (line 190)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->configureFormFields (line 1267)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->defineFormBuilder (line 1254)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->getFormBuilder (line 2980)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->buildForm (line 1311)
in vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php->getForm (line 336)
in vendor/symfony/http-kernel/HttpKernel.php->editAction (line 149)
in vendor/symfony/http-kernel/HttpKernel.php->handleRaw (line 66)
in vendor/symfony/http-kernel/Kernel.php->handle (line 188)
Kernel->handle(object(Request))
in public/index.php (line 37)
    Request::setTrustedHosts(explode(',', $trustedHosts));}$kernel = new Kernel($env, $debug);$request = Request::createFromGlobals();$response = $kernel->handle($request);$response->send();$kernel->terminate($request, $response);
</code>```

So Sonata try use route  _sonata_admin: mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message  but is not accessible

答:
You can do it like this:

```<code>'uri' => str_replace('{id}',$id,'/admin/app/property/{id}/property-media/list')
</code>```

If you need the route, you can find it with:

```<code>bin/console debug:router
</code>```

Body:
php bin/console debug:router |grep postboxmessage

  pt__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/list
  pl__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/list
  en__RG__admin_mea_postbox_postboxmessage_list                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/list
  pt__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/create
  pl__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/create
  en__RG__admin_mea_postbox_postboxmessage_create              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/create
  pt__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/batch
  pl__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/batch
  en__RG__admin_mea_postbox_postboxmessage_batch               ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/batch
  pt__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/{id}/edit
  pl__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/{id}/edit
  en__RG__admin_mea_postbox_postboxmessage_edit                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/{id}/edit
  pt__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/{id}/delete
  pl__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/{id}/delete
  en__RG__admin_mea_postbox_postboxmessage_delete              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/{id}/delete
  pt__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/export
  pl__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/export
  en__RG__admin_mea_postbox_postboxmessage_export              ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/export
  pt__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /admin/mea/postbox/postboxmessage/send
  pl__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /pl/admin/mea/postbox/postboxmessage/send
  en__RG__admin_mea_postbox_postboxmessage_send                ANY        ANY      ANY    /en/admin/mea/postbox/postboxmessage/send
  pt__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/list
  pl__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/list
  en__RG__admin_app_postboxthread_postboxmessage_list          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/list
  pt__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/create
  pl__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/create
  en__RG__admin_app_postboxthread_postboxmessage_create        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/create
  pt__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/batch
  pl__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/batch
  en__RG__admin_app_postboxthread_postboxmessage_batch         ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/batch
  pt__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  pl__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  en__RG__admin_app_postboxthread_postboxmessage_edit          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/edit
  pt__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  pl__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  en__RG__admin_app_postboxthread_postboxmessage_delete        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/delete
  pt__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  pl__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  en__RG__admin_app_postboxthread_postboxmessage_show          ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/{childId}/show
  pt__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /admin/app/postboxthread/{id}/postboxmessage/export
  pl__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /pl/admin/app/postboxthread/{id}/postboxmessage/export
  en__RG__admin_app_postboxthread_postboxmessage_export        ANY        ANY      ANY    /en/admin/app/postboxthread/{id}/postboxmessage/export

php bin/console router:match  /en/admin/app/postboxthread/{id}/postboxmessage/list

[OK] Route "en__RG__admin_app_postboxthread_postboxmessage_list" matches

+--------------+-------------------------------------------------------------------------------------------+
| Property     | Value                                                                                |
+--------------+-------------------------------------------------------------------------------------------+
| Route Name   | en__RG__admin_app_postboxthread_postboxmessage_list                                       |
| Path         | /en/admin/app/postboxthread/{id}/postboxmessage/list                                      |
| Path Regex   | #^/en/admin/app/postboxthread/(?P<id>[^/]++)/postboxmessage/list$#sD                      |
| Host         | ANY                                                                                |
| Host Regex   |                                                                                |
| Scheme       | ANY                                                                                |
| Method       | ANY                                                                                |
| Requirements | NO CUSTOM                                                                                |
| Class        | Symfony\Component\Routing\Route                                                           |
| Defaults     | _controller: Mea\PostBoxBundle\Sonata\Controller\PostBoxMessageCrudController::listAction |
|              | _locale: en                                                                               |
|              | _sonata_admin: mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message           |
|              | _sonata_name: admin_app_postboxthread_postboxmessage_list                                 |
| Options      | compiler_class: Symfony\Component\Routing\RouteCompiler                                   |
+--------------+-------------------------------------------------------------------------------------------+

This example partial work, but this route I guessed :)

PostBoxThreadAdmin

 /**
     * {@inheritdoc}
     */
    protected function configureTabMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null): void
    {
        if (!$childAdmin && !in_array($action, ['edit'])) {
            return;
        }

        $admin = $this->isChild() ? $this->getParent() : $this;

        $id = $admin->getRequest()->get('id');

        if ($this->isGranted('EDIT')) {
            $menu->addChild('Edit Thread', [
                'uri' => $admin->generateUrl('edit', ['id' => $id])
            ]);
        }

        $menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.message.list', ['id' => $id])
        );

    }

When i try

$menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.message', ['id' => $id])
        );

get

An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message`").

try

   $menu->addChild('Messages',
            $admin->generateMenuUrl('mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message', ['id' => $id])
        );

get

An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message`").

try

  $menu->addChild('Messages',
            $admin->generateMenuUrl('admin_app_postboxthread_postboxmessage_list', ['id' => $id])
        );

get

An exception has been thrown during the rendering of a template ("unable to find the route `mea.postbox.sonata.admin.thread.admin_app_postboxthread_postboxmessage_list`").

When i use

$menu->addChild('Messages',
                $admin->generateMenuUrl('mea.postbox.sonata.admin.message.list', ['id' => $id])
            );

child panel is shown but when i create new and save - i get

unable to find the route `mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message.send`

RuntimeException
in vendor/sonata-project/admin-bundle/src/Route/DefaultRouteGenerator.php (line 109)
in vendor/sonata-project/admin-bundle/src/Route/DefaultRouteGenerator.php->generateMenuUrl (line 60)
in vendor/Mea/PostBoxBundle/Sonata/Admin/PostBoxMessageAdmin.php->generateUrl (line 190)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->configureFormFields (line 1267)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->defineFormBuilder (line 1254)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->getFormBuilder (line 2980)
in vendor/sonata-project/admin-bundle/src/Admin/AbstractAdmin.php->buildForm (line 1311)
in vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php->getForm (line 336)
in vendor/symfony/http-kernel/HttpKernel.php->editAction (line 149)
in vendor/symfony/http-kernel/HttpKernel.php->handleRaw (line 66)
in vendor/symfony/http-kernel/Kernel.php->handle (line 188)
Kernel->handle(object(Request))
in public/index.php (line 37)
    Request::setTrustedHosts(explode(',', $trustedHosts));}$kernel = new Kernel($env, $debug);$request = Request::createFromGlobals();$response = $kernel->handle($request);$response->send();$kernel->terminate($request, $response);

So Sonata try use route  _sonata_admin: mea.postbox.sonata.admin.thread|mea.postbox.sonata.admin.message  but is not accessible

Body:
You can do it like this:

'uri' => str_replace('{id}',$id,'/admin/app/property/{id}/property-media/list')

If you need the route, you can find it with:

bin/console debug:router


问:
Select 'Foo', 'Bar' not returning anything
I just started using Postgre SQL, I've been on Oracle and pl/sql for about 5 years no.

I'm trying to do a simple select statement and not getting the results I expect.

My code is as follows:

```<code>SELECT 'Foo','Bar'
FROM   APP_TABLE
</code>```

Where APP_TABLE is a table in my database. When ran, it returns 0 records. In Oracle that would return [Foo][Bar] as my results. Why does this not return anything in Postgres?

From some research I found that this works:

```<code>SELECT  'Foo','Bar'
FROM    (Values('1'))
</code>```

and I get the expected [Foo][Bar] as my results, but not sure this is the best approach. Any help is appreciated!

答:
You could create a dummy dual table having only 1 row and 1 field.

You could also do it the  Postgres way, by not specifying any table at all:

```<code>SELECT 'Foo','Bar';
 ?column? | ?column?
----------+----------
 Foo      | Bar
(1 row)
</code>```

Body:
I just started using Postgre SQL, I've been on Oracle and pl/sql for about 5 years no.

I'm trying to do a simple select statement and not getting the results I expect.

My code is as follows:

SELECT 'Foo','Bar'
FROM   APP_TABLE

Where APP_TABLE is a table in my database. When ran, it returns 0 records. In Oracle that would return [Foo][Bar] as my results. Why does this not return anything in Postgres?

From some research I found that this works:

SELECT  'Foo','Bar'
FROM    (Values('1'))

and I get the expected [Foo][Bar] as my results, but not sure this is the best approach. Any help is appreciated!

Body:
You could create a dummy dual table having only 1 row and 1 field.

You could also do it the  Postgres way, by not specifying any table at all:

SELECT 'Foo','Bar';
 ?column? | ?column?
----------+----------
 Foo      | Bar
(1 row)


答:
An option with as.ITime

```<code>library(data.table)
as.numeric(as.ITime(Time$Time) )
#[1]  216  134 4225 1930
</code>```

Title: Is there a function in R that can convert a "time" factor (00:00:00) into seconds

Body:
Is there a function in R that can convert a "time" factor into seconds?

Time <- tibble(ID = 1:4, Time = c("00:03:36", "00:02:14", "01:10:25", "00:32:10"))

Body:
An option with as.ITime

library(data.table)
as.numeric(as.ITime(Time$Time) )
#[1]  216  134 4225 1930


问:
for loop repeats itself in python
I have created a web bot that iterates over a website e.g example.com/?id=int where int is some integer. the function gets the result in raw html using requests library then hands it to parseAndWrite to extract a div and save its value in a sqlite db:

```<code>def archive(initial_index, final_index):
    while True:
        try:
            for i in range(initial_index, final_index):
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

        except requests.exceptions.ConnectionError:
            print("[-] Connection lost. ")
            continue
        except:
            exit(1)
        break

archive(1, 10000)
</code>```

My problem is that, after some time, the loop doesn't continue to 10000 but repeats itself from a random value, resulting in many duplicate records in the database. What is causing this inconsistency ?

答:
If any connection error occurs, you restart at initial_index. Instead, you could retry the current index again and again, until the connection succeeds:

```<code>def archive(initial_index, final_index):
    for i in range(initial_index, final_index):
        while True:
            try:
                response = requests.get(f'https://www.example.com/?id={i}')
                parseAndWrite(response.text)
                print(f'{i} archived')
            except requests.exceptions.ConnectionError:
                print("[-] Connection lost. ")
            else:
                break

archive(1, 10000)
</code>```

Title: for loop repeats itself in python

Body:
I have created a web bot that iterates over a website e.g example.com/?id=int where int is some integer. the function gets the result in raw html using requests library then hands it to parseAndWrite to extract a div and save its value in a sqlite db:

def archive(initial_index, final_index):
    while True:
        try:
            for i in range(initial_index, final_index):
                res = requests.get('https://www.example.com/?id='+str(i))
                parseAndWrite(res.text)
                print(i, ' archived')

        except requests.exceptions.ConnectionError:
            print("[-] Connection lost. ")
            continue
        except:
            exit(1)
        break

archive(1, 10000)

My problem is that, after some time, the loop doesn't continue to 10000 but repeats itself from a random value, resulting in many duplicate records in the database. What is causing this inconsistency ?

Body:
If any connection error occurs, you restart at initial_index. Instead, you could retry the current index again and again, until the connection succeeds:

def archive(initial_index, final_index):
    for i in range(initial_index, final_index):
        while True:
            try:
                response = requests.get(f'https://www.example.com/?id={i}')
                parseAndWrite(response.text)
                print(f'{i} archived')
            except requests.exceptions.ConnectionError:
                print("[-] Connection lost. ")
            else:
                break

archive(1, 10000)


问:
Read all values from CSV into a List using CsvHelper
So I've been reading that I shouldn't write my own CSV reader/writer, so I've been trying to use the CsvHelper library installed via nuget. The CSV file is a grey scale image, with the number of rows being the image height and the number columns the width. I would like to read the values row-wise into a single List<string> or List<byte>.

The code I have so far is:

```<code>using CsvHelper;

public static List<string> ReadInCSV(string absolutePath)
{
    IEnumerable<string> allValues;

    using (TextReader fileReader = File.OpenText(absolutePath))
    {
        var csv = new CsvReader(fileReader);
        csv.Configuration.HasHeaderRecord = false;
        allValues = csv.GetRecords<string>
    }

    return allValues.ToList<string>();
}
</code>```

But allValues.ToList<string>() is throwing a:

CsvConfigurationException was unhandled by user code

An exception of type 'CsvHelper.Configuration.CsvConfigurationException' occurred in CsvHelper.dll but was not handled in user code

Additional information: Types that inherit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?

GetRecords is probably expecting my own custom class, but I'm just wanting the values as some primitive type or string. Also, I suspect the entire row is being converted to a single string, instead of each value being a separate string.

答:
```<code>static void WriteCsvFile(string filename, IEnumerable<Person> people)
    {

        StreamWriter textWriter = File.CreateText(filename);

        var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);

        csvWriter.WriteRecords(people);

        textWriter.Close();

    }
</code>```

Body:
So I've been reading that I shouldn't write my own CSV reader/writer, so I've been trying to use the CsvHelper library installed via nuget. The CSV file is a grey scale image, with the number of rows being the image height and the number columns the width. I would like to read the values row-wise into a single List<string> or List<byte>.

The code I have so far is:

using CsvHelper;

public static List<string> ReadInCSV(string absolutePath)
{
    IEnumerable<string> allValues;

    using (TextReader fileReader = File.OpenText(absolutePath))
    {
        var csv = new CsvReader(fileReader);
        csv.Configuration.HasHeaderRecord = false;
        allValues = csv.GetRecords<string>
    }

    return allValues.ToList<string>();
}

But allValues.ToList<string>() is throwing a:

CsvConfigurationException was unhandled by user code

An exception of type 'CsvHelper.Configuration.CsvConfigurationException' occurred in CsvHelper.dll but was not handled in user code

Additional information: Types that inherit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?

GetRecords is probably expecting my own custom class, but I'm just wanting the values as some primitive type or string. Also, I suspect the entire row is being converted to a single string, instead of each value being a separate string.


问:
What does the "?:^" regular expression mean?
I am looking at this sub-expression (this is in JavaScript):

```<code>(?:^|.....)
</code>```

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

答:
You're probably seeing it in this context

```<code>(?:...)
</code>```

It means that the group won't be captured or used for back-references.

EDIT: To reflect your modified question:

```<code>(?:^|....)
</code>```

means "match the beginning of the line or match ..." but don't capture the group or use it for back-references.

OwnerDisplayName: levik

ContentLicense: CC BY-SA 2.5

Body:
I am looking at this sub-expression (this is in JavaScript):

(?:^|.....)

I know that ? means "zero or one times" when it follows a character, but not sure what it means in this context.

LastEditorDisplayName: levik

Body:
You're probably seeing it in this context

(?:...)

It means that the group won't be captured or used for back-references.

EDIT: To reflect your modified question:

(?:^|....)

means "match the beginning of the line or match ..." but don't capture the group or use it for back-references.

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
Google Analytics: Adding a metric returns different result
I'm working on a Google Analytics data extraction and I realized a difference in the results when I add a metric.

When I query the API like this https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxx&start-date=2018-12-01&end-date=2018-12-31&metrics=ga:totalEvents&dimensions=ga:eventLabel,ga:eventCategory,ga:eventAction&max-results=100&start-index=1&filters=ga:eventLabel=~théories et pratiques de l'enseignement programmé: guide à l'usage des enseignants
 I receive this:

```<code>"totalsForAllResults": {
    "ga:totalEvents": "23"
  }
</code>```

When I add ga:dateHourMinute to the metrics, the same property returns 14 instead of 23. Is there a way for me the get the right totalEvents, in this case it's 23, and also get the date and time in the same query?

答:
From your comments we understand that you have reached the sampling threshold. Default reports are not subject to sampling. However, by applying a secondary dimension (in this case ga:dateHourMinute), you required an ad-hoc queries so your data are subject to the thresholds for sampling, see here:

https://support.google.com/analytics/answer/2637192?hl=en

What you can do is query two shorter periods and then add the values of events together.

Body:
I'm working on a Google Analytics data extraction and I realized a difference in the results when I add a metric.

When I query the API like this https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxx&start-date=2018-12-01&end-date=2018-12-31&metrics=ga:totalEvents&dimensions=ga:eventLabel,ga:eventCategory,ga:eventAction&max-results=100&start-index=1&filters=ga:eventLabel=~théories et pratiques de l'enseignement programmé: guide à l'usage des enseignants
 I receive this:

"totalsForAllResults": {
    "ga:totalEvents": "23"
  }

When I add ga:dateHourMinute to the metrics, the same property returns 14 instead of 23. Is there a way for me the get the right totalEvents, in this case it's 23, and also get the date and time in the same query?


问:
Cannot create JDBC driver of class '' for connect URL 'null' Tomcat 9, Oracle 12c, JDK 8,
I have a simple web service that is trying to open a connection to the database.

I am using jax-ws, Oracle 12c DB, Tomcat 9, Java 8.

Can anyone post the correct way to do this?

So far I've downloaded ojdbc7.jar and ucp.jar into the $TOMCAT_HOME/lib directory.

What goes in applicationPath/META-INF/web.xml ?

Right now I have the following:

```<code>  <resource-ref>
    <res-ref-name>jdbc/UCPPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>
</code>```

What goes in TOMCAT_HOME/conf/server.xml ?

Right now I have the following:

```<code><context docbase="demods" path="/demods" reloadable="true">
  <Resource
       name="jdbc/UCPPool"
       auth="Container"
       factory="oracle.ucp.jdbc.PoolDataSourceImpl"
       type="oracle.ucp.jdbc.PoolDataSource"
       description="Pas testing UCP Pool in Tomcat"
       connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
       minPoolSize="2"
       maxPoolSize="5"
       inactiveConnectionTimeout="20"
       user="test"
       password="test"
       url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracleDB12c)(PORT=1563))(CONNECT_DATA=(SERVICE_NAME=PPS)))"
       connectionPoolName="UCPPool"
       validateConnectionOnBorrow="true"
       sqlForValidateConnection="select 1 from DUAL" />
 </context>
</code>```

What goes in TOMCAT_HOME/conf/context.xml ?

I don't have anything in this file right now.

Here is the code that I am using to setup the JDBC connection:

```<code>         Context ctx = new InitialContext();
         Context envContext = (Context) ctx.lookup("java:comp/env");
         DataSource ds  = (DataSource) envContext.lookup("jdbc/UCPPool");
         Connection conn = null;
         try {
             conn = ds.getConnection();
         }
         catch (SQLException e) {
             return e.getMessage();
         }
</code>```

The message returned by the web service is:

```<code>"Cannot create JDBC driver of class '' for connect URL 'null'"
</code>```

What am I doing wrong?

Thanks in advance!

答:
Good news, I was able to get this to work today at the office.

Here is what I did:

I created a context.xml file and placed it in my eclipse project inside of META-INF/. In META-INF/context.xml I put the following code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context>
<Resource
        name="jdbc/orcljdbc_ds"
        auth="Container"
        type="javax.sql.DataSource"
        driverClassName="oracle.jdbc.OracleDriver"
        username="user1"
        password="password"
        url="jdbc:oracle:thin:@//myoracledb:1563/DEVSID"

/>
</Context>
</code>```

I did not put anything in the Tomcat context.xml or server.xml file, but I think that you can for different scenarios (i.e.Shared datasource with multiple applications running on single application server). I also did not put anything in my Eclipse project WEB-INF\web.xml.

I used the following code to test the connection:

```<code>package planAdminWS;

import javax.jws.WebMethod;
import javax.jws.WebService;

import java.io.PrintWriter;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

@WebService
public class PlanAdminWS {

    @WebMethod
     public String createPlan(String EIN, String PN)
     {
        return "Creating Plan: " + EIN + "/" + PN;
     }

    @WebMethod
    public String updatePlan(String EIN, String PN) throws NamingException, SQLException {
        // Get a context for the JNDI look up
        DataSource ds = getDataSource();
        Connection conn = null;
        try {
            conn = ds.getConnection();
            if (conn != null) {
                Statement stmt = null;
                ResultSet rs = null;
                String query = "select * from V$version";
                stmt = conn.createStatement();
                rs = stmt.executeQuery(query);
                while (rs.next()) {
                    System.out.println(rs.getString(1));
                    return "Database Version : " + rs.getString(1);
                }
            } else {
                return "Conn is NULL";
            }

        } catch (SQLException e) {
            return e.getMessage();
        }

        return "Could not get DB Version";
    }

     /*
      * Method to create a datasource after the JNDI lookup
      */

      private DataSource getDataSource() throws NamingException {
        Context ctx;
        ctx = new InitialContext();
        Context envContext = (Context) ctx.lookup("java:/comp/env");
        // Look up a data source
        javax.sql.DataSource ds
              = (javax.sql.DataSource) envContext.lookup ("jdbc/orcljdbc_ds");
        return ds;
      }
}
</code>```

this returned the following in SoapUI:

"Database Version : Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production"

Thanks for the help!!!

Here was another good resource: https://www.journaldev.com/2513/tomcat-datasource-jndi-example-java

Body:
I have a simple web service that is trying to open a connection to the database.

I am using jax-ws, Oracle 12c DB, Tomcat 9, Java 8.

Can anyone post the correct way to do this?

So far I've downloaded ojdbc7.jar and ucp.jar into the $TOMCAT_HOME/lib directory.

What goes in applicationPath/META-INF/web.xml ?

Right now I have the following:

  <resource-ref>
    <res-ref-name>jdbc/UCPPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

What goes in TOMCAT_HOME/conf/server.xml ?

Right now I have the following:

<context docbase="demods" path="/demods" reloadable="true">
  <Resource
       name="jdbc/UCPPool"
       auth="Container"
       factory="oracle.ucp.jdbc.PoolDataSourceImpl"
       type="oracle.ucp.jdbc.PoolDataSource"
       description="Pas testing UCP Pool in Tomcat"
       connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
       minPoolSize="2"
       maxPoolSize="5"
       inactiveConnectionTimeout="20"
       user="test"
       password="test"
       url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracleDB12c)(PORT=1563))(CONNECT_DATA=(SERVICE_NAME=PPS)))"
       connectionPoolName="UCPPool"
       validateConnectionOnBorrow="true"
       sqlForValidateConnection="select 1 from DUAL" />
 </context>

What goes in TOMCAT_HOME/conf/context.xml ?

I don't have anything in this file right now.

Here is the code that I am using to setup the JDBC connection:

         Context ctx = new InitialContext();
         Context envContext = (Context) ctx.lookup("java:comp/env");
         DataSource ds  = (DataSource) envContext.lookup("jdbc/UCPPool");
         Connection conn = null;
         try {
             conn = ds.getConnection();
         }
         catch (SQLException e) {
             return e.getMessage();
         }

The message returned by the web service is:

"Cannot create JDBC driver of class '' for connect URL 'null'"

What am I doing wrong?

Thanks in advance!

Body:
Good news, I was able to get this to work today at the office.

Here is what I did:

I created a context.xml file and placed it in my eclipse project inside of META-INF/. In META-INF/context.xml I put the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context>
<Resource
        name="jdbc/orcljdbc_ds"
        auth="Container"
        type="javax.sql.DataSource"
        driverClassName="oracle.jdbc.OracleDriver"
        username="user1"
        password="password"
        url="jdbc:oracle:thin:@//myoracledb:1563/DEVSID"

/>
</Context>

I did not put anything in the Tomcat context.xml or server.xml file, but I think that you can for different scenarios (i.e.Shared datasource with multiple applications running on single application server). I also did not put anything in my Eclipse project WEB-INF\web.xml.

I used the following code to test the connection:

package planAdminWS;

import javax.jws.WebMethod;
import javax.jws.WebService;

import java.io.PrintWriter;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

@WebService
public class PlanAdminWS {

    @WebMethod
     public String createPlan(String EIN, String PN)
     {
        return "Creating Plan: " + EIN + "/" + PN;
     }

    @WebMethod
    public String updatePlan(String EIN, String PN) throws NamingException, SQLException {
        // Get a context for the JNDI look up
        DataSource ds = getDataSource();
        Connection conn = null;
        try {
            conn = ds.getConnection();
            if (conn != null) {
                Statement stmt = null;
                ResultSet rs = null;
                String query = "select * from V$version";
                stmt = conn.createStatement();
                rs = stmt.executeQuery(query);
                while (rs.next()) {
                    System.out.println(rs.getString(1));
                    return "Database Version : " + rs.getString(1);
                }
            } else {
                return "Conn is NULL";
            }

        } catch (SQLException e) {
            return e.getMessage();
        }

        return "Could not get DB Version";
    }

     /*
      * Method to create a datasource after the JNDI lookup
      */

      private DataSource getDataSource() throws NamingException {
        Context ctx;
        ctx = new InitialContext();
        Context envContext = (Context) ctx.lookup("java:/comp/env");
        // Look up a data source
        javax.sql.DataSource ds
              = (javax.sql.DataSource) envContext.lookup ("jdbc/orcljdbc_ds");
        return ds;
      }
}

this returned the following in SoapUI:

"Database Version : Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production"

Thanks for the help!!!

Here was another good resource: https://www.journaldev.com/2513/tomcat-datasource-jndi-example-java


问:
Scala Spark/Databricks: .cache() not preventing re-calculation
This involves some complexity, and I may be unclear on some basics. Here goes:

As I understand it, spark has "transformations" and "actions". Transformations lazily build up a description of what you want to do, and actions make it happen. This can improve performance (allowing optimized plans), or it can lead to duplicated effort if you use multiple actions on a single dataframe, causing the transform to fire repeatedly. To avoid this, .cache() tells Spark to actually "save its work", so the dataframe you call it on shouldn't continue to be re-computed.

My problem is that it doesn't seem to be doing that. I have a function "Foo" that does a lot of computation to produce a (very small) dataframe. Foo runs quickly, and I can display the result. I have another function "Bar" that does a bunch of actions on a dataframe. Bar runs quickly on the (large) original input, but very slowly on the output of foo, even cached and coalesced. I can also "force" the cache-ing by writing the output of foo to disk and then re-reading it, at which point bar runs quickly:

```<code>display(bar(bigDF)) //Fast!

val profile = foo(bigDF).coalesce(1).cache()
display(profile) //Also fast! (and profile only has 2 rows, ~80 columns)

display(bar(profile)) //Slow!

profile
  .write.format("com.databricks.spark.csv")
  .option("header", "true")
  .save("filename.csv")
val dumb = spark.read.format("csv").option("header", "true").load("filename.csv")
display(bar(dumb)) //Fast again
</code>```

To me, this says that the .cache() isn't working the way I think it does - the slow call is repeatedly re-calling the transformations in foo, unless I write it to disk and force it to "forget" its history. Can someone explain what I'm missing?

答:
cache is doing what you expect, seems that there is something strange happening.

I expect that the coalesce(1) is the problem, try to leave that away and test if it's running faster. It could be that it destroys parallelism for bar.

If nothing helps, try to use checkpoint instead of cache it could be that the query plan is very long and complex, checkpoint would truncate that (it writes to disk)

For further analysis you would need to go into SparkUI to analyze the jobs

Body:
This involves some complexity, and I may be unclear on some basics. Here goes:

As I understand it, spark has "transformations" and "actions". Transformations lazily build up a description of what you want to do, and actions make it happen. This can improve performance (allowing optimized plans), or it can lead to duplicated effort if you use multiple actions on a single dataframe, causing the transform to fire repeatedly. To avoid this, .cache() tells Spark to actually "save its work", so the dataframe you call it on shouldn't continue to be re-computed.

My problem is that it doesn't seem to be doing that. I have a function "Foo" that does a lot of computation to produce a (very small) dataframe. Foo runs quickly, and I can display the result. I have another function "Bar" that does a bunch of actions on a dataframe. Bar runs quickly on the (large) original input, but very slowly on the output of foo, even cached and coalesced. I can also "force" the cache-ing by writing the output of foo to disk and then re-reading it, at which point bar runs quickly:

display(bar(bigDF)) //Fast!

val profile = foo(bigDF).coalesce(1).cache()
display(profile) //Also fast! (and profile only has 2 rows, ~80 columns)

display(bar(profile)) //Slow!

profile
  .write.format("com.databricks.spark.csv")
  .option("header", "true")
  .save("filename.csv")
val dumb = spark.read.format("csv").option("header", "true").load("filename.csv")
display(bar(dumb)) //Fast again

To me, this says that the .cache() isn't working the way I think it does - the slow call is repeatedly re-calling the transformations in foo, unless I write it to disk and force it to "forget" its history. Can someone explain what I'm missing?


问:
Why does multiplying input by pi in numpy.sin cause it to break?
I've come across an issue where if I multiply the input of numpy.sin() by pi it outputs a strange graph that in no way approximates the actual result. If I round pi to 3.14 it works, but any decimal places up to and including np.pi breaks it. Can anyone tell me what's causing this?

This is my code:

```<code>lim = 4096
x = np.arange(0,lim)
y = np.sin(2*np.pi*x)

plt.plot(x,y)
plt.show()
</code>```

This is the output of the plot using np.pi, this is using 3.14159265, this is using 3.141, this is using 3.14. As you can see, the amplitude is also screwy, being on the order of -12 for np.pi, -5 for 3.14159265, etc. What's going on?

答:
np.sin(x) expects x to be in radians, not degrees.

2*np.pi*x in radians is almost precisely an integer multiple of 360 degrees. Its sine is very close to 0, and that is what you see in the first plot.

3.14159265, etc. are even more different from the real Pi than np.pi, that is why you start seeing bigger y's. The reason why your plots look like sine waves is because of sampling.

Body:
I've come across an issue where if I multiply the input of numpy.sin() by pi it outputs a strange graph that in no way approximates the actual result. If I round pi to 3.14 it works, but any decimal places up to and including np.pi breaks it. Can anyone tell me what's causing this?

This is my code:

lim = 4096
x = np.arange(0,lim)
y = np.sin(2*np.pi*x)

plt.plot(x,y)
plt.show()

This is the output of the plot using np.pi, this is using 3.14159265, this is using 3.141, this is using 3.14. As you can see, the amplitude is also screwy, being on the order of -12 for np.pi, -5 for 3.14159265, etc. What's going on?


问:
How to pass an option into custom vue component?
I made a custom Vue component and published it through npm. My component is working as I expected in my main project but with current usage, users would need to send too much props to use my component efficiently and without duplicate code.

I installed my component as

//index.js in component folder
import MyComponent from "./MyComponent.vue";

export default {
  install(Vue, options) {
    Vue.component("my-component", MyComponent);
  }
};
```

<p>and registered at my project as</p>

<pre class="lang-js prettyprint-override"><code>//main.js in project folder
import Vue from 'vue'
import MyComponent from 'my-component'

Vue.use(MyComponent)
</code>```

using my custom component in my .vue files as:

<my-component v-model="myData" prop1="prop1" prop2="prop2" prop3="prop3"></my-component>
```

Since that prop usage looks so untidy and causes too many code duplicate for myself, I want to register that props in options and pass through my component. But couldn't figure out how to that.

答:
You can use the install phase to override the defaults like this:

import MyComponent from './components/MyComponent';

export default {
  install(Vue, options = {}) {
    let props = { ...MyComponent.props };
    Object.keys(options).forEach(k => {
      props[k] = { default: options[k] };
    });

    Vue.component('my-component', { ...MyComponent, props });
  },
};
```

<p>What this script does is allow you to do...</p>

<pre class="lang-js prettyprint-override"><code>Vue.use(MyComponent, {prop1:"abc", props:"def"});
</code>```

When you use the component somewhere in the app, the props are still interactive, and can be overriden, but you can leave as default. It does this by replacing the existing prop definitions with an object that only has default defined as the passed value. It's a bit of a hack, so I'm not sure how well it will hold up in some edge cases.

Body:
I made a custom Vue component and published it through npm. My component is working as I expected in my main project but with current usage, users would need to send too much props to use my component efficiently and without duplicate code.

I installed my component as

//index.js in component folder
import MyComponent from "./MyComponent.vue";

export default {
  install(Vue, options) {
    Vue.component("my-component", MyComponent);
  }
};

and registered at my project as

//main.js in project folder
import Vue from 'vue'
import MyComponent from 'my-component'

Vue.use(MyComponent)

using my custom component in my .vue files as:

<my-component v-model="myData" prop1="prop1" prop2="prop2" prop3="prop3"></my-component>

Since that prop usage looks so untidy and causes too many code duplicate for myself, I want to register that props in options and pass through my component. But couldn't figure out how to that.

Body:
You can use the install phase to override the defaults like this:

import MyComponent from './components/MyComponent';

export default {
  install(Vue, options = {}) {
    let props = { ...MyComponent.props };
    Object.keys(options).forEach(k => {
      props[k] = { default: options[k] };
    });

    Vue.component('my-component', { ...MyComponent, props });
  },
};

What this script does is allow you to do...

Vue.use(MyComponent, {prop1:"abc", props:"def"});

When you use the component somewhere in the app, the props are still interactive, and can be overriden, but you can leave as default. It does this by replacing the existing prop definitions with an object that only has default defined as the passed value. It's a bit of a hack, so I'm not sure how well it will hold up in some edge cases.


问:
find the position of elements in series 2 in series 1..series 1: [1,2,3,4,5,6,7] series 2[1,3,7] Sample Output: [0,2,6]

series 1: [1,2,3,4,5,6,7]

series 2[1,3,7]

Sample Output: [0,2,6]

```<code>import ast,sys
    import pandas as pd
    input_str = sys.stdin.read()
    input_list = ast.literal_eval(input_str)
    series1=pd.Series(input_list[0])
    series2=pd.Series(input_list[1])
    z =series2.size
    c=[]
    for i in range (0,z):
        if series2[i] in series1:
            c.append(series1.index(series2[i]))

out_list=c
print(list(map(int,out_list)))
</code>```

答:
Do you have to use pandas Series, or will something like this work?

```<code>in1 = [1,2,3,4,5,6,7]
in2 = [1,3,7]

output = [in1.index(x) for x in in2]
print(output)
</code>```

Output:

```<code>[0, 2, 6]
</code>```

Body:
series 1: [1,2,3,4,5,6,7]

series 2[1,3,7]

Sample Output: [0,2,6]

import ast,sys
    import pandas as pd
    input_str = sys.stdin.read()
    input_list = ast.literal_eval(input_str)
    series1=pd.Series(input_list[0])
    series2=pd.Series(input_list[1])
    z =series2.size
    c=[]
    for i in range (0,z):
        if series2[i] in series1:
            c.append(series1.index(series2[i]))

out_list=c
print(list(map(int,out_list)))

Body:
Do you have to use pandas Series, or will something like this work?

in1 = [1,2,3,4,5,6,7]
in2 = [1,3,7]

output = [in1.index(x) for x in in2]
print(output)

Output:

[0, 2, 6]