问:
How to use foreign key to add data to my database in React
I'm using React to send data to my PostgreSQL database using NodeJS. I have a foreign key (id) in my songs as well as my image that references to the album id for my title, date, and description. I'm using a uuid for my id in my album table. My question is how does my songs and image file table know that it was that album id on that page that was created with the songs and image?

Here's the page with the album(title, description, date) which gets saved its own table, the list of songs which gets saved in its own table and the image which gets saved in its own table. Both image and songs table have a album_id which references to the album's id:

Album

```<code>const addAlbum = (request, response) => {
  const { title, date, description, id } = request.body;
  const uuid = uuidv4();

for (let i = 0; i < request.body.length; i++) {
  db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body[i].title, request.body[i].date, request.body[i].description, uuid], (error, results) => {
    if (error) {
      throw error
    } else {
      console.log('INSERT ' + JSON.stringify(request.body));
    }
  })
}
}
</code>```

Songs

```<code> const upsertSong = (request, response) => {
    const { id } = request.body;
    const uuid = uuidv4();
    for (var i = 0; i < request.body.length; i++) {
    let insertQuery = {};
    const object = request.body[i];
    let params = [uuid, object.name, object.link, object.index, object.album_id];
    insertQuery.text = 'INSERT INTO songs (id, name, link, index, album_id) VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING RETURNING *';
    insertQuery.values = params;

    (async () => {

       await pool.query ('UPDATE songs SET name = $1, link = $2, index = $3, album_id = $4 WHERE id = $5 AND index = $3',
        [request.body[i].name, request.body[i].link, request.body[i].index, request.body[i].album_id, id], (err, result) => {
          try {
            if (err) throw err;
            if (result.rowCount > 0){
               console.log ('UPDATE Rows affected: ', result.rowCount);
               return;
             } else {
               pool.query(insertQuery, (error, res) =>{
               try {
                 if (error) throw error;
                 console.log ('INSERT Rows affected:', res.rowCount);
               }catch(er){
                 console.log("Error")
                 console.log(er);
                }
              });
            }
           } catch (e){
             console.log("Error 2")
             console.log(e);
            }
       });
      })().catch(e => console.log("Error 3" + e));
    }
    }
</code>```

index.js

```<code>app.post('/albums/:id/songs', db.upsertSong)
app.post('/albums/', album.addAlbum)
app.put('/songs/:id', db.upsertSong)
app.post('/albums/:id/upload', image.upsertImage);
app.put('/albums/:id/upload', image.upsertImage);
</code>```

The album info and songs info get inserted on the same save button in React but how does the song know that the album_id is from that album id on the same page?

答:
The crux of the issue is that the addAlbum method is not returning the ID of the newly-created album, so there's no way to associate the songs and images with the album after the album is inserted.  There are multiple ways to solve this, but were it me I would simply update the addAlbum method to return the album in its entirety after creation (that is, including the new UUID).  A post might look like this:

```<code>POST /albums HTTP/1.1
Content-Type: application/json

{
  "title": "Dillon",
  "date": "2020-01-01T00:00:00.000Z",
  "description": "An awesome political protest album."
}
</code>```

Given the suggestion above, the response would look like so:

```<code>{
  "title": "Dillon",
  "date": "2020-01-01T00:00:00.000Z",
  "description": "An awesome political protest album.",
  "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
</code>```

Then, on the front end, your code would look something like this (pseudocode).

const newAlbum = await albumDao.save(album);

for (const song of songs) {
  song.album_id = newAlbum.id;
  await songDao.save(song);
}
```

Another option is to save the album and all of its images and songs together in one orchestrated API.  The advantages of doing it this way are that 1) the server knows about the album ID, and 2) you can utilize transactions so that if a song or image fails to insert, the whole shebang gets rolled back.

Body:
I'm using React to send data to my PostgreSQL database using NodeJS. I have a foreign key (id) in my songs as well as my image that references to the album id for my title, date, and description. I'm using a uuid for my id in my album table. My question is how does my songs and image file table know that it was that album id on that page that was created with the songs and image?

Here's the page with the album(title, description, date) which gets saved its own table, the list of songs which gets saved in its own table and the image which gets saved in its own table. Both image and songs table have a album_id which references to the album's id:

Album

const addAlbum = (request, response) => {
  const { title, date, description, id } = request.body;
  const uuid = uuidv4();

for (let i = 0; i < request.body.length; i++) {
  db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body[i].title, request.body[i].date, request.body[i].description, uuid], (error, results) => {
    if (error) {
      throw error
    } else {
      console.log('INSERT ' + JSON.stringify(request.body));
    }
  })
}
}

Songs

 const upsertSong = (request, response) => {
    const { id } = request.body;
    const uuid = uuidv4();
    for (var i = 0; i < request.body.length; i++) {
    let insertQuery = {};
    const object = request.body[i];
    let params = [uuid, object.name, object.link, object.index, object.album_id];
    insertQuery.text = 'INSERT INTO songs (id, name, link, index, album_id) VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING RETURNING *';
    insertQuery.values = params;

    (async () => {

       await pool.query ('UPDATE songs SET name = $1, link = $2, index = $3, album_id = $4 WHERE id = $5 AND index = $3',
        [request.body[i].name, request.body[i].link, request.body[i].index, request.body[i].album_id, id], (err, result) => {
          try {
            if (err) throw err;
            if (result.rowCount > 0){
               console.log ('UPDATE Rows affected: ', result.rowCount);
               return;
             } else {
               pool.query(insertQuery, (error, res) =>{
               try {
                 if (error) throw error;
                 console.log ('INSERT Rows affected:', res.rowCount);
               }catch(er){
                 console.log("Error")
                 console.log(er);
                }
              });
            }
           } catch (e){
             console.log("Error 2")
             console.log(e);
            }
       });
      })().catch(e => console.log("Error 3" + e));
    }
    }

index.js

app.post('/albums/:id/songs', db.upsertSong)
app.post('/albums/', album.addAlbum)
app.put('/songs/:id', db.upsertSong)
app.post('/albums/:id/upload', image.upsertImage);
app.put('/albums/:id/upload', image.upsertImage);

The album info and songs info get inserted on the same save button in React but how does the song know that the album_id is from that album id on the same page?

Body:
The crux of the issue is that the addAlbum method is not returning the ID of the newly-created album, so there's no way to associate the songs and images with the album after the album is inserted.  There are multiple ways to solve this, but were it me I would simply update the addAlbum method to return the album in its entirety after creation (that is, including the new UUID).  A post might look like this:

POST /albums HTTP/1.1
Content-Type: application/json

{
  "title": "Dillon",
  "date": "2020-01-01T00:00:00.000Z",
  "description": "An awesome political protest album."
}

Given the suggestion above, the response would look like so:

{
  "title": "Dillon",
  "date": "2020-01-01T00:00:00.000Z",
  "description": "An awesome political protest album.",
  "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

Then, on the front end, your code would look something like this (pseudocode).

const newAlbum = await albumDao.save(album);

for (const song of songs) {
  song.album_id = newAlbum.id;
  await songDao.save(song);
}

Another option is to save the album and all of its images and songs together in one orchestrated API.  The advantages of doing it this way are that 1) the server knows about the album ID, and 2) you can utilize transactions so that if a song or image fails to insert, the whole shebang gets rolled back.


来源: stackexchange

问:
ColdFusion Sanatize SQL
I'm trying to loop over tableList and run a query for each table getting the count from each. Not all of the code is included but the problem is the cfqueryparam. When I run this code right now the error says "INVALID TABLE NAME". Here is what I am trying right now:

```<code><cfloop list="#tableList#" index="t">
<cfquery name="getcount" datasource="erisnetselect">
SELECT COUNT(*) FROM <cfqueryparam value='AUDITOR.#t#' sqltype="VARCHAR">
</cfquery>
</code>```

The problem is specifically this line:

```<code>SELECT COUNT(*) FROM <cfqueryparam value='AUDITOR.#t#' sqltype="VARCHAR">
</code>```

I have also tried:

```<code>SELECT COUNT(*) FROM AUDITOR.<cfqueryparam value='#t#' sqltype="VARCHAR">
</code>```

But I get the same error.

I think there might be a way to sanitize these table names before they hit the query but I'm not sure how to do it. If you need all of the code I can provide more but this is a huge page.

答:
cfqueryparam is a value placeholder for a prepared statement. You cannot use value placeholders for table or column names because a prepared statement requires the query to be complete and valid before any values are put in. One of the design goals of prepared statements is to prevent malicious injection by separating query and values. The separation is achieved by sending the query without actual values first (value placeholders are usually indicated with a question mark ?), have the SQL server parse and understand it (query interpreter) and then wait for data to place into the prepared value slots. This also comes with a performance benefit, because the SQL server can reuse already interpreted queries while sending a plain string statement with query and values would always require parsing it again.

To solve your problem, you will have to sanitize the table names either by using the appropriate command builder/quoter (depends on the SQL vendor, check your JDBC driver) or validate the name manually.

If you have to go with the manual way, you should be conservative and only allow foolproof characters, such as alphabetic letters, digits, underscores and hyphens. Consider this:

```<code><cfloop list="#tableList#" index="t">

    <!--- make sure the table name only consists of alphabetic letters, digits, underscores and hyphens --->
    <cfif not reFind("^[a-zA-Z0-9_-]+$", t)>
        <cfthrow message='The specified table name, which is "#t#", contains illegal characters.'>
    </cfif>

    <cfquery name="getcount" datasource="erisnetselect">
        SELECT COUNT(*) FROM AUDITOR.#t#
    </cfquery>

    ...
