问:
Getting Date() of Custom Type
I have a server API that is supplying JSON with dates of two different formats - one structure nested within another.

My Swift app pulling is using Swift Codable to decode the JSON, so I needed to add some special handling to allow the two custom date formats to be decoded.

Handily, I found this excellent guide to handling different formats within one structure.

```<code>struct FirstModel: Codable, Identifiable {
    var id: Int?
    let second: SecondModel
    let date: CustomDate<First>

    ...
}

struct SecondModel: Codable, Identifiable {
    var id: Int?
    let date: CustomDate<Second>

    ...
}
</code>```

The date formatters are defined as follows,

```<code>struct CustomDate<E:HasDateFormatter>: Codable {

    let value: Date
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let text = try container.decode(String.self)
        guard let date = E.dateFormatter.date(from: text) else {
            throw CustomDateError.general
        }
        self.value = date
    }
    enum CustomDateError: Error {
        case general
    }
}

struct First: HasDateFormatter {
    static var dateFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.init(identifier: Constants.localeUK)
        dateFormatter.dateFormat = "E, d MMM yyyy HH:mm zzz"
        return dateFormatter
    }
}

struct Second: HasDateFormatter {
    static var dateFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.init(identifier: Constants.localeUK)
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }
}
</code>```

This all works great.

My problem starts when I want to create an object to subsequently encode.

I can't even initialise a struct,

```<code>let first = FirstModel(id: nil, date: Date())
</code>```

The compiler gives the error,

Cannot convert value of type 'Date' to expected argument type 'CustomDate' for the 'date' parameter.

I understand that CustomDate(xxx) is a DateFormatter, so not a Date type, but I don't even know where to start to get a new Date object of that 'type'.  Please could someone help with the syntax for passing in the current date in a way the Swift compiler will accept.  Thanks.

PS. I also suspect I'm going to need a 'set' encoder at some point, amiright?

UPDATE

Following Joakim's suggested below, plus a suggested Fix from the compiler, I tried,

```<code>let date = try! CustomDate<First>(from: Date() as! Decoder)
</code>```

...which compiles, but then crashes at runtime, with error,

Could not cast value of type 'Foundation.Date' to 'Swift.Decoder'.

答:
You can create a custom decoding strategy that can fall back to the second dateFormat in case of failure. If you need to encode your custom structure following the same rule you would need to provide a custom encoding method as well:

First create your DateFormatters

```<code>extension Formatter {
    static let customUK: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_UK")
        formatter.dateFormat = "E, d MMM yyyy HH:mm zzz"
        return formatter
    }()
    static let yyyyMMdd: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_UK")
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
}
</code>```

Then your custom date decoding strategy

```<code>extension JSONDecoder.DateDecodingStrategy {
    static let customUK = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        guard
            let date = Formatter.customUK.date(from: string) ??
                Formatter.yyyyMMdd.date(from: string) else {
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
        }
        return date
    }
}
</code>```

Your custom encoding strategy as well

```<code>extension JSONEncoder.DateEncodingStrategy {
    static let customUK = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.customUK.string(from: $0))
    }
}
</code>```

If you need to make sure to encode your sub structure respecting the original date format you will need to provide your own encoding method to it:

```<code>struct First: Codable {
    var id: Int?
    let second: Second
    let date: Date
    init(id: Int?, date: Date = Date(), second: Second) {
        self.id = id
        self.date = date
        self.second = second
    }
}
</code>```

```<code>struct Second: Decodable {
    var id: Int?
    let date: Date
    init(id: Int?, date: Date = Date()) {
        self.id = id
        self.date = date
    }
}
</code>```

```<code>extension Second: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(Formatter.yyyyMMdd.string(for: date), forKey: .date)
    }
}
</code>```

Playground testing:

```<code>let first = First(id: 1, second: .init(id: 2))
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .customUK
let data = try! encoder.encode(first)

print(String(data: data, encoding: .utf8)!) // {"id":1,"second":{"id":2,"date":"2020-06-02"},"date":"Tue, 2 Jun 2020 16:31 GMT-3"}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .customUK
let firstDecoded = try! decoder.decode(First.self, from: data)
print(firstDecoded)  // "First(id: Optional(1), second: __lldb_expr_227.Second(id: Optional(2), date: 2020-06-02 03:00:00 +0000), date: 2020-06-02 19:38:00 +0000)\n"
</code>```

Title: Getting Date() of Custom Type

Body:
I have a server API that is supplying JSON with dates of two different formats - one structure nested within another.

My Swift app pulling is using Swift Codable to decode the JSON, so I needed to add some special handling to allow the two custom date formats to be decoded.

Handily, I found this excellent guide to handling different formats within one structure.

struct FirstModel: Codable, Identifiable {
    var id: Int?
    let second: SecondModel
    let date: CustomDate<First>

    ...
}

struct SecondModel: Codable, Identifiable {
    var id: Int?
    let date: CustomDate<Second>

    ...
}

The date formatters are defined as follows,

struct CustomDate<E:HasDateFormatter>: Codable {

    let value: Date
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let text = try container.decode(String.self)
        guard let date = E.dateFormatter.date(from: text) else {
            throw CustomDateError.general
        }
        self.value = date
    }
    enum CustomDateError: Error {
        case general
    }
}

struct First: HasDateFormatter {
    static var dateFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.init(identifier: Constants.localeUK)
        dateFormatter.dateFormat = "E, d MMM yyyy HH:mm zzz"
        return dateFormatter
    }
}

struct Second: HasDateFormatter {
    static var dateFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.init(identifier: Constants.localeUK)
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }
}

This all works great.

My problem starts when I want to create an object to subsequently encode.

I can't even initialise a struct,

let first = FirstModel(id: nil, date: Date())

The compiler gives the error,

Cannot convert value of type 'Date' to expected argument type 'CustomDate' for the 'date' parameter.

I understand that CustomDate(xxx) is a DateFormatter, so not a Date type, but I don't even know where to start to get a new Date object of that 'type'.  Please could someone help with the syntax for passing in the current date in a way the Swift compiler will accept.  Thanks.

PS. I also suspect I'm going to need a 'set' encoder at some point, amiright?

UPDATE

Following Joakim's suggested below, plus a suggested Fix from the compiler, I tried,

let date = try! CustomDate<First>(from: Date() as! Decoder)

...which compiles, but then crashes at runtime, with error,

Could not cast value of type 'Foundation.Date' to 'Swift.Decoder'.

Body:
You can create a custom decoding strategy that can fall back to the second dateFormat in case of failure. If you need to encode your custom structure following the same rule you would need to provide a custom encoding method as well:

First create your DateFormatters

extension Formatter {
    static let customUK: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_UK")
        formatter.dateFormat = "E, d MMM yyyy HH:mm zzz"
        return formatter
    }()
    static let yyyyMMdd: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_UK")
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
}

Then your custom date decoding strategy

extension JSONDecoder.DateDecodingStrategy {
    static let customUK = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        guard
            let date = Formatter.customUK.date(from: string) ??
                Formatter.yyyyMMdd.date(from: string) else {
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
        }
        return date
    }
}

Your custom encoding strategy as well

extension JSONEncoder.DateEncodingStrategy {
    static let customUK = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.customUK.string(from: $0))
    }
}

If you need to make sure to encode your sub structure respecting the original date format you will need to provide your own encoding method to it:

struct First: Codable {
    var id: Int?
    let second: Second
    let date: Date
    init(id: Int?, date: Date = Date(), second: Second) {
        self.id = id
        self.date = date
        self.second = second
    }
}

struct Second: Decodable {
    var id: Int?
    let date: Date
    init(id: Int?, date: Date = Date()) {
        self.id = id
        self.date = date
    }
}

extension Second: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(Formatter.yyyyMMdd.string(for: date), forKey: .date)
    }
}

Playground testing:

let first = First(id: 1, second: .init(id: 2))
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .customUK
let data = try! encoder.encode(first)

print(String(data: data, encoding: .utf8)!) // {"id":1,"second":{"id":2,"date":"2020-06-02"},"date":"Tue, 2 Jun 2020 16:31 GMT-3"}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .customUK
let firstDecoded = try! decoder.decode(First.self, from: data)
print(firstDecoded)  // "First(id: Optional(1), second: __lldb_expr_227.Second(id: Optional(2), date: 2020-06-02 03:00:00 +0000), date: 2020-06-02 19:38:00 +0000)\n"


来源: stackexchange

问:
"/bin/sh: [/bin/sh,: not found" response when spining up kilna/liquibase-postgres
when spinning up docker image [kilna/liquibase-postgres], we are getting:

```<code>"/bin/sh: [/bin/sh,: not found"
</code>```

As a response in the container log and the container is exiting abruptly.

Additional Note: We are using macOS Catalina and default bash is zsh.

Any pointers appreciated. Thank you

答:
The command given in the Dockerfile is incorrect.

```<code>"Cmd": [
                "/bin/sh",
                "-c",
                "['/bin/sh', '-i']"
            ],
</code>```

It has nested /bin/sh. Argument for the flag -c should be a single string. It can not be an array.

