问:
pygame - make a stickman jump using arrow keys but goes no higher than 10 units
the stickman I have is able to move and all, using the arrow keys, and but, when the up arrow key is pressed, I want him to only be able to go about 10 units every time the key is pressed, no matter how long it is pressed for. In other words I want him to jump, and have a limit to how high he can jump. I've tried a couple things but nothing has worked.</p>

```<code>import pygame

def drawMan(screen,x,y):
    #head
    pygame.draw.ellipse(screen,BLACK,[0+x,0+y,10,10], 0)
    #body
    pygame.draw.line(screen,BLACK,[4+x,17+y],[4+x,7+y], 2)
    #legs
    pygame.draw.line(screen,BLACK,[4+x,17+y],[9+x,27+y], 2)
    pygame.draw.line(screen,BLACK,[4+x,17+y],[-1+x,27+y], 2)
    #arms
    pygame.draw.line(screen,BLACK,[4+x,7+y],[8+x,17+y], 2)
    pygame.draw.line(screen,BLACK,[4+x,7+y],[0+x,17+y], 2)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BORDER = (100,100,100)

pygame.init()

size = (800, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Jump")

done = False

clock = pygame.time.Clock()

pygame.mouse.set_visible(1)

xCoord = 11
yCoord = 463

xSpeed = 0
ySpeed = 0

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                xSpeed = -3
            if event.key == pygame.K_RIGHT:
                xSpeed = 3
            if event.key == pygame.K_UP:
                ySpeed = -3

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                xSpeed = 0
            if event.key == pygame.K_RIGHT:
                xSpeed = 0
            if event.key == pygame.K_UP:
                ySpeed = 3

    if xCoord >= 780:
        xSpeed = 0
        xCoord -= 1
    elif xCoord <= 13:
        xSpeed = 0
        xCoord += 1
    elif yCoord > 465:
        ySpeed = 0
        yCoord -= 1
    elif yCoord <= 13:
        ySpeed = 0
        yCoord += 1
    else:
        xCoord += xSpeed
        yCoord += ySpeed

    screen.fill(WHITE)
    pygame.draw.line(screen, BORDER, [0,0],[800,0], 20)
    pygame.draw.line(screen, BORDER, [0,0],[0,500], 20)
    pygame.draw.line(screen, BORDER, [0,500],[800,500], 20)
    pygame.draw.line(screen, BORDER, [800,500],[800,0], 20)

    drawMan(screen,xCoord,yCoord)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()
</code>```

答:
dudee i know it is so late but i found out the answer for this and it is a simple thing</p>
```<code>import pygame as game
import keyboard
game.init()
dis=game.display.set_mode((1280,720))
state=0
simpclr=(24,24,24)
white=(255,255,255)
posx=5
posy=5
a=0
jcd=1
clock=game.time.Clock()
while not state:
    for event in game.event.get():
        if event.type==game.QUIT:
            state=1
    dis.fill(white)
    pl=game.Rect(posx,posy,20,20)
    game.draw.rect(dis,simpclr,pl)
    game.display.flip()
    posy+=2
    if keyboard.is_pressed('d'):
        posx+=5
    if jcd<10:
        if keyboard.is_pressed(" "):
            posy-=10
            jcd+=1
    if jcd<50 and jcd>=10:
        jcd+=1
    if jcd==50:
        jcd=1
    if posx==1230:
        posx-=5
    if posy==100:
        posy-=5
    game.display.flip()

    clock.tick(60)
game.quit()

</code>```

Body:
the stickman I have is able to move and all, using the arrow keys, and but, when the up arrow key is pressed, I want him to only be able to go about 10 units every time the key is pressed, no matter how long it is pressed for. In other words I want him to jump, and have a limit to how high he can jump. I've tried a couple things but nothing has worked.

import pygame

def drawMan(screen,x,y):
    #head
    pygame.draw.ellipse(screen,BLACK,[0+x,0+y,10,10], 0)
    #body
    pygame.draw.line(screen,BLACK,[4+x,17+y],[4+x,7+y], 2)
    #legs
    pygame.draw.line(screen,BLACK,[4+x,17+y],[9+x,27+y], 2)
    pygame.draw.line(screen,BLACK,[4+x,17+y],[-1+x,27+y], 2)
    #arms
    pygame.draw.line(screen,BLACK,[4+x,7+y],[8+x,17+y], 2)
    pygame.draw.line(screen,BLACK,[4+x,7+y],[0+x,17+y], 2)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BORDER = (100,100,100)

pygame.init()

size = (800, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Jump")

done = False

clock = pygame.time.Clock()

pygame.mouse.set_visible(1)

xCoord = 11
yCoord = 463

xSpeed = 0
ySpeed = 0

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                xSpeed = -3
            if event.key == pygame.K_RIGHT:
                xSpeed = 3
            if event.key == pygame.K_UP:
                ySpeed = -3

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                xSpeed = 0
            if event.key == pygame.K_RIGHT:
                xSpeed = 0
            if event.key == pygame.K_UP:
                ySpeed = 3

    if xCoord >= 780:
        xSpeed = 0
        xCoord -= 1
    elif xCoord <= 13:
        xSpeed = 0
        xCoord += 1
    elif yCoord > 465:
        ySpeed = 0
        yCoord -= 1
    elif yCoord <= 13:
        ySpeed = 0
        yCoord += 1
    else:
        xCoord += xSpeed
        yCoord += ySpeed

    screen.fill(WHITE)
    pygame.draw.line(screen, BORDER, [0,0],[800,0], 20)
    pygame.draw.line(screen, BORDER, [0,0],[0,500], 20)
    pygame.draw.line(screen, BORDER, [0,500],[800,500], 20)
    pygame.draw.line(screen, BORDER, [800,500],[800,0], 20)

    drawMan(screen,xCoord,yCoord)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()

Body:
dudee i know it is so late but i found out the answer for this and it is a simple thing

import pygame as game
import keyboard
game.init()
dis=game.display.set_mode((1280,720))
state=0
simpclr=(24,24,24)
white=(255,255,255)
posx=5
posy=5
a=0
jcd=1
clock=game.time.Clock()
while not state:
    for event in game.event.get():
        if event.type==game.QUIT:
            state=1
    dis.fill(white)
    pl=game.Rect(posx,posy,20,20)
    game.draw.rect(dis,simpclr,pl)
    game.display.flip()
    posy+=2
    if keyboard.is_pressed('d'):
        posx+=5
    if jcd<10:
        if keyboard.is_pressed(" "):
            posy-=10
            jcd+=1
    if jcd<50 and jcd>=10:
        jcd+=1
    if jcd==50:
        jcd=1
    if posx==1230:
        posx-=5
    if posy==100:
        posy-=5
    game.display.flip()

    clock.tick(60)
game.quit()


来源: stackexchange

问:
Is it possible to use mailgun.com as a SMTP server for personal outgoing emails, including the correct error return emails?
I am using mailgun.com for occassional mass-mailings. Would it be possible to also use it for sending personal emails from me and my wife? The specific problem is that email errors (e.g. "Recipient not found on the server") are only available in the mailgun console and I'd like for them to be received as an error emails sent back to the sender (as is the case with "standard" personal email services). Is it possible to set this up at mailgun.com?

Alternatively, is there a cheap (or even free) SMTP server available for sending emails from the custom domain I own?

(Note that RECEIVING emails to our domain is not a problem, we have that solved using email redirection on my domain.)

Detailed explanation of our setup and reasoning: Behind the scenes, we are both using personail gmail accounts (e.g. me@gmail.com and wife@gmail.com) but we don't advertise these anywhere and our "public" email addresses are me@mydomain.com and wife@mydomain.com. Mydomain.com uses Cloudflare email redirection to redirect our incoming emails back to our Gmail inboxes. We used "Send mail as" GMail feature to send emails as "me@mydomain.com" and "wife@mydomain.com" through smtp.gmail.com but this solution requires us to have "Less secure apps" enabled on our Google accounts and Google seems to be phasing this solution out. The fact that our "real" Gmail addresses are visible in the email headers is not a problem for us.

Originally, we've used free "legacy" Google Workspace accounts on mydomain.com but those are now also being phased out by Google. So we are looking for a SMTP server.

答:
Answering my own question:

I have found that smtp2go.com (which provides very similar services to mailgun.com) provides this option. Your SMTP account can be configured (in the "Advanced" tab) so that bounced email reports are delivered back to the sender's mailbox (or to different mailbox). Additionally, smtp2go's services are free if you send less than 1000 emails monthly so this seems like perfect solution to my problem.

ContentLicense: CC BY-SA 4.0


问:
Using SQL JSON_MODIFY to add/update a dictionary value
Is it possible to use JSON_MODIFY to update a dictionary value of <int,string>?
If my JSON is this:

```<code>{
  "items": {
     "1": "xxx",
     "2": "xxx",
     "3": "xxx"
  }
}
</code>```

I'm unable to add/update using the following:

```<code>DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'
UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.', @Id), @Value)
</code>```

I get the error: JSON path is not properly formatted. Unexpected character '1' is found at position 10. obviously because property names can't be numeric. I can workaround the error using a <string,string> dictionary as follows:

```<code>{
  "items": {
     "i1": "xxx",
     "i2": "xxx",
     "i3": "xxx"
  }
}
</code>```

Then the following works fine:

```<code>DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'
UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.i', @Id), @Value)
</code>```

However, now I'm tasked with extra work after deserializing the JSON to get the numeric ID I actually want. It's just a minor inconvenience, but I was hoping for a possible solution to keep my <int,string> dictionary. Any ideas?

I suppose I could use a dictionary like this <string,object> and simply ignore the keys when deserialized:

```<code>{
  "items": {
     "i1": { "id": 1, "name": "xxx" },
     "i2": { "id": 1, "name": "xxx" },
     "i3": { "id": 1, "name": "xxx" }
  }
}
</code>```

And then use

```<code>UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.i', @Id), JSON_QUERY(CONCAT('{"id":', @Id, ',"name":"', @Value, '"}')))
</code>```

I'm also not opposed to using an array as such:

```<code>{
  "items": [
     { "id": 1, "name": "xxx" },
     { "id": 2, "name": "xxx" },
     { "id": 3, "name": "xxx" }
  ]
}
</code>```

Unfortunately, I don't know a way to update/add when in this format, and the add/update has to be done in a single UPDATE statement.

I'm hoping for some magic formula to continue using my <int,string> dictionary.

答:
Thanks to @Charlieface, the solution is quite simple. You can navigate to numeric dictionary keys via double quotes:</p>
```<code>DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'

UPDATE MyTable
SET MyJsonColumn = JSON_MODIFY(ISNULL(MyJsonColumn, '{"items":{}}'), CONCAT('$.items."', @Id, '"'), @Value)
</code>```

Body:
Is it possible to use JSON_MODIFY to update a dictionary value of <int,string>?
If my JSON is this:

{
  "items": {
     "1": "xxx",
     "2": "xxx",
     "3": "xxx"
  }
}

I'm unable to add/update using the following:

DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'
UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.', @Id), @Value)

I get the error: JSON path is not properly formatted. Unexpected character '1' is found at position 10. obviously because property names can't be numeric. I can workaround the error using a <string,string> dictionary as follows:

{
  "items": {
     "i1": "xxx",
     "i2": "xxx",
     "i3": "xxx"
  }
}

Then the following works fine:

DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'
UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.i', @Id), @Value)

However, now I'm tasked with extra work after deserializing the JSON to get the numeric ID I actually want. It's just a minor inconvenience, but I was hoping for a possible solution to keep my <int,string> dictionary. Any ideas?

I suppose I could use a dictionary like this <string,object> and simply ignore the keys when deserialized:

{
  "items": {
     "i1": { "id": 1, "name": "xxx" },
     "i2": { "id": 1, "name": "xxx" },
     "i3": { "id": 1, "name": "xxx" }
  }
}

And then use

UPDATE MyTable SET MyJsonColumn = JSON_MODIFY(MyJsonColumn, CONCAT('$.items.i', @Id), JSON_QUERY(CONCAT('{"id":', @Id, ',"name":"', @Value, '"}')))

I'm also not opposed to using an array as such:

{
  "items": [
     { "id": 1, "name": "xxx" },
     { "id": 2, "name": "xxx" },
     { "id": 3, "name": "xxx" }
  ]
}

Unfortunately, I don't know a way to update/add when in this format, and the add/update has to be done in a single UPDATE statement.

I'm hoping for some magic formula to continue using my <int,string> dictionary.

Body:
Thanks to @Charlieface, the solution is quite simple. You can navigate to numeric dictionary keys via double quotes:

DECLARE @Id INT = 1
DECLARE @Value NVARCHAR(50) = 'zzz'

UPDATE MyTable
SET MyJsonColumn = JSON_MODIFY(ISNULL(MyJsonColumn, '{"items":{}}'), CONCAT('$.items."', @Id, '"'), @Value)


问:
Sort values of Observable array of objects
My service get data from Api :

async getCommunes(){
    return await this._http.get<any[]>(this.api)
      .pipe()
      .toPromise()
      .then((response: any) => {
        this._communes$.next(response);
      })
      .catch(err => console.log(err))
  }
```
<p>I call service in a component :</p>
<pre class="lang-js prettyprint-override"><code>
public communes$: Observable<any>;
constructor(private apiService: ApiService) { }

ngOnInit(): void {
   this.loadCommunes();
}

get communesFromService$(){
   return this.apiService.communes$;
}

async loadCommunes(){
  await this.apiService.getCommunes();
  this.communes$ =  this.apiService.communes$;
}
</code>```

I display data in Html by calling communesFrom Service$ (get method) :

{{record?.fields?.name}}

```
<p>My data are formated like below :</p>
<pre class="lang-json prettyprint-override"><code>
{
    "nhits": 38,
    "parameters": {
        "dataset": "communes-de-la-province-de-namur",
        "rows": 3,
        "start": 0,
        "format": "json",
        "timezone": "UTC"
    },
    "records": [
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "5f50799324d15038c9708e48c6a32c907922d00a",
            "fields": {
                "nsi": "93088",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.516510705656462,
                                50.31531488802985
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.26709679846407,
                    4.433557385138468
                ],
                "name": "Walcourt"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.433557385138468,
                    50.26709679846407
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "11fc2dbd6852c06f095e71adee7e0c1d334ccf24",
            "fields": {
                "nsi": "91054",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.971517147861946,
                                50.02965137853804
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    49.98493619689069,
                    4.901523112944346
                ],
                "name": "Gedinne"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.901523112944346,
                    49.98493619689069
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "82a588f6f7d3250b78564fd7a1f16c0a02d0e30a",
            "fields": {
                "nsi": "92045",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.827793680052161,
                                50.41154443216362
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.435523543496686,
                    4.754395027090274
                ],
                "name": "Floreffe"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.754395027090274,
                    50.435523543496686
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        }
    ]
}

</code>```

I only need 'name' field but order by ascending ('records' array).

I have tried this but it doesn't work. I also tried other solution but without success.:

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response => response.sort((a,b) => a.name - b.name)))
    );
  }