</code>```

ContentLicense: CC BY-SA 4.0

Title: ColdFusion Sanatize SQL

Body:
I'm trying to loop over tableList and run a query for each table getting the count from each. Not all of the code is included but the problem is the cfqueryparam. When I run this code right now the error says "INVALID TABLE NAME". Here is what I am trying right now:

<cfloop list="#tableList#" index="t">
<cfquery name="getcount" datasource="erisnetselect">
SELECT COUNT(*) FROM <cfqueryparam value='AUDITOR.#t#' sqltype="VARCHAR">
</cfquery>

The problem is specifically this line:

SELECT COUNT(*) FROM <cfqueryparam value='AUDITOR.#t#' sqltype="VARCHAR">

I have also tried:

SELECT COUNT(*) FROM AUDITOR.<cfqueryparam value='#t#' sqltype="VARCHAR">

But I get the same error.

I think there might be a way to sanitize these table names before they hit the query but I'm not sure how to do it. If you need all of the code I can provide more but this is a huge page.

Body:
cfqueryparam is a value placeholder for a prepared statement. You cannot use value placeholders for table or column names because a prepared statement requires the query to be complete and valid before any values are put in. One of the design goals of prepared statements is to prevent malicious injection by separating query and values. The separation is achieved by sending the query without actual values first (value placeholders are usually indicated with a question mark ?), have the SQL server parse and understand it (query interpreter) and then wait for data to place into the prepared value slots. This also comes with a performance benefit, because the SQL server can reuse already interpreted queries while sending a plain string statement with query and values would always require parsing it again.

To solve your problem, you will have to sanitize the table names either by using the appropriate command builder/quoter (depends on the SQL vendor, check your JDBC driver) or validate the name manually.

If you have to go with the manual way, you should be conservative and only allow foolproof characters, such as alphabetic letters, digits, underscores and hyphens. Consider this:

<cfloop list="#tableList#" index="t">

    <!--- make sure the table name only consists of alphabetic letters, digits, underscores and hyphens --->
    <cfif not reFind("^[a-zA-Z0-9_-]+$", t)>
        <cfthrow message='The specified table name, which is "#t#", contains illegal characters.'>
    </cfif>

    <cfquery name="getcount" datasource="erisnetselect">
        SELECT COUNT(*) FROM AUDITOR.#t#
    </cfquery>

    ...


问:
How would you communicate a wcf service with a windows service?
Two weeks ago I needed a way to communicate a wcf service with a windows service running on the same computer. The windows service had to get data from a external source and share it with the wcf service (hosted in IIS) who had to give it when a client made a request. I chose to do that with ipc.

I done it and now the windows service is the ipc server and the wcf service is the ipc client. This goes well but I think I made a mistake doing this because to make it run right the windows service must to be executed with the ASPNET account, for this the ASPNET password account must be assigned and when I do that the IIS does not work correctly.

I am thinking on different alternatives, but in all of them the problem persists. Some ideas?

Edit:

What I needed was a system that made public, in a web service hosted in IIS, data gotten through telnet from another old system, what is a little unstable. How the response of this second system was slow I chose to put a process (the windows service) between the web service and the old system. The windows service had to save the data collected from the old system and when the wcf service asked it give it all at once through ipc.

答: Why not just create another account with the same permission set of the ASPNET user which both the WCF service and your other service run under?  That way, you have control over the password.</p>

OwnerDisplayName: Alfred

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Alfred

OwnerDisplayName: casperOne


问:
What can be used as an identifier for a #define directive in C/C++
I'm curious as to what can be used as an identifier for the #define directive in C and/or C++. Is every string token legal?

For example, would the following code compile?

```<code>#define EMPTY ;;

for(EMPTY){
  function();
}
</code>```

答:
The syntactic rules for regular identifiers such as names of variables, functions, goto labels, etc... are the same for  identifiers used with preprocessor directives.

The C standard has a precise and unique definition for the word identifier, so wherever the word identifier appears in the standard, it is that same thing.

Body:
I'm curious as to what can be used as an identifier for the #define directive in C and/or C++. Is every string token legal?

For example, would the following code compile?

#define EMPTY ;;

for(EMPTY){
  function();
}


问:
kiali showing unkown traffic via sending through ambassador
I have installed service mesh(Istio) and working with Ambassador to route traffic to our application. Whenever I am sending traffic through Istio Ingress its working fine and working with the ambassador but when sending through Ambassador, It is showing unknown, You can see on the attached image, could be related to the fact that the ambassador does not use an Istio sidecar.

Used code to deploy Ambassador service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: ambassador
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
    - name: ambassador-http
      port: 80
      targetPort: 8080
  selector:
    service: ambassador
---
</code>```

Is there anything to I can add here to make it possible?

Thanks

答:
All the traffic coming from a source that is not part of the service mesh is going to be shown as unknown.

See what kiali says about the unknowns:
https://kiali.io/faq/graph/#many-unknown

Body:
I have installed service mesh(Istio) and working with Ambassador to route traffic to our application. Whenever I am sending traffic through Istio Ingress its working fine and working with the ambassador but when sending through Ambassador, It is showing unknown, You can see on the attached image, could be related to the fact that the ambassador does not use an Istio sidecar.

Used code to deploy Ambassador service:

apiVersion: v1
kind: Service
metadata:
  name: ambassador
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
    - name: ambassador-http
      port: 80
      targetPort: 8080
  selector:
    service: ambassador
---

Is there anything to I can add here to make it possible?

Thanks


问:
How to query data from SSAS Tabular in C#?
I am unable to find any useful resources on this.
Basically, we are working on ASP.NET web API which needs to consume the SSAS Tabular Model.

I went through Microsoft.AnalysisServices.AdomdClient, but it looks like its specific for Multidimensional models and not for the Tabular ones.

What is the cleanest way to query SSAS Tabular using C#?

答:
Adomdcommand can be used for Tabulars as well passing DAX query and connection to Tabular. Its possible to read from Tabulars. </p>

<p>Below link has an example to read from Tabular using OLEDB and ADOMD.
https://www.sqlbi.com/articles/execute-dax-queries-through-ole-db-and-adomd-net/ </p>

Body:
Adomdcommand can be used for Tabulars as well passing DAX query and connection to Tabular. Its possible to read from Tabulars.

Below link has an example to read from Tabular using OLEDB and ADOMD.
https://www.sqlbi.com/articles/execute-dax-queries-through-ole-db-and-adomd-net/


问:
Python - why mock patch decorator does not pass the mocked object to the test function when `new` argument is not DEFAULT
in Python 3.6, I use unittest.mock.patch to patch a function like this:

```<code>class SampleTest(TestCase):

    @mock.patch('some_module.f')
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()

</code>```

This passes a mock.MagicMock() as mocked_f and everything works fine. However, when I want to use a custom mock object instead of the default mock.MagicMock() using new argument, the patch decorator does not pass the mocked object to the test_f method. Running this code will raise a TypeError:

```<code>class SampleTest(TestCase):

    @mock.patch('some_module.f', new=lambda: 8)
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()
</code>```

```<code>TypeError: test_f() missing 1 required positional argument: 'mocked_f'
</code>```

My question is: why is this happening?

答:
I think it's probably correct that the reason the mocked object is not passed to the decorated function when new is specified, is that you will normally already have a reference to the that object, and so don't need it passed into the decorated function.

Notice however that if you use new_callable instead of new then the mocked object is passed to the decorated function. This makes sense since you normally won't have a reference to the object returned from the callable.

so you can do something like the following:

```<code>def my_custom_mock_factory():
    my_mock = mock.Mock()
    # customisations to my_mock
    return my_mock

class SampleTest(TestCase):

    @mock.patch('some_module.f', new_callable=my_custom_mock_factory)
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()
</code>```

Body:
in Python 3.6, I use unittest.mock.patch to patch a function like this:

class SampleTest(TestCase):

    @mock.patch('some_module.f')
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()

This passes a mock.MagicMock() as mocked_f and everything works fine. However, when I want to use a custom mock object instead of the default mock.MagicMock() using new argument, the patch decorator does not pass the mocked object to the test_f method. Running this code will raise a TypeError:

class SampleTest(TestCase):

    @mock.patch('some_module.f', new=lambda: 8)
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()

TypeError: test_f() missing 1 required positional argument: 'mocked_f'

My question is: why is this happening?

Body:
I think it's probably correct that the reason the mocked object is not passed to the decorated function when new is specified, is that you will normally already have a reference to the that object, and so don't need it passed into the decorated function.

Notice however that if you use new_callable instead of new then the mocked object is passed to the decorated function. This makes sense since you normally won't have a reference to the object returned from the callable.

so you can do something like the following:

def my_custom_mock_factory():
    my_mock = mock.Mock()
    # customisations to my_mock
    return my_mock

class SampleTest(TestCase):

    @mock.patch('some_module.f', new_callable=my_custom_mock_factory)
    def test_f(self, mocked_f):
        f()
        mocked_f.assert_called()


问:
Create new column that takes the sum of another column values and group by condition in R
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

```<code>`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr
</code>```

Desired output would like something like this:

```<code>`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014
</code>```

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

答:
Here is an example with data.table

data:

```<code>library(data.table)

data <- data.table(building = c("Alex", "Alex", "Mike"),
               population = c(1312, 3123, 2139),
               location = c("Denver", "Arizona", "Detroit"))

   building population location
1:     Alex       1312   Denver
2:     Alex       3123  Arizona
3:     Mike       2139  Detroit
</code>```

code:

```<code>data[, popsum := sum(population), by = building][]

   building population location popsum
1:     Alex       1312   Denver   4435
2:     Alex       3123  Arizona   4435
3:     Mike       2139  Detroit   2139
</code>```

Is that what you're looking for?

Body:
I would like to add a new column that is titled "pop sum" which takes the sum of all rows that has population data and is grouped by location. I tried group_by with Building and then sum = sum(pop) but that did work. I will just show one building but there are 30+ UNIQUE buildings Reference dataframe below:

`Date Ran`           Year Month      Building   Population MonthN
  <dttm>              <dbl> <chr>        <fct>       <num>    <chr>
1 2018-09-28 00:00:00  2018 September     ALEX       1196    Sep
2 2018-08-30 00:00:00  2018 August        ALEX       1172    Aug
3 2018-07-19 00:00:00  2018 July          ALEX       1171    Jul
4 2018-06-30 00:00:00  2018 June          ALEX       1167    Jun
5 2018-05-11 00:00:00  2018 May           ALEX       1154    May
6 2018-04-09 00:00:00  2018 April         ALEX       1154    Apr

Desired output would like something like this:

`Date Ran`           Year Month      Building   Population   MonthN  Pop Sum
  <dttm>              <dbl> <chr>         <fct>      <dbl>     <chr>      <num>
1 2018-09-28 00:00:00  2018 September     ALEX       1196       Sep        7014
2 2018-08-30 00:00:00  2018 August        ALEX       1172       Aug        7014
3 2018-07-19 00:00:00  2018 July          ALEX       1171       Jul        7014
4 2018-06-30 00:00:00  2018 June          ALEX       1167       Jun        7014
5 2018-05-11 00:00:00  2018 May           ALEX       1154       May        7014
6 2018-04-09 00:00:00  2018 April         ALEX       1154       Apr        7014

A function or for loop would be great but if there are any R packages I could load in to generate new column that would be great

Body:
Here is an example with data.table

data:

library(data.table)

data <- data.table(building = c("Alex", "Alex", "Mike"),
               population = c(1312, 3123, 2139),
               location = c("Denver", "Arizona", "Detroit"))

   building population location
1:     Alex       1312   Denver
2:     Alex       3123  Arizona
3:     Mike       2139  Detroit

code:

data[, popsum := sum(population), by = building][]

   building population location popsum
1:     Alex       1312   Denver   4435
2:     Alex       3123  Arizona   4435
3:     Mike       2139  Detroit   2139

Is that what you're looking for?


问:
WebDriverException: 'chromedriver.exe' executable may have wrong permissions
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

```<code>chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)
</code>```

The Error

```<code>Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code>```

And if I change the code and place '' around chromedriver like this

```<code>chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
</code>```

I get this

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

```<code>chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
</code>```

And it seems to maybe pass it? As now I am on to this error :

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

```<code> if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())
</code>```

答:
You need to take care of a few things:

While using Selenium's python client, to pass the absolute path of the ChromeDriver you need to use the single forward slash along with the raw i.e. r switch.

The argument chrome_options is now deprecated, instead you need to use options.

Your effective code block will be:

```<code>  options = webdriver.ChromeOptions()
  options.headless = True
  # previously: options.set_headless(headless=True)
  # long ago: options.add_argument('--headless')
  options.add_argument('--window-size=1200x600')
  driver = webdriver.Chrome(executable_path = r'C:\Users\james\Downloads\ML\New folder\chromedriver.exe', options = options)
</code>```

References

You can find a couple of relevant discussions in:

'Webdrivers' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Body:
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

The Error

Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

And if I change the code and place '' around chromedriver like this

chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

I get this

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

And it seems to maybe pass it? As now I am on to this error :

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

 if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())

Body:
You need to take care of a few things:

While using Selenium's python client, to pass the absolute path of the ChromeDriver you need to use the single forward slash along with the raw i.e. r switch.

The argument chrome_options is now deprecated, instead you need to use options.

Your effective code block will be:

  options = webdriver.ChromeOptions()
  options.headless = True
  # previously: options.set_headless(headless=True)
  # long ago: options.add_argument('--headless')
  options.add_argument('--window-size=1200x600')
  driver = webdriver.Chrome(executable_path = r'C:\Users\james\Downloads\ML\New folder\chromedriver.exe', options = options)

References

You can find a couple of relevant discussions in:

'Webdrivers' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?


问:
JQuery inside js function
I am using the jquery autocomplete ui,trying to make it automatically open the menu when the user clicks in the text box.
When i use $("#selector").autocomplete( "search" , "" ); outside a function it works as intended (of course this works only one time per refresh) but when i try it inside a function it does nothing and i dont know why.

EDIT: I am also working with flask-admin who uses jinja.

```<code>{% extends 'admin/model/list.html' %}
{% import 'admin/model/layout.html' as model_layout with context %}

{% if search_supported %}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="text" id="selector" onfocus="func()" />

<script>
$("#selector").autocomplete({
  source: ['test',"test2"],
  minLength: 0,
  autoFocus: true,
});

$("#selector").autocomplete( "search" , "" ); //this works

function func(){
 $("#selector").autocomplete( "search" , "" ); //this doesnt
}
</script>
{% endif %}
</code>```

答:
I would try this. You will need to make sure your script is in the  or at the end of  and properly wrapped with .