So, it gives docker run kilna /bin/sh: [/bin/sh,: not found error.

Change the CMD as CMD ["/bin/sh", "-c", "/bin/sh -i"], build and run.

```<code>$ docker run -it kilna
/ #
</code>```

ContentLicense: CC BY-SA 4.0

Body:
when spinning up docker image [kilna/liquibase-postgres], we are getting:

"/bin/sh: [/bin/sh,: not found"

As a response in the container log and the container is exiting abruptly.

Additional Note: We are using macOS Catalina and default bash is zsh.

Any pointers appreciated. Thank you

Body:
The command given in the Dockerfile is incorrect.

"Cmd": [
                "/bin/sh",
                "-c",
                "['/bin/sh', '-i']"
            ],

It has nested /bin/sh. Argument for the flag -c should be a single string. It can not be an array.

So, it gives docker run kilna /bin/sh: [/bin/sh,: not found error.

Change the CMD as CMD ["/bin/sh", "-c", "/bin/sh -i"], build and run.

$ docker run -it kilna
/ #


问:
How to keep android emulator always on top in ubuntu 14.04
How to keep android emulator always on top in ubuntu 14.04
I am using Android Studio 2.1.1 and emulator version of 25.1.6
It was working before updating Android SDK Tools to 25.1.6.</p>

答:
I know that this question if for Ubuntu, but anyone who wants another solution, as me on Debian, you could try this:

Right click on taskbar over "Android Emulator"

More Actions

Keep Above Others

ContentLicense: CC BY-SA 3.0


问:
Is it possible to use on_message and @client.command in the same code?
I am trying to make a discord bot. However some of my commands have had to be done on the outdated on_message event because they wont work under the commands extension. Is there any line of code i need to add to make the command extension work at the same time. What i mean is i have some on_message events and when i add a @client.command to the end of the code the @client.command commands wont respond.

Here is an example code of what i am trying to achieve here.

```<code>@client.event
async def on_message(message):
    if message.content.startswith('ggg'):
        print('hello')
    elif message.content.startswith('hello')
        print('hello')

@client.command()
async def example():
    print('hello')
</code>```

Obviously the code would be more developed. That was just an example.

答:
Of course it can work. Only thing you need to know is await client.process_commands(message). In discord.py docs you can read about this issue.

Also check this: on_message() and @bot.command issue

Body:
I am trying to make a discord bot. However some of my commands have had to be done on the outdated on_message event because they wont work under the commands extension. Is there any line of code i need to add to make the command extension work at the same time. What i mean is i have some on_message events and when i add a @client.command to the end of the code the @client.command commands wont respond.

Here is an example code of what i am trying to achieve here.

@client.event
async def on_message(message):
    if message.content.startswith('ggg'):
        print('hello')
    elif message.content.startswith('hello')
        print('hello')

@client.command()
async def example():
    print('hello')

Obviously the code would be more developed. That was just an example.


问:
Unable to load data in express server which is coming from front end
Whenever I send data from front end data is going to the back-end but I'm receiving empty object in body. I user body parser also but I'm getting same error. Below is my server code.

Error

```<code>Error!
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/sms", ok: false, …}
error: {error: SyntaxError: Unexpected token Y in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "You sent: undefined to Express"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/sms"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/sms"
__proto__: HttpResponseBase
</code>```

app.js

```<code>const express = require("express");
var app = express();
const bodyparser=require("body-parser");
const cors=require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))

app.post('/sms', function (req, res) {
    const body = req.body.Body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
  })

app.get("/",(req,res) =>{
    res.send("We are in home");;

})

app.post("/users",(req,res) =>{
  console.log(req.body);

})

app.listen(8080);
</code>```

答:
There is a bug in your code.

```<code>const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())

app.post('/sms', function (req, res) {
    console.log(req.body)
    const body = req.body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
})

app.get("/", (req, res) => {
    res.send("We are in home");;

})

app.post("/users", (req, res) => {
    console.log(req.body);
    res.json({ success: true })
})

app.listen(8080);
</code>```

Try this. I've modified a couple of lines

Body:
Whenever I send data from front end data is going to the back-end but I'm receiving empty object in body. I user body parser also but I'm getting same error. Below is my server code.

Error

Error!
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/sms", ok: false, …}
error: {error: SyntaxError: Unexpected token Y in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "You sent: undefined to Express"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/sms"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/sms"
__proto__: HttpResponseBase

app.js

const express = require("express");
var app = express();
const bodyparser=require("body-parser");
const cors=require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))

app.post('/sms', function (req, res) {
    const body = req.body.Body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
  })

app.get("/",(req,res) =>{
    res.send("We are in home");;

})

app.post("/users",(req,res) =>{
  console.log(req.body);

})

app.listen(8080);

Body:
There is a bug in your code.

const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())

app.post('/sms', function (req, res) {
    console.log(req.body)
    const body = req.body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
})

app.get("/", (req, res) => {
    res.send("We are in home");;

})

app.post("/users", (req, res) => {
    console.log(req.body);
    res.json({ success: true })
})

app.listen(8080);

Try this. I've modified a couple of lines


问:
Is a self-closing
 tag valid?
I recently came across some HTML that used self-closing
 tags like so:

Item 1

Item 2

```

This renders correctly in Google Chrome, but the Mozilla developer documentation doesn't make any mention of this form and my editor yells at me when I type this. Is this valid HTML?

答:
No, it isn't. You can test this with a validator.

The / is an error so browsers will ignore it, treating it as a start tag.

The
 elements are therefore children of the
 elements (which they have to be since they aren't allowed to be children of
 elements).

The next
 (or
) implicitly ends the previous
 because the end tag is optional for that element.

Title: Is a self-closing <li> tag valid?

Body:
I recently came across some HTML that used self-closing
 tags like so:

Item 1

Item 2

This renders correctly in Google Chrome, but the Mozilla developer documentation doesn't make any mention of this form and my editor yells at me when I type this. Is this valid HTML?

Body:
No, it isn't. You can test this with a validator.

The / is an error so browsers will ignore it, treating it as a start tag.

The <p> elements are therefore children of the <li> elements (which they have to be since they aren't allowed to be children of <ul> elements).

The next <li> (or </ul>) implicitly ends the previous <li> because the end tag is optional for that element.


问:
Swift - Hide & Show Object
When I press the button hide to my text, after I press button to show my text. Where is my fault? My English very bad, sorry...</p>

```<code>@IBOutlet weak var myHiddenText: UILabel!

@IBAction func showBtn(sender: AnyObject) {
  myHiddenText.hidden = true

  if myHiddenText.hidden == true {
    myHiddenText.hidden = false
  }

  if myHiddenText.hidden == false {
    myHiddenText.hidden = true
  }

}
</code>```

答:
I know this may not help you but it may help someone else. If you want to hide multiple objects you could do this.

Step 1: Reference all the objects you want to hide with @IBOutlet

Step 2: Declare this variable

```<code>var buttons_are_hidden: Bool = false
</code>```

Step 3: Put this code where you need it

```<code>if self.buttons_are_hidden == true {
        self.first_object.isHidden = true
        self.second_object.isHidden = true
        self.third_object.isHidden = true
        self.buttons_are_hidden = true
    } else {
            self.first_object.isHidden = true
            self.second_object.isHidden = true
            self.third_object.isHidden = true
            self.buttons_are_hidden = true
        }
</code>```

Hope it helps someone!

Title: Swift - Hide & Show Object

Body:
When I press the button hide to my text, after I press button to show my text. Where is my fault? My English very bad, sorry...

@IBOutlet weak var myHiddenText: UILabel!

@IBAction func showBtn(sender: AnyObject) {
  myHiddenText.hidden = true

  if myHiddenText.hidden == true {
    myHiddenText.hidden = false
  }

  if myHiddenText.hidden == false {
    myHiddenText.hidden = true
  }

}

Body:
I know this may not help you but it may help someone else. If you want to hide multiple objects you could do this.

Step 1: Reference all the objects you want to hide with @IBOutlet

Step 2: Declare this variable

var buttons_are_hidden: Bool = false

Step 3: Put this code where you need it

if self.buttons_are_hidden == true {
        self.first_object.isHidden = true
        self.second_object.isHidden = true
        self.third_object.isHidden = true
        self.buttons_are_hidden = true
    } else {
            self.first_object.isHidden = true
            self.second_object.isHidden = true
            self.third_object.isHidden = true
            self.buttons_are_hidden = true
        }

Hope it helps someone!


问:
How to convert a file into a list and then that list into a dictionary and load it into the program everytime I run it
I made a User login system in which user must enter one of three alphabets that is x to stop the program, y if you are a new user and n if you are not a new user.

```<code>self.register = input('Enter y if you have register or n if you are new or x to quit:')
</code>```

If user enter's 'n' then it will create a new user and store it into a dictionary:-
ex:- username = Fread
     password = hello

{'Fread':'hello'}

From here if user enter's y then it will check if te user exist with this condition:-

```<code>        self.existing_Id = input('Please enter your existing id here:')
        self.existing_Password = input('Please enter your existing password here:')
        if self.existing_Id in self.save and self.save[self.id] == self.password:
            print('you have successfully logged in')
        else:
            print('user not found please try again')
</code>```

Also if the user already exist then it will also not create a user:-

```<code>        while True:
        self.id = input('please enter your ID here:')
        if self.id in self.save:
            print('User already exist!!!')
            break