```

How can I do that?

any suggestions is helpfull.

Thanks

答:
You can use just-sort-by - which is a very light library.

npm install just-sort-by
```
<p>If your array is what is returned from the API call, then:</p>
```import sortBy from 'just-sort-by';

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response) => sortBy(response, (item) => item.fields.name))
    );
}
```

Body:
My service get data from Api :

async getCommunes(){
    return await this._http.get<any[]>(this.api)
      .pipe()
      .toPromise()
      .then((response: any) => {
        this._communes$.next(response);
      })
      .catch(err => console.log(err))
  }

I call service in a component :

public communes$: Observable<any>;
constructor(private apiService: ApiService) { }

ngOnInit(): void {
   this.loadCommunes();
}

get communesFromService$(){
   return this.apiService.communes$;
}

async loadCommunes(){
  await this.apiService.getCommunes();
  this.communes$ =  this.apiService.communes$;
}

I display data in Html by calling communesFrom Service$ (get method) :

{{record?.fields?.name}}

My data are formated like below :

{
    "nhits": 38,
    "parameters": {
        "dataset": "communes-de-la-province-de-namur",
        "rows": 3,
        "start": 0,
        "format": "json",
        "timezone": "UTC"
    },
    "records": [
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "5f50799324d15038c9708e48c6a32c907922d00a",
            "fields": {
                "nsi": "93088",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.516510705656462,
                                50.31531488802985
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.26709679846407,
                    4.433557385138468
                ],
                "name": "Walcourt"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.433557385138468,
                    50.26709679846407
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "11fc2dbd6852c06f095e71adee7e0c1d334ccf24",
            "fields": {
                "nsi": "91054",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.971517147861946,
                                50.02965137853804
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    49.98493619689069,
                    4.901523112944346
                ],
                "name": "Gedinne"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.901523112944346,
                    49.98493619689069
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "82a588f6f7d3250b78564fd7a1f16c0a02d0e30a",
            "fields": {
                "nsi": "92045",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.827793680052161,
                                50.41154443216362
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.435523543496686,
                    4.754395027090274
                ],
                "name": "Floreffe"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.754395027090274,
                    50.435523543496686
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        }
    ]
}

I only need 'name' field but order by ascending ('records' array).

I have tried this but it doesn't work. I also tried other solution but without success.:

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response => response.sort((a,b) => a.name - b.name)))
    );
  }

How can I do that?

any suggestions is helpfull.

Thanks

Body:
You can use just-sort-by - which is a very light library.

npm install just-sort-by

If your array is what is returned from the API call, then:

import sortBy from 'just-sort-by';

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response) => sortBy(response, (item) => item.fields.name))
    );
}


问:
Using ArrayList in a sub-template on .jsp page
I have a JSP home page with a menu. I want that menu to be on multiple pages so I created a menu.jsp template. I imported, all static source code appears but the <c:forEach /> tag is not picking it up. When I print (just put it plainly in the html) out my ${allCategories} variable I get all the data correctly.

In a controller, I set model.addAttribute("allCategories", categoryService.getPrimaryCategories());

home.jsp where the categories were before is importing <jsp:include page="menu.jsp"/>

