问:
HTML FormData File is not posted to REST API
I am trying to POST a file from a front-end index.html to an Express Server running in the background. The API is then supposed to save the file into Firebase Storage. The server is running properly and it is receiving the POST, but there is no data in the req.body.

index.html - Front-end

```<code><form method="POST" id="form">
 <input type="file" id="file" name="file" multiple>
 <input type="submit">
</form>

<script>
 const form = document.querySelector('#form')

 const postFile = (e) => {
  e.preventDefault()
  const header = { "Content-Type": "multipart/form-data" }

  let formData = new FormData()
  formData.append('file', this.file.files[0])

  fetch('http://localhost:3003/file', {
   method: form.method,
   headers: header,
   body: formData
  }).then(() => {
      alert("OK")
  }).catch(() => {
      alert("Nope")
  })
 }

 form.addEventListener('submit', (e) => postFile(e))
</script>
</code>```

server.js - Back-end (Incomplete)

```<code>const server = express()
const routes = require('./routes')

server.use(cors())
server.use(express.urlencoded({
    limit: '50mb',
    extended: true
}))
server.use(express.json({
    limit: '50mb',
    extended: true
}))
server.use(routes)
server.listen(3003)
</code>```

fileController.js - Back-end (Incomplete)

```<code>exports.addFile = async (req, res) => {
    try {
        console.log(req.body)

        return res.status(200).send({
            message: "Ok"
        })
    } catch (e) {
        return res.status(500).send({
            message: e.message
        })
    }
</code>```

When I console.log(this.file.files[0]) before fetching it actually returns the File as it is supposed to, but in the server is just an empty array.
Front-end console.log;
Server console.log

答:
Ok, problem is solved. As Wezelkrozum pointed out, I could've used multer (npm install --save multer)

Changes Applied:

index.html

```<code><form method="POST" id="form" **enctype="multipart/form-data"**>
 <input type="file" id="file" name="file" multiple>
 <input type="submit">
</form>

<script>
 const form = document.querySelector('#form')

 const postFile = (e) => {
  e.preventDefault()

  let formData = new FormData()
  formData.append('file', this.file.files[0])

  fetch('http://localhost:3003/file', { //Removed the Headers
   method: form.method,
   body: formData
  }).then(() => {
      alert("OK")
  }).catch(() => {
      alert("Nope")
  })
 }

 form.addEventListener('submit', (e) => postFile(e))
</script>
</code>```

routes.js

```<code>const express = require('express')
const multer = require('multer')
const routes = express.Router()

const upload = multer({dest: 'uploads/'}) //Folder where the temp file is stored

routes.post('/file', upload.single('file'), fileController.addFile) //This is for one file only
module.exports = routes
</code>```

Then in the Controller the file properties will come as req.file, just like:

```<code>let file = req.file
</code>```

EDIT:

To get the actual file content you must use:

```<code>npm install fs

fs.readFileSync(file.path)
</code>```

It will return a buffer of the file, needed for any operation related with File or Blob

Body:
I am trying to POST a file from a front-end index.html to an Express Server running in the background. The API is then supposed to save the file into Firebase Storage. The server is running properly and it is receiving the POST, but there is no data in the req.body.

index.html - Front-end

<form method="POST" id="form">
 <input type="file" id="file" name="file" multiple>
 <input type="submit">
</form>

server.js - Back-end (Incomplete)

const server = express()
const routes = require('./routes')

server.use(cors())
server.use(express.urlencoded({
    limit: '50mb',
    extended: true
}))
server.use(express.json({
    limit: '50mb',
    extended: true
}))
server.use(routes)
server.listen(3003)

fileController.js - Back-end (Incomplete)