</code>```

Here i am trying to save all the username and password into file then everytime i stop and rerun te code again it should load all the previous saved file into a dictionary?

答:
What you're trying to do is called serialization : Turning python objects into things you can write into files, and back into python objects.

Python has some built in capabilities in the form of pickles :

from pathlib import Path
import pickle

SAVE_FILE = Path('some/path/file.pickle')

def save_state(state_dict):
    pickle.dump(state_dict, SAVE_FILE)

def restore_state():
    return pickle.load(SAVE_FILE)
```

<p>In this example, you can use the <code>save_state</code> function before exiting the program to write your data to <code>some/path/file.saved</code>, and <code>load_state</code> when you open to read data.</p>

<p>Note that pickling has some security issues if the saved state file will be handled by someone malicious. In those circumstances, you could do a similar job with the JSON module,  albeit with a little less leway with the data structures you could store in the file.</p>

<pre class="lang-py prettyprint-override"><code>import JSON
from pathlib import Path

SAVE_FILE = Path('some/path/file.json')

def save_state(state_dict):
    JSON.dump(state_dict, SAVE_FILE)

def restore_state():
    return JSON.load(SAVE_FILE)
</code>```

Body:
I made a User login system in which user must enter one of three alphabets that is x to stop the program, y if you are a new user and n if you are not a new user.

self.register = input('Enter y if you have register or n if you are new or x to quit:')

If user enter's 'n' then it will create a new user and store it into a dictionary:-
ex:- username = Fread
     password = hello

{'Fread':'hello'}

From here if user enter's y then it will check if te user exist with this condition:-

        self.existing_Id = input('Please enter your existing id here:')
        self.existing_Password = input('Please enter your existing password here:')
        if self.existing_Id in self.save and self.save[self.id] == self.password:
            print('you have successfully logged in')
        else:
            print('user not found please try again')

Also if the user already exist then it will also not create a user:-

        while True:
        self.id = input('please enter your ID here:')
        if self.id in self.save:
            print('User already exist!!!')
            break

Here i am trying to save all the username and password into file then everytime i stop and rerun te code again it should load all the previous saved file into a dictionary?

Body:
What you're trying to do is called serialization : Turning python objects into things you can write into files, and back into python objects.

Python has some built in capabilities in the form of pickles :

from pathlib import Path
import pickle

SAVE_FILE = Path('some/path/file.pickle')

def save_state(state_dict):
    pickle.dump(state_dict, SAVE_FILE)

def restore_state():
    return pickle.load(SAVE_FILE)

In this example, you can use the save_state function before exiting the program to write your data to some/path/file.saved, and load_state when you open to read data.

Note that pickling has some security issues if the saved state file will be handled by someone malicious. In those circumstances, you could do a similar job with the JSON module,  albeit with a little less leway with the data structures you could store in the file.

import JSON
from pathlib import Path

SAVE_FILE = Path('some/path/file.json')

def save_state(state_dict):
    JSON.dump(state_dict, SAVE_FILE)

def restore_state():
    return JSON.load(SAVE_FILE)


问:
In-memory Database that Sync with a Central Database
Scenario: Hundreds of nodes running an HTTP server responding to time-critical requests (requests must be processed and a response must be sent back within milliseconds eg. 50 milliseconds max). Each server will serve about 500 requests per second (making all nodes collectively serving more than 100,000 qps). In order to avoid connecting to a central (remote) database for each request, each node will have an in-memory replica of the database (database should be able to only hold a few hundred megabytes of data).

Question 1: Are there any database technologies that implement this kind of multiple (hundreds of) in-memory replicas that synchronize in realtime (or near-realtime) with a central database?

Question 2: Are there any architectural patterns that address this scenario?

答:
Oracle's GoldenGate is a potential solution. I can't speak to the systems you tagged: redis and couchdb. I have heard positive things about redis, but it's purely anecdotal; I don't have any direct, hands-on, experience.
My own company's eXtremeDB can also accommodate this type of workload. There are a couple of configurations to choose from, but this isn't an appropriate venue to explore them with you. Please reach out to us if you'd like to get into it.</p>


问:
strange behaviour of ternary operator in recursion
There is a properly working code:

```<code>#include <iostream>

int sum_odd_digits(int n)
{
  if(n==0) return 0;
  else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
}

int main(int argc, char ** argv)
{
  std::cout<<sum_odd_digits(25897641)<<std::endl;
  return 0;
}
</code>```

But if to remove the outer parenthesis, i. e. replace

```<code>else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
</code>```

with

```<code>else return ((n%2)!=0)?n%10:0 + sum_odd_digits(n/10);
</code>```

the program begins giving a wrong output result, i. e. begins working incorrectly.

Why? What is the difference between these 2 lines?

答:
That's an associativity problem case, due to precedence, your compiler will understand :

```<code>variable = Expression1 ? Expression2 : Expression3; //General Ternary Syntax
</code>```

Where : 0 + sum_odd_digits(n/10) = Expression 3.

Body:
There is a properly working code:

#include <iostream>

int sum_odd_digits(int n)
{
  if(n==0) return 0;
  else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
}

int main(int argc, char ** argv)
{
  std::cout<<sum_odd_digits(25897641)<<std::endl;
  return 0;
}

But if to remove the outer parenthesis, i. e. replace

else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);

with

else return ((n%2)!=0)?n%10:0 + sum_odd_digits(n/10);

the program begins giving a wrong output result, i. e. begins working incorrectly.

Why? What is the difference between these 2 lines?

Body:
That's an associativity problem case, due to precedence, your compiler will understand :

variable = Expression1 ? Expression2 : Expression3; //General Ternary Syntax

Where : 0 + sum_odd_digits(n/10) = Expression 3.


问:
Change cursor to 'move' on 'dragstart'
I am trying to change the cursor to 'move' after the dragging starts. I tried setting the dropEffect property to move but that doesn't work. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

How can I change the cursor to move only AFTER the dragstart event fires?

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.dropEffect = "move";
  console.log(e);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" draggable="true">Drag Me</button></code>```

答:
To solve this, I had to change the cursor on dragstart and revert it back on dragend

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);
button.addEventListener("dragend", dragEnd);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.effectAllowed = "move";
  e.target.style.cursor='move';
  console.log(e);
}

function dragEnd(e) {
  e.target.style.cursor='default';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" draggable="true">Test Me</button></code>```

Title: Change cursor to 'move' on 'dragstart'

Body:
I am trying to change the cursor to 'move' after the dragging starts. I tried setting the dropEffect property to move but that doesn't work. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

How can I change the cursor to move only AFTER the dragstart event fires?

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.dropEffect = "move";
  console.log(e);
}

<button type="button" draggable="true">Drag Me</button>

Body:
To solve this, I had to change the cursor on dragstart and revert it back on dragend

const button = document.querySelector("button");
console.log(button);

button.addEventListener("dragstart", dragStart);
button.addEventListener("dragend", dragEnd);

function dragStart(e) {
  e.dataTransfer.setData("text/plain", 'hello');
  e.dataTransfer.effectAllowed = "move";
  e.target.style.cursor='move';
  console.log(e);
}

function dragEnd(e) {
  e.target.style.cursor='default';
}

<button type="button" draggable="true">Test Me</button>


问:
Databrick SCALA: spark dataframe inside function
I have a databricks scala notebook. I am writing the following

```<code>var df=(some code to create the dataframe)

if (STRING1 == "testing"){

var df2=df.withColumn("New",lit("astring"))

}

df2.show()
</code>```

and seems like I am not able to show df2, and df2 must be declare first ... how can I do that ?

答:
The problem is when you declare a variable inside the if statement, the scope is only available till the end of the if block.

So you could either move the df2 within the if block

```<code>var df=(some code to create the dataframe)

if (STRING1 == "testing"){
var df2=df.withColumn("New",lit("astring"))
df2.show()
}

</code>```

or just declare df2 outside of the if statement

```<code>var df=(some code to create the dataframe)

var df2= if (STRING1 == "testing"){
df.withColumn("New",lit("astring"))
} else df
df2.show()
</code>```

Body:
I have a databricks scala notebook. I am writing the following

var df=(some code to create the dataframe)

if (STRING1 == "testing"){

var df2=df.withColumn("New",lit("astring"))

}

df2.show()

and seems like I am not able to show df2, and df2 must be declare first ... how can I do that ?

Body:
The problem is when you declare a variable inside the if statement, the scope is only available till the end of the if block.

So you could either move the df2 within the if block

var df=(some code to create the dataframe)

if (STRING1 == "testing"){
var df2=df.withColumn("New",lit("astring"))
df2.show()
}

or just declare df2 outside of the if statement

var df=(some code to create the dataframe)

var df2= if (STRING1 == "testing"){
df.withColumn("New",lit("astring"))
} else df
df2.show()


问:
TypeScript: Element implicitly has an 'any' type for RegExp
So, I want to create a function that would take a duration string (e.g 12ms, 7.5 MIN, 400H), parse it and convert it to milliseconds.

const units = {
  MS: 1,
  S: 1 * 1000,
  MIN: 60 * 1 * 1000,
  H: 60 * 60 * 1 * 1000
}