in menu.jsp I am unable to get <c:forEach items="${allCategories}" var="category"> to work but when I just put
${allCategories}
 at the beginning of the file it shows stuff like  [Category(id=1281, name=Bundles, image=https://images...
How do I get the data correctly in the sub-template so it works like directly on the page?

答:
You could try using the JSP include directive. It is used to include a file during the translation phase. For example,</p>
```<code><%@ include file = "menu.jsp" >
</code>```

Body:
You could try using the JSP include directive. It is used to include a file during the translation phase. For example,

<%@ include file = "menu.jsp" >


问:
postsql trouble when populating a table with comma separator
I am trying to populate a table, and I have values with "," from my array "name". so This is not working, if I use something other than a comma separator, it says

```<code>BadCopyFileFormat: missing data for column
</code>```
```<code>s = "CREATE TABLE IF NOT EXISTS tokens (address varchar(100) NOT NULL,symbol varchar(100) NOT NULL,name varchar(100) NOT NULL)"
db_cursor.execute(s)

with open('data/tokens.csv', 'r', encoding="utf-8") as f:
    next(f)  # Skip the header row.
    db_cursor.copy_from(f, 'tokens', sep=',')
    db_conn.commit()
</code>```

My data look like

```<code>address symbol name
x23fva3  ABC    ABC
2vajd83  DAP
29vb4h2  Wink   Jamal, ab
2jsbg93  x3     xon3
</code>```

Is there a way to populate the table with missing values??

答:
What I got to work:

```<code>cat data/tokens.csv

address |symbol|name
x23fva3 | ABC | ABC
2vajd83 | DAP |
29vb4h2 | Wink | Jamal, ab
2jsbg93 | x3 | xon3

with open('data/tokens.csv', 'r', encoding="utf-8") as f:
    next(f)  # Skip the header row.
    db_cursor.copy_from(f, 'tokens', sep='|')
    db_conn.commit()

select * from tokens ;
 address  | symbol |    name
----------+--------+------------
 x23fva3  |  ABC   |  ABC
 2vajd83  |  DAP   |
 29vb4h2  |  Wink  |  Jamal, ab
 2jsbg93  |  x3    |  xon3

</code>```

I use the pipe(|) regularly for this sort of thing as it very rarely shows up in data on its own.

UPDATE

For a file with empty values there needs to still be a separator for each field like:

```<code>address |symbol|name
x23fva3 | ABC | ABC
2vajd83 | DAP |
32vb4h3 |     |
1jsbg94 |     | xon3

</code>```

Body:
I am trying to populate a table, and I have values with "," from my array "name". so This is not working, if I use something other than a comma separator, it says

BadCopyFileFormat: missing data for column

s = "CREATE TABLE IF NOT EXISTS tokens (address varchar(100) NOT NULL,symbol varchar(100) NOT NULL,name varchar(100) NOT NULL)"
db_cursor.execute(s)

with open('data/tokens.csv', 'r', encoding="utf-8") as f:
    next(f)  # Skip the header row.
    db_cursor.copy_from(f, 'tokens', sep=',')
    db_conn.commit()

My data look like

address symbol name
x23fva3  ABC    ABC
2vajd83  DAP
29vb4h2  Wink   Jamal, ab
2jsbg93  x3     xon3

Is there a way to populate the table with missing values??

Body:
What I got to work:

cat data/tokens.csv

address |symbol|name
x23fva3 | ABC | ABC
2vajd83 | DAP |
29vb4h2 | Wink | Jamal, ab
2jsbg93 | x3 | xon3

with open('data/tokens.csv', 'r', encoding="utf-8") as f:
    next(f)  # Skip the header row.
    db_cursor.copy_from(f, 'tokens', sep='|')
    db_conn.commit()

select * from tokens ;
 address  | symbol |    name
----------+--------+------------
 x23fva3  |  ABC   |  ABC
 2vajd83  |  DAP   |
 29vb4h2  |  Wink  |  Jamal, ab
 2jsbg93  |  x3    |  xon3

I use the pipe(|) regularly for this sort of thing as it very rarely shows up in data on its own.

UPDATE

For a file with empty values there needs to still be a separator for each field like:

address |symbol|name
x23fva3 | ABC | ABC
2vajd83 | DAP |
32vb4h3 |     |
1jsbg94 |     | xon3


问:
Rails Mongodb default value
The database is mongodb connected to rails. Suppose there are already some records in the db. Now, I add a new boolean field in the model. What will become the value of this field for the already existing records ? Is it nil or true or false ? Thanks in advance.</p>

答:
For existing records that field should return nil

Example

def SomeModel
  field :foo, type: :boolean
  field :bar, type: :boolean, default: true
end
```
<p>then assuming you have previous records:</p>
<pre class="lang-rb prettyprint-override"><code>SomeModel.first.foo #=> nil
SomeModel.first.bar #=> true
</code>```

If the field is more complex, you can always make a migration to fix the value for any records whose fields dont match what you want.

EDIT: migrations are typically associated with relational databases but for the purpose of running them once and keeping the code in the codebase it might be a solution

Title: Rails Mongodb default value

Body:
For existing records that field should return nil

Example

def SomeModel
  field :foo, type: :boolean
  field :bar, type: :boolean, default: true
end

then assuming you have previous records:

SomeModel.first.foo #=> nil
SomeModel.first.bar #=> true

If the field is more complex, you can always make a migration to fix the value for any records whose fields dont match what you want.

EDIT: migrations are typically associated with relational databases but for the purpose of running them once and keeping the code in the codebase it might be a solution


问:
How to solve Unhandled exception error when importing csv file in MysqlWorkbench?
When I imported an .csv file using import wizard of MySQL Workbench (utf8), the following error popped out.

Unhandled exception: 'ascii' codec can't decode byte 0xc2 in position 444: ordinal not in range(128)

I'm new to SQL so I don't know how to fix this. Please help me.

答:
I do not know how your table was created, but when I create it using:

```<code>CREATE TABLE `office_supplies` (
  `Order ID` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Order Date` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Ship Mode` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Region` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Product ID` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Category` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Sub-Category` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Product Name` varchar(245) CHARACTER SET utf8 DEFAULT NULL,
  `Sales` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Quantity` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Discount` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Profit` varchar(45) CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

(which is, of course, not want you want, but .... )

I can import your CSV:

```<code>Order ID,Order Date,Ship Mode,Region,Product ID,Category,Sub-Category,Product Name,Sales,Quantity,Discount,Profit,
CA-2015-110870,12/12/2015,First Class,West,TEC-AC-10002926,Technology,Accessories,Logitech Wireless Marathon Mouse M705,299.94,6,0,
CA-2015-110870,12/12/2015,First Class,West,OFF-SU-10001225,Office Supplies,Supplies,Staple remover,25.76,7,0,
CA-2014-143210,01/12/2014,First Class,East,TEC-PH-10004434,Technology,Phones,Cisco IP Phone 7961G VoIP phone - Dark gray,271.9,2,0,
</code>```

using:

```<code>LOAD DATA
INFILE 'D:/MySQL Server 8.0/Uploads/office_supplies.csv'
INTO TABLE office_supplies
COLUMNS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES
</code>```

Note: I only had to add one ',' at the end of line 1.

More info on the LOAD DATA ...

Body:
I do not know how your table was created, but when I create it using:

CREATE TABLE `office_supplies` (
  `Order ID` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Order Date` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Ship Mode` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Region` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Product ID` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Category` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Sub-Category` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Product Name` varchar(245) CHARACTER SET utf8 DEFAULT NULL,
  `Sales` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Quantity` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Discount` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `Profit` varchar(45) CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

(which is, of course, not want you want, but .... )

I can import your CSV:

Order ID,Order Date,Ship Mode,Region,Product ID,Category,Sub-Category,Product Name,Sales,Quantity,Discount,Profit,
CA-2015-110870,12/12/2015,First Class,West,TEC-AC-10002926,Technology,Accessories,Logitech Wireless Marathon Mouse M705,299.94,6,0,
CA-2015-110870,12/12/2015,First Class,West,OFF-SU-10001225,Office Supplies,Supplies,Staple remover,25.76,7,0,
CA-2014-143210,01/12/2014,First Class,East,TEC-PH-10004434,Technology,Phones,Cisco IP Phone 7961G VoIP phone - Dark gray,271.9,2,0,

using:

LOAD DATA
INFILE 'D:/MySQL Server 8.0/Uploads/office_supplies.csv'
INTO TABLE office_supplies
COLUMNS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES

Note: I only had to add one ',' at the end of line 1.

More info on the LOAD DATA ...


问:
PHP: Strtotime / date ignoring timezone?
having some trouslb with strtotime, its easier to show by example :)

```<code>date_default_timezone_set('Europe/London');             //  Set timezone to local /
echo date("d/m/Y", strtotime("1-6-2003"));   // Expected: 01/06/2003    Got:    01/06/2003
echo date("d/m/Y", strtotime("16-12-2003")); // Expected: 16/12/2003    Got:    16/12/2003
echo date("d/m/Y", strtotime("10-12-03"));   // Expected: 10/12/2003    Got:    03/12/2010
</code>```

Any ideas how to get around this problem? I am using strtotime to try and negate problems with users entering dates in different formats.

Thank you for reading,

Rik.

答: strtotime does not support that kind of date format. See the documentation for a list of supported formats. Read the documentation next time.

ContentLicense: CC BY-SA 3.0

Body:
having some trouslb with strtotime, its easier to show by example :)

date_default_timezone_set('Europe/London');             //  Set timezone to local /
echo date("d/m/Y", strtotime("1-6-2003"));   // Expected: 01/06/2003    Got:    01/06/2003
echo date("d/m/Y", strtotime("16-12-2003")); // Expected: 16/12/2003    Got:    16/12/2003
echo date("d/m/Y", strtotime("10-12-03"));   // Expected: 10/12/2003    Got:    03/12/2010

Any ideas how to get around this problem? I am using strtotime to try and negate problems with users entering dates in different formats.

Thank you for reading,

Rik.


问:
No such file or directory error - Pandas, Python
When I try to access an .xls file, I encounter the following error:
No such file or directory.

I am sure that I haven't misspelled the name of my file and that my directory is valid. I'm loading other files from this directory and it works, but not with this one file...
What's interesting, after typing the code below I can see the names of all my files in the directory:

```<code>for f in MyDirectory:
    print(f)
</code>```

MyDirectory is defined earlier in code as:

```<code>MyDirectory = [file for file in os.listdir(r'./folder1/folder2/') if file.endswith(".xlsx") or file.endswith(".xls")]
</code>```

I can see all the files including the one I cannot load.
Do you have any idea what can be the source of this problem and how can I handle it?

Thanks in advance!

答:
You can either use os.listdir() in conjunction with os.path.join() or you could use glob as follows:

```<code>from glob import glob

for filename in glob('./folder1/folder2/*.xls*'):
  with open(filename) as data:
    pass # process file here
</code>```

This is convenient because glob returns the full path based on the given parameter e.g., ./folder1/folder2/foo.xls

Note that this may not give exactly the same results as you seem to be intending because it will match files ending with xls, xlst, xlsm or indeed any file that has xls at the start of its suffix. You may need to account for that

Body:
When I try to access an .xls file, I encounter the following error:
No such file or directory.

I am sure that I haven't misspelled the name of my file and that my directory is valid. I'm loading other files from this directory and it works, but not with this one file...
What's interesting, after typing the code below I can see the names of all my files in the directory:

for f in MyDirectory:
    print(f)

MyDirectory is defined earlier in code as:

MyDirectory = [file for file in os.listdir(r'./folder1/folder2/') if file.endswith(".xlsx") or file.endswith(".xls")]

I can see all the files including the one I cannot load.
Do you have any idea what can be the source of this problem and how can I handle it?

Thanks in advance!

Body:
You can either use os.listdir() in conjunction with os.path.join() or you could use glob as follows:

from glob import glob

for filename in glob('./folder1/folder2/*.xls*'):
  with open(filename) as data:
    pass # process file here

This is convenient because glob returns the full path based on the given parameter e.g., ./folder1/folder2/foo.xls

Note that this may not give exactly the same results as you seem to be intending because it will match files ending with xls, xlst, xlsm or indeed any file that has xls at the start of its suffix. You may need to account for that


问:
Implementing binary constraint in PuLP Objective Function
I'm trying to determine the maximum revenue that can be earned from a battery connected to the grid using linear programming. The battery can earn revenues in two markets, the energy market and the frequency market. My model is throwing an error when I include a binary constraint in the objective function (TypeError: Non-constant expressions cannot be multiplied).

My Objective function is:

N is the time horizon of the optimisation

 is the energy price at time t

 are the allocated discharge and charge power at time t

 is the frequency price at time t

 is the allocated frequency power at time t

The battery should only be active in one market (energy or frequency) at each time period t. So needs a constraint that looks something like this:

where  is a binary variable that activates activity x.