$(function() {
  $("#selector").autocomplete({
    source: ['test', "test2"],
    minLength: 0,
    autoFocus: true,
  }).focus(function(e) {
    $(this).autocomplete("search", "");
    return false;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input type="text" id="selector" />
</div></code>```

Title: JQuery inside js function

Body:
I am using the jquery autocomplete ui,trying to make it automatically open the menu when the user clicks in the text box.
When i use $("#selector").autocomplete( "search" , "" ); outside a function it works as intended (of course this works only one time per refresh) but when i try it inside a function it does nothing and i dont know why.

EDIT: I am also working with flask-admin who uses jinja.

{% extends 'admin/model/list.html' %}
{% import 'admin/model/layout.html' as model_layout with context %}

{% if search_supported %}

<input type="text" id="selector" onfocus="func()" />

{% endif %}

Body:
I would try this. You will need to make sure your script is in the <head> or at the end of <body> and properly wrapped with <script></script>.

$(function() {
  $("#selector").autocomplete({
    source: ['test', "test2"],
    minLength: 0,
    autoFocus: true,
  }).focus(function(e) {
    $(this).autocomplete("search", "");
    return false;
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input type="text" id="selector" />
</div>


问:
Set contentDescription for ActionBar's up button
I'm trying to customize the "Navigate up" default contentDescription that is associated with the up button of the ActionBar (I'm using ActionBarSherlock).

From ActionBarView's source:

```<code>public void setHomeButtonEnabled(boolean enable) {
    mHomeLayout.setEnabled(enable);
    mHomeLayout.setFocusable(enable);
    // Make sure the home button has an accurate content description for accessibility.
    if (!enable) {
        mHomeLayout.setContentDescription(null);
    } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
        mHomeLayout.setContentDescription(mContext.getResources().getText(
                R.string.abs__action_bar_up_description));
    } else {
        mHomeLayout.setContentDescription(mContext.getResources().getText(
                R.string.abs__action_bar_home_description));
    }
}
</code>```

so the key would be how to get a reference to mHomeLayout. getWindow().getDecorView().findViewById(android.R.id.home) is not working, as it's returning an ImageView.

How could I do?

Thanks ;)

答:
In xml, use "navigationContentDescription"</p>

```<code><androidx.appcompat.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:layout_alignParentTop="true"
    app:navigationContentDescription="@string/back"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to customize the "Navigate up" default contentDescription that is associated with the up button of the ActionBar (I'm using ActionBarSherlock).

From ActionBarView's source:

public void setHomeButtonEnabled(boolean enable) {
    mHomeLayout.setEnabled(enable);
    mHomeLayout.setFocusable(enable);
    // Make sure the home button has an accurate content description for accessibility.
    if (!enable) {
        mHomeLayout.setContentDescription(null);
    } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
        mHomeLayout.setContentDescription(mContext.getResources().getText(
                R.string.abs__action_bar_up_description));
    } else {
        mHomeLayout.setContentDescription(mContext.getResources().getText(
                R.string.abs__action_bar_home_description));
    }
}

so the key would be how to get a reference to mHomeLayout. getWindow().getDecorView().findViewById(android.R.id.home) is not working, as it's returning an ImageView.

How could I do?

Thanks ;)

Body:
In xml, use "navigationContentDescription"

<androidx.appcompat.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:layout_alignParentTop="true"
    app:navigationContentDescription="@string/back"/>


问:
git-grep not using multiple threads
I am trying to use git grep to search all revisions of a very large repository. The command I am using is:

```<code>$ git rev-list --all | xargs git grep -I --threads 10 --line-number \
  --only-matching "SomeString"
</code>```

I am using the latest official version of git on mac:

```<code>$ git --version
git version 2.19.1
</code>```

It's taking a very long time, looking at activity monitor git is only using one thread. However the docs say it should use 8 by default. It only uses one thread with or without the --threads <num> option. I don't have any other config set that would override this setting either:

```<code>$ git config --list
credential.helper=osxkeychain
user.name=****
user.email=****
</code>```

Any ideas what I'm missing? Can anybody else use git-grep and confirm that they see multiple threads?

Thanks for any help

答:
The number of threads to allocate to xargs will depends on the number of threads used by git grep.

It used to be 8 by default for git grep.

But:

With Git 2.26 (Q1 2020), this is now the number of cores.

See commit f1928f0, commit 70a9fef, commit 1184a95, commit 6c30762, commit c441ea4, commit d799242, commit 1d1729c, commit 31877c9, commit b1fc9da, commit d5b0bac, commit faf123c, commit c3a5bb3 (16 Jan 2020) by Matheus Tavares (matheustavares).

(Merged by Junio C Hamano -- gitster -- in commit 56ceb64, 14 Feb 2020)

grep: use no. of cores as the default no. of threads

Signed-off-by: Matheus Tavares

When --threads is not specified, git grep will use 8 threads by default.

This fixed number may be too many for machines with fewer cores and too little for machines with more cores.

  So, instead, use the number of logical cores available in the machine, which seems to result in the best overall performance.

The following measurements correspond to the mean elapsed times for 30 git grep executions in chromium's repository with a 95% confidence interval (each set of 30 were performed after 2 warmup runs).

  Regex 1 is 'abcd[02]' and Regex 2 is '(static|extern) (int|double) \*'.

(chromium’s repo at commit 03ae96f (“Add filters testing at DSF=2”, 04-06-2019), after a 'git gc' execution.)

```<code>      |          Working tree         |           Object Store
------|-------------------------------|--------------------------------
 #ths |  Regex 1      |  Regex 2      |   Regex 1      |   Regex 2
------|---------------|---------------|----------------|---------------
  32  |  2.92s ± 0.01 |  3.72s ± 0.21 |   5.36s ± 0.01 |   6.07s ± 0.01
  16  |  2.84s ± 0.01 |  3.57s ± 0.21 |   5.05s ± 0.01 |   5.71s ± 0.01
   8  |  2.53s ± 0.00 |  3.24s ± 0.21 |   4.86s ± 0.01 |   5.48s ± 0.01
   4  |  2.43s ± 0.02 |  3.22s ± 0.20 |   5.22s ± 0.02 |   6.03s ± 0.02
   2  |  3.06s ± 0.20 |  4.52s ± 0.01 |   7.52s ± 0.01 |   9.06s ± 0.01
   1  |  6.16s ± 0.01 |  9.25s ± 0.02 |  14.10s ± 0.01 |  17.22s ± 0.01
</code>```

The above tests were performed in a desktop running Debian 10.0 with Intel(R) Xeon(R) CPU E3-1230 V2 (4 cores w/ hyper-threading), 32GB of RAM and a 7200 rpm, SATA 3.1 HDD.

Bellow, the tests were repeated for a machine with SSD: a Manjaro laptop with Intel(R) i7-7700HQ (4 cores w/ hyper-threading) and 16GB of RAM:

```<code>      |          Working tree          |           Object Store
------|--------------------------------|--------------------------------
 #ths |  Regex 1      |  Regex 2       |   Regex 1      |   Regex 2
------|---------------|----------------|----------------|---------------
  32  |  3.29s ± 0.21 |   4.30s ± 0.01 |   6.30s ± 0.01 |   7.30s ± 0.02
  16  |  3.19s ± 0.20 |   4.14s ± 0.02 |   5.91s ± 0.01 |   6.83s ± 0.01
   8  |  2.90s ± 0.04 |   3.82s ± 0.20 |   5.70s ± 0.02 |   6.53s ± 0.01
   4  |  2.84s ± 0.02 |   3.77s ± 0.20 |   6.19s ± 0.02 |   7.18s ± 0.02
   2  |  3.73s ± 0.21 |   5.57s ± 0.02 |   9.28s ± 0.01 |  11.22s ± 0.01
   1  |  7.48s ± 0.02 |  11.36s ± 0.03 |  17.75s ± 0.01 |  21.87s ± 0.08
</code>```

Title: git-grep not using multiple threads

Body:
I am trying to use git grep to search all revisions of a very large repository. The command I am using is:

$ git rev-list --all | xargs git grep -I --threads 10 --line-number \
  --only-matching "SomeString"

I am using the latest official version of git on mac:

$ git --version
git version 2.19.1

It's taking a very long time, looking at activity monitor git is only using one thread. However the docs say it should use 8 by default. It only uses one thread with or without the --threads <num> option. I don't have any other config set that would override this setting either:

$ git config --list
credential.helper=osxkeychain
user.name=****
user.email=****

Any ideas what I'm missing? Can anybody else use git-grep and confirm that they see multiple threads?

Thanks for any help

Body:
The number of threads to allocate to xargs will depends on the number of threads used by git grep.

It used to be 8 by default for git grep.

But:

With Git 2.26 (Q1 2020), this is now the number of cores.

See commit f1928f0, commit 70a9fef, commit 1184a95, commit 6c30762, commit c441ea4, commit d799242, commit 1d1729c, commit 31877c9, commit b1fc9da, commit d5b0bac, commit faf123c, commit c3a5bb3 (16 Jan 2020) by Matheus Tavares (matheustavares).

(Merged by Junio C Hamano -- gitster -- in commit 56ceb64, 14 Feb 2020)

grep: use no. of cores as the default no. of threads

Signed-off-by: Matheus Tavares

When --threads is not specified, git grep will use 8 threads by default.

This fixed number may be too many for machines with fewer cores and too little for machines with more cores.

  So, instead, use the number of logical cores available in the machine, which seems to result in the best overall performance.

The following measurements correspond to the mean elapsed times for 30 git grep executions in chromium's repository with a 95% confidence interval (each set of 30 were performed after 2 warmup runs).

  Regex 1 is 'abcd[02]' and Regex 2 is '(static|extern) (int|double) \*'.

(chromium’s repo at commit 03ae96f (“Add filters testing at DSF=2”, 04-06-2019), after a 'git gc' execution.)

      |          Working tree         |           Object Store
------|-------------------------------|--------------------------------
 #ths |  Regex 1      |  Regex 2      |   Regex 1      |   Regex 2
------|---------------|---------------|----------------|---------------
  32  |  2.92s ± 0.01 |  3.72s ± 0.21 |   5.36s ± 0.01 |   6.07s ± 0.01
  16  |  2.84s ± 0.01 |  3.57s ± 0.21 |   5.05s ± 0.01 |   5.71s ± 0.01
   8  |  2.53s ± 0.00 |  3.24s ± 0.21 |   4.86s ± 0.01 |   5.48s ± 0.01
   4  |  2.43s ± 0.02 |  3.22s ± 0.20 |   5.22s ± 0.02 |   6.03s ± 0.02
   2  |  3.06s ± 0.20 |  4.52s ± 0.01 |   7.52s ± 0.01 |   9.06s ± 0.01
   1  |  6.16s ± 0.01 |  9.25s ± 0.02 |  14.10s ± 0.01 |  17.22s ± 0.01

The above tests were performed in a desktop running Debian 10.0 with Intel(R) Xeon(R) CPU E3-1230 V2 (4 cores w/ hyper-threading), 32GB of RAM and a 7200 rpm, SATA 3.1 HDD.

Bellow, the tests were repeated for a machine with SSD: a Manjaro laptop with Intel(R) i7-7700HQ (4 cores w/ hyper-threading) and 16GB of RAM:

      |          Working tree          |           Object Store
------|--------------------------------|--------------------------------
 #ths |  Regex 1      |  Regex 2       |   Regex 1      |   Regex 2
------|---------------|----------------|----------------|---------------
  32  |  3.29s ± 0.21 |   4.30s ± 0.01 |   6.30s ± 0.01 |   7.30s ± 0.02
  16  |  3.19s ± 0.20 |   4.14s ± 0.02 |   5.91s ± 0.01 |   6.83s ± 0.01
   8  |  2.90s ± 0.04 |   3.82s ± 0.20 |   5.70s ± 0.02 |   6.53s ± 0.01
   4  |  2.84s ± 0.02 |   3.77s ± 0.20 |   6.19s ± 0.02 |   7.18s ± 0.02
   2  |  3.73s ± 0.21 |   5.57s ± 0.02 |   9.28s ± 0.01 |  11.22s ± 0.01
   1  |  7.48s ± 0.02 |  11.36s ± 0.03 |  17.75s ± 0.01 |  21.87s ± 0.08


问:
Typecasting HashSets in C#
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?</p>

```<code>public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}
</code>```

答: I don't think this is possible since HashSet is not covariant. It implements IEnumerable<T>, which is, but that restricts you to creating a new HashSet from the old one. They won't be kept in sync.

Title: Typecasting HashSets in C#

Body:
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?

public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}


问:
How to switch from one storyboard to another storyboard
Team,

I have two storyboard.
One For authentication
And another for My application Dashboard.

For Authentication Storyboard The initialisation screen is loginScreen.
After login successfully i am loading Dashboard Storyboard.
For dashboard storyboard the initial screen is MainViewController.

Here I am implemented logout from in DashboardStoryboard. So now i want to switch back to my Authentication Storyboard.

Here its going back to loginScreen.
But I thing its not proper way for implementing.
It will be more helpful is there a way I can do better?

```<code>-(void)logout{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Authentication" bundle: nil];
    LoginViewScreenController *loginViewScreenController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewScreenController"];
    [self.navigationController pushViewController: loginViewScreenController animated:NO];
}
</code>```

Your feedback is highly appreciated.

答:
```<code>    let sb = UIStoryboard(name: "Main", bundle: nil)
    let homeVC = sb.instantiateViewController(withIdentifier: "TabBarController")
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = homeVC
</code>```

Body:
Team,

I have two storyboard.
One For authentication
And another for My application Dashboard.

For Authentication Storyboard The initialisation screen is loginScreen.
After login successfully i am loading Dashboard Storyboard.
For dashboard storyboard the initial screen is MainViewController.

Here I am implemented logout from in DashboardStoryboard. So now i want to switch back to my Authentication Storyboard.

Here its going back to loginScreen.
But I thing its not proper way for implementing.
It will be more helpful is there a way I can do better?

-(void)logout{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Authentication" bundle: nil];
    LoginViewScreenController *loginViewScreenController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewScreenController"];
    [self.navigationController pushViewController: loginViewScreenController animated:NO];
}

Your feedback is highly appreciated.


问:
Spawn Failed problem publishing to Apple Store
When we hit the button to do the final publish to Apple Store we get a "Spawn failed" error and cannot find out why.  Apple quite rightly say "it's not our problem as you're using someone else's tools" but that's not really helpful.  Anyone have any pointers on where to look.

Spawn failed.
, Error: Spawn failed.
    at CloudPublishService.getiOSError (C:\Users\XXX\AppData\Roaming.nativescript-cli\extensions\node_modules\nativescript-cloud\lib\services\cloud-publish-service.js:79:21)
    at CloudPublishService. (C:\Users\XXX\AppData\Roaming.nativescript-cli\extensions\node_modules\nativescript-cloud\lib\services\cloud-publish-service.js:96:29)
    at Generator.next ()
    at fulfilled (C:\Users\XXX\AppData\Roaming.nativescript-cli\extensions\node_modules\nativescript-cloud\lib\services\cloud-publish-service.js:4:58)

答: If you're sure you're entering the right credentials and the app-specific password, you may need to check if the Application Version (if you're using NativeScript Sidekick, it's in the Properties tab) is not equal to a version you've already published to the App Store. This fixed the 'Spawn failed' error for me.</p>


问:
PHP Regex to match HTML code using capturing group
I'm stuck trying to write a regular expression in PHP that matches A HREF tags using capturing groups.

My current code looks like this:

$content = preg_replace_callback(
  '/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
...```
</div>
</div>
</p>

<p>The code works perfectly fine for anything like this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Test link</code>```

But I have some URLs that look like this - note the nested :

Test link```

My second capturing group matches for ^< which is why the  doesn't match. I was trying to change the group to match anything BUT . That's where I failed, thanks to my lack of regex experience :)

Could any regex expert please point me in the right direction?

答:
This should be sufficient for your example

```<code><a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>(?:<[^>]+>)?([^<]*)(?:<[^>]+>)?<\/a>
</code>```

Adding the (?:<[^>]+>)? will match the extra tags if they exists.

See this in action here.

Body:
I'm stuck trying to write a regular expression in PHP that matches A HREF tags using capturing groups.

My current code looks like this:

$content = preg_replace_callback(
  '/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
...

The code works perfectly fine for anything like this:

Test link

But I have some URLs that look like this - note the nested :

Test link

My second capturing group matches for ^< which is why the  doesn't match. I was trying to change the group to match anything BUT . That's where I failed, thanks to my lack of regex experience :)

Could any regex expert please point me in the right direction?

Body:
This should be sufficient for your example

<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>(?:<[^>]+>)?([^<]*)(?:<[^>]+>)?<\/a>

Adding the (?:<[^>]+>)? will match the extra tags if they exists.

See this in action here.


问:
Declaring a variable inside or outside an foreach loop: which is faster/better?
Which one of these is the faster/better one?

This one:

```<code>List<User> list = new List<User>();
User u;

foreach (string s in l)
{
    u = new User();
    u.Name = s;
    list.Add(u);
}
</code>```

Or this one:

```<code>List<User> list = new List<User>();

foreach (string s in l)
{
    User u = new User();
    u.Name = s;
    list.Add(u);
}
</code>```

My newbie-developing skills tells me the first one is better, but a friend of mine tells me I'm wrong, but could not give me a good reason why the second one is better.

Is there any difference in performance at all?

答:
I went to verify this issue.

```<code>namespace Test
{
  class Foreach
  {
    string[] names = new[] { "ABC", "MNL", "XYZ" };

    void Method1()
    {
      List<User> list = new List<User>();
      User u;

      foreach (string s in names)
      {
        u = new User();
        u.Name = s;
        list.Add(u);
      }
    }

    void Method2()
    {

      List<User> list = new List<User>();

      foreach (string s in names)
      {
        User u = new User();
        u.Name = s;
        list.Add(u);
      }
    }
  }

  public class User { public string Name; }
}
</code>```

CIL spills out that only variables get a different numbering.

So I prepared something what was supposed to be much better one.

```<code>namespace Test
{
  class Loop
  {

    public TimeSpan method1 = new TimeSpan();
    public TimeSpan method2 = new TimeSpan();

    Stopwatch sw = new Stopwatch();

    public void Method1()
    {
      sw.Restart();

      C c;
      C c1;
      C c2;
      C c3;
      C c4;

      int i = 1000;
      while (i-- > 0)
      {
        c = new C();
        c1 = new C();
        c2 = new C();
        c3 = new C();
        c4 = new C();
      }

      sw.Stop();
      method1 = method1.Add(sw.Elapsed);
    }

    public void Method2()
    {
      sw.Restart();

      int i = 1000;
      while (i-- > 0)
      {
        var c = new C();
        var c1 = new C();
        var c2 = new C();
        var c3 = new C();
        var c4 = new C();
      }

      sw.Stop();
      method2 = method2.Add(sw.Elapsed);
    }
  }

  class C { }
}
</code>```

CIL shows no difference.

As was already pointed out declaration is not allocation so there is no performance penalty on it.

Test

```<code>namespace Test
{
  class Foreach
  {
    string[] names = new[] { "ABC", "MNL", "XYZ" };

    public TimeSpan method1 = new TimeSpan();
    public TimeSpan method2 = new TimeSpan();

    Stopwatch sw = new Stopwatch();

    void Method1()
    {
      sw.Restart();

      List<User> list = new List<User>();
      User u;

      foreach (string s in names)
      {
        u = new User();
        u.Name = s;
        list.Add(u);
      }

      sw.Stop();
      method1 = method1.Add(sw.Elapsed);
    }

    void Method2()
    {
      sw.Restart();

      List<User> list = new List<User>();

      foreach (string s in names)
      {
        User u = new User();
        u.Name = s;
        list.Add(u);
      }

      sw.Stop();
      method2 = method2.Add(sw.Elapsed);
    }
  }

  public class User { public string Name; }
</code>```

Body:
Which one of these is the faster/better one?

This one:

List<User> list = new List<User>();
User u;

foreach (string s in l)
{
    u = new User();
    u.Name = s;
    list.Add(u);
}

Or this one:

List<User> list = new List<User>();

foreach (string s in l)
{
    User u = new User();
    u.Name = s;
    list.Add(u);
}

My newbie-developing skills tells me the first one is better, but a friend of mine tells me I'm wrong, but could not give me a good reason why the second one is better.

Is there any difference in performance at all?

Body:
I went to verify this issue.

namespace Test
{
  class Foreach
  {
    string[] names = new[] { "ABC", "MNL", "XYZ" };

    void Method1()
    {
      List<User> list = new List<User>();
      User u;

      foreach (string s in names)
      {
        u = new User();
        u.Name = s;
        list.Add(u);
      }
    }

    void Method2()
    {

      List<User> list = new List<User>();

      foreach (string s in names)
      {
        User u = new User();
        u.Name = s;
        list.Add(u);
      }
    }
  }

  public class User { public string Name; }
}

CIL spills out that only variables get a different numbering.

So I prepared something what was supposed to be much better one.

namespace Test
{
  class Loop
  {

    public TimeSpan method1 = new TimeSpan();
    public TimeSpan method2 = new TimeSpan();

    Stopwatch sw = new Stopwatch();

    public void Method1()
    {
      sw.Restart();

      C c;
      C c1;
      C c2;
      C c3;
      C c4;

      int i = 1000;
      while (i-- > 0)
      {
        c = new C();
        c1 = new C();
        c2 = new C();
        c3 = new C();
        c4 = new C();
      }

      sw.Stop();
      method1 = method1.Add(sw.Elapsed);
    }

    public void Method2()
    {
      sw.Restart();

      int i = 1000;
      while (i-- > 0)
      {
        var c = new C();
        var c1 = new C();
        var c2 = new C();
        var c3 = new C();
        var c4 = new C();
      }

      sw.Stop();
      method2 = method2.Add(sw.Elapsed);
    }
  }

  class C { }
}

CIL shows no difference.

As was already pointed out declaration is not allocation so there is no performance penalty on it.

Test

namespace Test
{
  class Foreach
  {
    string[] names = new[] { "ABC", "MNL", "XYZ" };

    public TimeSpan method1 = new TimeSpan();
    public TimeSpan method2 = new TimeSpan();

    Stopwatch sw = new Stopwatch();

    void Method1()
    {
      sw.Restart();

      List<User> list = new List<User>();
      User u;

      foreach (string s in names)
      {
        u = new User();
        u.Name = s;
        list.Add(u);
      }

      sw.Stop();
      method1 = method1.Add(sw.Elapsed);
    }

    void Method2()
    {
      sw.Restart();

      List<User> list = new List<User>();

      foreach (string s in names)
      {
        User u = new User();
        u.Name = s;
        list.Add(u);
      }

      sw.Stop();
      method2 = method2.Add(sw.Elapsed);
    }
  }

  public class User { public string Name; }


问:
IBM DB2 issue--System.BadImageFormatException: Could not load file or assembly IBM.DB2.DLL or one of its dependencies
I am getting the above mentioned error message. I have made enough research and tried out various options but still no luck.

Here arethe details below:

```<code>OS: Windows 7 64 bit version

    Visual studio version: 2013 Premium

   .NET framework version is : 4.0.30319

   ASP.NET version: 4.0.30319.34249

   IIS version: 7.0

   DB2 installed path: C:\Program Files (x86)\IBM

   DLL path: C:\Program Files (x86)\IBM\SQLLIB\BIN\netf40\IBM.DB2.dll

   DLL Version: 9.7.4.4
</code>```

I have also changed my solution configuration manager platform to Any CPU and also I have changed the settings in the application pool by setting the property enable 32-bit application to True.

But still am getting the same error. Is there any other workaround?

Please help me with your suggestions.

答:
I faced the same problem and got the solution from the following link. It worked when I removed the local copy and set copy to local property to False.

A link to the solution

Body:
I am getting the above mentioned error message. I have made enough research and tried out various options but still no luck.

Here arethe details below:

OS: Windows 7 64 bit version

    Visual studio version: 2013 Premium

   .NET framework version is : 4.0.30319

   ASP.NET version: 4.0.30319.34249

   IIS version: 7.0

   DB2 installed path: C:\Program Files (x86)\IBM

   DLL path: C:\Program Files (x86)\IBM\SQLLIB\BIN\netf40\IBM.DB2.dll

   DLL Version: 9.7.4.4

I have also changed my solution configuration manager platform to Any CPU and also I have changed the settings in the application pool by setting the property enable 32-bit application to True.

But still am getting the same error. Is there any other workaround?

Please help me with your suggestions.


问:
Plotting and extracting fft phase
Here is a code that compares fft phase plotting with 2 different methods :

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

phase = np.pi / 4
f = 1
fs = f*20
dur=10
t = np.linspace(0, dur, num=fs*dur, endpoint=False)
y = np.cos(2 * np.pi * t + phase)
Y = scipy.fftpack.fftshift(scipy.fftpack.fft(y))
f = scipy.fftpack.fftshift(scipy.fftpack.fftfreq(len(t)))

p = np.angle(Y)
p[np.abs(Y) < 1] = 0

fig, ax = plt.subplots(2, 1)
ax[0].plot(t, y)
ax[1].plot(f*fs, p, label='from fft')
ax[1].phase_spectrum(y, fs, window=None, label='from phase_spectrum')
plt.legend()
plt.show()
</code>```

here is the result :

Here is result when signal number of period is not an integer :

I have several questions :

why are phase plot with phase_spectrum or using fft and the angle so different? Using fft and then np.angle produces good results, but how can we explain magnitude_spectrum result?

Here we are in a very simple case where we have sine periodic signal with N periods For if I have a widepand signal and I want to extract phase at f how can I do? For example here with both methods presented in example, I'm not sure I can extract a precise phase. With phase_spectrum, at f = 1 I cannot find back pi/4. And with fft and then np.angle, in order to extract the good phase I need to be sure signal number of period is an integer.

答:
You can extract the phase referenced to the center of your data window by doing an fftshift (circular rotate by N/2) before the FFT.  This is because, after an fftshift, atan2() always is related to the ratio of oddness to eveness of the data around its center (as decomposed to an odd function plus an even function).

So calculate the phase of the signal in the middle of your window during its generation, and use that instead of the phase at the beginning.

Title: Plotting and extracting fft phase

Body:
Here is a code that compares fft phase plotting with 2 different methods :

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

phase = np.pi / 4
f = 1
fs = f*20
dur=10
t = np.linspace(0, dur, num=fs*dur, endpoint=False)
y = np.cos(2 * np.pi * t + phase)
Y = scipy.fftpack.fftshift(scipy.fftpack.fft(y))
f = scipy.fftpack.fftshift(scipy.fftpack.fftfreq(len(t)))

p = np.angle(Y)
p[np.abs(Y) < 1] = 0

fig, ax = plt.subplots(2, 1)
ax[0].plot(t, y)
ax[1].plot(f*fs, p, label='from fft')
ax[1].phase_spectrum(y, fs, window=None, label='from phase_spectrum')
plt.legend()
plt.show()

here is the result :

Here is result when signal number of period is not an integer :

I have several questions :

why are phase plot with phase_spectrum or using fft and the angle so different? Using fft and then np.angle produces good results, but how can we explain magnitude_spectrum result?

Here we are in a very simple case where we have sine periodic signal with N periods For if I have a widepand signal and I want to extract phase at f how can I do? For example here with both methods presented in example, I'm not sure I can extract a precise phase. With phase_spectrum, at f = 1 I cannot find back pi/4. And with fft and then np.angle, in order to extract the good phase I need to be sure signal number of period is an integer.


问:
Move a button in the screen
I have an UIButton and I want to move that button by touching and swiping it in the screen. When I release the touch it will be in the current position. Explain clearly, please.

答:
check this

you should make move frame from the points and move frame accordingly so that your button moves in places of touches

Title: Move a button in the screen


问:
Reading strings from csv does not print \n
Im reading strings from a csv file. These strings contain "\n" chars to represent new lines.
How can I print these strings with the correct new lines? Using str() didn't work.

CSV File has only one line:

Dest, Test\n Test2\n Test3
```

<p>The code below prints <code>Test\n Test2\n Test3</code></p>

```for ifile in files:
    with open(orderPath + '\\' + ifile) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')

        for row in csv_reader:

            dest = row[0]
            message = row[1]

            message = str(message)
            print(message)
```

答:
If I understand correctly, you want to replace the sequence of literal characters '\' and 'n' in your input with newlines:

Instead of:

```<code>message = str(message)
</code>```

You want:

```<code>message = message.replace('\\n', '\n')
</code>```

Body:
Im reading strings from a csv file. These strings contain "\n" chars to represent new lines.
How can I print these strings with the correct new lines? Using str() didn't work.

CSV File has only one line:

Dest, Test\n Test2\n Test3

The code below prints Test\n Test2\n Test3

for ifile in files:
    with open(orderPath + '\\' + ifile) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')

        for row in csv_reader:

            dest = row[0]
            message = row[1]

            message = str(message)
            print(message)

Body:
If I understand correctly, you want to replace the sequence of literal characters '\' and 'n' in your input with newlines:

Instead of:

message = str(message)

You want:

message = message.replace('\\n', '\n')


问:
How can I grant the account permission to list enabled APIs?
During a build on Cloud Build, I get the following warning:

Step #2: WARNING: Unable to verify that the Appengine Flexible API is enabled for project [xxxxx]. You may not have permission to list enabled services on this project. If it is not enabled, this may cause problems in running your deployment. Please ask the project owner to ensure that the Appengine Flexible API has been enabled and that this account has permission to list enabled APIs.

I'd like to get rid of this warning to get a clean build log.

Since the build succeeds, the problem must not be with Appengine Flexible API being disabled. No; the problem must be that the account does not have permission to list enabled APIs.

How can I fix that (either in the Console or at the command line)?

答:
To verify your account and enable the API within the cloudbuild I had to add the account as role/App Engine Deployer and that worked on my case.
Also on another project I've created new SA and that I've added Editor permissions and that worked too. It was for testing purposes but it worked.

The steps to verify that it's working too below :

gcloud config set account youraccountname

gcloud config set project yourprojectname

Then :
- gcloud auth activate-service-account yourname@yourproject.iam.gserviceaccount.com --key-file=yourfilekey.json

Then to verify that it's working do : gcloud services list and you will see all the NAME and the TITLE of your services list.


问:
AttributeError: 'Str' Object Has No Attribute 'Mean_validation_score' in python
This error occurs in my code: AttributeError: 'str' object has no attribute 'mean_validation_score'. What can I do to resolve it?</p>

```<code>GridMean = [result.mean_validation_score for result in
gridA.cv_results_]
print(GridMean)
plt.plot(k_values, GridMean)
plt.xlabel('Value of "K" for KNN')
plt.ylabel('CrossValidated Accuracy')
</code>```

答:
I presume you are working with sklearn.model_selection.GridSearchCV, with gridA being an instance of GridSearchCV.

I am not sure when the method mean_validation_score was deprecated for GridSearchCV objects, but for sklearn 0.22 you can get the scores calling them with the key 'mean_test_score' being gridA.cv_results a dictionary. Like this:

GridMean = gridA.cv_results_['mean_test_score']

Body:
This error occurs in my code: AttributeError: 'str' object has no attribute 'mean_validation_score'. What can I do to resolve it?

GridMean = [result.mean_validation_score for result in
gridA.cv_results_]
print(GridMean)
plt.plot(k_values, GridMean)
plt.xlabel('Value of "K" for KNN')
plt.ylabel('CrossValidated Accuracy')


问:
How to import JAVA packages in cmd?
This is the first time I am compiling a program, and it doesn't seem to be working out.  Looks like some packages are not being located - so for this question, I'll just focus on one:

Steps I've take so far:

1) setting up the System Variable Path to include java

2) in CMD.exe:  jar tf log4j.jar  I did this to make sure it includes log4j.Logger  and it does.

3) I Shift+rightclick and open command prompt from this folder:

4) Then I enter javac TNT.java and i get the following error (along with others):

Any thoughts?

I set the classpath to the same folders with set classpath = "name of folder" no change...
edit
5) have also tried
javac -cp jdkbindirectory;jrebindirectory;theabovefolder TNT.java

I get this:
blahblahblah

答:
You shouldn't set the classpath using an environment variable as it is bad practice. What if you accidentally change it later for a different project and your current project breaks?

When including classes in the classpath, you can include the path of the root of the package of the class, as in the folder that contains the folders in the package structure. However, when you're including a jar in your classpath, you need to put the entire path of the jar file (relative to the current working directory) all the way up to the jarname.jar.

Also, remember that by default, java looks in the current working directory and uses that as its default classpath. However, as soon as you specify a classpath it no longer does that automatically for you. Be sure that you're including your current directory in your classpath as well.

Finally, be sure to surround the classpath in quotes otherwise java might think its a part of another argument.

I would try this:

```<code>javac -cp "./;log4j.jar" TNT.java
</code>```

And then to execute the class file:

```<code>java -cp "./;log4j.jar" TNT
</code>```

Hope this works, good luck!

Title: How to import JAVA packages in cmd?

Body:
You shouldn't set the classpath using an environment variable as it is bad practice. What if you accidentally change it later for a different project and your current project breaks?

When including classes in the classpath, you can include the path of the root of the package of the class, as in the folder that contains the folders in the package structure. However, when you're including a jar in your classpath, you need to put the entire path of the jar file (relative to the current working directory) all the way up to the jarname.jar.

Also, remember that by default, java looks in the current working directory and uses that as its default classpath. However, as soon as you specify a classpath it no longer does that automatically for you. Be sure that you're including your current directory in your classpath as well.

Finally, be sure to surround the classpath in quotes otherwise java might think its a part of another argument.

I would try this:

javac -cp "./;log4j.jar" TNT.java

And then to execute the class file:

java -cp "./;log4j.jar" TNT

Hope this works, good luck!


问:
OpenShift: namespaces is forbidden: User <user-name> cannot list resource "namespaces" in API group at the cluster scope
I've created a new user and assigned it admin role to one project.

I'm running some code that tries to deploy to that project, however I get this:

```<code>namespaces is forbidden: User <user-name> cannot list resource "namespaces" in API group at the cluster scope
</code>```

How can I add this role to this user?

I tried doing this:

```<code># oc adm policy add-cluster-role-to-user namespaces my-admin
Warning: role 'namespaces' not found
clusterrole.rbac.authorization.k8s.io/namespaces added: "my-admin"

# oc adm policy add-role-to-user namespaces my-admin
clusterrole.rbac.authorization.k8s.io/namespaces added: "my-admin"
</code>```

They don't seem to have any effect.

Using OpenShift 4.2

答:
Here's list of default roles and overview about roles. You can check role's posibilities via:

```<code>oc describe clusterrole.rbac
</code>```

It returns list of available roles with assigned verbs. For instance, there's cluster wide role 'cluster-reader' with following verbs on namespaces which is can be used to list namespaces:

```<code>namespaces  []  []  [get list watch]
</code>```

Body:
I've created a new user and assigned it admin role to one project.

I'm running some code that tries to deploy to that project, however I get this:

namespaces is forbidden: User <user-name> cannot list resource "namespaces" in API group at the cluster scope

How can I add this role to this user?

I tried doing this:

# oc adm policy add-cluster-role-to-user namespaces my-admin
Warning: role 'namespaces' not found
clusterrole.rbac.authorization.k8s.io/namespaces added: "my-admin"

# oc adm policy add-role-to-user namespaces my-admin
clusterrole.rbac.authorization.k8s.io/namespaces added: "my-admin"

They don't seem to have any effect.

Using OpenShift 4.2

Body:
Here's list of default roles and overview about roles. You can check role's posibilities via:

oc describe clusterrole.rbac

It returns list of available roles with assigned verbs. For instance, there's cluster wide role 'cluster-reader' with following verbs on namespaces which is can be used to list namespaces:

namespaces  []  []  [get list watch]


问:
How do I make a WebDav call using HttpClient?
Specifically I want to call MKCOL through HttpClient to create a folder for Apache Jackrabbit through the Sling REST API.

I've tried variants of

```<code>BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("MKCOL", restUrl);
</code>```

But no dice so far.  I'm guessing this is less difficult than I'm making it.

I also see there is MkColMethod for something like

```<code>MkColMethod mkColMethod = new MkColMethod(restUrl);
</code>```

But I don't know how to utilize this.  I think it may have worked with a previous version of HttpClient.  I'm using 4.x

答:
Best is to look at the Sling integration tests, which use Sling's RESTful APIs to create content.

The "old" SlingIntegrationTestClient class is used to test Sling itself and uses httpclient 3.x to create content. It is used by the tests found here, so you can find examples there.

The "new" SlingClient class is meant to be a cleaner and simpler re-implementation of that, used by the Sling testing tools described at http://sling.apache.org/site/sling-testing-tools.html . It uses httpclient 4.x which has a slightly different API.

The SlingClient.mkdir and mkdirs methods do use the MKCOL method.

Body:
Specifically I want to call MKCOL through HttpClient to create a folder for Apache Jackrabbit through the Sling REST API.

I've tried variants of

BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("MKCOL", restUrl);

But no dice so far.  I'm guessing this is less difficult than I'm making it.

I also see there is MkColMethod for something like

MkColMethod mkColMethod = new MkColMethod(restUrl);

But I don't know how to utilize this.  I think it may have worked with a previous version of HttpClient.  I'm using 4.x


问:
How to remove the nth element from a tuple?
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

```<code>constexpr auto t = std::tuple(1, 2, 3, 4);
</code>```

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

```<code>std::tuple(1, 2, 4);
</code>```

This is the closest I got until now:

```<code>template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}
</code>```

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

```<code>return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);
</code>```

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

```<code>template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}
</code>```

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

```<code>if constexpr(sizeof...(tail) - 1 == N)
</code>```

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

答:
Another solution would be to create two index sequences that refer to the before and after parts of the tuple.

```<code>template<std::size_t nth, std::size_t... Head, std::size_t... Tail, typename... Types>
constexpr auto remove_nth_element_impl(std::index_sequence<Head...>, std::index_sequence<Tail...>, std::tuple<Types...> const& tup) {
    return std::tuple{
        std::get<Head>(tup)...,
        // We +1 to refer one element after the one removed
        std::get<Tail + nth + 1>(tup)...
    };
}