export function toMS(str: string): number {
  let regex = /^(?<number>\d+(?:\.\d+)?)(?:\s*(?<unit>MS|S|MIN|H))?$/i

  if (!regex.test(str)) {
    throw new TypeError(`Expected a duration, got: ${str}`)
  }

  let match = str.match(regex)

  let number = Number(match?.groups?.number)
  let unit = (match?.groups?.unit || 'ms').toUpperCase()

  return Math.floor(number * units[unit])
}```

So, function toMS() takes a string, tests if the provided string is valid (number + whitespace (optional) + unit abbr (optional)) and if it's valid - parses it using str.match(regex).

Everything works fine until: units[unit]. It gives me an error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type.

I've had the same error before with function arguments & class constructors and it was easy to solve since the user provides data. But now I have no idea how to solve that, cause I can't force str.match(regex).groups.unit to have a specific type like : 'MS | S | MIN | H.

I know that it is also possible to create tsconfig.json with "noImplicitAny": false but in my case that's not good at all.

答:
The problem is that TypeScript has no way of knowing whether your regex will really match MS|S|MIN|H. This is dependent types territory, and TypeScript is not that powerful yet.

The only thing TypeScript knows is that what you've matched is going to be a string, because both match?.groups?.unit and 'ms' expressions yield string.

What you can do is letting TypeScript know that your units is an object with keys of type string and values of type number, and check whether what you've matched is a property on the units object. Like this:

const units: { [k: string]: number } = { // letting TypeScript know
  MS: 1,
  S: 1 * 1000,
  MIN: 60 * 1 * 1000,
  H: 60 * 60 * 1 * 1000,
};

export function toMS(str: string): number {
  const regex = /^(?<number>\d+(?:\.\d+)?)(?:\s*(?<unit>MS|S|MIN|H))?$/i;

  if (!regex.test(str)) {
    throw new TypeError(`Expected a duration, got: ${str}`);
  }

  const match = str.match(regex);
  const number = Number(match?.groups?.number);
  const unit = (match?.groups?.unit || 'ms').toUpperCase();

  if (unit in units) { // checking whether your matched string is something you can handle, in runtime
    return Math.floor(number * units[unit]);
  } else {
    throw new Error(`couldn't find units! :(`);
  }
}
```

Body:
So, I want to create a function that would take a duration string (e.g 12ms, 7.5 MIN, 400H), parse it and convert it to milliseconds.

const units = {
  MS: 1,
  S: 1 * 1000,
  MIN: 60 * 1 * 1000,
  H: 60 * 60 * 1 * 1000
}

export function toMS(str: string): number {
  let regex = /^(?<number>\d+(?:\.\d+)?)(?:\s*(?<unit>MS|S|MIN|H))?$/i

  if (!regex.test(str)) {
    throw new TypeError(`Expected a duration, got: ${str}`)
  }

  let match = str.match(regex)

  let number = Number(match?.groups?.number)
  let unit = (match?.groups?.unit || 'ms').toUpperCase()

  return Math.floor(number * units[unit])
}

So, function toMS() takes a string, tests if the provided string is valid (number + whitespace (optional) + unit abbr (optional)) and if it's valid - parses it using str.match(regex).

Everything works fine until: units[unit]. It gives me an error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type.

I've had the same error before with function arguments & class constructors and it was easy to solve since the user provides data. But now I have no idea how to solve that, cause I can't force str.match(regex).groups.unit to have a specific type like : 'MS | S | MIN | H.

I know that it is also possible to create tsconfig.json with "noImplicitAny": false but in my case that's not good at all.


问:
ScannerError when parsing a list with scalars that have colon

Python 3.7 (Windows)

ruamel.yaml 0.16.10

ruamel.yaml.clib 0.2.0

I have a fairly simple YAML file that I'm loading:

test: [C:\Users\Administrator, C:\Documents]
```
<p>Here is example Python code that loads this YAML file (called test.yaml)</p>
<pre class="lang-py prettyprint-override"><code>import ruamel.yaml
yaml_object = ruamel.yaml.YAML(typ='safe')
with open('test.yaml') as f:
    data = yaml_object.load(f)
</code>```

results in error

ruamel.yaml.scanner.ScannerError: while scanning a plain scalar found

unexpected ':'

Interestingly, if I just call safe_load directly
ie.

data = ruamel.yaml.safe_load(f)
```
<p>this works fine.</p>
<p>Also, if I change the source file to use the dash style of list
ie.</p>
<pre class="lang-yaml prettyprint-override"><code>test:
   - C:\Users\Administrator
   - C:\Documents
</code>```

This also works with yaml_object and direct safe_load

Is there something I need to do to yaml_object so that it will work with the bracket-style list?

答:
If you do:

```<code>ruamel.yaml.YAML(typ='safe').load(document)
</code>```

in ruamel.yaml, you will invoke the C extension, i.e. libyaml,  (assuming it can be loaded) and that is libyaml which has unfixed behavior with regards to colons not followed by non-space in keys

This behaviour was fixed in both the round-trip loader:

```<code>ruamel.yaml.YAML().load(document)
</code>```

as well as in the pure Python safe version

```<code>ruamel.yaml.YAML(typ='safe', pure=True).load(document)
</code>```

this latter form is, what you should use, and it is mostly equivalent to ruamel.yaml.safe_load(document) (which you should not use anymore).

So the behavior is to be expected (at least until I replace the C extension) and IIRC this is not the only bug in that libyaml compared to ruamel.yaml using pure Python.

Body:
Python 3.7 (Windows)

ruamel.yaml 0.16.10

ruamel.yaml.clib 0.2.0

I have a fairly simple YAML file that I'm loading:

test: [C:\Users\Administrator, C:\Documents]

Here is example Python code that loads this YAML file (called test.yaml)

import ruamel.yaml
yaml_object = ruamel.yaml.YAML(typ='safe')
with open('test.yaml') as f:
    data = yaml_object.load(f)

results in error

ruamel.yaml.scanner.ScannerError: while scanning a plain scalar found

unexpected ':'

Interestingly, if I just call safe_load directly
ie.

data = ruamel.yaml.safe_load(f)

this works fine.

Also, if I change the source file to use the dash style of list
ie.

test:
   - C:\Users\Administrator
   - C:\Documents

This also works with yaml_object and direct safe_load

Is there something I need to do to yaml_object so that it will work with the bracket-style list?

Body:
If you do:

ruamel.yaml.YAML(typ='safe').load(document)

in ruamel.yaml, you will invoke the C extension, i.e. libyaml,  (assuming it can be loaded) and that is libyaml which has unfixed behavior with regards to colons not followed by non-space in keys

This behaviour was fixed in both the round-trip loader:

ruamel.yaml.YAML().load(document)

as well as in the pure Python safe version

ruamel.yaml.YAML(typ='safe', pure=True).load(document)

this latter form is, what you should use, and it is mostly equivalent to ruamel.yaml.safe_load(document) (which you should not use anymore).

So the behavior is to be expected (at least until I replace the C extension) and IIRC this is not the only bug in that libyaml compared to ruamel.yaml using pure Python.


问:
Sql: How to get previous row/day close quote?
I've a "classic" sql table for Stock Quotes:

Date, Ticker, Open, High, Low, Close, Volume

I want to calculate % change of day, so i need to get Previous day Close and Today Close.

How can I do efficently  in standard Sql ?

EDIT: my data example. Change value have to be calculated getting previous day close.

Thanks

答:
```<code>sel ticker,quotedate,open,high,low,close,
100.00*(abs(close-lag(close) over(order by quotedate)))/lag(close) over(order by quotedate) as change
from table
</code>```

This would be a typical SQL way using lag

Body:
sel ticker,quotedate,open,high,low,close,
100.00*(abs(close-lag(close) over(order by quotedate)))/lag(close) over(order by quotedate) as change
from table

This would be a typical SQL way using lag


问:
Mongoosejs - Filter out populate results
I want to return all chat conversations, where the logged in user (user_id) is  a participant.

I want to populate the participants only returning the profile.firstname (maybe some other later), i then want to filter out the participants so that it does not bring back the loggedInUser (user_id) in the participants array.

chat.controller.js INDEX

```<code> Chat.find({participants: user_id})
            .populate('participants', {
                select: 'profile.firstname',
                where('_id').ne(user_id) // This need to change
            })
            .exec(function (err, chats) { });
</code>```

chat.model.js

```<code>const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

let ChatSchema = new Schema({

        participants: [{
            type: Schema.Types.ObjectId, ref: 'User'
        }],

        messages: [{
            type: Schema.Types.ObjectId, ref: 'Message'
        }],

    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
    });

module.exports = mongoose.model('Chat', ChatSchema);
</code>```

答:
The mongoose populate() documentation has a few changes. The solution should be</p>

```<code>Chat.find({
        participants: user_id
    })
    .populate({
        path: 'participants'
        select: 'profile.firstname',
        match: {
            _id: {
                $ne: user_id
            }
        }
    })
    .exec(function(err, chats) {});