exports.addFile = async (req, res) => {
    try {
        console.log(req.body)

        return res.status(200).send({
            message: "Ok"
        })
    } catch (e) {
        return res.status(500).send({
            message: e.message
        })
    }

When I console.log(this.file.files[0]) before fetching it actually returns the File as it is supposed to, but in the server is just an empty array.
Front-end console.log;
Server console.log

Body:
Ok, problem is solved. As Wezelkrozum pointed out, I could've used multer (npm install --save multer)

Changes Applied:

index.html

<form method="POST" id="form" **enctype="multipart/form-data"**>
 <input type="file" id="file" name="file" multiple>
 <input type="submit">
</form>

<script>
 const form = document.querySelector('#form')

 const postFile = (e) => {
  e.preventDefault()

  let formData = new FormData()
  formData.append('file', this.file.files[0])

  fetch('http://localhost:3003/file', { //Removed the Headers
   method: form.method,
   body: formData
  }).then(() => {
      alert("OK")
  }).catch(() => {
      alert("Nope")
  })
 }

 form.addEventListener('submit', (e) => postFile(e))
</script>

routes.js

const express = require('express')
const multer = require('multer')
const routes = express.Router()

const upload = multer({dest: 'uploads/'}) //Folder where the temp file is stored

routes.post('/file', upload.single('file'), fileController.addFile) //This is for one file only
module.exports = routes

Then in the Controller the file properties will come as req.file, just like:

let file = req.file

EDIT:

To get the actual file content you must use:

npm install fs

fs.readFileSync(file.path)

It will return a buffer of the file, needed for any operation related with File or Blob


来源: stackexchange

问:
How to manage memory/usage of a NSMutableArray of NSMutableArrays
I am currently trying to write a class to create faux grid system to keep track of a NSMutableArray of game entities using a NSMutableArray of NSMutableArrays. Given my limited experience with Objective-C programming, I am unsure of how certain things work.

Here is the init method:

```<code>#define MAX_BALL_ROWCOUNT 6
#define MAX_BALL_COLCOUNT 4
- (id) initWithMutableArray:(NSMutableArray *)aList {
self = [super init];
if (self != nil) {
    ballList = [[NSMutableArray alloc] initWithCapacity: MAX_BALL_ROWCOUNT];

    for (int i=0; i<MAX_BALL_ROWCOUNT; i++) {
        NSMutableArray *balls = [[NSMutableArray alloc] initWithCapacity:MAX_BALL_COLCOUNT];
        [ballList addObject:balls];
        [balls release];
    }

    int x = 0;

    for (NSMutableArray *array in ballList) {
        for (int i = 0; i<MAX_BALL_COLCOUNT; i++) {
            [array addObject:[aList objectAtIndex:x]];
            x++;
            }
        }
    }

return self;
}
</code>```

ballList is the class's NSMutableArray that will store NSMutableArrays.

aList is the NSMutableArray containing the GameEntities I wish to keep track of that is passed into this class.

All the sizes and amount of entities to store are fixed, which is why there is no checks on the sizes of the arrays nor the number of entities to store.

So the first question I have involves freeing memory. This is the dealloc function I currently have:

```<code>- (void) dealloc {
    [ballList release];
    [super dealloc];
}
</code>```

Does calling a release on ballList cause the release to be called on the NSMutableArrays that it contains (which will subsequently call the release on the objects those NSMutableArrays contain) or do I have to write something like:

```<code>for (NSMutableArray *array in ballList) {
    [array release];
}
[ballList release];
</code>```

My second question involves the usage of this array of arrays. Is this the proper way to traverse through ballList?

```<code>- (void) update {
    for (NSMutableArray *array in ballList) {
        for (GameEntity *balls in array) {
            (CGPoint) location = [balls getLocation];
            [balls setLocation: CGPointMake(location.x+1, location.y+1)];
        }
    }
}
</code>```

Lastly, in the code above where it sets the balls location, does it only affect the contents within ballList or does the original aList that is passed into ballList change as well? If the contents in the original aList do not change, how would I write it so that they do?

If people have suggestions for a better way to keep track of the entities in a grid system, I'd be open to those too. Thanks in advance.

答:
First : One release is enough for the NSMutableArray instance to release all it's object.

```<code>    [ballList release];
</code>```

Second : Your code for updating GameEntity instance is fine and will also effect to the original aList (which you called) .

ContentLicense: CC BY-SA 3.0

Body:
I am currently trying to write a class to create faux grid system to keep track of a NSMutableArray of game entities using a NSMutableArray of NSMutableArrays. Given my limited experience with Objective-C programming, I am unsure of how certain things work.

Here is the init method:

#define MAX_BALL_ROWCOUNT 6
#define MAX_BALL_COLCOUNT 4
- (id) initWithMutableArray:(NSMutableArray *)aList {
self = [super init];
if (self != nil) {
    ballList = [[NSMutableArray alloc] initWithCapacity: MAX_BALL_ROWCOUNT];

    for (int i=0; i<MAX_BALL_ROWCOUNT; i++) {
        NSMutableArray *balls = [[NSMutableArray alloc] initWithCapacity:MAX_BALL_COLCOUNT];
        [ballList addObject:balls];
        [balls release];
    }

    int x = 0;

    for (NSMutableArray *array in ballList) {
        for (int i = 0; i<MAX_BALL_COLCOUNT; i++) {
            [array addObject:[aList objectAtIndex:x]];
            x++;
            }
        }
    }

return self;
}

ballList is the class's NSMutableArray that will store NSMutableArrays.

aList is the NSMutableArray containing the GameEntities I wish to keep track of that is passed into this class.

All the sizes and amount of entities to store are fixed, which is why there is no checks on the sizes of the arrays nor the number of entities to store.

So the first question I have involves freeing memory. This is the dealloc function I currently have:

- (void) dealloc {
    [ballList release];
    [super dealloc];
}

Does calling a release on ballList cause the release to be called on the NSMutableArrays that it contains (which will subsequently call the release on the objects those NSMutableArrays contain) or do I have to write something like:

for (NSMutableArray *array in ballList) {
    [array release];
}
[ballList release];

My second question involves the usage of this array of arrays. Is this the proper way to traverse through ballList?

- (void) update {
    for (NSMutableArray *array in ballList) {
        for (GameEntity *balls in array) {
            (CGPoint) location = [balls getLocation];
            [balls setLocation: CGPointMake(location.x+1, location.y+1)];
        }
    }
}

Lastly, in the code above where it sets the balls location, does it only affect the contents within ballList or does the original aList that is passed into ballList change as well? If the contents in the original aList do not change, how would I write it so that they do?

If people have suggestions for a better way to keep track of the entities in a grid system, I'd be open to those too. Thanks in advance.

Body:
First : One release is enough for the NSMutableArray instance to release all it's object.

    [ballList release];

Second : Your code for updating GameEntity instance is fine and will also effect to the original aList (which you called) .


问:
How to add element of a list to list of dictionary in python
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

```<code>fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]
</code>```

list

```<code>rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]
</code>```

Desired output

```<code>[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]
</code>```

I will appreciate any help in getting this done.
Thank you

答:
You could try this:</p>

```<code>myit = iter(rev_per_emp)
for dict in fortunne_500:
  dict['rev_per_emp'] = next(myit)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]

list

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

Desired output

[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]

I will appreciate any help in getting this done.
Thank you

Body:
You could try this:

myit = iter(rev_per_emp)
for dict in fortunne_500:
  dict['rev_per_emp'] = next(myit)


问:
When organising an InfluxDB database, which of these two approaches would be most preferred?
I am trying to decide how measurements should be organised in an InfluxDB the database (which I believe they call schema design and data layout) but I think this may be a more general database type question.

Let's say as a simple example that I am measuring two quantites, temperature and humidity (imaginative, I know!), in two locations, living room and outside.

InfluxDB has the syntax for inserting data points:

measurement, tag_key=tag_value field_key=field_value

and so there are two obvious (at least to me) options. Briefly, the first option would insert a data point like this:

```<code>INSERT temperature,location=outside value=15
INSERT humidity,location=outside value=50
</code>```

whereas the second option would do it this way:

```<code>INSERT sensor_measurements,location=outside temperature=15,humidity=50
</code>```

My questions are more high level:

Is there a preferred/accepted way to go about this?

Will I run into problems with either of these if I try to scale it up to more quantities/locations/data types?

Does either of the methods offer an advantage if I later on try to graph these things in Grafana, for example, or if I try to implement later some of the many InfluxQL functions?

Does anyone have any general advice about this to offer?

My own thoughts:

Option 1 seems to me to be more like what is implied by the InfluxDB description "measurement". Both temperature and humidity are separate quantities. But it seems a little clunky to just call it "value".

Option 2 appears to have the advantage that both the humidity and the temperature share exactly the same timestamp. This would come in useful, for example, if I wanted to import the data into some other software and do a correlation between the two quantites, and would mean I wouldn't have to do any interpolation or binning to get them to match up.

I am not sure if it is a bad idea with Option 2 to just have a general measurement called sensor_measurements, and will be hard to maintain later.

In detail:

Option 1

Have a separate "measurement" for each of temperature and humidity, use the location as a "tag", and just name the "field" as value:

At time t1, insert the data:

```<code>INSERT humidity,location=outside value=50
INSERT temperature,location=outside value=15
INSERT humidity,location=living_room value=65
INSERT temperature,location=living_room value=28
</code>```

At time t2, insert some different data:

```<code>INSERT humidity,location=outside value=50
INSERT temperature,location=outside value=15
INSERT humidity,location=living_room value=65
INSERT temperature,location=living_room value=28
</code>```

I can then get access to the living room temperature by querying the following:

```<code>> SELECT value FROM temperature WHERE location='living_room'

name: temperature
time                value
----                -----
1590416682017481091 28
1590416723963187592 29
</code>```

I can also use the group by function to do something like this:

```<code>SELECT value FROM temperature GROUP BY "location"
</code>```

Option 2

Have a combined "measurement" called sensor_measurements, for example, use a "tag" for location, and then have separate "fields" for each of temperature and humidity:

At time t1, insert the data:

```<code>INSERT sensor_measurements,location=outside temperature=15,humidity=50
INSERT sensor_measurements,location=living_room temperature=28,humidity=65
</code>```

At time t2, insert some different data:

```<code>INSERT sensor_measurements,location=outside temperature=14,humidity=56
INSERT sensor_measurements,location=living_room temperature=29,humidity=63
</code>```

I can now get access to the living room temperature by querying the following:

```<code>> SELECT temperature FROM sensor_measurements WHERE location='living_room'

name: sensor_measurements
time                temperature
----                -----------
1590416731530452068 28
1590416757055629103 29
</code>```

I can now use the group by function to do something like this:

```<code>SELECT temperature FROM sensor_measurements GROUP BY "location"
</code>```

答:
I would use option 2 from offered options, because less records = less resources = better query response time (in theory). Generally, both approaches look good.

But I will use more generic 3rd option in real world. Single generic metrics measurement with tags metric,location and field value:

```<code>INSERT metrics,metric=temperature,location=outside value=15
INSERT metrics,metric=humidity,location=living_room value=50
INSERT metrics,metric=temperature,location=living_room value=28
INSERT metrics,metric=humidity,location=living_room value=65
</code>```

That gives me opportunity to create single generic Grafana dashboard, where user will have option to select visualized metric/location via dashboard variable (generated directly from the InfluxDB, e.g. SHOW TAG VALUES WITH KEY = "metric"). Any new inserted metrics (e.g. `illuminance , pressure, wind-speed, wind-direction, ...) or location can be immediately visualized in this generic dashboard. Eventually, some metrics may have also additional tags. That is good and I will be able to use ad-hoc Grafana variable, so users will be able specify any number of key/value filters on the fly. Grafana doc.

Body:
I am trying to decide how measurements should be organised in an InfluxDB the database (which I believe they call schema design and data layout) but I think this may be a more general database type question.

Let's say as a simple example that I am measuring two quantites, temperature and humidity (imaginative, I know!), in two locations, living room and outside.

InfluxDB has the syntax for inserting data points:

measurement, tag_key=tag_value field_key=field_value

and so there are two obvious (at least to me) options. Briefly, the first option would insert a data point like this:

INSERT temperature,location=outside value=15
INSERT humidity,location=outside value=50

whereas the second option would do it this way:

INSERT sensor_measurements,location=outside temperature=15,humidity=50

My questions are more high level:

Is there a preferred/accepted way to go about this?

Will I run into problems with either of these if I try to scale it up to more quantities/locations/data types?

Does either of the methods offer an advantage if I later on try to graph these things in Grafana, for example, or if I try to implement later some of the many InfluxQL functions?

Does anyone have any general advice about this to offer?

My own thoughts:

Option 1 seems to me to be more like what is implied by the InfluxDB description "measurement". Both temperature and humidity are separate quantities. But it seems a little clunky to just call it "value".

Option 2 appears to have the advantage that both the humidity and the temperature share exactly the same timestamp. This would come in useful, for example, if I wanted to import the data into some other software and do a correlation between the two quantites, and would mean I wouldn't have to do any interpolation or binning to get them to match up.

I am not sure if it is a bad idea with Option 2 to just have a general measurement called sensor_measurements, and will be hard to maintain later.

In detail:

Option 1

Have a separate "measurement" for each of temperature and humidity, use the location as a "tag", and just name the "field" as value:

At time t1, insert the data:

INSERT humidity,location=outside value=50
INSERT temperature,location=outside value=15
INSERT humidity,location=living_room value=65
INSERT temperature,location=living_room value=28

At time t2, insert some different data:

INSERT humidity,location=outside value=50
INSERT temperature,location=outside value=15
INSERT humidity,location=living_room value=65
INSERT temperature,location=living_room value=28

I can then get access to the living room temperature by querying the following:

> SELECT value FROM temperature WHERE location='living_room'

name: temperature
time                value
----                -----
1590416682017481091 28
1590416723963187592 29

I can also use the group by function to do something like this:

SELECT value FROM temperature GROUP BY "location"

Option 2

Have a combined "measurement" called sensor_measurements, for example, use a "tag" for location, and then have separate "fields" for each of temperature and humidity:

At time t1, insert the data:

INSERT sensor_measurements,location=outside temperature=15,humidity=50
INSERT sensor_measurements,location=living_room temperature=28,humidity=65

At time t2, insert some different data:

INSERT sensor_measurements,location=outside temperature=14,humidity=56
INSERT sensor_measurements,location=living_room temperature=29,humidity=63