template<std::size_t nth, typename... Types>
constexpr auto remove_nth_element(std::tuple<Types...> const& tup) {
    return remove_nth_element_impl<nth>(
        std::make_index_sequence<nth>(), // We -1 to drop one element
        std::make_index_sequence<sizeof...(Types) - nth - 1>(),
        tup
    );
}
</code>```

Here's a test for this function:

```<code>int main() {
    constexpr auto tup = std::tuple{1, 1.2, 'c'};
    constexpr auto tup2 = remove_nth_element<0>(tup);
    constexpr auto tup3 = remove_nth_element<2>(tup);
    static_assert(std::is_same_v<decltype(tup2), const std::tuple<double, char>>);
    static_assert(std::is_same_v<decltype(tup3), const std::tuple<int, double>>);
    return 0;
}
</code>```

Live example

This solution has the advantages of not constructing intermediary tuples and not using std::tuple_cat, which both can be hard on compile times.

Body:
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

constexpr auto t = std::tuple(1, 2, 3, 4);

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

std::tuple(1, 2, 4);

This is the closest I got until now:

template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

if constexpr(sizeof...(tail) - 1 == N)

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

Body:
Another solution would be to create two index sequences that refer to the before and after parts of the tuple.

template<std::size_t nth, std::size_t... Head, std::size_t... Tail, typename... Types>
constexpr auto remove_nth_element_impl(std::index_sequence<Head...>, std::index_sequence<Tail...>, std::tuple<Types...> const& tup) {
    return std::tuple{
        std::get<Head>(tup)...,
        // We +1 to refer one element after the one removed
        std::get<Tail + nth + 1>(tup)...
    };
}

template<std::size_t nth, typename... Types>
constexpr auto remove_nth_element(std::tuple<Types...> const& tup) {
    return remove_nth_element_impl<nth>(
        std::make_index_sequence<nth>(), // We -1 to drop one element
        std::make_index_sequence<sizeof...(Types) - nth - 1>(),
        tup
    );
}

Here's a test for this function:

int main() {
    constexpr auto tup = std::tuple{1, 1.2, 'c'};
    constexpr auto tup2 = remove_nth_element<0>(tup);
    constexpr auto tup3 = remove_nth_element<2>(tup);
    static_assert(std::is_same_v<decltype(tup2), const std::tuple<double, char>>);
    static_assert(std::is_same_v<decltype(tup3), const std::tuple<int, double>>);
    return 0;
}

Live example

This solution has the advantages of not constructing intermediary tuples and not using std::tuple_cat, which both can be hard on compile times.


问:
Cannot install scipy with pypy (g++ build error)
As of 2020, installing scipy with pypy is possible. (Is it possible to install scipy under pypy?)

```<code>pypy3 -mpip install scipy
</code>```

However, the wheel fails with this kind of error:

```<code>  error: Command "g++ -pthread -DNDEBUG -O2 -fPIC -I/tmp/pip-build-env-lfdsn__t/overlay/site-packages/numpy/core/include -I/usr/lib/pypy3/include -c scipy/_lib/_uarray/_uarray_dispatch.cxx -o build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o -MMD -MF build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o.d -std=c++14 -fvisibility=hidden" failed with exit status 1

  ERROR: Failed building wheel for scipy