</code>```

Body:
I want to return all chat conversations, where the logged in user (user_id) is  a participant.

I want to populate the participants only returning the profile.firstname (maybe some other later), i then want to filter out the participants so that it does not bring back the loggedInUser (user_id) in the participants array.

chat.controller.js INDEX

 Chat.find({participants: user_id})
            .populate('participants', {
                select: 'profile.firstname',
                where('_id').ne(user_id) // This need to change
            })
            .exec(function (err, chats) { });

chat.model.js

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

let ChatSchema = new Schema({

        participants: [{
            type: Schema.Types.ObjectId, ref: 'User'
        }],

        messages: [{
            type: Schema.Types.ObjectId, ref: 'Message'
        }],

    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
    });

module.exports = mongoose.model('Chat', ChatSchema);

Body:
The mongoose populate() documentation has a few changes. The solution should be

Chat.find({
        participants: user_id
    })
    .populate({
        path: 'participants'
        select: 'profile.firstname',
        match: {
            _id: {
                $ne: user_id
            }
        }
    })
    .exec(function(err, chats) {});


问:
accessing camera and mic in sandboxed iframe from different subdomain
I have basic video chat nodeJS webapp using twilio javascript SDK

video.xyz.com

which I am trying to add in a iframe of a webapplet running on different webservice and sub domain

demo.xyz.com

Browser shows Camera and microphone access prompt when i run directly and it works fine. But inside iframe i am not able to access camera and mic.

Both webapplets are running on same port but different subdomains.

I have tried setting document.domain on video chat app to match parent page app where iframe will be added, but didn't get that to work.
I get this error in chrome:

"Uncaught DOMException: Failed to set the 'domain' property on 'Document': Assignment is forbidden for sandboxed iframes."

I do have allow mic and camera attribute.

```<code><iframe allow="camera; microphone" sandbox="allow-forms allow-scripts" src="https://video.xyz.com"></iframe>
</code>```

What do i need to do get camera access in iframe? Which web app will need this change? Does this need CORS?

Thanks in advance. Any help would be appreciated.

答:
Just read https://groups.google.com/forum/#!topic/bigbluebutton-dev/jauJm_sBbU8

This worked before:

```<code><iframe src="example.com" allow="camera; microphone"/>
</code>```

In my case , the webpage has a HTTP response header:
"Content-Security-Policy: child-src 'self' *;"
And the URL's origin in Iframe is not the same as its parent's URL origin.

But now we should do like this:(tested in Chrome Version 83.0.4103.61 )

```<code><iframe src="example.com" allow="camera https://example.com; microphone https://example.com"/>
</code>```

Body:
I have basic video chat nodeJS webapp using twilio javascript SDK

video.xyz.com

which I am trying to add in a iframe of a webapplet running on different webservice and sub domain

demo.xyz.com

Browser shows Camera and microphone access prompt when i run directly and it works fine. But inside iframe i am not able to access camera and mic.

Both webapplets are running on same port but different subdomains.

I have tried setting document.domain on video chat app to match parent page app where iframe will be added, but didn't get that to work.
I get this error in chrome:

"Uncaught DOMException: Failed to set the 'domain' property on 'Document': Assignment is forbidden for sandboxed iframes."

I do have allow mic and camera attribute.

What do i need to do get camera access in iframe? Which web app will need this change? Does this need CORS?

Thanks in advance. Any help would be appreciated.

Body:
Just read https://groups.google.com/forum/#!topic/bigbluebutton-dev/jauJm_sBbU8

This worked before:

<iframe src="example.com" allow="camera; microphone"/>

In my case , the webpage has a HTTP response header:
"Content-Security-Policy: child-src 'self' *;"
And the URL's origin in Iframe is not the same as its parent's URL origin.

But now we should do like this:(tested in Chrome Version 83.0.4103.61 )

<iframe src="example.com" allow="camera https://example.com; microphone https://example.com"/>


问:
How to deploy to AWS Beanstalk with GitLab CI
How To Deploy a Node App on AWS Elastic Beanstalk, Docker, and Gitlab ci.

I've created a simple node application. Dockerized the node application.

What I'm trying to do is deploy my application using gitlab ci.

This is what I have so far:

```<code>image: docker:git
services:
  - docker:dind

stages:
  - build
  - release
  - release-prod

variables:
  CI_REGISTRY: registry.gitlab.com
  CONTAINER_TEST_IMAGE: registry.gitlab.com/testapp/routing:$CI_COMMIT_REF_NAME
  CONTAINER_RELEASE_IMAGE: registry.gitlab.com/testapp/routing:latest

before_script:
  - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"

build:
  stage: build
  script:
    - docker build -t $CONTAINER_TEST_IMAGE -f Dockerfile.prod .
    - docker push $CONTAINER_TEST_IMAGE

release-image:
  stage: release
  script:
    - docker pull $CONTAINER_TEST_IMAGE
    - docker tag $CONTAINER_TEST_IMAGE $CONTAINER_RELEASE_IMAGE
    - docker push $CONTAINER_RELEASE_IMAGE
  only:
    - master

release-prod:
  stage: release-prod
  script:

  when: manual

</code>```

I'm stuck on release-prod stage. I'm just not sure how I can deploy the app to AWS Beanstalk.

Since I have the docker images have been created and stored in gitlab registry. All I want to do is instruct AWS Beanstalk to download the docker images from gitlab registry and are start the application.

I also have a Dockerrun.aws.json which defines the services.

答:
Your Dockerrun.aws.json file is what Beanstalk uses as the final say in what is deployed.

The option I found to work for us was to make a custom docker image with the eb cli installed so we can run eb deploy... from the gitlab-ci.yml file.

This requires AWS permissions for the runner to be able to access the aws service though so a user or permissions come into play. But they would any way it's setup.

GitLab project - CI/CD settings aws user keys (Ideally it's set up to use an IAM role instead but User/keys will work - I'm not too familiar with getting temporary access which might be the best thing for this but again, I'm not sure how that works)

We use a custom EC2 instance as our runner to run the pipeline so I'm not sure about shared runners - we had a concern of passing aws user creds to a shared runner pipeline...

build stage:
build and push the docker image to our ECR repository or your use case

deploy stage:
have a custom image stored in GitLab that has pre installed the eb cli. Then run eb deploy env-name

This is the dockerfile we use for our PHP project. Some of the installs aren't necessary for your case... This could also be improved by adding a USER and package versions. This will create a docker image that has the eb cli installed though.

```<code>FROM node:12

RUN apt-get update && apt-get -y --allow-unauthenticated install apt-transport-https ca-certificates curl gnupg2 software-properties-common ruby-full \
    && add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
RUN apt-get update && apt-get -y --allow-unauthenticated install docker-ce \
    && apt-get -y install build-essential zlib1g-dev libssl-dev libncurses-dev libffi-dev libsqlite3-dev libreadline-dev libbz2-dev python-pip python3-pip
RUN git clone https://github.com/aws/aws-elastic-beanstalk-cli-setup.git \
    && ./aws-elastic-beanstalk-cli-setup/scripts/bundled_installer
RUN python3 --version && apt-get update && apt-get -y install python3-pip \
    && pip3 install awscli boto3 botocore && pip3 install boto3 botocore --upgrade

</code>```

Example gitlab-ci.yml setup

```<code>release-prod:
  image: registry.gitlab.com/your-acct/project/custom-image
  stage: release-prod
  script:
    - service docker start
    - echo 'export PATH="/root/.ebcli-virtual-env/executables:$PATH"' >> ~/.bash_profile && source ~/.bash_profile
    - echo 'export PATH=/root/.pyenv/versions/3.7.2/bin:$PATH' >> /root/.bash_profile && source /root/.bash_profile
    - eb deploy your-environment
  when: manual