I can now get access to the living room temperature by querying the following:

> SELECT temperature FROM sensor_measurements WHERE location='living_room'

name: sensor_measurements
time                temperature
----                -----------
1590416731530452068 28
1590416757055629103 29

I can now use the group by function to do something like this:

SELECT temperature FROM sensor_measurements GROUP BY "location"

Body:
I would use option 2 from offered options, because less records = less resources = better query response time (in theory). Generally, both approaches look good.

But I will use more generic 3rd option in real world. Single generic metrics measurement with tags metric,location and field value:

INSERT metrics,metric=temperature,location=outside value=15
INSERT metrics,metric=humidity,location=living_room value=50
INSERT metrics,metric=temperature,location=living_room value=28
INSERT metrics,metric=humidity,location=living_room value=65

That gives me opportunity to create single generic Grafana dashboard, where user will have option to select visualized metric/location via dashboard variable (generated directly from the InfluxDB, e.g. SHOW TAG VALUES WITH KEY = "metric"). Any new inserted metrics (e.g. `illuminance , pressure, wind-speed, wind-direction, ...) or location can be immediately visualized in this generic dashboard. Eventually, some metrics may have also additional tags. That is good and I will be able to use ad-hoc Grafana variable, so users will be able specify any number of key/value filters on the fly. Grafana doc.


问:
Getting full branch coverage in equals() method with EclEmma
This is tedious, but I've got an assignment where I need to achieve full coverage of the equals() method to earn all possible points. I'm having issues getting full statement/branch coverage due to the getClass() portion of the equals() method. So far I've gotten 1/2 branches covered, but I can't get my mind around how to get to the second.

Equals method below:

```<code>public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        //Lots of other tests checking the functionality of the program that I've figured out already
        return true;
    }
</code>```

The unit test that is getting me 1/2 branches covered:

```<code>assertFalse(!s1.getClass().equals(s1.getClass()));
</code>```

Since I've gotten 1/2 branches covered I assume the second is possible. But idk.

Thanks

答:
Some information you've left out is what class the "s1" object is, and what class this equals method is in.  It's reasonable to assume that "s1" is of the same type as the class your "equals" method is defined in.

Under that assumption, the line in question (converted to the simpler version alluded to by @howlger):

```<code>assertTrue(s1.getClass().equals(s1.getClass()));
</code>```

Is not even executing your "equals" method.  That's because you're calling "s1.getClass().equals(...)" instead of "s1.equals(...)".

An assertion that would actually be testing your code would be more like this:

```<code>assertTrue(s1.equals(s1));
</code>```

To address your coverage question, this obviously by itself would not give you full coverage in the method.  It will match the first "if" and return true.

Assertions that should give you closer to complete coverage would include these:

```<code>// s1 and s2 are different instances of the same class, with identical contents
assertTrue(s1.equals(s2));
// s1 and s2 are different instances of the same class, with different contents
assertFalse(s1.equals(s2));
// s1 and s2 are different instances of different classes
assertFalse(s1.equals(s2));
</code>```

In addition, it's useful to note that you can run your test in the debugger, with breakpoints in the "equals" method, to verify exactly what path the code takes.

Body:
This is tedious, but I've got an assignment where I need to achieve full coverage of the equals() method to earn all possible points. I'm having issues getting full statement/branch coverage due to the getClass() portion of the equals() method. So far I've gotten 1/2 branches covered, but I can't get my mind around how to get to the second.

Equals method below:

public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        //Lots of other tests checking the functionality of the program that I've figured out already
        return true;
    }

The unit test that is getting me 1/2 branches covered:

assertFalse(!s1.getClass().equals(s1.getClass()));

Since I've gotten 1/2 branches covered I assume the second is possible. But idk.

Thanks

Body:
Some information you've left out is what class the "s1" object is, and what class this equals method is in.  It's reasonable to assume that "s1" is of the same type as the class your "equals" method is defined in.

Under that assumption, the line in question (converted to the simpler version alluded to by @howlger):

assertTrue(s1.getClass().equals(s1.getClass()));

Is not even executing your "equals" method.  That's because you're calling "s1.getClass().equals(...)" instead of "s1.equals(...)".

An assertion that would actually be testing your code would be more like this:

assertTrue(s1.equals(s1));

To address your coverage question, this obviously by itself would not give you full coverage in the method.  It will match the first "if" and return true.

Assertions that should give you closer to complete coverage would include these:

// s1 and s2 are different instances of the same class, with identical contents
assertTrue(s1.equals(s2));
// s1 and s2 are different instances of the same class, with different contents
assertFalse(s1.equals(s2));
// s1 and s2 are different instances of different classes
assertFalse(s1.equals(s2));

In addition, it's useful to note that you can run your test in the debugger, with breakpoints in the "equals" method, to verify exactly what path the code takes.


问:
Is it possible to make an interface method return the type of another method with a generic type parameters in C#?
So I'm trying to create some fluent code to execute a web request. I want it to look something like this...

```<code>// Result should be of type MyClass
var result = await _webRequests.Get("Api/Route/Here")
                               .Returns<MyClass>()
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

// Result should be of type HttpResponseMessage
var result = await _webRequests.Get("Api/Route/Here")
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();
</code>```

I'm aiming to get it so that if the Returns method is not specified, then it returns a HttpResponseMessage and if it is specified, it returns the type specified.

_webRequests is an interface with some basic HttpMethod calls in there

```<code>IUseRequired Get(string url);
IUseRequired Post(string url);
</code>```

Then the IUseRequired interface has the required methods for the call...

```<code>IUseOptionalOrExecute UsesApi(string apiName);
</code>```

All the UsesApi method does is tell which HTTPClient to use when using IHttpClientFactory.

Now the IUseOptionalOrExecute interface is where the problem starts...

```<code>IUseOptionalOrExecute Returns<TReturn>();
IUseOptionalOrExecute HasToken(string token);
Task<TReturn> ExecuteAsync();
</code>```

I want it to look something like this, so whatever is passed in to the Returns method will be used as the return of the ExecuteAsync method. Of course this doesn't work, because ExecuteAsync has no idea what TReturn is. I've thought about storing the type as a variable when the Returns method is called, but I can't set the return type of Execute to be a variable type. Or can I?
Anyone know a way I can get around this? Thanks!

答: Use typeof(TReturn) to determine the type.</p>

Body:
So I'm trying to create some fluent code to execute a web request. I want it to look something like this...

// Result should be of type MyClass
var result = await _webRequests.Get("Api/Route/Here")
                               .Returns<MyClass>()
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

// Result should be of type HttpResponseMessage
var result = await _webRequests.Get("Api/Route/Here")
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

I'm aiming to get it so that if the Returns method is not specified, then it returns a HttpResponseMessage and if it is specified, it returns the type specified.

_webRequests is an interface with some basic HttpMethod calls in there

IUseRequired Get(string url);
IUseRequired Post(string url);

Then the IUseRequired interface has the required methods for the call...

IUseOptionalOrExecute UsesApi(string apiName);

All the UsesApi method does is tell which HTTPClient to use when using IHttpClientFactory.

Now the IUseOptionalOrExecute interface is where the problem starts...

IUseOptionalOrExecute Returns<TReturn>();
IUseOptionalOrExecute HasToken(string token);
Task<TReturn> ExecuteAsync();

I want it to look something like this, so whatever is passed in to the Returns method will be used as the return of the ExecuteAsync method. Of course this doesn't work, because ExecuteAsync has no idea what TReturn is. I've thought about storing the type as a variable when the Returns method is called, but I can't set the return type of Execute to be a variable type. Or can I?
Anyone know a way I can get around this? Thanks!


问:
Default UNIX permissions of Mongodb files in the hard drive
I noticed that the files in the data/ directory, hosting the databases and collections, are the r permission for others.

So basically, anyone can read the data! Isn't it strange, or is it something I'm missing?

I found no solution to change this behavior in the mondodb configuration (ubuntu 18.04). When you search mongodb file permissions, you will find threads about user permissions inside the database.

Thank you!

答:
Im going to assume you're using WiredTiger, the default storage engine for mongo. Either way, the same concept applies.

You'll see the .wt files (the ones you're talking about), although readable by permission, are not very readable to the eye. Try look for yourself with less <example>.wt.

They're stored in a specific format, with compression and some encryption. Realistically, they shouldn't be able to be retrieved from outside of your server - and your users in the server should trusted, or given limited access to the locations of these files.

In short, if you apply the proper policies, and keep your actual database and server secure, then this is normal and expected. I hope this makes sense.


问:
best approch among EXE and MSI
I have an application that needs to be delivered as a package.

What are the best among EXE and MSI Installers, and why?

Is there any open source tool to decompile the EXE or MSI?

答:
It depends on what kind of EXE you are talking about.

MSI is setup package that is run by Windows Installer. If you make setup project with Visual Studio it will provide both MSI and EXE for you. EXE in this case just a bootstrapper (MSI or EXE). It will run MSI after checks that Windows Installer is in place.

If you use other tools like InnoSetup, this EXE is a setup package itself, not a bootstrapper.

Regarding to your question about MSI editor: Orca MSI Editor.

If don't need need very complicated installer, I suggest using Visual Studio setup project as it is simple, yet powerful enough.

Title: best approch among EXE and MSI


问:
is there any method to hide the message below "No result Found "

i am using react type ahead npm package **
**https://ericgio.github.io/react-bootstrap-typeahead/#asynchronous-searching

i want to show only  matching result not any other message in
dropdown like its showing no match found!

答:
Does using

emptyLabel=''
```