Ok, so that's what I trying to achieve. I'm struggling to create such a constraint in pulp that essentially switches off participation in one of the markets if the value in the other is higher (all other constraints being met). In my battery class, I've created decision variables for each of the power activities and also for their on/off status.

self.charge = \
pulp.LpVariable.dicts(
    "charging_power",
    ('c_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_charge_power_capacity,
    cat='Continuous')

self.discharge = \
pulp.LpVariable.dicts(
    "discharging_power",
    ('d_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_discharge_power_capacity,
    cat='Continuous')

self.freq = \
pulp.LpVariable.dicts(
    "freq_power",
    ('f_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_freq_power_capacity,
    cat='Continuous')

self.charge_status = \
pulp.LpVariable.dicts(
    "charge_status",
    ('c_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

self.discharge_status = \
pulp.LpVariable.dicts(
    "discharge_status",
    ('d_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

self.freq_status = \
pulp.LpVariable.dicts(
    "freq_status",
    ('ds3_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

```
<p>In my objective function, I included these binary variables.</p>
<pre class="lang-py prettyprint-override"><code>
self.model = pulp.LpProblem("Max Profit", pulp.LpMaximize)

self.model +=\
pulp.lpSum(
    [self.charge['c_t_' + str(i)]*-1*prices[i] *
     self.charge_status['c_status_t_' + str(i)] for i in range(0,self.time_horizon)]
    + [self.discharge['d_t_' + str(i)]*prices[i] *
     self.discharge_status['d_status_t_' + str(i)] for i in range(0,self.time_horizon)]
    + [self.freq['f_t_' + str(i)]*freq_prices[i] *
     self.freq_status['freq_status_t_' + str(i)] for i in range(0,self.time_horizon)]
)

</code>```

The constraint for these binary variables, I set up as follows:

 for hour_of_sim in range(1,self.time_horizon+1):
    self.model += \
        pulp.lpSum([self.charge_status['c_status_t_' + str(i)] for i in range(0,self.time_horizon)] +\
                   [self.discharge_status['d_status_t_' + str(i)] for i in range(0,self.time_horizon)] +\
                   [self.freq_status['freq_status_t_' + str(i)] for i in range(0,self.time_horizon)]
                  ) <= 1

```

When I try to solve, I get a

TypeError: Non-constant expressions cannot be multiplied

on the objective function. Doesn't like my binary variables, runs if they are removed. There must be an alternative way of setting this up which is escaping me?

答:
The comment is correct...  you are violating "linearity" by multiplying 2 variables together.  Fortunately, this is easy to linearize.  You have a binary variable controlling the mode, so the key element you are looking for (google it) is a Big-M constraint, where you use the binary variable multiplied by a max value (or just something sufficiently large) to limit the other variable either to the max, or clamp it to zero.

An example below.  I also re-arranged things a bit.  You might find this style more readable.  Two main things on style:

You are constantly re-creating the indices you are using which is really painful to read and error prone.  Just make them and re-use them...and you don't need to get complicated with the index set values

You can easily double-index this model, which I think is more clear than making multiple sets of variables.  You essentially have 2 sets you are working with:  Time periods, and Op modes.  Just make those sets and double index.

Example

```<code># battery modes

import pulp

# some data
num_periods = 3
rate_limits = { 'energy'    : 10,
                'freq'      : 20}
price = 2  # this could be a table or double-indexed table of [t, m] or ....

# SETS
M = rate_limits.keys()   # modes.  probably others...  discharge?
T = range(num_periods)   # the time periods

TM = {(t, m) for t in T for m in M}

model = pulp.LpProblem('Batts', pulp.LpMaximize)

# VARS
model.batt = pulp.LpVariable.dicts('batt_state', indexs=TM, lowBound=0, cat='Continuous')
model.op_mode = pulp.LpVariable.dicts('op_mode', indexs=TM, cat='Binary')

# Constraints

# only one op mode in each time period...
for t in T:
    model += sum(model.op_mode[t, m] for m in M) <= 1

# Big-M constraint. limit rates for each rate, in each period.
# this does 2 things:  it is equivalent to the upper bound parameter in the var declaration
#                      It is a Big-M type of constraint which uses the binary var as a control <-- key point
for t, m in TM:
    model += model.batt[t, m] <= rate_limits[m] * model.op_mode[t, m]

# OBJ
model += sum(model.batt[t, m] * price for t, m in TM)

print(model)

#  solve...
</code>```

Yields:

```<code>Batts:
MAXIMIZE
2*batt_state_(0,_'energy') + 2*batt_state_(0,_'freq') + 2*batt_state_(1,_'energy') + 2*batt_state_(1,_'freq') + 2*batt_state_(2,_'energy') + 2*batt_state_(2,_'freq') + 0
SUBJECT TO
_C1: op_mode_(0,_'energy') + op_mode_(0,_'freq') <= 1

_C2: op_mode_(1,_'energy') + op_mode_(1,_'freq') <= 1

_C3: op_mode_(2,_'energy') + op_mode_(2,_'freq') <= 1

_C4: batt_state_(2,_'freq') - 20 op_mode_(2,_'freq') <= 0

_C5: batt_state_(2,_'energy') - 10 op_mode_(2,_'energy') <= 0

_C6: batt_state_(1,_'freq') - 20 op_mode_(1,_'freq') <= 0

_C7: batt_state_(1,_'energy') - 10 op_mode_(1,_'energy') <= 0

_C8: batt_state_(0,_'freq') - 20 op_mode_(0,_'freq') <= 0

_C9: batt_state_(0,_'energy') - 10 op_mode_(0,_'energy') <= 0

VARIABLES
batt_state_(0,_'energy') Continuous
batt_state_(0,_'freq') Continuous
batt_state_(1,_'energy') Continuous
batt_state_(1,_'freq') Continuous
batt_state_(2,_'energy') Continuous
batt_state_(2,_'freq') Continuous
0 <= op_mode_(0,_'energy') <= 1 Integer
0 <= op_mode_(0,_'freq') <= 1 Integer
0 <= op_mode_(1,_'energy') <= 1 Integer
0 <= op_mode_(1,_'freq') <= 1 Integer
0 <= op_mode_(2,_'energy') <= 1 Integer
0 <= op_mode_(2,_'freq') <= 1 Integer
</code>```

Body:
I'm trying to determine the maximum revenue that can be earned from a battery connected to the grid using linear programming. The battery can earn revenues in two markets, the energy market and the frequency market. My model is throwing an error when I include a binary constraint in the objective function (TypeError: Non-constant expressions cannot be multiplied).

My Objective function is:

N is the time horizon of the optimisation

 is the energy price at time t

 are the allocated discharge and charge power at time t

 is the frequency price at time t

 is the allocated frequency power at time t

The battery should only be active in one market (energy or frequency) at each time period t. So needs a constraint that looks something like this:

where  is a binary variable that activates activity x.

Ok, so that's what I trying to achieve. I'm struggling to create such a constraint in pulp that essentially switches off participation in one of the markets if the value in the other is higher (all other constraints being met). In my battery class, I've created decision variables for each of the power activities and also for their on/off status.

self.charge = \
pulp.LpVariable.dicts(
    "charging_power",
    ('c_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_charge_power_capacity,
    cat='Continuous')

self.discharge = \
pulp.LpVariable.dicts(
    "discharging_power",
    ('d_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_discharge_power_capacity,
    cat='Continuous')

self.freq = \
pulp.LpVariable.dicts(
    "freq_power",
    ('f_t_' + str(i) for i in range(0,time_horizon)),
    lowBound=0, upBound=max_freq_power_capacity,
    cat='Continuous')

self.charge_status = \
pulp.LpVariable.dicts(
    "charge_status",
    ('c_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

self.discharge_status = \
pulp.LpVariable.dicts(
    "discharge_status",
    ('d_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

self.freq_status = \
pulp.LpVariable.dicts(
    "freq_status",
    ('ds3_status_t_' + str(i) for i in range(0,time_horizon)),
    cat='Binary')

In my objective function, I included these binary variables.

self.model = pulp.LpProblem("Max Profit", pulp.LpMaximize)

self.model +=\
pulp.lpSum(
    [self.charge['c_t_' + str(i)]*-1*prices[i] *
     self.charge_status['c_status_t_' + str(i)] for i in range(0,self.time_horizon)]
    + [self.discharge['d_t_' + str(i)]*prices[i] *
     self.discharge_status['d_status_t_' + str(i)] for i in range(0,self.time_horizon)]
    + [self.freq['f_t_' + str(i)]*freq_prices[i] *
     self.freq_status['freq_status_t_' + str(i)] for i in range(0,self.time_horizon)]
)

The constraint for these binary variables, I set up as follows:

 for hour_of_sim in range(1,self.time_horizon+1):
    self.model += \
        pulp.lpSum([self.charge_status['c_status_t_' + str(i)] for i in range(0,self.time_horizon)] +\
                   [self.discharge_status['d_status_t_' + str(i)] for i in range(0,self.time_horizon)] +\
                   [self.freq_status['freq_status_t_' + str(i)] for i in range(0,self.time_horizon)]
                  ) <= 1

When I try to solve, I get a

TypeError: Non-constant expressions cannot be multiplied

on the objective function. Doesn't like my binary variables, runs if they are removed. There must be an alternative way of setting this up which is escaping me?

Body:
The comment is correct...  you are violating "linearity" by multiplying 2 variables together.  Fortunately, this is easy to linearize.  You have a binary variable controlling the mode, so the key element you are looking for (google it) is a Big-M constraint, where you use the binary variable multiplied by a max value (or just something sufficiently large) to limit the other variable either to the max, or clamp it to zero.

An example below.  I also re-arranged things a bit.  You might find this style more readable.  Two main things on style:

You are constantly re-creating the indices you are using which is really painful to read and error prone.  Just make them and re-use them...and you don't need to get complicated with the index set values

You can easily double-index this model, which I think is more clear than making multiple sets of variables.  You essentially have 2 sets you are working with:  Time periods, and Op modes.  Just make those sets and double index.

Example

# battery modes

import pulp

# some data
num_periods = 3
rate_limits = { 'energy'    : 10,
                'freq'      : 20}
price = 2  # this could be a table or double-indexed table of [t, m] or ....

# SETS
M = rate_limits.keys()   # modes.  probably others...  discharge?
T = range(num_periods)   # the time periods

TM = {(t, m) for t in T for m in M}

model = pulp.LpProblem('Batts', pulp.LpMaximize)

# VARS
model.batt = pulp.LpVariable.dicts('batt_state', indexs=TM, lowBound=0, cat='Continuous')
model.op_mode = pulp.LpVariable.dicts('op_mode', indexs=TM, cat='Binary')

# Constraints

# only one op mode in each time period...
for t in T:
    model += sum(model.op_mode[t, m] for m in M) <= 1

# Big-M constraint. limit rates for each rate, in each period.
# this does 2 things:  it is equivalent to the upper bound parameter in the var declaration
#                      It is a Big-M type of constraint which uses the binary var as a control <-- key point
for t, m in TM:
    model += model.batt[t, m] <= rate_limits[m] * model.op_mode[t, m]

# OBJ
model += sum(model.batt[t, m] * price for t, m in TM)

print(model)

#  solve...

Yields:

Batts:
MAXIMIZE
2*batt_state_(0,_'energy') + 2*batt_state_(0,_'freq') + 2*batt_state_(1,_'energy') + 2*batt_state_(1,_'freq') + 2*batt_state_(2,_'energy') + 2*batt_state_(2,_'freq') + 0
SUBJECT TO
_C1: op_mode_(0,_'energy') + op_mode_(0,_'freq') <= 1

_C2: op_mode_(1,_'energy') + op_mode_(1,_'freq') <= 1

_C3: op_mode_(2,_'energy') + op_mode_(2,_'freq') <= 1

_C4: batt_state_(2,_'freq') - 20 op_mode_(2,_'freq') <= 0

_C5: batt_state_(2,_'energy') - 10 op_mode_(2,_'energy') <= 0

_C6: batt_state_(1,_'freq') - 20 op_mode_(1,_'freq') <= 0

_C7: batt_state_(1,_'energy') - 10 op_mode_(1,_'energy') <= 0

_C8: batt_state_(0,_'freq') - 20 op_mode_(0,_'freq') <= 0

_C9: batt_state_(0,_'energy') - 10 op_mode_(0,_'energy') <= 0

VARIABLES
batt_state_(0,_'energy') Continuous
batt_state_(0,_'freq') Continuous
batt_state_(1,_'energy') Continuous
batt_state_(1,_'freq') Continuous
batt_state_(2,_'energy') Continuous
batt_state_(2,_'freq') Continuous
0 <= op_mode_(0,_'energy') <= 1 Integer
0 <= op_mode_(0,_'freq') <= 1 Integer
0 <= op_mode_(1,_'energy') <= 1 Integer
0 <= op_mode_(1,_'freq') <= 1 Integer
0 <= op_mode_(2,_'energy') <= 1 Integer
0 <= op_mode_(2,_'freq') <= 1 Integer


问:
Wait for multiple statements to execute with R2DBC
I need to execute multiple statement with R2DBC but couldn't find useful DatabaseClient#inConnection* examples... So my function keeps getting out too early:

```<code>public Publisher<Person> groupStatements(DatabaseClient client, Person person) {
// yes, I know that's harsh, but hey! so is JPA's @ElementCollection
return client.sql("DELETE FROM persons_address WHERE person = :id")
    .bind("id", person.getId())
    .fetch().rowsUpdated()
    .map(deleted -> {
        // now recreate every relationship
        GenericExecuteSpec statement = client.sql("INSERT INTO persons_address (person, address) VALUES (:person, :address)");
        person.getOfficePlaces().forEach(address -> {
            statement
                .bind("person", person.getId()).bind("address", address.getId())
                .fetch().rowsUpdated()  // there we go AWOL
                .subscribe(inserted -> {
                    // logging here
                });
        });
        return person;  //FIXME wait! need above grouped statements to complete
    });
}
</code>```

NB: I'm using H2 as a backend.
Thanks for any information!

答:
I found a proper batch processing technic (here replacing the map/deleted section), but even got stuck because Statement#execute is returning a Publisher with only #subscribe method and I couldn't return from the chain. So I fed the beast with a few gearing</p>
```<code>//DEBUG I couldn't figure out how to use labels! good enough
private static final String SQL_INSERT = "INSERT INTO persons_address (person, address) VALUES ($1, $2)";
...
.flatMap(deleted -> {
    if (person.getOfficePlaces().isEmpty()) {
        return Mono.just(person);
    } else {
        return client.inConnection(cnx -> {
            Statement stmt = cnx.createStatement(SQL_INSERT);
            person.getOfficePlaces().forEach(address -> {
                stmt.bind(0, person.getId()).bind(1, address.getId()).add();
            });
            return Flux.from(stmt.execute()).last().map(dontcare -> person);
        });
    }
</code>```

Body:
I need to execute multiple statement with R2DBC but couldn't find useful DatabaseClient#inConnection* examples... So my function keeps getting out too early:

public Publisher<Person> groupStatements(DatabaseClient client, Person person) {
// yes, I know that's harsh, but hey! so is JPA's @ElementCollection
return client.sql("DELETE FROM persons_address WHERE person = :id")
    .bind("id", person.getId())
    .fetch().rowsUpdated()
    .map(deleted -> {
        // now recreate every relationship
        GenericExecuteSpec statement = client.sql("INSERT INTO persons_address (person, address) VALUES (:person, :address)");
        person.getOfficePlaces().forEach(address -> {
            statement
                .bind("person", person.getId()).bind("address", address.getId())
                .fetch().rowsUpdated()  // there we go AWOL
                .subscribe(inserted -> {
                    // logging here
                });
        });
        return person;  //FIXME wait! need above grouped statements to complete
    });
}

NB: I'm using H2 as a backend.
Thanks for any information!

Body:
I found a proper batch processing technic (here replacing the map/deleted section), but even got stuck because Statement#execute is returning a Publisher with only #subscribe method and I couldn't return from the chain. So I fed the beast with a few gearing

//DEBUG I couldn't figure out how to use labels! good enough
private static final String SQL_INSERT = "INSERT INTO persons_address (person, address) VALUES ($1, $2)";
...
.flatMap(deleted -> {
    if (person.getOfficePlaces().isEmpty()) {
        return Mono.just(person);
    } else {
        return client.inConnection(cnx -> {
            Statement stmt = cnx.createStatement(SQL_INSERT);
            person.getOfficePlaces().forEach(address -> {
                stmt.bind(0, person.getId()).bind(1, address.getId()).add();
            });
            return Flux.from(stmt.execute()).last().map(dontcare -> person);
        });
    }


问:
Cloud run converts request headers to lower case
I've created dotnet Api based application in cloud run and it got deployed successfully. I was expecting all the request headers will be received as it is when I'm invoking the application (even though http request headers are case insensitive).
But customer headers sent to application got received in the lowercase but headers like content-type received in the camelcase. I've also got information from the document

By default, Cloud Run downgrades HTTP/2 requests to HTTP/1 when those requests are sent to the container.

Is this issue occurs due to that?

Please let me know is there any option in cloud run to receive request headers in the same case as it was sent to the application.

答:
According to the specification, the header keys are now (it has been updated Septembre 30 2019) case insensitive (and converted to lower case). The value of the header is case sensitive.

It's similar to HTTP/2 and QUIC (HTTP/3) specification and homogenous.

And there is no option to change that on Google Cloud.


问:
what is the best way to check if a string is date value?
Reflection does not seem to be working for time. What is the best approach here?</p>
```<code>package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
    stringDate := "07/26/2020"

    // parse string date to golang time
    t, _ := time.Parse("01/02/2006", stringDate)

    ts := ""

    ts = t.String()

    v := reflect.ValueOf(ts)

    fmt.Println(ts) // prints "2020-07-26 00:00:00 +0000 UTC"

    fmt.Println(v.Type()) //  prints "string". How do I get this to time.Time ?

}
</code>```

答:
This seems to do it:</p>
```<code>package main
import "time"

func isDateValue(stringDate string) bool {
   _, err := time.Parse("01/02/2006", stringDate)
   return err == nil
}

func main() {
   ok := isDateValue("07/26/2020")
   println(ok)
}
</code>```

Body:
Reflection does not seem to be working for time. What is the best approach here?

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
    stringDate := "07/26/2020"

    // parse string date to golang time
    t, _ := time.Parse("01/02/2006", stringDate)

    ts := ""

    ts = t.String()

    v := reflect.ValueOf(ts)

    fmt.Println(ts) // prints "2020-07-26 00:00:00 +0000 UTC"

    fmt.Println(v.Type()) //  prints "string". How do I get this to time.Time ?

}

Body:
This seems to do it:

package main
import "time"

func isDateValue(stringDate string) bool {
   _, err := time.Parse("01/02/2006", stringDate)
   return err == nil
}

func main() {
   ok := isDateValue("07/26/2020")
   println(ok)
}


问:
How to issue ticket in Amadeus after flight-order request?
```<code>{
   "data":{
      "type":"flight-order",
      "id":"eJzTd9cPijL1Cg8FAAuUAn0%3D",
      "associatedRecords":[
         {
            "reference":"RZ5JWU",
            "creationDate":"2022-01-13T05:40:00.000",
            "originSystemCode":"GDS",
            "flightOfferId":"1"
         }
      ],
      "flightOffers":[
         {
            "type":"flight-offer",
            "id":"1",
            "source":"GDS",
            "nonHomogeneous":false,
            "lastTicketingDate":"2022-03-31",
            "itineraries":[
               {
                  "segments":[
                     {
                        "departure":{
                           "iataCode":"ISB",
                           "at":"2022-03-30T01:40:00"
                        },
                        "arrival":{
                           "iataCode":"DXB",
                           "terminal":"1",
                           "at":"2022-03-31T03:55:00"
                        },
                        "carrierCode":"PK",
                        "number":"233",
                        "aircraft":{
                           "code":"320"
                        },
                        "operating":{

                        },
                        "id":"1",
                        "numberOfStops":0,
                        "co2Emissions":[
                           {
                              "weight":141,
                              "weightUnit":"KG",
                              "cabin":"ECONOMY"
                           }
                        ]
                     }
                  ]
               }
            ],
            "price":{
               "currency":"PKR",
               "total":"25235.00",
               "base":"15190.00",
               "fees":[
                  {
                     "amount":"0.00",
                     "type":"TICKETING"
                  },
                  {
                     "amount":"0.00",
                     "type":"SUPPLIER"
                  },
                  {
                     "amount":"0.00",
                     "type":"FORM_OF_PAYMENT"
                  }
               ],
               "grandTotal":"25234.00",
               "billingCurrency":"PKR"
            },
            "pricingOptions":{
               "fareType":[
                  "PUBLISHED"
               ],
               "includedCheckedBagsOnly":true
            },
            "validatingAirlineCodes":[
               "PK"
            ],
            "travelerPricings":[
               {
                  "travelerId":"1",
                  "fareOption":"STANDARD",
                  "travelerType":"ADULT",
                  "price":{
                     "currency":"PKR",
                     "total":"25234.00",
                     "base":"15190.00",
                     "taxes":[
                        {
                           "amount":"5000.00",
                           "code":"RG"
                        },
                        {
                           "amount":"2000.00",
                           "code":"SP"
                        },
                        {
                           "amount":"2800.00",
                           "code":"YD"
                        },
                        {
                           "amount":"244.00",
                           "code":"ZR"
                        }
                     ],
                     "refundableTaxes":"10044.00"
                  },
                  "fareDetailsBySegment":[
                     {
                        "segmentId":"1",
                        "cabin":"ECONOMY",
                        "fareBasis":"VLOWPK",
                        "class":"V",
                        "includedCheckedBags":{
                           "weight":30,
                           "weightUnit":"KG"
                        }
                     }
                  ]
               }
            ]
         }
      ],
      "travelers":[
         {
            "id":"1",
            "dateOfBirth":"2003-01-03",
            "gender":"FEMALE",
            "name":{
               "firstName":"Fakhar",
               "lastName":"Khan"
            },
            "documents":[
               {
                  "number":"AG324234234",
                  "issuanceDate":"2015-01-17",
                  "expiryDate":"2025-01-17",
                  "issuanceCountry":"PK",
                  "issuanceLocation":"Pakistan",
                  "nationality":"PK",
                  "documentType":"PASSPORT",
                  "holder":true
               }
            ],
            "contact":{
               "purpose":"STANDARD",
               "phones":[
                  {
                     "deviceType":"MOBILE",
                     "countryCallingCode":"92",
                     "number":"3452345678"
                  }
               ],
               "emailAddress":"hamidafridi.droidor@gmail.com"
            }
         }
      ],
      "remarks":{
         "general":[
            {
               "subType":"GENERAL_MISCELLANEOUS",
               "text":"ONLINE BOOKING FROM INCREIBLE VIAJES"
            }
         ]
      },
      "ticketingAgreement":{
         "option":"DELAY_TO_CANCEL",
         "delay":"6D"
      },
      "contacts":[
         {
            "addresseeName":{
               "firstName":"PABLO RODRIGUEZ"
            },
            "address":{
               "lines":[
                  "Calle Prado, 16"
               ],
               "postalCode":"28014",
               "countryCode":"ES",
               "cityName":"Madrid"
            },
            "purpose":"STANDARD",
            "phones":[
               {
                  "deviceType":"LANDLINE",
                  "countryCallingCode":"34",
                  "number":"480080071"
               },
               {
                  "deviceType":"MOBILE",
                  "countryCallingCode":"33",
                  "number":"480080072"
               }
            ],
            "companyName":"INCREIBLE VIAJES",
            "emailAddress":"support@increibleviajes.es"
         }
      ]
   },
   "dictionaries":{
      "locations":{
         "ISB":{
            "cityCode":"ISB",
            "countryCode":"PK"
         },
         "DXB":{
            "cityCode":"DXB",
            "countryCode":"AE"
         }
      }
   }
}
</code>```

I request for create-order then returned #PNR and now want to issue ticket. #Amadeus

答:
As of now, this Flight Create Orders API allows you to book a flight and generate a PNR, but it does not allow for ticketing. Therefore, one of the requirements in order to use the API in production is to sign a contract with an airline consolidator to issue tickets.

Please check the requirements on the API page. If you want help to find a consolidator get in touch with us via the support channel and we can recommend you one.

Body:
{
   "data":{
      "type":"flight-order",
      "id":"eJzTd9cPijL1Cg8FAAuUAn0%3D",
      "associatedRecords":[
         {
            "reference":"RZ5JWU",
            "creationDate":"2022-01-13T05:40:00.000",
            "originSystemCode":"GDS",
            "flightOfferId":"1"
         }
      ],
      "flightOffers":[
         {
            "type":"flight-offer",
            "id":"1",
            "source":"GDS",
            "nonHomogeneous":false,
            "lastTicketingDate":"2022-03-31",
            "itineraries":[
               {
                  "segments":[
                     {
                        "departure":{
                           "iataCode":"ISB",
                           "at":"2022-03-30T01:40:00"
                        },
                        "arrival":{
                           "iataCode":"DXB",
                           "terminal":"1",
                           "at":"2022-03-31T03:55:00"
                        },
                        "carrierCode":"PK",
                        "number":"233",
                        "aircraft":{
                           "code":"320"
                        },
                        "operating":{

                        },
                        "id":"1",
                        "numberOfStops":0,
                        "co2Emissions":[
                           {
                              "weight":141,
                              "weightUnit":"KG",
                              "cabin":"ECONOMY"
                           }
                        ]
                     }
                  ]
               }
            ],
            "price":{
               "currency":"PKR",
               "total":"25235.00",
               "base":"15190.00",
               "fees":[
                  {
                     "amount":"0.00",
                     "type":"TICKETING"
                  },
                  {
                     "amount":"0.00",
                     "type":"SUPPLIER"
                  },
                  {
                     "amount":"0.00",
                     "type":"FORM_OF_PAYMENT"
                  }
               ],
               "grandTotal":"25234.00",
               "billingCurrency":"PKR"
            },
            "pricingOptions":{
               "fareType":[
                  "PUBLISHED"
               ],
               "includedCheckedBagsOnly":true
            },
            "validatingAirlineCodes":[
               "PK"
            ],
            "travelerPricings":[
               {
                  "travelerId":"1",
                  "fareOption":"STANDARD",
                  "travelerType":"ADULT",
                  "price":{
                     "currency":"PKR",
                     "total":"25234.00",
                     "base":"15190.00",
                     "taxes":[
                        {
                           "amount":"5000.00",
                           "code":"RG"
                        },
                        {
                           "amount":"2000.00",
                           "code":"SP"
                        },
                        {
                           "amount":"2800.00",
                           "code":"YD"
                        },
                        {
                           "amount":"244.00",
                           "code":"ZR"
                        }
                     ],
                     "refundableTaxes":"10044.00"
                  },
                  "fareDetailsBySegment":[
                     {
                        "segmentId":"1",
                        "cabin":"ECONOMY",
                        "fareBasis":"VLOWPK",
                        "class":"V",
                        "includedCheckedBags":{
                           "weight":30,
                           "weightUnit":"KG"
                        }
                     }
                  ]
               }
            ]
         }
      ],
      "travelers":[
         {
            "id":"1",
            "dateOfBirth":"2003-01-03",
            "gender":"FEMALE",
            "name":{
               "firstName":"Fakhar",
               "lastName":"Khan"
            },
            "documents":[
               {
                  "number":"AG324234234",
                  "issuanceDate":"2015-01-17",
                  "expiryDate":"2025-01-17",
                  "issuanceCountry":"PK",
                  "issuanceLocation":"Pakistan",
                  "nationality":"PK",
                  "documentType":"PASSPORT",
                  "holder":true
               }
            ],
            "contact":{
               "purpose":"STANDARD",
               "phones":[
                  {
                     "deviceType":"MOBILE",
                     "countryCallingCode":"92",
                     "number":"3452345678"
                  }
               ],
               "emailAddress":"hamidafridi.droidor@gmail.com"
            }
         }
      ],
      "remarks":{
         "general":[
            {
               "subType":"GENERAL_MISCELLANEOUS",
               "text":"ONLINE BOOKING FROM INCREIBLE VIAJES"
            }
         ]
      },
      "ticketingAgreement":{
         "option":"DELAY_TO_CANCEL",
         "delay":"6D"
      },
      "contacts":[
         {
            "addresseeName":{
               "firstName":"PABLO RODRIGUEZ"
            },
            "address":{
               "lines":[
                  "Calle Prado, 16"
               ],
               "postalCode":"28014",
               "countryCode":"ES",
               "cityName":"Madrid"
            },
            "purpose":"STANDARD",
            "phones":[
               {
                  "deviceType":"LANDLINE",
                  "countryCallingCode":"34",
                  "number":"480080071"
               },
               {
                  "deviceType":"MOBILE",
                  "countryCallingCode":"33",
                  "number":"480080072"
               }
            ],
            "companyName":"INCREIBLE VIAJES",
            "emailAddress":"support@increibleviajes.es"
         }
      ]
   },
   "dictionaries":{
      "locations":{
         "ISB":{
            "cityCode":"ISB",
            "countryCode":"PK"
         },
         "DXB":{
            "cityCode":"DXB",
            "countryCode":"AE"
         }
      }
   }
}

I request for create-order then returned #PNR and now want to issue ticket. #Amadeus


问:
How can I return only what's inside my
 tag if someone makes a cURL or wget request to my link?
I have a simple "hello world" python script here

print("Hello World")

I uploaded it to my site (similar to Pastebin or GitHub gist)

https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5

When I shared the link, I can see the icon, and the title field as the actual text, it's nice. Tested in iPhone below

When I curl the link, I got <title> & <link> tags come with it like this:

```<code><title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />```print("Hello World")```
</code>```

Which of course will break if I remotely executed my codes like this

```<code>curl https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5 | python

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   153    0   153    0     0    354      0 --:--:-- --:--:-- --:--:--   353
  File "<stdin>", line 1
    <title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />```print("Hello World")```
    ^
SyntaxError: invalid syntax
</code>```

How can I return only what's inside my ``` tag if someone makes a cURL or wget to my link?

答:
You could attempt to sniff the User-Agent header but it isn't a good way to determine what type of content to provide to a client.

A better approach (utilizing the features built into HTTP that are designed for handling different representations of the same content) might be to use the Accept header.

In Python, you could use the accept-types module for this.

```<code>return_type = get_best_match(request.META.get('HTTP_ACCEPT'), ['text/html', 'application/python'])

if return_type == 'application/python':
        return render_python()
else:
        return render_html()
</code>```

See this question for handling it in PHP.

Then the client could ask for the Python code if they wanted it:

```<code>curl -H "Accept: application/python" http://example.com/foo | python
</code>```

Title: How can I return only what's inside my <pre> tag if someone makes a cURL or wget request to my link?

Body:
I have a simple "hello world" python script here

print("Hello World")

I uploaded it to my site (similar to Pastebin or GitHub gist)

https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5

When I shared the link, I can see the icon, and the title field as the actual text, it's nice. Tested in iPhone below

When I curl the link, I got <title> & <link> tags come with it like this:

<title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />
print("Hello World")

Which of course will break if I remotely executed my codes like this

curl https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5 | python

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   153    0   153    0     0    354      0 --:--:-- --:--:-- --:--:--   353
  File "<stdin>", line 1
    <title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />
print("Hello World")

    ^
SyntaxError: invalid syntax

How can I return only what's inside my
 tag if someone makes a cURL or wget to my link?

Body:
You could attempt to sniff the User-Agent header but it isn't a good way to determine what type of content to provide to a client.

A better approach (utilizing the features built into HTTP that are designed for handling different representations of the same content) might be to use the Accept header.

In Python, you could use the accept-types module for this.

return_type = get_best_match(request.META.get('HTTP_ACCEPT'), ['text/html', 'application/python'])

if return_type == 'application/python':
        return render_python()
else:
        return render_html()

See this question for handling it in PHP.

Then the client could ask for the Python code if they wanted it:

curl -H "Accept: application/python" http://example.com/foo | python


问:
Change process.env variable for single test using JEST
i have the following code in a file that i'm trying to test:

foo.js

```<code>let localEnv = (process.env.LOCAL_ENVIRONMENT).toLowerCase() === 'prod' ? 'prod' : 'stage';
</code>```

currently, i set this value using setupFiles which points to env.js and it contains:

```<code>process.env.LOCAL_ENVIRONMENT = 'prod';
</code>```

my question is, how do i change process.env.LOCAL_ENVIRONMENT to test (or anything else) in foo.test.js? Just need to do this in a single test, so this line will be covered in my test coverage.

I tried doing something like this but it didn't work...

foo.test.js

```<code>test('Nonprod', async () => {
  process.env.LOCAL_ENVIRONMENT = 'test';
  ...
});
</code>```

答:
You can alter the value as you tried. However you have to take into account that in your original file you only access the variable when you first load this script. In order to make this work you have to do sth like this:

// in your test file foo.test.js
const prev = process.env.LOCAL_ENVIRONMENT
process.env.LOCAL_ENVIRONMENT = 'test'; // from now on the env var is test
const myModule = require('./foo.js'); // foo.js is executed and the var is read as test
process.env.LOCAL_ENVIRONMENT = prev; // change value back
```
<p>This has some caveheats as you cant test multiple scenarios with this (as the module is only loaded in once).</p>
<p>If you want to test more scenarios you have multiple options:</p>
<p>One would be to split the logic and process.env.LOCAL_ENVIRONMENT apart, for example</p>
```function getLocalEnv(env = process.env.LOCAL_ENVIRONMENT) {
  return env.toLowerCase() === 'prod' ? 'prod' : 'stage';
}
```

This function is now very easy to test and doesn't depend on env vars for that anymore

Body:
i have the following code in a file that i'm trying to test:

foo.js

let localEnv = (process.env.LOCAL_ENVIRONMENT).toLowerCase() === 'prod' ? 'prod' : 'stage';

currently, i set this value using setupFiles which points to env.js and it contains:

process.env.LOCAL_ENVIRONMENT = 'prod';

my question is, how do i change process.env.LOCAL_ENVIRONMENT to test (or anything else) in foo.test.js? Just need to do this in a single test, so this line will be covered in my test coverage.

I tried doing something like this but it didn't work...

foo.test.js

test('Nonprod', async () => {
  process.env.LOCAL_ENVIRONMENT = 'test';
  ...
});

Body:
You can alter the value as you tried. However you have to take into account that in your original file you only access the variable when you first load this script. In order to make this work you have to do sth like this:

// in your test file foo.test.js
const prev = process.env.LOCAL_ENVIRONMENT
process.env.LOCAL_ENVIRONMENT = 'test'; // from now on the env var is test
const myModule = require('./foo.js'); // foo.js is executed and the var is read as test
process.env.LOCAL_ENVIRONMENT = prev; // change value back

This has some caveheats as you cant test multiple scenarios with this (as the module is only loaded in once).

If you want to test more scenarios you have multiple options:

One would be to split the logic and process.env.LOCAL_ENVIRONMENT apart, for example

function getLocalEnv(env = process.env.LOCAL_ENVIRONMENT) {
  return env.toLowerCase() === 'prod' ? 'prod' : 'stage';
}

This function is now very easy to test and doesn't depend on env vars for that anymore


问:
Search for an object in an array using filtering object as a parameter
What's the most efficient way to search for object in an array using another object (not a function).

In javascript there is an array method .find() that accepts a callback to seek an item. How to create a similar function that accepts an object representing an object I want to find (that satisfies provided key-value conditions)? For example:

```<code>const array = [
   {
       param1: 'abc',
       param2: 'def',
       param3: 123,
   },
   {
       param1: 'test',
       param2: 'test2',
       param3: 321,
   },
   {
       param1: 'zzz',
       param2: 'test2',
       param3: 333,
   }
]

findInArray(array, {
   param1: 'test',
   param2: 'test2'
}) // must return 2nd object in an array
</code>```

答:
Try this code, you can define your filter and loop on the array to find your desired item .

var filter = {
   param1: 'test',
   param2: 'test2'
};
const array = [
   {
       param1: 'abc',
       param2: 'def',
       param3: 123,
   },
   {
       param1: 'test',
       param2: 'test2',
       param3: 321,
   },
   {
       param1: 'zzz',
       param2: 'test2',
       param3: 333,
   }
]

item = array.filter(function(item) {
  for (var key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});

console.log(item)```

Body:
What's the most efficient way to search for object in an array using another object (not a function).

In javascript there is an array method .find() that accepts a callback to seek an item. How to create a similar function that accepts an object representing an object I want to find (that satisfies provided key-value conditions)? For example:

const array = [
   {
       param1: 'abc',
       param2: 'def',
       param3: 123,
   },
   {
       param1: 'test',
       param2: 'test2',
       param3: 321,
   },
   {
       param1: 'zzz',
       param2: 'test2',
       param3: 333,
   }
]

findInArray(array, {
   param1: 'test',
   param2: 'test2'
}) // must return 2nd object in an array


问:
Will an implicit stack switch occur when switching from compatibility mode to 64-bit mode at the same privilege level?
When switching from compatibility mode to 64-bit mode at the same privilege level by a far call, fields such as BASE or LIMIT in segment registers are ignored, and 64-bit pointer registers are all available. However, if the BASE field is ignored, the stack base address will become 0x0 implicitly, which means an implicit stack switch will be raised, am I right?
And if my understanding is correct, how does the CPU switch back to the original stack when returning via the ret instruction?</p>

答:
Note that in x86 terminology, "stack switching" has a specific technical meaning involving loading a new SS:[ER]SP from the TSS, e.g. when user-space runs an int instruction.  This is not what you're talking about, just that ss.base + esp might be different from 0 + rsp.

Yes, I think that's correct, in the unusual case where your 32-bit code had SS.base != 0.

All  mainstream OSes use a flat memory model with CS/DS/ES/SS bases all zero (and limit=-1), so this is a non-issue.

BTW, Windows x64 does this user-space mode switch in practice in its DLLs, as part of its WoW64 (i.e. Windows (32-bit) on Windows64).  Instead of using sysenter or whatever to call into the kernel directly, user-space makes a far call to 64-bit code that uses sycall.

That would be a lot less convenient if 32-bit code was running with a non-zero SS base.  (I'm not sure whether the CS:EIP return address would be pushed at ss.base + ESP or at [RSP]; if the latter, it would still be possible for the 64-bit code to actually return if memory was allocated at rsp as well as ss.base + rsp.)


Title: How to extract the Max value within the same key

Body:
{'201001': [36, 88, 65, 113, 51, 88, 37, 106, 96, 68, 104, 93],
 '201002': [65, 85, 97, 52],
 '201003': [85, 63, 86, 52, 71, 53, 51, 48, 52],
 '201004': [82, 39, 97, 114, 74, 30, 97],
 '201005': [97, 66, 109, 98, 94, 78, 99, 53, 67, 56],
 '201006': [116, 98, 39, 69, 33, 84, 62, 39],
 '201007': [72, 98, 37],
 '201008': [98, 31, 99, 105, 109, 72, 30, 34]}

I have a dictionary looks something like this, and I want to extract the maximum value within the same key. And create a new dictionary with only one max value per key.

Body:
dict_t = {
    "201001":[1,2,3,4,5],
    "201002":[6,7,8,9,1],
    "201003":[8,9,10,12],
    "201004":[1,20,21,40,100],
}
{key:max(val) for key,val in dict_t.items()}
#output
{'201001': 5, '201002': 9, '201003': 12, '201004': 100}


问:
Showing animated "loading" gif before the actual html content appears in Lightbox/Facebox
Hey guys, I'm trying to show an animated gif for 2 seconds before the actuall content appears in a lightbox (Facebox). How can make this happen?

The Facebox module gets triggered after a form submit and so far I have this code:

```<code><script type="text/javascript">

    $('#submitform').submit(function() {
        $('#loader').show();
        $.post('/file.php', function() {
            $('#loader').hide();
        });
        return false;
    });

</script>
</code>```

The loader is placed in like this:

```<code><div id="info" style="display:none;">
    The content...

<div id="loader"><img src="http://notifly.se/notifly/images/loader.gif"></div></div>
</code>```

Thanx!!!

答:
Found the solution to this problem in the Facebox documentation.

You need to wrap your code around:

```<code>$(document).bind('reveal.facebox', function() { *//code here//* }
</code>```

Now all jQuery works inside of Facebox.

Body:
Hey guys, I'm trying to show an animated gif for 2 seconds before the actuall content appears in a lightbox (Facebox). How can make this happen?

The Facebox module gets triggered after a form submit and so far I have this code:

The loader is placed in like this:

    The content...

Thanx!!!

Body:
Found the solution to this problem in the Facebox documentation.

You need to wrap your code around:

$(document).bind('reveal.facebox', function() { *//code here//* }

Now all jQuery works inside of Facebox.


答:
You can combine Array.find() with a loop that iterates over your query object's keys:

const array = [{
    param1: 'abc',
    param2: 'def',
    param3: 123,
  },
  {
    param1: 'test',
    param2: 'test2',
    param3: 321,
  },
  {
    param1: 'zzz',
    param2: 'test2',
    param3: 333,
  }
]
, findInArray = (arr, query) =>
  arr.find(el => {
    let result = true
    for(const key in query){
      if(el[key] !== query[key]){
        result = false
        break
      }
    }
    return result
  })

console.log(findInArray(array, {
  param1: 'test',
  param2: 'test2'
}))

console.log(findInArray(array, {
  param1: 'abc',
  param3: 123
}))

console.log(findInArray(array, {
  param1: 'abc',
  param2: 'abc',
  param3: 123
}))```

Title: Search for an object in an array using filtering object as a parameter


问:
Chrome Extension with Firbease "URL violates Content Security Policy"
Basically im doing a chrome extension with firebase, the auth works perfectly, but when I click the boton that triggers a post to the firebase db this error appears
error csp

The set function to db (Triggers on onClick): function db

And this is my manifest.json:
manifest.json

答:
In Chrome Manifest version 3, you can’t load external scripts. You need to download all Firebase packages and include them in your extension package to be used with a service worker.

This video helped me: https://m.youtube.com/watch?v=UjH2INUPmF4


问:
Is Orleans reminder execution interleaved?
If there are two different reminders on the same grain activation to be fired at the same point, given that grain execution context is single-threaded, will both reminders be executed and interleaved at the same time?

Also, is the reminder execution limited by the default 30s timeout ?

答:
Reminders are invoked using regular grain method calls: the IRemindable interface is a regular grain interface. IRemindable.ReceiveReminder(...) is not marked as [AlwaysInterleave], so it will only be interleaved if your grain class is marked as [Reentrant].

In short: no, reminder calls are not interleaved by default.

Reminders do not override the SiloMessagingOptions.ResponseTimeout value, so the default execution time will be 30s.

If you have a reminder that might need a very long time to execute, you can follow a pattern of starting the long-running work in a background task and ensuring that it is still running (not completed or faulted) whenever the relevant reminder fires.

Here is an example of using that pattern:

public class MyGrain : Grain, IMyGrain
{
    private readonly CancellationTokenSource _deactivating = new CancellationTokenSource();
    private Task _processQueueTask;
    private IGrainReminder _reminder = null;

    public Task ReceiveReminder(string reminderName, TickStatus status)
    {
        // Ensure that the reminder task is running.
        if (_processQueueTask is null || _processQueueTask.IsCompleted)
        {
            if (_processQueueTask?.Exception is Exception exception)
            {
                // Log that an error occurred.
            }

            _processQueueTask = DoLongRunningWork();
            _processQueueTask.Ignore();
        }

        return Task.CompletedTask;
    }

    public override async Task OnActivateAsync()
    {
        if (_reminder != null)
        {
            return;
        }

        _reminder = await RegisterOrUpdateReminder(
            "long-running-work",
            TimeSpan.FromMinutes(1),
            TimeSpan.FromMinutes(1)
        );
    }

    public override async Task OnDeactivateAsync()
    {
        _deactivating.Cancel(throwOnFirstException: false);

        Task processQueueTask = _processQueueTask;
        if (processQueueTask != null)
        {
            // Optionally add some max deactivation timeout here to stop waiting after (eg) 45 seconds

            await processQueueTask;
        }
    }

    public async Task StopAsync()
    {
        if (_reminder == null)
        {
            return;
        }
        await UnregisterReminder(_reminder);
        _reminder = null;
    }

    private async Task DoLongRunningWork()
    {
        // Log that we are starting the long-running work
        while (!_deactivating.IsCancellationRequested)
        {
            try
            {
                // Do long-running work
            }
            catch (Exception exception)
            {
                // Log exception. Potentially wait before retrying loop, since it seems like GetMessageAsync may have failed for us to end up here.
            }
        }
    }
}
```


问:
How do I take the name of the Firebase document? Swift
How do I take the name of the Firebase document, directly from the information of the logged in user?

Basically I have a user collection and a Degree Course collection.

When I use the func
GetCorsodiLaurea

I don't want to manually insert the document name in .document ("")
But I would like to automatically take the name of the document directly from the user's info
The field that declares which course is connected to the user is "TipoCorso".
As you can see in the Degree Courses collection there is the value of the "TipoCorso" field

Here is the code of the function and a screen of the Firebase Database:

```<code>  import SwiftUI
  import Firebase
  import FirebaseFirestoreSwift
  import FirebaseDatabase

  class ProfileViewModel : ObservableObject{
@Published var userInfo = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
@Published var userDegree = userDegreeModel(Name: "", TotalSubjects: "")

var ref = Firestore.firestore()
let uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()

init() {
    fetchUser()
    GetCorsodiLaurea()
}

func fetchUser() {

    ref.collection("users").document(uid).getDocument { [self] (doc, err) in guard let user = doc else { return }

        let Nome = user.data()?["Nome"] as! String
        let Cognome = user.data()?["Cognome"] as! String
        let photoURL = user.data()?["photoURL"] as! String
        let Nomeintero = user.data()?["Nomeintero"] as! String
        let Tipocorso = user.data()?["Tipocorso"] as! String
        let Corsodilaurea = user.data()?["Corsodilaurea"] as! String

        DispatchQueue.main.async {
            self.userInfo = UserModel(Nome: Nome, Cognome: Cognome, photoURL: photoURL, Nomeintero: Nomeintero, Corsodilaurea: Corsodilaurea, Tipocorso: Tipocorso)            }
    }

}

func GetCorsodiLaurea() {
    db.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
    let Name = DegreeCourses.data()?["Name"] as! String
    let TotalSubjects = DegreeCourses.data()?["TotalSubjects"] as! String

           // [END doc_reference]
           // [END collection_reference]
    DispatchQueue.main.async {
    self.userDegree = userDegreeModel(Name: Name, TotalSubjects: TotalSubjects)
    }

    }

}

}
</code>```

User

DegreeCourses

答:
When you call the fetchUeser() function it looks like you are populating the UserModel with the specific user's Tipocorso.

So in the GetCorsodiLaurea function you can call Tipocorso member in userInfo variable.

ref.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }

Edit: You are most likely getting the error because the fetchUsers() function hasn't completed fully (as it is waiting for Firebase to respond) but the execution has already proceeded to the GetCorsodiLaurea() function.

To fix this add, a escaping closure to the fetchUsers() function and call the GetCorsodiLaurea() function in the closure. This way, the compiler won't try and execute the functions asynchronously.

  import SwiftUI
  import Firebase
  import FirebaseFirestoreSwift
  import FirebaseDatabase

  class ProfileViewModel : ObservableObject{
@Published var userInfo = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
@Published var userDegree = userDegreeModel(Name: "", TotalSubjects: "")

var ref = Firestore.firestore()
let uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()

init() {
    //GetCorsodilaurea() will only get called after fetchUser() is complete
    fetchUser(completion: {
      GetCorsodiLaurea()
    })

}

func fetchUser(completion: @escaping () -> Void)) {

    ref.collection("users").document(uid).getDocument { [self] (doc, err) in guard let user = doc else { return }

        let Nome = user.data()?["Nome"] as! String
        let Cognome = user.data()?["Cognome"] as! String
        let photoURL = user.data()?["photoURL"] as! String
        let Nomeintero = user.data()?["Nomeintero"] as! String
        let Tipocorso = user.data()?["Tipocorso"] as! String
        let Corsodilaurea = user.data()?["Corsodilaurea"] as! String

        //don't do this async
        self.userInfo = UserModel(Nome: Nome, Cognome: Cognome, photoURL: photoURL, Nomeintero: Nomeintero, Corsodilaurea: Corsodilaurea, Tipocorso: Tipocorso)
        completion()
    }

}

func GetCorsodiLaurea() {
    db.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
    let Name = DegreeCourses.data()?["Name"] as! String
    let TotalSubjects = DegreeCourses.data()?["TotalSubjects"] as! String

           // [END doc_reference]
           // [END collection_reference]
    DispatchQueue.main.async {
    self.userDegree = userDegreeModel(Name: Name, TotalSubjects: TotalSubjects)
    }

    }

}

```

Body:
How do I take the name of the Firebase document, directly from the information of the logged in user?

Basically I have a user collection and a Degree Course collection.

When I use the func
GetCorsodiLaurea

I don't want to manually insert the document name in .document ("")
But I would like to automatically take the name of the document directly from the user's info
The field that declares which course is connected to the user is "TipoCorso".
As you can see in the Degree Courses collection there is the value of the "TipoCorso" field

Here is the code of the function and a screen of the Firebase Database:

  import SwiftUI
  import Firebase
  import FirebaseFirestoreSwift
  import FirebaseDatabase

  class ProfileViewModel : ObservableObject{
@Published var userInfo = UserModel(Nome: "", Cognome: "", photoURL: "", Nomeintero: "", Corsodilaurea: "", Tipocorso: "")
@Published var userDegree = userDegreeModel(Name: "", TotalSubjects: "")

var ref = Firestore.firestore()
let uid = Auth.auth().currentUser!.uid
let db = Firestore.firestore()

init() {
    fetchUser()
    GetCorsodiLaurea()
}

func fetchUser() {

    ref.collection("users").document(uid).getDocument { [self] (doc, err) in guard let user = doc else { return }

        let Nome = user.data()?["Nome"] as! String
        let Cognome = user.data()?["Cognome"] as! String
        let photoURL = user.data()?["photoURL"] as! String
        let Nomeintero = user.data()?["Nomeintero"] as! String
        let Tipocorso = user.data()?["Tipocorso"] as! String
        let Corsodilaurea = user.data()?["Corsodilaurea"] as! String

        DispatchQueue.main.async {
            self.userInfo = UserModel(Nome: Nome, Cognome: Cognome, photoURL: photoURL, Nomeintero: Nomeintero, Corsodilaurea: Corsodilaurea, Tipocorso: Tipocorso)            }
    }

}

func GetCorsodiLaurea() {
    db.collection("DegreeCourses").document(self.userInfo.Tipocorso).getDocument { [self] (doc, err) in guard let DegreeCourses = doc else { return }
    let Name = DegreeCourses.data()?["Name"] as! String
    let TotalSubjects = DegreeCourses.data()?["TotalSubjects"] as! String

           // [END doc_reference]
           // [END collection_reference]
    DispatchQueue.main.async {
    self.userDegree = userDegreeModel(Name: Name, TotalSubjects: TotalSubjects)
    }

    }

}

}

User

DegreeCourses