</code>```

you could also add the echo commands to the custom gitlab image also so all you need to run is eb deploy...

Hope this helps a little

Body:
How To Deploy a Node App on AWS Elastic Beanstalk, Docker, and Gitlab ci.

I've created a simple node application. Dockerized the node application.

What I'm trying to do is deploy my application using gitlab ci.

This is what I have so far:

image: docker:git
services:
  - docker:dind

stages:
  - build
  - release
  - release-prod

variables:
  CI_REGISTRY: registry.gitlab.com
  CONTAINER_TEST_IMAGE: registry.gitlab.com/testapp/routing:$CI_COMMIT_REF_NAME
  CONTAINER_RELEASE_IMAGE: registry.gitlab.com/testapp/routing:latest

before_script:
  - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"

build:
  stage: build
  script:
    - docker build -t $CONTAINER_TEST_IMAGE -f Dockerfile.prod .
    - docker push $CONTAINER_TEST_IMAGE

release-image:
  stage: release
  script:
    - docker pull $CONTAINER_TEST_IMAGE
    - docker tag $CONTAINER_TEST_IMAGE $CONTAINER_RELEASE_IMAGE
    - docker push $CONTAINER_RELEASE_IMAGE
  only:
    - master

release-prod:
  stage: release-prod
  script:

  when: manual

I'm stuck on release-prod stage. I'm just not sure how I can deploy the app to AWS Beanstalk.

Since I have the docker images have been created and stored in gitlab registry. All I want to do is instruct AWS Beanstalk to download the docker images from gitlab registry and are start the application.

I also have a Dockerrun.aws.json which defines the services.

Body:
Your Dockerrun.aws.json file is what Beanstalk uses as the final say in what is deployed.

The option I found to work for us was to make a custom docker image with the eb cli installed so we can run eb deploy... from the gitlab-ci.yml file.

This requires AWS permissions for the runner to be able to access the aws service though so a user or permissions come into play. But they would any way it's setup.

GitLab project - CI/CD settings aws user keys (Ideally it's set up to use an IAM role instead but User/keys will work - I'm not too familiar with getting temporary access which might be the best thing for this but again, I'm not sure how that works)

We use a custom EC2 instance as our runner to run the pipeline so I'm not sure about shared runners - we had a concern of passing aws user creds to a shared runner pipeline...

build stage:
build and push the docker image to our ECR repository or your use case

deploy stage:
have a custom image stored in GitLab that has pre installed the eb cli. Then run eb deploy env-name

This is the dockerfile we use for our PHP project. Some of the installs aren't necessary for your case... This could also be improved by adding a USER and package versions. This will create a docker image that has the eb cli installed though.

FROM node:12

RUN apt-get update && apt-get -y --allow-unauthenticated install apt-transport-https ca-certificates curl gnupg2 software-properties-common ruby-full \
    && add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
RUN apt-get update && apt-get -y --allow-unauthenticated install docker-ce \
    && apt-get -y install build-essential zlib1g-dev libssl-dev libncurses-dev libffi-dev libsqlite3-dev libreadline-dev libbz2-dev python-pip python3-pip
RUN git clone https://github.com/aws/aws-elastic-beanstalk-cli-setup.git \
    && ./aws-elastic-beanstalk-cli-setup/scripts/bundled_installer
RUN python3 --version && apt-get update && apt-get -y install python3-pip \
    && pip3 install awscli boto3 botocore && pip3 install boto3 botocore --upgrade

Example gitlab-ci.yml setup

release-prod:
  image: registry.gitlab.com/your-acct/project/custom-image
  stage: release-prod
  script:
    - service docker start
    - echo 'export PATH="/root/.ebcli-virtual-env/executables:$PATH"' >> ~/.bash_profile && source ~/.bash_profile
    - echo 'export PATH=/root/.pyenv/versions/3.7.2/bin:$PATH' >> /root/.bash_profile && source /root/.bash_profile
    - eb deploy your-environment
  when: manual

you could also add the echo commands to the custom gitlab image also so all you need to run is eb deploy...

Hope this helps a little


问:
Is there a way to tell SQL Server to check the table for a duplicate before inserting each new row?
I tried using the SQL below to insert values from one table, importTable, into another table, POInvoicing. It appears that the way this query below works is it checks the POInvoicing table for any possible duplicates from the importTable and for those entries that are not duplicates, it inserts them into the table. The end result is SQL inserting duplicates that already exist in importTable. Is there a way to tell SQL Server to check the table for a possible duplicate entry, if not, add the next row. Then check the table for a duplicate entry, if not, add the next row. I know this will be slower but speed isn't an issue.

INSERT INTO POInvoicing
    (VendorID, InvoiceNo)
SELECT dbo.importTable.VendorID,
       dbo.importTable.InvoiceNo
  FROM dbo.importTable
WHERE NOT EXISTS (SELECT VendorID,
                         InvoiceNo
                    FROM POInvoicing
                   WHERE POInvoicing.VendorID = dbo.importTable.VendorID AND
                         POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)
```

This isn't exactly the functionality I was hoping for. What I want is for the query to insert a row into the table and then check for "duplicates" before inserting the next row. What constitutes a duplicate in the importTable would be the combination of VendorID and InvoiceNo. There are about a dozen different columns in importTable and technically each row is distinct, so DISTINCT won't work here.

I can't simply remove duplicates from the importTable for a couple of reasons not relevant to the question above (though I can provide it if necessary), so that method is out.

答:
If you really don't care (or refuse to tell us) how you want to decide between two rows with the same VendorID and InvoiceNo values, you can pick an arbitrary row like this:

```<code>;WITH NewRows AS
(
  SELECT VendorID, InvoiceNo, InvoiceDate, /* ... other columns ... */
    rn = ROW_NUMBER() OVER (PARTITION BY VendorID, InvoiceNo ORDER BY (SELECT NULL))
  FROM dbo.importTable AS i
  WHERE NOT EXISTS (SELECT 1 FROM dbo.POInvoicing AS p
                      WHERE p.VendorID = i.VendorID
                      AND p.InvoiceNo = i.InvoiceNo)
)
INSERT dbo.POInvoicing(VendorID, InvoiceNo, InvoiceDate /* , ... other columns ... */)
  SELECT VendorID, InvoiceNo, InvoiceDate /* , ... other columns */
  FROM NewRows
  WHERE rn = 1;
</code>```

If you later decide there is a specific row you want in the case of duplicates, you can swap out (SELECT NULL) for something else. For example, to take the row with the latest invoice date:

```<code>OVER (PARTITION BY VendorID, InvoiceNo ORDER BY InvoiceDate DESC)
</code>```

Again, I wasn't asking questions here to be annoying, it was to help you get the solution you need. If you want SQL Server to pick between two duplicates, you can either tell it how to pick, or you'll have to accept arbitrary / non-deterministic results. You should not jump the fence for looping / cursors just because the first thing you tried didn't work the way you wanted it to.

Also please always specify the schema and use sensible table aliases.

Body:
I tried using the SQL below to insert values from one table, importTable, into another table, POInvoicing. It appears that the way this query below works is it checks the POInvoicing table for any possible duplicates from the importTable and for those entries that are not duplicates, it inserts them into the table. The end result is SQL inserting duplicates that already exist in importTable. Is there a way to tell SQL Server to check the table for a possible duplicate entry, if not, add the next row. Then check the table for a duplicate entry, if not, add the next row. I know this will be slower but speed isn't an issue.

INSERT INTO POInvoicing
    (VendorID, InvoiceNo)
SELECT dbo.importTable.VendorID,
       dbo.importTable.InvoiceNo
  FROM dbo.importTable
WHERE NOT EXISTS (SELECT VendorID,
                         InvoiceNo
                    FROM POInvoicing
                   WHERE POInvoicing.VendorID = dbo.importTable.VendorID AND
                         POInvoicing.InvoiceNo = dbo.importTable.InvoiceNo)

This isn't exactly the functionality I was hoping for. What I want is for the query to insert a row into the table and then check for "duplicates" before inserting the next row. What constitutes a duplicate in the importTable would be the combination of VendorID and InvoiceNo. There are about a dozen different columns in importTable and technically each row is distinct, so DISTINCT won't work here.

I can't simply remove duplicates from the importTable for a couple of reasons not relevant to the question above (though I can provide it if necessary), so that method is out.

Body:
If you really don't care (or refuse to tell us) how you want to decide between two rows with the same VendorID and InvoiceNo values, you can pick an arbitrary row like this:

;WITH NewRows AS
(
  SELECT VendorID, InvoiceNo, InvoiceDate, /* ... other columns ... */
    rn = ROW_NUMBER() OVER (PARTITION BY VendorID, InvoiceNo ORDER BY (SELECT NULL))
  FROM dbo.importTable AS i
  WHERE NOT EXISTS (SELECT 1 FROM dbo.POInvoicing AS p
                      WHERE p.VendorID = i.VendorID
                      AND p.InvoiceNo = i.InvoiceNo)
)
INSERT dbo.POInvoicing(VendorID, InvoiceNo, InvoiceDate /* , ... other columns ... */)
  SELECT VendorID, InvoiceNo, InvoiceDate /* , ... other columns */
  FROM NewRows
  WHERE rn = 1;

If you later decide there is a specific row you want in the case of duplicates, you can swap out (SELECT NULL) for something else. For example, to take the row with the latest invoice date:

OVER (PARTITION BY VendorID, InvoiceNo ORDER BY InvoiceDate DESC)

Again, I wasn't asking questions here to be annoying, it was to help you get the solution you need. If you want SQL Server to pick between two duplicates, you can either tell it how to pick, or you'll have to accept arbitrary / non-deterministic results. You should not jump the fence for looping / cursors just because the first thing you tried didn't work the way you wanted it to.

Also please always specify the schema and use sensible table aliases.


问:
MVCS - Model View Controller Service
I've been using MVC for a long time and heard about the "Service" layer (for example in Java web project) and I've been wondering if that is a real architectural pattern given I can't find a lot of information about it.

The idea of MVCS is to have a Service layer between the controller and the model, to encapsulate all the business logic that could be in the controller. That way, the controllers are just there to forward and control the execution. And you can call a Service in many controllers (for example, a website and a webservice), without duplicating code.

答:
The service layer can be interpreted a lot of ways, but it's usually where you have your core business processing logic, and sits below your MVC architecture, but above your data access architecture.

For example, you layer of a complete system may look like this:

View Layer: Your MVC framework & code of choice

Service Layer: Your Controller will call this layer's objects to get or update Models, or other requests.

Data Access Objects: These are abstractions that your service layer will call to get/update the data it needs. This layer will generally either call a Database or some other system (eg: LDAP server, web service, or NoSql-type DB)

The service layer would then be responsible for:

Retrieving and creating your 'Model' from various data sources (or data access objects).

Updating values across various repositories/resources.

Performing application-specific logic and manipulations, etc.

The Model you use in your MVC may or may not come from your services. You may want to take the results your service gives you and manipulate them into a model that's more specific to your medium (eg: a web page).

Title: MVCS - Model View Controller Service


问:
How to use double quotes in xml?
I use QT's QDomDocument. There is a problem when using QDomDocument::setContent(), the compiler complains at this line:

< field regexp = "text".+"text" >

I tried so:

< field regexp = "text"".+""text" >

< field regexp = "text'"'.+'"'text" >

< field regexp = "text\".+\"text" >

答:
XML attribute values can be delimited by ', which is useful when the attribute value must contain a ".

So, if the attribute value in intended to be, say, text".+"text, use:

```<code><field regexp='text".+"text'>
</code>```

Alternatively, " can be used for ".