<p>as a property work for you?</p>

<p>Eg:</p>

<pre class="lang-js prettyprint-override"><code><AsyncTypeahead
  id="async-example"
  emptyLabel=''
</code>```

If you want to the entire bottom menu option to disappear, I'd recommend submitting a patch to the project:

```<code>diff --git a/src/components/Menu.react.js b/src/components/Menu.react.js
index 9e403f9..c25b2f5 100644
--- a/src/components/Menu.react.js
+++ b/src/components/Menu.react.js
@@ -83,12 +83,12 @@ class Menu extends React.Component<MenuComponentProps> {
     } = this.props;

     const contents = Children.count(children) === 0 ?
-      <BaseMenuItem disabled role="option">
+      (emptyLabel ? <BaseMenuItem disabled role="option">
         {emptyLabel}
-      </BaseMenuItem> :
+      </BaseMenuItem> : null) :
       children;

-    return (
+    return contents ? (
       <ul
         aria-label={this.props['aria-label']}
         className={cx('rbt-menu', 'dropdown-menu', 'show', className)}
@@ -108,7 +108,7 @@ class Menu extends React.Component<MenuComponentProps> {
         }}>
         {contents}
       </ul>
-    );
+    ) : null;
   }
 }

</code>```

Body:
Does using

emptyLabel=''

as a property work for you?

Eg:

<AsyncTypeahead
  id="async-example"
  emptyLabel=''

If you want to the entire bottom menu option to disappear, I'd recommend submitting a patch to the project:

diff --git a/src/components/Menu.react.js b/src/components/Menu.react.js
index 9e403f9..c25b2f5 100644
--- a/src/components/Menu.react.js
+++ b/src/components/Menu.react.js
@@ -83,12 +83,12 @@ class Menu extends React.Component<MenuComponentProps> {
     } = this.props;

     const contents = Children.count(children) === 0 ?
-      <BaseMenuItem disabled role="option">
+      (emptyLabel ? <BaseMenuItem disabled role="option">
         {emptyLabel}
-      </BaseMenuItem> :
+      </BaseMenuItem> : null) :
       children;

-    return (
+    return contents ? (
       <ul
         aria-label={this.props['aria-label']}
         className={cx('rbt-menu', 'dropdown-menu', 'show', className)}
@@ -108,7 +108,7 @@ class Menu extends React.Component<MenuComponentProps> {
         }}>
         {contents}
       </ul>
-    );
+    ) : null;
   }
 }


问:
Why does my javascript object get faster and faster?
So, I'm trying to code a game where there is a ball that chases the player, and currently I'm coding the player physics. For some reason, as the player walks back and forth, it gets faster and faster, but I can't figure out why.  I think it might have something to do with me multiplying the physicsX variable by .85, but I can't figure out how that would affect it. Here is my code-

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {y: baseY - 5, height: 32}
  var ground = {y: 140}
    if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
} else {
  touchingGround = true;
}
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }
  physicsX = 0;
  window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
    physicsX = physicsX + 0.001;
  }
  if (e.key == "ArrowLeft") {
    physicsX = physicsX - 0.001;
  }
  physicsX = physicsX * 0.85
  baseX = baseX + physicsX;
});

}
function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  width: 100%;
  height: 100%;
  margin: 0%;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <canvas id="canvas"></canvas>

```

答:
The playerX variable only decreases by 15% (0.15) every time a key is pressed. To fix this, simply move that line outside of the keypress event listener into the game loop (just somewhere where it'll be run on each iteration of the loop).

Edit: As @user120242 mentioned, the event listener should be moved outside of the loop too. However, my slightly modified solution preserves (I believe intended) horizontal velocity. The only problem is that there's a delay in the keypress with both solutions, which you can refer to How to fix delay in javascript keydown for.

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;
//move this outside
window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
      physicsX += 5;
  }
  if (e.key == "ArrowLeft") {
      physicsX -= 5;
  }
});

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {
    y: baseY - 5,
    height: 32
  }
  var ground = {
    y: 140
  }
  if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
  } else {
    touchingGround = true;
  }
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY += physicsY;
  }
  //physicsX = 0; remove this line of code
  //moving the line here will guarantee physicsX decreases on each
  //iteration of the loop.
  physicsX *= 0.85;
  baseX += physicsX;
}

function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

Also, using += can simplify your code. For example:
playerX = playerX + 15; is the same as playerX += 15;

Body:
So, I'm trying to code a game where there is a ball that chases the player, and currently I'm coding the player physics. For some reason, as the player walks back and forth, it gets faster and faster, but I can't figure out why.  I think it might have something to do with me multiplying the physicsX variable by .85, but I can't figure out how that would affect it. Here is my code-

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {y: baseY - 5, height: 32}
  var ground = {y: 140}
    if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
} else {
  touchingGround = true;
}
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }
  physicsX = 0;
  window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
    physicsX = physicsX + 0.001;
  }
  if (e.key == "ArrowLeft") {
    physicsX = physicsX - 0.001;
  }
  physicsX = physicsX * 0.85
  baseX = baseX + physicsX;
});

}
function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();

canvas {
  width: 100%;
  height: 100%;
  margin: 0%;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <canvas id="canvas"></canvas>

Body:
The playerX variable only decreases by 15% (0.15) every time a key is pressed. To fix this, simply move that line outside of the keypress event listener into the game loop (just somewhere where it'll be run on each iteration of the loop).

Edit: As @user120242 mentioned, the event listener should be moved outside of the loop too. However, my slightly modified solution preserves (I believe intended) horizontal velocity. The only problem is that there's a delay in the keypress with both solutions, which you can refer to How to fix delay in javascript keydown for.

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;
//move this outside
window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
      physicsX += 5;
  }
  if (e.key == "ArrowLeft") {
      physicsX -= 5;
  }
});

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {
    y: baseY - 5,
    height: 32
  }
  var ground = {
    y: 140
  }
  if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
  } else {
    touchingGround = true;
  }
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY += physicsY;
  }
  //physicsX = 0; remove this line of code
  //moving the line here will guarantee physicsX decreases on each
  //iteration of the loop.
  physicsX *= 0.85;
  baseX += physicsX;
}

function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();

<canvas id="canvas"></canvas>

Also, using += can simplify your code. For example:
playerX = playerX + 15; is the same as playerX += 15;


问:
DyanmoDB Scan with Filter
I can't figure out the correct syntax to perform a scan and filter on a table. I want to filter on books written after 2018.

Given this book model:

```<code>import { attribute, hashKey, rangeKey, table } from '@aws/dynamodb-data-mapper-annotations';

@table('book')
export class Book {
    @hashKey()
    isbn?: string;

    @rangeKey()
    written?: string; // an ISO-8601 string, e.g. 2020-05-30T16:34:20.985Z

    @attribute()
    title?: string;
}

</code>```

My scan query filter:

```<code>mapper.scan(Book, { filter: '> 2018' }); // what goes here?
</code>```

Unfortunantly, I get this TypeScript error:

```<code>Type 'string' is not assignable to type '(ConditionExpressionSubject & EqualityExpressionPredicate) | (ConditionExpressionSubject & InequalityExpressionPredicate) | ... 15 more ... | undefined'.
</code>```

What is the correct filter syntax?

答:
The AWS DynamoDB lib documentation is terrible but I ended up figuring it out:</p>

```<code>import { ConditionExpression } from '@aws/dynamodb-expressions';

// ... later in the file ...

const dateFilter: ConditionExpression = {
    type: 'GreaterThanOrEqualTo',
    subject: 'written',
    object: '2018'
};

const paginator = mapper.scan(Book, { filter: dateFilter });
for await (const book of paginator) {
    console.log(book); // book available here
}
</code>```

Title: DyanmoDB Scan with Filter

Body:
I can't figure out the correct syntax to perform a scan and filter on a table. I want to filter on books written after 2018.

Given this book model:

import { attribute, hashKey, rangeKey, table } from '@aws/dynamodb-data-mapper-annotations';

@table('book')
export class Book {
    @hashKey()
    isbn?: string;

    @rangeKey()
    written?: string; // an ISO-8601 string, e.g. 2020-05-30T16:34:20.985Z

    @attribute()
    title?: string;
}

My scan query filter:

mapper.scan(Book, { filter: '> 2018' }); // what goes here?

Unfortunantly, I get this TypeScript error:

Type 'string' is not assignable to type '(ConditionExpressionSubject & EqualityExpressionPredicate) | (ConditionExpressionSubject & InequalityExpressionPredicate) | ... 15 more ... | undefined'.

What is the correct filter syntax?

Body:
The AWS DynamoDB lib documentation is terrible but I ended up figuring it out:

import { ConditionExpression } from '@aws/dynamodb-expressions';

// ... later in the file ...

const dateFilter: ConditionExpression = {
    type: 'GreaterThanOrEqualTo',
    subject: 'written',
    object: '2018'
};

const paginator = mapper.scan(Book, { filter: dateFilter });
for await (const book of paginator) {
    console.log(book); // book available here
}


问:
How to automatically reload .NET Core project in Visual Studio 2019
I tried to automatically reload ASP.NET Core project as I do using Angular with Node or NPM.

When I change the code of the .NET Core project and save, I want the web page to be automatically refreshed in the web browser.

答:
Follow the procedure indicated in the Microsoft's page.

Nuget package Microsoft. VisualStudio. Web. BrowserLink

Install NuGet Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

app.UseBrowserLink(); in the startup.cs page on the configure method.

and enter image description here

now when you change something on your code Ctrl + Maj + enter and everything is saved and actualized on your browser.


问:
SVG/Inkscape - "Failed to load the requested file"
Hopefully someone out there knows about SVG files. I'm just running through a Mozilla tutorial about SVG graphics and one of the exercises is reviewing this code:

```<code><?xml version="1.0" standalone="no"?>
<svg width="200" height="280" xmlns="http://www/w3.org/2000/svg" version="1.1">
    <polyline points="40 60 80 20 120 60" stroke="black" stroke-width="20"
                stroke-linecap="butt" fill="none" stroke-linejoin="miter"/>
    <polyline points="40 160 80 120 120 160" stroke="black" stroke-width="20"
                stroke-linecap="round" fill="none" stroke-linejoin="round"/>
    <polyline points="40 260 80 220 120 260" stroke="black" stroke-width="20"
                stroke-linecap="square" fill="none" stroke-linejoin="bevel"/>
</svg>
</code>```

It's supposed to create a graphic of three angles pointing upward.
I have 8 other SVG files which convert to Inkscape without any problem. But the graphic from the code above will not convert over to Inkscape, and Inkscape gives me this error: "Failed to load the requested file"
Is there something I'm missing? I've tried to change all the parameters in the code thinking maybe the graphic is too big but it still doesn't work.

答: Well, I answered my own question. I converted the SVG file to an HTML, and I opened the file in my browser and the graphic is displayed!</p>

Body:
Hopefully someone out there knows about SVG files. I'm just running through a Mozilla tutorial about SVG graphics and one of the exercises is reviewing this code:

<?xml version="1.0" standalone="no"?>
<svg width="200" height="280" xmlns="http://www/w3.org/2000/svg" version="1.1">
    <polyline points="40 60 80 20 120 60" stroke="black" stroke-width="20"
                stroke-linecap="butt" fill="none" stroke-linejoin="miter"/>
    <polyline points="40 160 80 120 120 160" stroke="black" stroke-width="20"
                stroke-linecap="round" fill="none" stroke-linejoin="round"/>
    <polyline points="40 260 80 220 120 260" stroke="black" stroke-width="20"
                stroke-linecap="square" fill="none" stroke-linejoin="bevel"/>
</svg>

It's supposed to create a graphic of three angles pointing upward.
I have 8 other SVG files which convert to Inkscape without any problem. But the graphic from the code above will not convert over to Inkscape, and Inkscape gives me this error: "Failed to load the requested file"
Is there something I'm missing? I've tried to change all the parameters in the code thinking maybe the graphic is too big but it still doesn't work.


问:
Excel SQL query how to specify a column number not name
I'm trying to query and filter an OleDataTable in C#, so not VBA inside of Excel.

```<code>string strSQL = "SELECT * FROM [Sheet1$] WHERE [Columns1$] is not null";  // to filter out any empty values, works if used column name like [UserInfo].
OleDbCommand cmd = new OleDbCommand(strSQL, connExcel);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(da);
dtData = new DataTable();
DataSet dtDataT = new DataSet();
dtData.Locale = System.Globalization.CultureInfo.InvariantCulture;
string FilePath = copyfile.ToString();
da.Fill(dtData);
</code>```

in the place of [Columns1$] I've tried Columns(1), Columns(A), not suceeded.

答:
You need to specify HDR=NO in your connection string, after which columns names will be assigned automatically as F1, F2, etc.

https://www.connectionstrings.com/excel/

Body:
I'm trying to query and filter an OleDataTable in C#, so not VBA inside of Excel.

string strSQL = "SELECT * FROM [Sheet1$] WHERE [Columns1$] is not null";  // to filter out any empty values, works if used column name like [UserInfo].
OleDbCommand cmd = new OleDbCommand(strSQL, connExcel);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(da);
dtData = new DataTable();
DataSet dtDataT = new DataSet();
dtData.Locale = System.Globalization.CultureInfo.InvariantCulture;
string FilePath = copyfile.ToString();
da.Fill(dtData);

in the place of [Columns1$] I've tried Columns(1), Columns(A), not suceeded.


问:
How to update models in VS 2019 from database in Entity Framework in ASP.NET Core
By VS 2019, I created an API project (database first), everything it's working well, now I made some changes in the database like add new tables and some property and modify data type for others and so on.., the question is how to update models to match the database in SQL?

this is a screenshot for my project:

答:
```<code>Hi I am Considering you are using EFCore, please confirm !!
As per available information over internet
EF core for DB first ( from db to EF ) approach to Modify new/existing entity
</code>```

you need to follow steps as:

EF model require to run Scaffold with flag Force

EF model require to run Scaffold with flag Force  this will remove all
  your local changes in model
  (for me it was IdentityDBContext and override identityUser changes)

after run the all your model migration

running all migration will bring everything in sync bw EF and DB

now you need to do the local changaes again over solution
  ( for me update IdentityDBContext and override identityUser changes
  back as it was before db changes )

also as per below answer please notice EDMX object is not available yet,
anyone has any clue then please share here.

Body:
Hi I am Considering you are using EFCore, please confirm !!
As per available information over internet
EF core for DB first ( from db to EF ) approach to Modify new/existing entity

you need to follow steps as:

EF model require to run Scaffold with flag Force

EF model require to run Scaffold with flag Force  this will remove all
  your local changes in model
  (for me it was IdentityDBContext and override identityUser changes)

after run the all your model migration

running all migration will bring everything in sync bw EF and DB

now you need to do the local changaes again over solution
  ( for me update IdentityDBContext and override identityUser changes
  back as it was before db changes )

also as per below answer please notice EDMX object is not available yet,
anyone has any clue then please share here.


问:
SQL query for finding how many books have more than 20 reviews
I am new to SQL queries and I am having trouble to the following problem. We have a table of book reviews (review_id, book_id,...) and a table review_good_bad (review_id, IsGood) that shows if the review is good or not.

Review_id of the table review_good_bad is a foreign key and IsGood is a boolean. I have to find how many books have at least 20 reviews.

I have tried this:

```<code>Select count(dinstict r.book_id)
From reviews r, review_good_bad rgb
Where r.review_id = rgb.review_id
Group by r.book_id
Having count (rgb.IsGood) >= 20
</code>```

However it is not what I am asking for. Any ideas?

Thanks in advance

答:
If you want good reviews which your CODE suggests you want:

```<code>select count(*)
from (select book_id
      from reviews r
           review_good_bad rgb
           using (book_id)
      where rgb.IsGood
      group by book_id
     ) r;
</code>```

Doing unnecessary comparisons -- such as your code does with isGood -- is misleading at best and can lead to poor performance.  Filtering before aggregation usually improves performance.

Note that your data structure doesn't really make sense.  You should just store IsGood in the reviews table.

This also replaces your archaic syntax with proper, explicit, standard, readable JOIN syntax.  This also allows niceties such as the using clause.

If you don't need the IsGood then it should not be reference in the query.  And neither should the table it is in.  Just use:

```<code>select count(*)
from (select r.book_id
      from reviews r
      group by book_id
      having count(*) >= 20
     ) r;
</code>```

This should be the simplest answer to your question (if not about good reviews).

Body:
I am new to SQL queries and I am having trouble to the following problem. We have a table of book reviews (review_id, book_id,...) and a table review_good_bad (review_id, IsGood) that shows if the review is good or not.

Review_id of the table review_good_bad is a foreign key and IsGood is a boolean. I have to find how many books have at least 20 reviews.

I have tried this:

Select count(dinstict r.book_id)
From reviews r, review_good_bad rgb
Where r.review_id = rgb.review_id
Group by r.book_id
Having count (rgb.IsGood) >= 20

However it is not what I am asking for. Any ideas?

Thanks in advance

Body:
If you want good reviews which your CODE suggests you want:

select count(*)
from (select book_id
      from reviews r
           review_good_bad rgb
           using (book_id)
      where rgb.IsGood
      group by book_id
     ) r;

Doing unnecessary comparisons -- such as your code does with isGood -- is misleading at best and can lead to poor performance.  Filtering before aggregation usually improves performance.

Note that your data structure doesn't really make sense.  You should just store IsGood in the reviews table.

This also replaces your archaic syntax with proper, explicit, standard, readable JOIN syntax.  This also allows niceties such as the using clause.