</code>```

Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly

Using --no-use-pep517 option give similar result:

```<code>    error: Command "g++ -pthread -DNDEBUG -O2 -fPIC -I/home/ezako/.local/lib/pypy3.6/site-packages/numpy/core/include -I/usr/lib/pypy3/include -c scipy/_lib/_uarray/_uarray_dispatch.cxx -o build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o -MMD -MF build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o.d -std=c++14 -fvisibility=hidden" failed with exit status 1
ERROR: Command errored out with exit status 1: /usr/bin/pypy3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2ffzze2v/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2ffzze2v/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8avik0f1/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/ezako/.local/include/python3.6/scipy Check the logs for full command output.
</code>```

Numpy has been sucessfully installed with pypy3.

```<code>➜ pypy3 -V
Python 3.6.9 (7.3.0+dfsg-1~ppa1~ubuntu19.04, Dec 26 2019, 11:14:16)
[PyPy 7.3.0 with GCC 8.3.0]
</code>```

答:
Here is what worked for me. I unpacked the latest nightly

```<code>pypy -mensurepip
pypy -mpip install --upgrade pip setuptools wheel
pypy -mpip install numpy pybind11
pypy -mpip install scipy
</code>```

Apparently you need to install pybind11 separately since it does not work properly in a PEP 517 isolated build.

Body:
As of 2020, installing scipy with pypy is possible. (Is it possible to install scipy under pypy?)

pypy3 -mpip install scipy

However, the wheel fails with this kind of error:

  error: Command "g++ -pthread -DNDEBUG -O2 -fPIC -I/tmp/pip-build-env-lfdsn__t/overlay/site-packages/numpy/core/include -I/usr/lib/pypy3/include -c scipy/_lib/_uarray/_uarray_dispatch.cxx -o build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o -MMD -MF build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o.d -std=c++14 -fvisibility=hidden" failed with exit status 1

  ERROR: Failed building wheel for scipy

Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly

Using --no-use-pep517 option give similar result:

    error: Command "g++ -pthread -DNDEBUG -O2 -fPIC -I/home/ezako/.local/lib/pypy3.6/site-packages/numpy/core/include -I/usr/lib/pypy3/include -c scipy/_lib/_uarray/_uarray_dispatch.cxx -o build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o -MMD -MF build/temp.linux-x86_64-3.6/scipy/_lib/_uarray/_uarray_dispatch.o.d -std=c++14 -fvisibility=hidden" failed with exit status 1
ERROR: Command errored out with exit status 1: /usr/bin/pypy3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2ffzze2v/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2ffzze2v/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8avik0f1/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/ezako/.local/include/python3.6/scipy Check the logs for full command output.

Numpy has been sucessfully installed with pypy3.

➜ pypy3 -V
Python 3.6.9 (7.3.0+dfsg-1~ppa1~ubuntu19.04, Dec 26 2019, 11:14:16)
[PyPy 7.3.0 with GCC 8.3.0]

Body:
Here is what worked for me. I unpacked the latest nightly

pypy -mensurepip
pypy -mpip install --upgrade pip setuptools wheel
pypy -mpip install numpy pybind11
pypy -mpip install scipy

Apparently you need to install pybind11 separately since it does not work properly in a PEP 517 isolated build.