```<code><field regexp="text".+"text">
</code>```

See also:

When to escape double quote in XML

Simplified XML Escaping

Title: How to use double quotes in xml?

Body:
XML attribute values can be delimited by ', which is useful when the attribute value must contain a ".

So, if the attribute value in intended to be, say, text".+"text, use:

<field regexp='text".+"text'>

Alternatively, &quot; can be used for ".

<field regexp="text&quot;.+&quot;text">

See also:

When to escape double quote in XML

Simplified XML Escaping


问:
Drag and Drop on Disabled ImageButton
When I drag and drop something onto an image button, I want it to change colour.
This works fine when the button is enabled using this code:

```<code>DragEvent.ACTION_DRAG_DROP -> {
   it.background.mutate().setColorFilter(ContextCompat.getColor(mContext, R.color.entered_zone), PorterDuff.Mode.SRC_IN)
   return@OnDragListener true
}
</code>```

However, if I do:
endorsedBtn.isEnabled = false

Then the button will not change colour.
Why is this and is there something I can do?

答:
From the documentation:

Note that this step only occurs if the user drops the drag shadow within the bounding box of a View whose listener is registered to receive drag events. If the user releases the drag shadow in any other situation, no ACTION_DROP drag event is sent.

Disabling your image button also disables the listeners for it.

You can create a custom button and decide on your own inner disabling function.

More information here.

Title: Drag and Drop on Disabled ImageButton

Body:
When I drag and drop something onto an image button, I want it to change colour.
This works fine when the button is enabled using this code:

DragEvent.ACTION_DRAG_DROP -> {
   it.background.mutate().setColorFilter(ContextCompat.getColor(mContext, R.color.entered_zone), PorterDuff.Mode.SRC_IN)
   return@OnDragListener true
}

However, if I do:
endorsedBtn.isEnabled = false

Then the button will not change colour.
Why is this and is there something I can do?


问:
Why won't my app render when state changes?
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

```<code>const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props
</code>```

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

```<code>useEffect(() => {
  hasVoted()
}, [userVotes])
</code>```

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

```<code>function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}
</code>```

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.

答:
you seem to be somewhat on the right track here but your problem  may lay elsewhere,provided the props are passed correctly,because the application does re-render when the state changes. if you want to just disable button you can just use simple html attribute to do that

```<code>    {alreadyVoted ? (
        <button class="btn btn-success" disabled="disabled">
          Upvote
        </button>
      ) : (
        <button
          class="btn btn-success"
          onClick={() =>
        // Add the id to the setUserVotes here
       setAlreadyVoted(true)}
        >
          Upvote
        </button>
      )}
</code>```

Take a look at this codesandbox that i just created and get back to me if you have any issues still

Body:
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

useEffect(() => {
  hasVoted()
}, [userVotes])

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.

Body:
you seem to be somewhat on the right track here but your problem  may lay elsewhere,provided the props are passed correctly,because the application does re-render when the state changes. if you want to just disable button you can just use simple html attribute to do that

    {alreadyVoted ? (
        <button class="btn btn-success" disabled="disabled">
          Upvote
        </button>
      ) : (
        <button
          class="btn btn-success"
          onClick={() =>
        // Add the id to the setUserVotes here
       setAlreadyVoted(true)}
        >
          Upvote
        </button>
      )}

Take a look at this codesandbox that i just created and get back to me if you have any issues still


问:
How to check if a certain value is present in any firestore document
Here's my code:

var bJoin = document.getElementById('bJoin');
var joincode = document.getElementById('joincodeipt');
bJoin.addEventListener('click', function(){
    db.collection('arrayslist').where('id','==',joincode).get().then(snapshot => {
        if(snapshot.exists){
            snapshot.docs.forEach(doc => {

            })
        } else {
            console.log('false')
        }

    })
})
```

<p>Essentially I want to check if <code>joincode</code> exists anywhere in <code>arrayslist</code>.
The <code>joincode</code> is the same as the <code>id</code>.</p>

<p>On both occassions (valid or invalid code), this outputs:</p>

```Uncaught FirebaseError: Function Query.where() called with invalid data.
Unsupported field value: a custom HTMLInputElement object
```

How do I fix this?

答:
The error message is telling you that you can't pass an HTMLInputElement to where().  Firestore doesn't know how to reach into that element and get the value that the user entered.  What you can do instead is reach into it yourself to get its string value and pass that along.  If you want to get the string value out of the element, you can use its value property.

```<code>db.collection('arrayslist').where('id','==',joincode.value)
</code>```

Body:
Here's my code:

var bJoin = document.getElementById('bJoin');
var joincode = document.getElementById('joincodeipt');
bJoin.addEventListener('click', function(){
    db.collection('arrayslist').where('id','==',joincode).get().then(snapshot => {
        if(snapshot.exists){
            snapshot.docs.forEach(doc => {

            })
        } else {
            console.log('false')
        }

    })
})

Essentially I want to check if joincode exists anywhere in arrayslist.
The joincode is the same as the id.

On both occassions (valid or invalid code), this outputs:

Uncaught FirebaseError: Function Query.where() called with invalid data.
Unsupported field value: a custom HTMLInputElement object

How do I fix this?

Body:
The error message is telling you that you can't pass an HTMLInputElement to where().  Firestore doesn't know how to reach into that element and get the value that the user entered.  What you can do instead is reach into it yourself to get its string value and pass that along.  If you want to get the string value out of the element, you can use its value property.

db.collection('arrayslist').where('id','==',joincode.value)


答:
The issue is that your joincode is a HTMLInputElement and you cannot compare a id with an html element.

You can fix this by using the value of the input element by using:

joincode.value
```

Title: How to check if a certain value is present in any firestore document


问:
How to use Firebase Remote Config in Cloud Functions?
I’m new in firebase, I want to use Firebase Remote Config to store configuration data related to my business logic and retrieve it from my HTTPS triggered Firebase Functions.

How can do that using TypeScript?

答: The firebase-admin node sdk has been updated to include this functionality. Update to the latest version and follow the documentation.</p>


问:
Replace values outside range with NA using replace_with_na function
I have the following dataset

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60
</code>```

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60
</code>```

I've tried several things with replace_with_na_at function where this seemed most logical:

```<code>test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)
</code>```

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

答:
We can use map2

```<code>library(purrr)
library(dplyr)
df1[c('b', 'c')] <- map2(df1 %>%
       select(b, c), list(c(4, 9), c(50,80)), ~
           replace(.x, .x < .y[1]|.x > .y[2], NA))
</code>```

Body:
I have the following dataset

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60

I've tried several things with replace_with_na_at function where this seemed most logical:

test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

Body:
We can use map2

library(purrr)
library(dplyr)
df1[c('b', 'c')] <- map2(df1 %>%
       select(b, c), list(c(4, 9), c(50,80)), ~
           replace(.x, .x < .y[1]|.x > .y[2], NA))


问:
Jest Snapshots fail on SVG props
Jest snapshot test fail when including Fontawesome-React icon components.
I don't pass a title or aria-labelledby to the SVG components, and even when I do pass it those props, the snapshot continues to hash the props. Tests fail to pass since a new hash is generated in those two props every time the tests run.

"@fortawesome/react-fontawesome": "^0.1.4",

"jest": "^23.6.0",

```<code>        <svg
    -     aria-labelledby="svg-inline--fa-title-y4Cv9dkIlhtu"
    +     aria-labelledby="svg-inline--fa-title-gIn5ZJBsxixz"
          className="svg-inline--fa fa-user-circle fa-w-16 fa-1x "
          color="whitesmoke"
          data-css-knsav2=""
          data-icon="user-circle"
          data-prefix="fas"
    @@ -23,11 +23,11 @@
          }
          viewBox="0 0 496 512"
          xmlns="http://www.w3.org/2000/svg"
        >
          <title
    -       id="svg-inline--fa-title-y4Cv9dkIlhtu"
    +       id="svg-inline--fa-title-gIn5ZJBsxixz"
            style={Object {}}
          >
            User Profile
          </title>
</code>```

答:
People have been resolving this (it's kind of a hack) with overriding Math.random:

https://github.com/FortAwesome/react-fontawesome/issues/194

Title: Jest Snapshots fail on SVG props

Body:
Jest snapshot test fail when including Fontawesome-React icon components.
I don't pass a title or aria-labelledby to the SVG components, and even when I do pass it those props, the snapshot continues to hash the props. Tests fail to pass since a new hash is generated in those two props every time the tests run.

"@fortawesome/react-fontawesome": "^0.1.4",

"jest": "^23.6.0",

        <svg
    -     aria-labelledby="svg-inline--fa-title-y4Cv9dkIlhtu"
    +     aria-labelledby="svg-inline--fa-title-gIn5ZJBsxixz"
          className="svg-inline--fa fa-user-circle fa-w-16 fa-1x "
          color="whitesmoke"
          data-css-knsav2=""
          data-icon="user-circle"
          data-prefix="fas"
    @@ -23,11 +23,11 @@
          }
          viewBox="0 0 496 512"
          xmlns="http://www.w3.org/2000/svg"
        >
          <title
    -       id="svg-inline--fa-title-y4Cv9dkIlhtu"
    +       id="svg-inline--fa-title-gIn5ZJBsxixz"
            style={Object {}}
          >
            User Profile
          </title>