If you don't need the IsGood then it should not be reference in the query.  And neither should the table it is in.  Just use:

select count(*)
from (select r.book_id
      from reviews r
      group by book_id
      having count(*) >= 20
     ) r;

This should be the simplest answer to your question (if not about good reviews).


答:
MSI is a Microsoft Installer, it is newer than the older EXE ,  Wise Installer and many others support it.  It allows for a smarter install with what needs to be deployed (like CAB files, and registry settings etc...) and it can check for previous installs etc..

MSI are ONLY installations, while EXE can do other things like run.

I would use InstallShield and build an MSI

I'm unsure about #2

Title: best approch among EXE and MSI

Body:
I have an application that needs to be delivered as a package.

What are the best among EXE and MSI Installers, and why?

Is there any open source tool to decompile the EXE or MSI?


问:
Get image path from SQLITE recycler view Error
Can anyone help me to understand my mistake?
What I am trying to achieve is to get the image path from SQLite dB and insert into recycler view. Folder with all images will be in res/drawable.
In adapter class, I have declared Context and is private global and in onCreateViewHolder, I added context = parent.getContext();
Also in DBModel class, I changed everywhere from bitmap to string and in DB file from blob to TEXT.

```<code>public void onBindViewHolder(@NonNull DBViewHolder holder, int position) {

    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription());

    //context = holder.image_sign.getContext();
    //int resAd = getIdentifier(image_path,"drawable",context.getPackageName());
    int i = context.getResources().getIdentifier(objModelClass.getImage(),"drawable",context.getPackageName());
    holder.image_sign.setImageResource(i);

        //holder.image_sign.setImageBitmap(objModelClass.getImage());  <- It works but i don't want that.
    }

>  E/AndroidRuntime: FATAL EXCEPTION: main
>             Process: com.example.dissertation, PID: 5449
>             java.lang.NullPointerException: name is null
>                 at android.content.res.ResourcesImpl.getIdentifier(ResourcesImpl.java:240)
>                 at android.content.res.Resources.getIdentifier(Resources.java:1927)
</code>```

答:
Could you try this code block?    </p>

```<code>String uri = "@drawable/" + objModelClass.getImage();

int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());

Drawable res = context.getResources().getDrawable(imageResource);
holder.image_sign.setImageDrawable(res);
</code>```

Body:
Can anyone help me to understand my mistake?
What I am trying to achieve is to get the image path from SQLite dB and insert into recycler view. Folder with all images will be in res/drawable.
In adapter class, I have declared Context and is private global and in onCreateViewHolder, I added context = parent.getContext();
Also in DBModel class, I changed everywhere from bitmap to string and in DB file from blob to TEXT.

public void onBindViewHolder(@NonNull DBViewHolder holder, int position) {

    ModelClass objModelClass = objModelClassArrayList.get(position);

    holder.description_sign.setText(objModelClass.getDescription());

    //context = holder.image_sign.getContext();
    //int resAd = getIdentifier(image_path,"drawable",context.getPackageName());
    int i = context.getResources().getIdentifier(objModelClass.getImage(),"drawable",context.getPackageName());
    holder.image_sign.setImageResource(i);

        //holder.image_sign.setImageBitmap(objModelClass.getImage());  <- It works but i don't want that.
    }

>  E/AndroidRuntime: FATAL EXCEPTION: main
>             Process: com.example.dissertation, PID: 5449
>             java.lang.NullPointerException: name is null
>                 at android.content.res.ResourcesImpl.getIdentifier(ResourcesImpl.java:240)
>                 at android.content.res.Resources.getIdentifier(Resources.java:1927)

Body:
Could you try this code block?

String uri = "@drawable/" + objModelClass.getImage();

int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());

Drawable res = context.getResources().getDrawable(imageResource);
holder.image_sign.setImageDrawable(res);


问:
Python3 - List comprehension: Not in nested lists
I have some simple code:

```<code>list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

for l in list2:

    new_list = [x for x in list1 if x[0] != l]
    print(new_list)
</code>```

I want my output to be:

```<code>'four'
'five'
'six'
</code>```

...instead however I am getting:

```<code>[['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
</code>```

...what am I doing wrong?

Thanks

答:
```<code>list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

s = set(f for f, *_ in list1)   # OR s = set(f[0] for f in list1)
out = [v for v in list2 if v not in s]

print(*out, sep='\n')
</code>```

Prints:

```<code>four
five
six
</code>```

Body:
I have some simple code:

list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

for l in list2:

    new_list = [x for x in list1 if x[0] != l]
    print(new_list)

I want my output to be:

'four'
'five'
'six'

...instead however I am getting:

[['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
[['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]

...what am I doing wrong?

Thanks

Body:
list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

s = set(f for f, *_ in list1)   # OR s = set(f[0] for f in list1)
out = [v for v in list2 if v not in s]

print(*out, sep='\n')

Prints:

four
five
six


问:
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed
After migrating my django and userena packages like below

Django 1.8  to Django 1.9.7

django-userena 1.4.1 to django-userena==2.0.1

After running the project , I am getting below this error

```<code>Unhandled exception in thread started by <function wrapper at 0xb689641c>
Traceback (most recent call last):
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/Documents/swamy/sample_project/july/5/sample11/sampleapp/urls.py", line 28, in <module>
(r'^grappelli/', include('grappelli.urls')),
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/grappelli/urls.py", line 8, in <module>
from .views.switch import switch_user
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/grappelli/views/switch.py", line 18, in <module>
User = get_user_model()
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 155, in get_user_model
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
</code>```

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed

Here are INSTALLED_APPS in my settings file,

```<code>'grappelli.dashboard',
'grappelli',
'filebrowser',
'django.contrib.admindocs',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'django.contrib.redirects',
'django.contrib.sitemaps',
'haystack',
'memcache_status',
'stheme',
'home',
'customers',
'orders',
#'legacy',
'products',
'bloglets',
'utils',
'catax',
'sqls',
'quotes',
#'django_stylus',
#'djgrid',
#'obdjects',
'quickpages',
'loginas',
#'pyjade',
'django_countries',
'debug_toolbar',
'djide',
#'dbtemplates',
#'aloha',  # out temporarily, migrate to alternate https://github.com/ntucker/django-aloha-edit - JJW
'coffeescript',
'django_wysiwyg',
#'django_bfm',
'userena',
'guardian',
#'apps',
#'filer',
'easy_thumbnails',
'taggit',
#'taggit_templatetags',
# 'social_auth',
'social.apps.django_app.default',
#'socialregistration',
#'socialregistration.contrib.linkedin',
'email_extras',
#'csvimport',
'csvimport.app.CSVImportConf',
'django_extensions',
'webshell',
'easy_select2',
#'plata',
#'plata.contact',
#'plata.discount',
#'plata.payment',
#'plata.shop',
'lastmodule',
</code>```

I guess there are some changes in python apps.But I can't find the reason... Does anyone help to fix this issue ?

Thanks In Advance !

答:
This error appeared when I had an improperly configured model and added it to the admin backend.

```<code>Wrong:
   class VolunteerExperience:
 ...

Correct:
   class VolunteerExperience(models.Model):
 ...
</code>```

I hope this helps someone who gets misdirected by the exception message "django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed"

Now I know that this message most likely indicates an incorrectly configured model.

Body:
After migrating my django and userena packages like below

Django 1.8  to Django 1.9.7

django-userena 1.4.1 to django-userena==2.0.1

After running the project , I am getting below this error

Unhandled exception in thread started by <function wrapper at 0xb689641c>
Traceback (most recent call last):
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/Documents/swamy/sample_project/july/5/sample11/sampleapp/urls.py", line 28, in <module>
(r'^grappelli/', include('grappelli.urls')),
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/grappelli/urls.py", line 8, in <module>
from .views.switch import switch_user
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/grappelli/views/switch.py", line 18, in <module>
User = get_user_model()
File "/home/Documents/environments/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 155, in get_user_model
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed

Here are INSTALLED_APPS in my settings file,

'grappelli.dashboard',
'grappelli',
'filebrowser',
'django.contrib.admindocs',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'django.contrib.redirects',
'django.contrib.sitemaps',
'haystack',
'memcache_status',
'stheme',
'home',
'customers',
'orders',
#'legacy',
'products',
'bloglets',
'utils',
'catax',
'sqls',
'quotes',
#'django_stylus',
#'djgrid',
#'obdjects',
'quickpages',
'loginas',
#'pyjade',
'django_countries',
'debug_toolbar',
'djide',
#'dbtemplates',
#'aloha',  # out temporarily, migrate to alternate https://github.com/ntucker/django-aloha-edit - JJW
'coffeescript',
'django_wysiwyg',
#'django_bfm',
'userena',
'guardian',
#'apps',
#'filer',
'easy_thumbnails',
'taggit',
#'taggit_templatetags',
# 'social_auth',
'social.apps.django_app.default',
#'socialregistration',
#'socialregistration.contrib.linkedin',
'email_extras',
#'csvimport',
'csvimport.app.CSVImportConf',
'django_extensions',
'webshell',
'easy_select2',
#'plata',
#'plata.contact',
#'plata.discount',
#'plata.payment',
#'plata.shop',
'lastmodule',

I guess there are some changes in python apps.But I can't find the reason... Does anyone help to fix this issue ?

Thanks In Advance !

Body:
This error appeared when I had an improperly configured model and added it to the admin backend.

Wrong:
   class VolunteerExperience:
 ...

Correct:
   class VolunteerExperience(models.Model):
 ...

I hope this helps someone who gets misdirected by the exception message "django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed"

Now I know that this message most likely indicates an incorrectly configured model.


问:
Using finditer as performant regex splitter
I have large strings that look similar to this (it is only an excerpt, of course):

content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
```

<p>and I want to return as performant as possible only the substrings that start with a number from 6 to 11 characters long and go to the next of this number or just to the end if such a number cannot be found any more.</p>

<p>So the text consists of any characters (including newlines and other special characters) and the only reliable separator is a number between 6 and 11 characters long. At this separator the text is to be split to start further processing. The processing happens within a web application and should run as an independent thread. Therefore, it would be useful if the substring matches came back iterable.</p>

<p>So I think that <code>re.finditer()</code> is what I need, but I have problems getting this working. I've tried a lot. The version that comes closest to my wanted result is using a regex with a lookahead assertion <code>/(?=\d{6,11}).*/</code> together with <code>re.finditer()</code>, see:</p>

<pre class="lang-py prettyprint-override"><code>In [1]: import re
In [2]: content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
In [3]: pattern = re.compile(r"(?=\d{6,11}).*")
In [4]: for item in re.finditer(pattern, content):
   ...:     print(item)
   ...:
<re.Match object; span=(0, 43), match='78934789;;;;foo foo bar bar;;;;ping pong;;;'>
<re.Match object; span=(46, 80), match='78923456901;;;;Some more text;;;;;'>
<re.Match object; span=(83, 126), match='187894;;;;Number 12345 should not match;;;;'>
<re.Match object; span=(129, 136), match='123456 '>
</code>```

But the newlines and the rest of the content string are not included. I've played a bit with flags like re.DOTALL or re.MULTILINE, and even with regex library which supports lookup assertions with variable lengths. Everything without success, so I'm stuck on this point.

To be as exact as possible, these are the substrings for given content string, a generator should return/yield:

```<code>"78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n"
"78923456901;;;;Some more text;;;;;\n\n\n"
"187894;;;;Number 12345 should not match;;;;\n\n\n"
"123456 \n\n\nthis should be included;;;;;;\n\n\n"
</code>```

As you can see in my approach above, newline characters are not included, and using a re.DOTALL flag in my approach would lead to an unwanted behaviour, that .* will match too much, then.

What I want to know is: Is this possible using a regular expression and to be also performant (i.e. not iterating twice over the string) or should I better write my own generator function, instead (eventually a bit more complex)?

答:
My approach would be:

```<code>import re
def splitter(content):
    pieces = re.split(r'(\d{6,11})', content)  # split at the delimiter
    pieces = filter(bool, pieces)  # filter empty items
    yield from [item + next(pieces, '') for item in pieces]  # combine every two items
</code>```

With the result:

```<code>>>> content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
>>> gen = splitter(content)
>>> list(gen)
['78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n', '78923456901;;;;Some more text;;;;;\n\n\n', '187894;;;;Number 12345 should not match;;;;\n\n\n', '123456 \n\n\nthis should be included;;;;;;\n\n\n']
</code>```

Body:
I have large strings that look similar to this (it is only an excerpt, of course):

content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"

and I want to return as performant as possible only the substrings that start with a number from 6 to 11 characters long and go to the next of this number or just to the end if such a number cannot be found any more.

So the text consists of any characters (including newlines and other special characters) and the only reliable separator is a number between 6 and 11 characters long. At this separator the text is to be split to start further processing. The processing happens within a web application and should run as an independent thread. Therefore, it would be useful if the substring matches came back iterable.

So I think that re.finditer() is what I need, but I have problems getting this working. I've tried a lot. The version that comes closest to my wanted result is using a regex with a lookahead assertion /(?=\d{6,11}).*/ together with re.finditer(), see:

In [1]: import re
In [2]: content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
In [3]: pattern = re.compile(r"(?=\d{6,11}).*")
In [4]: for item in re.finditer(pattern, content):
   ...:     print(item)
   ...:
<re.Match object; span=(0, 43), match='78934789;;;;foo foo bar bar;;;;ping pong;;;'>
<re.Match object; span=(46, 80), match='78923456901;;;;Some more text;;;;;'>
<re.Match object; span=(83, 126), match='187894;;;;Number 12345 should not match;;;;'>
<re.Match object; span=(129, 136), match='123456 '>

But the newlines and the rest of the content string are not included. I've played a bit with flags like re.DOTALL or re.MULTILINE, and even with regex library which supports lookup assertions with variable lengths. Everything without success, so I'm stuck on this point.

To be as exact as possible, these are the substrings for given content string, a generator should return/yield:

"78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n"
"78923456901;;;;Some more text;;;;;\n\n\n"
"187894;;;;Number 12345 should not match;;;;\n\n\n"
"123456 \n\n\nthis should be included;;;;;;\n\n\n"

As you can see in my approach above, newline characters are not included, and using a re.DOTALL flag in my approach would lead to an unwanted behaviour, that .* will match too much, then.

What I want to know is: Is this possible using a regular expression and to be also performant (i.e. not iterating twice over the string) or should I better write my own generator function, instead (eventually a bit more complex)?

Body:
My approach would be:

import re
def splitter(content):
    pieces = re.split(r'(\d{6,11})', content)  # split at the delimiter
    pieces = filter(bool, pieces)  # filter empty items
    yield from [item + next(pieces, '') for item in pieces]  # combine every two items

With the result:

>>> content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
>>> gen = splitter(content)
>>> list(gen)
['78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n', '78923456901;;;;Some more text;;;;;\n\n\n', '187894;;;;Number 12345 should not match;;;;\n\n\n', '123456 \n\n\nthis should be included;;;;;;\n\n\n']


答:
Your current solution is only filtering sub lists from list1 where the first element is not equal to the element from list2.

Instead you want to filter elements from list2 that don't exist at all from the first elements in list1, then print them out line by line.

An O(n) solution would be to convert list1 to a set of only first elements, since set lookups are O(1), then print out elements from list2 that don't exist in this set.

```<code>list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

lookups = {sublst[0] for sublst in list1}
# {'three', 'one', 'two'}

for item in list2:
    if item not in lookups:
        print(item)
</code>```

Or a slower O(n * m) solution using all() to check every sublist in list1 individually. n would be the number of items in list2, and m would be the number of sub lists in list1.

```<code>for item in list2:
    if all(item != sublst[0] for sublst in list1):
        print(item)
</code>```

Which can also be done with any():

```<code>for item in list2:
    if not any(item == sublst[0] for sublst in list1):
        print(item)
</code>```

Output:

```<code>four
five
six
</code>```

Title: Python3 - List comprehension: Not in nested lists

Body:
Your current solution is only filtering sub lists from list1 where the first element is not equal to the element from list2.

Instead you want to filter elements from list2 that don't exist at all from the first elements in list1, then print them out line by line.

An O(n) solution would be to convert list1 to a set of only first elements, since set lookups are O(1), then print out elements from list2 that don't exist in this set.

list1 = [['one', 'blue', 'cat'], ['two', 'green', 'dog'], ['three', 'red', 'horse']]
list2 = ['one', 'three', 'four', 'five', 'six']

lookups = {sublst[0] for sublst in list1}
# {'three', 'one', 'two'}

for item in list2:
    if item not in lookups:
        print(item)

Or a slower O(n * m) solution using all() to check every sublist in list1 individually. n would be the number of items in list2, and m would be the number of sub lists in list1.

for item in list2:
    if all(item != sublst[0] for sublst in list1):
        print(item)

Which can also be done with any():

for item in list2:
    if not any(item == sublst[0] for sublst in list1):
        print(item)

Output:

four
five
six


问:
remote: GitLab: You are not allowed to push code to protected branches on this project
I am trying to push to master branch of a repo and I am failing to do so, since it is protected.

I tried to look into the project settings and do not see any option for protected branches. The only option I could see is members.

```<code>remote: GitLab: You are not allowed to push code to protected branches on this project.
To git@gitlab.ins.risk.regn.net:cmd/release.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@gitlab.ins.risk.regn.net:cmd/release.git'
</code>```

My repo has only one branch, with no contents in it so far.

I do see protected branches options of my other Repos but not for this specific one.

It is a new repo with no contents and with only default branch.

I have the master permission.

Unfortunately I am not able to upload the image here somehow.

Please suggest how to push code to master branch.

答:
Settings>Repo>Expand.. worked for me
Few branches could be secured. Keep in mind the master branch is default protected. As a matter of course the master will be able to commit to protected branches.

Check out: https://gitlab.com/gitlab-org/gitlab-foss/-/issues/51741

Body:
I am trying to push to master branch of a repo and I am failing to do so, since it is protected.

I tried to look into the project settings and do not see any option for protected branches. The only option I could see is members.

remote: GitLab: You are not allowed to push code to protected branches on this project.
To git@gitlab.ins.risk.regn.net:cmd/release.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@gitlab.ins.risk.regn.net:cmd/release.git'

My repo has only one branch, with no contents in it so far.

I do see protected branches options of my other Repos but not for this specific one.

It is a new repo with no contents and with only default branch.

I have the master permission.

Unfortunately I am not able to upload the image here somehow.

Please suggest how to push code to master branch.


问:
Specifying directory for checkout
I'm not sure if the following is possible or not:

I have uploaded my Maven project test-app to my repository. I would now like to go onto a different machine and checkout this project from the repository so I can later build it. I enter the following onto the command line:

```<code>C:\projects\workspace\testproject>mvn scm:checkout -DconnectionUrl=repo.url
</code>```

The project is correctly checked out, but the problem is instead of going to C:\projects\workspace\testproject\target it goes to C:\projects\workspace\testproject\${project.basedir}\target. I have tried setting the basedir using -Dbasedir=C:\projects\workspace\testproject but it does not change anything. Is there a way to specify the directory that checked-out project will go to? I am using Maven 3.0.3. Thank you very much for your time.

答:
You could try -Dbasedir=.

If that does not help, scm:checkout goal seems to have checkoutDirectory parameter, which you can try using.

Also, you may want to look at scm:bootstrap to build the project from a fresh copy of the source in the scm repository

Title: Specifying directory for checkout

Body:
I'm not sure if the following is possible or not:

I have uploaded my Maven project test-app to my repository. I would now like to go onto a different machine and checkout this project from the repository so I can later build it. I enter the following onto the command line:

C:\projects\workspace\testproject>mvn scm:checkout -DconnectionUrl=repo.url

The project is correctly checked out, but the problem is instead of going to C:\projects\workspace\testproject\target it goes to C:\projects\workspace\testproject\${project.basedir}\target. I have tried setting the basedir using -Dbasedir=C:\projects\workspace\testproject but it does not change anything. Is there a way to specify the directory that checked-out project will go to? I am using Maven 3.0.3. Thank you very much for your time.


问:
How to deal with certificates using Selenium?
I am using Selenium to launch a browser. How can I deal with the webpages (URLs) that will ask the browser to accept a certificate or not?

In Firefox, I may have a website like that asks me to accept its certificate like this:

On the Internet Explorer browser, I may get something like this:

On Google Chrome:

I repeat my question: How can I automate the acceptance of a website's certificate when I launch a browser (Internet Explorer, Firefox and Google Chrome) with Selenium (Python programming language)?

答:
```<code>    ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
    options.setAcceptInsecureCerts(true);
</code>```


问:
How to run regular bash from cmder and not wsl bash?
After I install docker on my windows 10, I get a message that I need to install wsl2 also. - So I did.

But now my cmder run wsl when I run bash command. before it just run the bash command.

the problem with bash wsl most of my commands are not avaiable.

How to restore the settings to run bash not by wsl?

答:
In Cmder, open settings: Win + Alt + P

Under Startup > Tasks, add a task called {bash} with the following settings:

Task parameters (set icon):

```<code>      For Cmder icon:  /icon "%CMDER_ROOT%\cmder.exe"
</code>```

```<code>      For Git icon: /icon "C:\Program Files (x86)\Git\etc\git.ico"
</code>```

Commands (open Git's bash shell):

```<code>      "C:\Program Files (x86)\Git\bin\sh.exe" -l -new_console:d:%USERPROFILE%
</code>```

Under Startup, set startup options to Specified name task --> {bash}

Please check below couple of articles and should solve an issue.

https://gist.github.com/nickautomatic/02ccb76292f7f8d9767e
  https://gingter.org/2016/11/16/running-windows-10-ubuntu-bash-in-cmder/

Body:
In Cmder, open settings: Win + Alt + P

Under Startup > Tasks, add a task called {bash} with the following settings:

Task parameters (set icon):

      For Cmder icon:  /icon "%CMDER_ROOT%\cmder.exe"

      For Git icon: /icon "C:\Program Files (x86)\Git\etc\git.ico"

Commands (open Git's bash shell):

      "C:\Program Files (x86)\Git\bin\sh.exe" -l -new_console:d:%USERPROFILE%

Under Startup, set startup options to Specified name task --> {bash}

Please check below couple of articles and should solve an issue.

https://gist.github.com/nickautomatic/02ccb76292f7f8d9767e
  https://gingter.org/2016/11/16/running-windows-10-ubuntu-bash-in-cmder/


问:
Display Product Count in WooCommerce category with subcategory
How to display total number of product in category with subcategory in WooCommerce?
I'm try using this code, but it work perfectly only in categories without subcategory. </p>

```<code>add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 10);

  function add_product_count_view() {
    global $wp_query;

    $category_id = $wp_query->get_queried_object()->term_id;
    $term = get_term( $category_id, 'product_cat' );

    echo $term->name . '(' . $term->count . ')';
  }
</code>```

答:
Paste this code in function.php:

```<code>  add_action( 'count_product_title', 'add_product_count_view', 10);

  function add_product_count_view() {
    global $wp_query;

    $category_id = $wp_query->get_queried_object()->term_id;
    //echo sprintf( _n( '%d товар', '%d товаров', $term->count ), $term->count );
    $query = new WP_Query( array(
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => $category_id,
            'include_children' => true,
        ),
    ),
    'nopaging' => true,
    'fields' => 'ids',
    ) );

    if( function_exists("is_shop") && $category_id != 0) {
    echo '(' .esc_html( $query->post_count ) . ')';
    }
  }
</code>```

Paste in your template
<?php do_action('count_product_title');?>

Body:
How to display total number of product in category with subcategory in WooCommerce?
I'm try using this code, but it work perfectly only in categories without subcategory.

add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 10);

  function add_product_count_view() {
    global $wp_query;

    $category_id = $wp_query->get_queried_object()->term_id;
    $term = get_term( $category_id, 'product_cat' );

    echo $term->name . '(' . $term->count . ')';
  }

Body:
Paste this code in function.php:

  add_action( 'count_product_title', 'add_product_count_view', 10);

  function add_product_count_view() {
    global $wp_query;

    $category_id = $wp_query->get_queried_object()->term_id;
    //echo sprintf( _n( '%d товар', '%d товаров', $term->count ), $term->count );
    $query = new WP_Query( array(
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => $category_id,
            'include_children' => true,
        ),
    ),
    'nopaging' => true,
    'fields' => 'ids',
    ) );

    if( function_exists("is_shop") && $category_id != 0) {
    echo '(' .esc_html( $query->post_count ) . ')';
    }
  }

Paste in your template
<?php do_action('count_product_title');?>


问:
How to restrict user input to a prespecifed number of words?
My program first asks the user to specify the number of words they wish to enter and then takes them as input. Now I want the program to function correctly and restrict the user if he tries entering more words than previously specifed.

Here is my attempt:

```<code>if __name__ == '__main__':
    num_words = int(input('How many words would you like to turn backwards?  '))
    words = []
    for i in range(num_words):
        word = input('please enter string:')
        if len(word.split()) >= 2:
            print('Please only enter one word', end ='')
        else:
            words.append(word)
    print(words)
</code>```

答:
Is this what you mean:</p>

```<code>if __name__ == '__main__':

    num_words = 2
    while num_words == 2:
        num_words = int(input('How many words would you like to turn backwords?  '))
        if num_words == 2:
            print('Please only enter one word')

    words = 2
    while words == 2:
        word = input('Enter your string: ')
        words = len(word.split())
        if words == 2:
            print('Please only enter one word')

    print(''.join(sorted(words,revers=True)))
</code>```

Body:
My program first asks the user to specify the number of words they wish to enter and then takes them as input. Now I want the program to function correctly and restrict the user if he tries entering more words than previously specifed.

Here is my attempt:

if __name__ == '__main__':
    num_words = int(input('How many words would you like to turn backwards?  '))
    words = []
    for i in range(num_words):
        word = input('please enter string:')
        if len(word.split()) >= 2:
            print('Please only enter one word', end ='')
        else:
            words.append(word)
    print(words)

Body:
Is this what you mean:

if __name__ == '__main__':

    num_words = 2
    while num_words == 2:
        num_words = int(input('How many words would you like to turn backwords?  '))
        if num_words == 2:
            print('Please only enter one word')

    words = 2
    while words == 2:
        word = input('Enter your string: ')
        words = len(word.split())
        if words == 2:
            print('Please only enter one word')

    print(''.join(sorted(words,revers=True)))


问:
Spark: Trying to run spark-shell, but get 'cmd' is not recognized as an internal or
I'm trying to install Spark on my Windows desktop. Everything should work fine, but I get an error "'cmd' is not recognized as an internal or external command... "

I installed Scala, Java JDK and unzipped Spark tgz in C:\, but for some reason can't get Spark to start in cmd. Any ideas?

答:
I had the same issue (launch spark-shell and get the the system cannot find the path)
After following the above process (changing the spark_home to exclude the /bin it worked fine
thanks for sharing guys</p>