问:
Trying to sort an array list of price in US currency, it's sorting ¢79 > $3.50
I have the below array :

```<code>String Array = [$3.50 , $ 4.00, 79¢ , 90¢, $8.50] ;
</code>```

How can we sort this array list for the output like

```<code>79¢ , 90¢ , $3.50, $4.00, $8.50
</code>```

I also tried parsing it to remove the currency signs but that makes 79 > 3.50

thanks for the help.

答:
I would use the following algorithm for your purpose:

Separates the numbers with the currency exchange mark with
Array.split().

Multiplies all values (by currency exchange rate) all by the same
    currency exchange rate.

Sorts the values.

Divide the values again to the same currency they were, each value
    to return to the same currency exchange rate that was.

Reconnects the icon of each currency.

It's a bit tricky and requires work, but possible, good luck!

Body:
I have the below array :

String Array = [$3.50 , $ 4.00, 79¢ , 90¢, $8.50] ;

How can we sort this array list for the output like

79¢ , 90¢ , $3.50, $4.00, $8.50

I also tried parsing it to remove the currency signs but that makes 79 > 3.50

thanks for the help.


问:
How can I get the browser's scrollbar sizes?
How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?</p>

答:
It seems to work, but maybe there is a simpler solution that works in all browsers?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV
document.body.removeChild(scrollDiv);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.scrollbar-measure {
 width: 100px;
 height: 100px;
 overflow: scroll;
 position: absolute;
 top: -9999px;
}</code>```

Body:
It seems to work, but maybe there is a simpler solution that works in all browsers?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV
document.body.removeChild(scrollDiv);

.scrollbar-measure {
 width: 100px;
 height: 100px;
 overflow: scroll;
 position: absolute;
 top: -9999px;
}


问:
Storing Pandas dataframe in working memory
Is there some way to take a dataframe, say,

```<code>df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
</code>```

and store it in temp memory as a binary object that can then be opened with

```<code>open(df, 'rb')
</code>```

So then, rather than do something like

```<code>open('/home/user/data.csv', 'rb')
</code>```

the code would be

```<code>df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

df_rb = *command to store in temp working memory as binary readable*

open(df_rb, 'rb')
</code>```

答:
Pandas has df.to_pickle() method:

From the docs:

Pickle (serialize) object to file.

```<code>df.to_pickle("./dummy.pkl")
</code>```

Then read this pickled df using read_pickle()

From the docs:

Load pickled pandas object (or any object) from file.

```<code>unpickled_df = pd.read_pickle("./dummy.pkl")
</code>```

Body:
Is there some way to take a dataframe, say,

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

and store it in temp memory as a binary object that can then be opened with

open(df, 'rb')

So then, rather than do something like

open('/home/user/data.csv', 'rb')

the code would be

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

df_rb = *command to store in temp working memory as binary readable*

open(df_rb, 'rb')

Body:
Pandas has df.to_pickle() method:

From the docs:

Pickle (serialize) object to file.

df.to_pickle("./dummy.pkl")

Then read this pickled df using read_pickle()

From the docs:

Load pickled pandas object (or any object) from file.

unpickled_df = pd.read_pickle("./dummy.pkl")


问:
Every time I try to run my data visualization (bokeh) Flask application, I get a SystemExit
```<code>import requests
from flask import Flask, redirect, url_for
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.resources import CDN
from bokeh.embed import file_html

def get_total_confirmed_us():
    output_file("COVID_19_Data.html")
    country = 'united-states'
    status = 'confirmed'
    url = 'https://api.covid19api.com/total/country/{}/status/{}?from=2020-05-01T00:00:00Z&to=2020-05-30T00:00:00Z'.format(country, status)
    response = requests.get(url)
    us_confirmed = response.json()
    us_confirmed = pd.DataFrame(us_confirmed)
    plot = figure()
    plot.line(range(len(us_confirmed)), us_confirmed['Cases'])
    show(plot)

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def run():
    return redirect(url_for('static', filename = 'COVID_19_Data.html'))

%tb
if __name__ == "__main__":
    app.debug = True
    app.run(host = "0.0.0.0", port = 5000, use_reloader = False)
</code>```

Every time I run my my Flask app locally, I get a System Exit. Does anyone know how to fix this? I will show you the error below:

```<code><ipython-input-1-9f0d70378116> in <module>
     31     app.debug = True
     32     get_ipython().run_line_magic('tb', '')
---> 33     app.run(host = "0.0.0.0", port = 5000)

~\Anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options)
    988
    989         try:
--> 990             run_simple(host, port, self, **options)
    991         finally:
    992             # reset the first request information if the development server

~\Anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context)    1005         from ._reloader import run_with_reloader  1006
-> 1007         run_with_reloader(inner, extra_files, reloader_interval, reloader_type)    1008     else:    1009         inner()

~\Anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
    330             reloader.run()
    331         else:
--> 332             sys.exit(reloader.restart_with_reloader())
    333     except KeyboardInterrupt:
    334         pass

SystemExit: 1

 * Serving Flask app "__main__" (lazy loading)  * Environment: production    WARNING: This is a development server. Do not use it in a production deployment.    Use a production WSGI server instead.  * Debug mode: on  * Restarting with stat An exception has occurred, use %tb to see the full traceback.

SystemExit: 1
</code>```

I am a beginner with Flask so I do not know what any of this error mean. By the way, I am running this code on Jupyter Notebook and am trying to create a Flask App where I can show my COVID 19 Data Visualization and build up more features once this error is resolved.

答:
check  if you wrote:  app = Flask(name, static_folder='static').
also if you have the static folder.

Body:
import requests
from flask import Flask, redirect, url_for
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.resources import CDN
from bokeh.embed import file_html

def get_total_confirmed_us():
    output_file("COVID_19_Data.html")
    country = 'united-states'
    status = 'confirmed'
    url = 'https://api.covid19api.com/total/country/{}/status/{}?from=2020-05-01T00:00:00Z&to=2020-05-30T00:00:00Z'.format(country, status)
    response = requests.get(url)
    us_confirmed = response.json()
    us_confirmed = pd.DataFrame(us_confirmed)
    plot = figure()
    plot.line(range(len(us_confirmed)), us_confirmed['Cases'])
    show(plot)

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def run():
    return redirect(url_for('static', filename = 'COVID_19_Data.html'))

%tb
if __name__ == "__main__":
    app.debug = True
    app.run(host = "0.0.0.0", port = 5000, use_reloader = False)

Every time I run my my Flask app locally, I get a System Exit. Does anyone know how to fix this? I will show you the error below:

<ipython-input-1-9f0d70378116> in <module>
     31     app.debug = True
     32     get_ipython().run_line_magic('tb', '')
---> 33     app.run(host = "0.0.0.0", port = 5000)

~\Anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options)
    988
    989         try:
--> 990             run_simple(host, port, self, **options)
    991         finally:
    992             # reset the first request information if the development server

~\Anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context)    1005         from ._reloader import run_with_reloader  1006
-> 1007         run_with_reloader(inner, extra_files, reloader_interval, reloader_type)    1008     else:    1009         inner()

~\Anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
    330             reloader.run()
    331         else:
--> 332             sys.exit(reloader.restart_with_reloader())
    333     except KeyboardInterrupt:
    334         pass

SystemExit: 1

 * Serving Flask app "__main__" (lazy loading)  * Environment: production    WARNING: This is a development server. Do not use it in a production deployment.    Use a production WSGI server instead.  * Debug mode: on  * Restarting with stat An exception has occurred, use %tb to see the full traceback.

SystemExit: 1

I am a beginner with Flask so I do not know what any of this error mean. By the way, I am running this code on Jupyter Notebook and am trying to create a Flask App where I can show my COVID 19 Data Visualization and build up more features once this error is resolved.


问:
Splitting strings in half, python
I have this string my_string = '717460881855742062' how can I split it in half? The string is auto-generated so just splitting by the 1 won't work

答:
You can try do this way: </p>

```<code>firsthalf, secondhalf = my_string[:len(my_string)//2], my_string[len(my_string)//2:]
</code>```

Title: Splitting strings in half, python

Body:
You can try do this way:

firsthalf, secondhalf = my_string[:len(my_string)//2], my_string[len(my_string)//2:]


问:
NoSQL database design problem for notice management app?
I am trying to make a database in NoSQL for learning purpose

Its a simple Notice management (Add/ edit/ Delete notice from notice borad) application in PHP.

I have Memcached (Membase actually) where I can store data as key value pair.

For adding a notice, I am generating a unique id {using uniqueid()function} and storing notice detail in it. But the problem is,
1. How to list all the notices?

I also want to add serial key to Notices. To do that, I need to know the serial key of last inserted data. 2. How do I find out the last inserted Notice?

If find this question inappropriate, cuz this is somewhat relational datamodel (or you may say, it should be implemented in relational database), please let me know any use case scenario where I can use NoSQL to learn more about it.

答:
The first thing to learn about NoSQL is that there are a lot of NoSQL solutions out there, with different capabilities.  You need to pick the one that is most appropriate.  In this case Redis will make your life a lot easier with the design that you've chosen.

The heart of the issue is the CAP theorem.  Many NoSQL solutions deliberately choose to not guarantee consistency.  Once you have thrown that away, you can't guarantee that the same ID is not handed out twice.  Therefore it makes sense to either use timestamps, or use something else (like Redis) to generate the unique ids which you can store wherever you want.