问:
Do `readline`, `readlines`, `writeline` and `writelines` require `file` object `f` to be opened in text mode not binary mode?
Afileobject f has following IO methods, according to Python in a Nutshell:

f.read(size=-1)

In v2, or in v3 when f is open in binary mode, read reads up to size
  bytes from f’s file and returns them as a bytestring. read reads and
  returns less than size bytes if the file ends before size bytes are
  read. When size is less than 0, read reads and returns all bytes up to
  the end of the file. read returns an empty string when the file’s
  current position is at the end of the file or when size equals 0. In
  v3, when f is open in text mode, size is a number of characters, not
  bytes, and read returns a text string.

f.readline(size=-1)

Reads and returns one line from f’s file, up to the end of line (\n),
  included. When size is greater than or equal to 0, readline reads no
  more than size bytes. In that case, the returned string might not end
  with \n. \n might also be absent when readline reads up to the end of
  the file without finding \n. readline returns an empty string when
  the file’s current position is at the end of the file or when size
  equals 0.

f.readlines(size=-1)

Reads and returns a list of all lines in f’s file, each a string
  ending in \n. If size>0, readlines stops and returns the list after
  collecting data for a total of about size bytes rather than reading
  all the way to the end of the file; in that case, the last string in
  the list might not end in \n.

Do readline and readlines require file object f to be opened in text mode not binary mode?

The Same question for writeline and writelines.

答:
No, they also work in binary mode, splitting on b'\n', and returning a list of bytes objects.

Tried with Python 3.5.2, got this output:

```<code>[14:52:44]adamer8:~ ()$ cat Sample.txt
country
code
bold
hello
yellow
country
code
bold
country
[14:52:48]adamer8:~ ()$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','rb')
>>> content = f.readlines()
>>> print(content)
[b'country\n', b'code\n', b'bold\n', b'hello\n', b'yellow\n', b'country\n', b'code\n', b'bold\n', b'country\n']
>>> type(content[0])
<class 'bytes'>
>>>
</code>```

when opening the file with mode 'r' instead, we get strings:

```<code>Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','r')
>>> content = f.readlines()
>>> print(content)
['country\n', 'code\n', 'bold\n', 'hello\n', 'yellow\n', 'country\n', 'code\n', 'bold\n', 'country\n']
>>> type(content[0])
<class 'str'>
>>>
</code>```

Body:
No, they also work in binary mode, splitting on b'\n', and returning a list of bytes objects.

Tried with Python 3.5.2, got this output:

[14:52:44]adamer8:~ ()$ cat Sample.txt
country
code
bold
hello
yellow
country
code
bold
country
[14:52:48]adamer8:~ ()$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','rb')
>>> content = f.readlines()
>>> print(content)
[b'country\n', b'code\n', b'bold\n', b'hello\n', b'yellow\n', b'country\n', b'code\n', b'bold\n', b'country\n']
>>> type(content[0])
<class 'bytes'>
>>>

when opening the file with mode 'r' instead, we get strings:

Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','r')
>>> content = f.readlines()
>>> print(content)
['country\n', 'code\n', 'bold\n', 'hello\n', 'yellow\n', 'country\n', 'code\n', 'bold\n', 'country\n']
>>> type(content[0])
<class 'str'>
>>>


来源: stackexchange

问:
how to redirect to another page if condition true
i want to redirect if user state is loggedIn to true then it redirect to homescreen it show state is change when i login but did'nt redirect to homescreen.

```<code>`componentDidMount() {
//realtime auth state subscriber
this.auth_unsb = firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ loggedIn: true });
    //if logged in
    this.handleUser(user);

    //each time user logs in, subscribe to realtime changes for it's doc
    this.user_unsb = this.firebase
      .firestore()
      .collection("users")
      .doc(user.uid)
      .onSnapshot(
        doc =>
          //sync user data to store
          (Store.currentUserDoc = doc.data()),
        e => {}
      );
  } //if logged out
  else {
    this.setState({ loggedIn: false });
    //unsubscribing from realtime user do changes
    if (this.user_unsb) this.user_unsb();
    return <Redirect to="/login" />;
  }
});
</code>```

}
`

答:
If you want to redirect easily you can use the following code :

```<code>if (your_condition) {
    window.location.href = 'your/path';
}
</code>```

This universal with JavaScript.

ContentLicense: CC BY-SA 4.0

Body:
i want to redirect if user state is loggedIn to true then it redirect to homescreen it show state is change when i login but did'nt redirect to homescreen.

`componentDidMount() {
//realtime auth state subscriber
this.auth_unsb = firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ loggedIn: true });
    //if logged in
    this.handleUser(user);

    //each time user logs in, subscribe to realtime changes for it's doc
    this.user_unsb = this.firebase
      .firestore()
      .collection("users")
      .doc(user.uid)
      .onSnapshot(
        doc =>
          //sync user data to store
          (Store.currentUserDoc = doc.data()),
        e => {}
      );
  } //if logged out
  else {
    this.setState({ loggedIn: false });
    //unsubscribing from realtime user do changes
    if (this.user_unsb) this.user_unsb();
    return <Redirect to="/login" />;
  }
});

}
`

Body:
If you want to redirect easily you can use the following code :

if (your_condition) {
    window.location.href = 'your/path';
}

This universal with JavaScript.


问:
Why isn't the code working (here) when I try to change values of a list using 'for' loop?
Let's say there's this random list:

```<code>st=['smthg','xyz','random','000','666']
</code>```

I want to change the values of the indices 1 to 3 using this for loop:

```<code>for anythg in st:
      st[1:3]='whtevr'
</code>```

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

```<code>'t','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',
</code>```

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

```<code>for i in range(1,4):
    st[i]='whtevr'
</code>```

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

答:
First of all, in the code:

```<code>for anythg in st:
    st[1:3]='whatever'
</code>```

You don't need the loop, because that would just be repeating the same action twice.

```<code>st[1:3]='whatever'
</code>```

st[1:3] means ['xyz', 'random']. When you assign that to 'whatever', it just changes those two variables:

```<code>['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']
</code>```

It replaced ['xyz', 'random'] with 'whatever'. That's what's causing the behavior that you see.

Body:
Let's say there's this random list:

st=['smthg','xyz','random','000','666']

I want to change the values of the indices 1 to 3 using this for loop:

for anythg in st:
      st[1:3]='whtevr'

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

't','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

for i in range(1,4):
    st[i]='whtevr'

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
First of all, in the code:

for anythg in st:
    st[1:3]='whatever'

You don't need the loop, because that would just be repeating the same action twice.

st[1:3]='whatever'

st[1:3] means ['xyz', 'random']. When you assign that to 'whatever', it just changes those two variables:

['smthg', 'w', 'h', 'a', 't', 'e', 'v', 'e', 'r', '000', '666']

It replaced ['xyz', 'random'] with 'whatever'. That's what's causing the behavior that you see.


问:
Pass an array of enums in C#
I need to allow multiple roles to have access to a method, in a controller in C# Web api.

I have a custom AuthorizeAttribute which takes an enum of role type, how can I make it so it accepts multiple enums ie. a variable length array of enums.

This is the code I have written for the Attribute:

```<code>private readonly RoleEnum roleInApplication;

public ScopeAuthorizeAttribute(RoleEnum roleInApplication)
{
    this.roleInApplication = roleInApplication;
}

public override void OnAuthorization(HttpActionContext actionContext)
{
    base.OnAuthorization(actionContext);
    .......
    var relatedPermisssionRole = (db call to get the rolename..etc)
    RoleEnum role;
    if (Enum.TryParse(relatedPermisssionRole, out role) && role == roleInApplication)
    {
            // Succeed if the scope array contains the required scope
            return;
     }
  }

    HandleUnauthorizedRequest(actionContext);
}
</code>```

And in the controller, I use it like this:

```<code>[ScopeAuthorize(RoleEnum.ADMIN)]
public async Task<IHttpActionResult> Create(MyModel model)
</code>```

How do I allow multiple roles? eg.

```<code>[ScopeAuthorize(RoleEnum.ADMIN, RoleEnum.USER)]
public async Task<IHttpActionResult> Create(MyModel model)
</code>```

答:
You can create constructor param. I'm updating the code as below.</p>

```<code>private readonly List<RoleEnum> roleInApplications;

public ScopeAuthorizeAttribute(params RoleEnum[] roleInApplications)
{
    this.roleInApplications = roleInApplications.toList();
}
</code>```

Title: Pass an array of enums in C#

Body:
I need to allow multiple roles to have access to a method, in a controller in C# Web api.

I have a custom AuthorizeAttribute which takes an enum of role type, how can I make it so it accepts multiple enums ie. a variable length array of enums.

This is the code I have written for the Attribute:

private readonly RoleEnum roleInApplication;

public ScopeAuthorizeAttribute(RoleEnum roleInApplication)
{
    this.roleInApplication = roleInApplication;
}

public override void OnAuthorization(HttpActionContext actionContext)
{
    base.OnAuthorization(actionContext);
    .......
    var relatedPermisssionRole = (db call to get the rolename..etc)
    RoleEnum role;
    if (Enum.TryParse(relatedPermisssionRole, out role) && role == roleInApplication)
    {
            // Succeed if the scope array contains the required scope
            return;
     }
  }

    HandleUnauthorizedRequest(actionContext);
}

And in the controller, I use it like this:

[ScopeAuthorize(RoleEnum.ADMIN)]
public async Task<IHttpActionResult> Create(MyModel model)

How do I allow multiple roles? eg.

[ScopeAuthorize(RoleEnum.ADMIN, RoleEnum.USER)]
public async Task<IHttpActionResult> Create(MyModel model)

Body:
You can create constructor param. I'm updating the code as below.

private readonly List<RoleEnum> roleInApplications;

public ScopeAuthorizeAttribute(params RoleEnum[] roleInApplications)
{
    this.roleInApplications = roleInApplications.toList();
}


问:
python3 using a generator to filter file with multiline records
I need to read huge files structured as multiline records and write to a file records with certain indices, say record numbers R = 1, 2 and 1093.
If records are N = 3 lines each this amounts to reading the file line by line and then write lines numbers 1, 2, 3 and 4, 5, 6 and 3277, 3278, 3279 (in that the first line in each record Ri starts at line number Ri-1 * N + 1.

I guess one could calculate the lines to write and go through the file line by line and write those lines. However, is it possible to "zip" consecutive lines 1, 2 and 3 into a generator object containing records and filter these somehow or would or print them directly to file if they enumerate to R ?
Something along this pseudocode :

```<code>def subset(file_in, file_out, N, R):
    with open(file_in, "rt") as fin, open(file_out, "wt") as fout:
        line = (line.rstrip() for line in fin)
        record = enumerate(zip(line, line, line)) # What if records are of size N
        for i, r in record if i in R:
            fout.write(r)
</code>```

What to do if you want the record size N as parameter ?

UPDATE EXAMPLE

An example for file_in (4 records, 3 lines/record):

```<code>dslfkj
2
a
dflkj
3
g
fds
2
b
fsdlkj
1
n
</code>```

Then subset(file_in, file_out, 3, [1,3]) would give (file_out)

```<code>dslfkj
2
a
fds
2
b
</code>```

答:
For this problem, it makes sense just to tackle this directly line by line, using floor division.

For Example:

```<code>fin = '''
dslfkj
2
a
dflkj
3
g
fds
2
b
fsdlkj
1
'''

line_gen = (line.rstrip() for line in fin.strip().split())

R = [1, 3]
R = [val - 1 for val in R] #zero indexing
N = 3
for i, line in enumerate(line_gen):
    if i // N in R:
        print(line)
</code>```

Output:

```<code>dslfkj
2
a
fds
2
b
</code>```

Your function can look something like follows: (you may want to check if it works out of the box or requires tweaks. i did not check the file opening portion.

```<code>def subset(file_in, file_out, N, R):
    R = [val - 1 for val in R] #zero indexing
    with open(file_in, "rt") as fin, open(file_out, "wt") as fout:
        line_gen = (line.rstrip() for line in fin)
        for i, line in enumerate(line_gen):
            if i // N in R:
                fout.write(line)
                fout.write('\n')
</code>```

Edit: The answer below pertains to how you could use the generators and group the values together. Having said that, i do not think you should need to use it. However, if you still wish to, you can construct your function based off of it.

Old answer:

You can create n references to the object using list, and then unpack using the * (aka splat) operator.

For example:

```<code>from itertools import zip_longest
line = (x for x in range(100, 132))
n = 3
record = zip(*([line] * n)) #equivalent to *[line, line, line] which is unpacked into zip arguments
for i, r in enumerate(record):
    print(i, r)

0 (100, 101, 102)
1 (103, 104, 105)
2 (106, 107, 108)
3 (109, 110, 111)
4 (112, 113, 114)
5 (115, 116, 117)
6 (118, 119, 120)
7 (121, 122, 123)
8 (124, 125, 126)
9 (127, 128, 129)
</code>```

Also, depending on what you want to happen for "leftover" lines, you may want to use zip_longest instead.

Body:
I need to read huge files structured as multiline records and write to a file records with certain indices, say record numbers R = 1, 2 and 1093.
If records are N = 3 lines each this amounts to reading the file line by line and then write lines numbers 1, 2, 3 and 4, 5, 6 and 3277, 3278, 3279 (in that the first line in each record Ri starts at line number Ri-1 * N + 1.

I guess one could calculate the lines to write and go through the file line by line and write those lines. However, is it possible to "zip" consecutive lines 1, 2 and 3 into a generator object containing records and filter these somehow or would or print them directly to file if they enumerate to R ?
Something along this pseudocode :

def subset(file_in, file_out, N, R):
    with open(file_in, "rt") as fin, open(file_out, "wt") as fout:
        line = (line.rstrip() for line in fin)
        record = enumerate(zip(line, line, line)) # What if records are of size N
        for i, r in record if i in R:
            fout.write(r)

What to do if you want the record size N as parameter ?

UPDATE EXAMPLE

An example for file_in (4 records, 3 lines/record):

dslfkj
2
a
dflkj
3
g
fds
2
b
fsdlkj
1
n

Then subset(file_in, file_out, 3, [1,3]) would give (file_out)

dslfkj
2
a
fds
2
b

Body:
For this problem, it makes sense just to tackle this directly line by line, using floor division.

For Example:

fin = '''
dslfkj
2
a
dflkj
3
g
fds
2
b
fsdlkj
1
'''

line_gen = (line.rstrip() for line in fin.strip().split())

R = [1, 3]
R = [val - 1 for val in R] #zero indexing
N = 3
for i, line in enumerate(line_gen):
    if i // N in R:
        print(line)

Output:

dslfkj
2
a
fds
2
b

Your function can look something like follows: (you may want to check if it works out of the box or requires tweaks. i did not check the file opening portion.

def subset(file_in, file_out, N, R):
    R = [val - 1 for val in R] #zero indexing
    with open(file_in, "rt") as fin, open(file_out, "wt") as fout:
        line_gen = (line.rstrip() for line in fin)
        for i, line in enumerate(line_gen):
            if i // N in R:
                fout.write(line)
                fout.write('\n')

Edit: The answer below pertains to how you could use the generators and group the values together. Having said that, i do not think you should need to use it. However, if you still wish to, you can construct your function based off of it.

Old answer:

You can create n references to the object using list, and then unpack using the * (aka splat) operator.

For example:

from itertools import zip_longest
line = (x for x in range(100, 132))
n = 3
record = zip(*([line] * n)) #equivalent to *[line, line, line] which is unpacked into zip arguments
for i, r in enumerate(record):
    print(i, r)

0 (100, 101, 102)
1 (103, 104, 105)
2 (106, 107, 108)
3 (109, 110, 111)
4 (112, 113, 114)
5 (115, 116, 117)
6 (118, 119, 120)
7 (121, 122, 123)
8 (124, 125, 126)
9 (127, 128, 129)

Also, depending on what you want to happen for "leftover" lines, you may want to use zip_longest instead.


问:
alert, true or false, changes from true to false and false to true
TradingView PineScript code. Need an alert when it changes from true to false and false to true.

```<code>//@version=2
study

threshold = input(title="Threshold", type=float, defval=0.0014,
step=0.0001)

buying = l3_0 > threshold ? true : l3_0 < -threshold ? false : buying[1]

hline(0, title="base line")
//bgcolor(l3_0 > 0.0014 ? green : l3_0 < -0.0014 ? red : gray, transp=20)
bgcolor(buying ? green : red, transp=20)
plot(l3_0, color=silver, style=area, transp=50)
plot(l3_0, color=aqua, title="prediction")

//longCondition = buying
//if (longCondition)
//    strategy.entry("Long", strategy.long)

//shortCondition = buying != true
//if (shortCondition)
//    strategy.entry("Short", strategy.short)
</code>```

Have changed it to a study. As a strategy it gave an alert and plotted the direction on the chart. Changed it to a study but the alert is only supposed to go when it changes. On  my study it alerts every candle and not on the change over. Anything I tried just gives a long or short on every candle.

答:
You can use the change() function to check if a variable has changed.

```<code>//@version=3
study("Custom alert condition", overlay=true)
my_variable = close > open

alertcondition(change(my_variable), title='Triggers when close is above the open or vice versa', message='Candle color changed!')
// this is here because a study chart requires at least one plot, bgcolor or barcolor call
// setting the bar color to na (i.e. N/A) does nothing
barcolor(na)
</code>```

You can then go to the alarm clock icon in the upper right and create a new alert that uses this custom condition. There are options to trigger it once per minute, once per bar or other.

Here's a testing alert condition to see if you have created the alert correctly, set it to trigger every minute and it should trigger quickly.

```<code>//@version=3
study("Testing condition", overlay=true)
alertcondition(close, title='Triggers when close changes', message='Close has changed!')
barcolor(na)
</code>```

Body:
TradingView PineScript code. Need an alert when it changes from true to false and false to true.

//@version=2
study

threshold = input(title="Threshold", type=float, defval=0.0014,
step=0.0001)

buying = l3_0 > threshold ? true : l3_0 < -threshold ? false : buying[1]

hline(0, title="base line")
//bgcolor(l3_0 > 0.0014 ? green : l3_0 < -0.0014 ? red : gray, transp=20)
bgcolor(buying ? green : red, transp=20)
plot(l3_0, color=silver, style=area, transp=50)
plot(l3_0, color=aqua, title="prediction")

//longCondition = buying
//if (longCondition)
//    strategy.entry("Long", strategy.long)

//shortCondition = buying != true
//if (shortCondition)
//    strategy.entry("Short", strategy.short)

Have changed it to a study. As a strategy it gave an alert and plotted the direction on the chart. Changed it to a study but the alert is only supposed to go when it changes. On  my study it alerts every candle and not on the change over. Anything I tried just gives a long or short on every candle.

Body:
You can use the change() function to check if a variable has changed.

//@version=3
study("Custom alert condition", overlay=true)
my_variable = close > open

alertcondition(change(my_variable), title='Triggers when close is above the open or vice versa', message='Candle color changed!')
// this is here because a study chart requires at least one plot, bgcolor or barcolor call
// setting the bar color to na (i.e. N/A) does nothing
barcolor(na)

You can then go to the alarm clock icon in the upper right and create a new alert that uses this custom condition. There are options to trigger it once per minute, once per bar or other.

Here's a testing alert condition to see if you have created the alert correctly, set it to trigger every minute and it should trigger quickly.

//@version=3
study("Testing condition", overlay=true)
alertcondition(close, title='Triggers when close changes', message='Close has changed!')
barcolor(na)


问:
Intl.NumberFormat is not supporting in Lower Versions of IE while trying to format number to remove Thousands separator with different culture
I'm trying to format number and remove thousands separator with respect to different culture ,
It is working in IE 11 but not in lower versions.</p>

```<code> var test=new Intl.NumberFormat('en-US', {
  minimumIntegerDigits: 4,
  maximumFractionDigits: 4,
  useGrouping: false
}).format(formattedNumber); //formattedNumber=11,222,33.555
</code>```

答: According to caniuse.com, the Intl api is unavailable for IE <= 10. You should look into using a polyfill, such as https://github.com/andyearnshaw/Intl.js, or another number formatting library that supports older browsers.</p>

Body:
I'm trying to format number and remove thousands separator with respect to different culture ,
It is working in IE 11 but not in lower versions.

 var test=new Intl.NumberFormat('en-US', {
  minimumIntegerDigits: 4,
  maximumFractionDigits: 4,
  useGrouping: false
}).format(formattedNumber); //formattedNumber=11,222,33.555


问:
Order array by values inside it's objects and date
I have an array like this:

```<code>[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
},
{
Animal:{Tag:3, Eats:"Water"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
}]
</code>```

I want to order it in such way that it is first ordered by "Eats" and within them it should be ordered by "DateAndTime". So, ideally it should return like this:

```<code>[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
}
,
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
},
{
Animal:{Tag:3, Eats:"Meat"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
}]
</code>```

Using lodash I was able to order it by the DateAndTime but I couldn't order it by "Eats" first. Any help would be appreciated. Thank you!

答:
You can use string#localeCompare to sort the array first on the Eats fields and then on the DateAndTime field.

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }];
data.sort((a,b) => a.Animal.Eats.localeCompare(b.Animal.Eats) || a.DateAndTime.localeCompare(b.DateAndTime));
console.log(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0;}</code>```

You can use lodash#sortBy to sort the data.

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }],
    result = _.sortBy(data, ['Animal.Eats', 'DateAndTime']);
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0;}</code>```

```

Body:
I have an array like this:

[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
},
{
Animal:{Tag:3, Eats:"Water"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
}]

I want to order it in such way that it is first ordered by "Eats" and within them it should be ordered by "DateAndTime". So, ideally it should return like this:

[{
Animal:{Tag:1, Eats:"Grass"},
Color:{Id:1, ColorName: "Black",
DateAndTime:"2019-06-06T13:45:00"
}
,
{
Animal:{Tag:4, Eats:"Grass"},
Color:{Id:4, ColorName: "Yellow",
DateAndTime:"2019-06-06T14:45:00"
},
{
Animal:{Tag:3, Eats:"Meat"},
Color:{Id:3, ColorName: "White",
DateAndTime:"2019-06-06T11:45:00"
},
{
Animal:{Tag:2, Eats:"Meat"},
Color:{Id:2, ColorName: "Brown",
DateAndTime:"2019-06-07T13:45:00"
}]

Using lodash I was able to order it by the DateAndTime but I couldn't order it by "Eats" first. Any help would be appreciated. Thank you!

Body:
You can use string#localeCompare to sort the array first on the Eats fields and then on the DateAndTime field.

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }];
data.sort((a,b) => a.Animal.Eats.localeCompare(b.Animal.Eats) || a.DateAndTime.localeCompare(b.DateAndTime));
console.log(data);

.as-console-wrapper {max-height: 100% !important; top: 0;}

You can use lodash#sortBy to sort the data.

let data = [{ Animal:{Tag:1, Eats:"Grass"}, Color:{Id:1, ColorName: "Black"}, DateAndTime:"2019-06-06T13:45:00" }, { Animal:{Tag:2, Eats:"Meat"}, Color:{Id:2, ColorName: "Brown"}, DateAndTime:"2019-06-07T13:45:00" }, { Animal:{Tag:3, Eats:"Water"}, Color:{Id:3, ColorName:"White"}, DateAndTime:"2019-06-06T11:45:00" }, { Animal:{Tag:4, Eats:"Grass"}, Color:{Id:4, ColorName: "Yellow"}, DateAndTime:"2019-06-06T14:45:00" }],
    result = _.sortBy(data, ['Animal.Eats', 'DateAndTime']);
console.log(result);

.as-console-wrapper {max-height: 100% !important; top: 0;}

<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>


问:
Does any one know how to solve the following equation?
When I reading this paper http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1976ApJ...209..214B&data_type=PDF_HIGH&whole_paper=YES&type=PRINTER&filetype=.pdf
I try to solve eq(49) numerically, it seems a fokker-planck equation, I find finite difference method doesn't work, it's unstable.
Does any one know how to solve it?</p>

答:
computational science stack exchange is where you can ask and hope for an answer. Or you could try its physics cousin. The equation, you quote, is integro-differential equation, fairly non-linear... Fokker-Plank looking equation. Definitely not the typical Fokker-Plank.

What you can try is to discretize the space part of the function g(x,t)  using finite differences or finite-elements. After all, 0 < x < x_max and you have boundary conditions. You also have to discretize the corresponding integration. So maybe finite elements might be more appropriate? Finite elements means you can write g(x, t) as a series of a well chosen basis of compactly supported simple enough functions Bj(x) : j = 1...N in the interval [0, x_max]

```<code>g(x,t) = sum_j=1:N  gj(t)*Bj(x)
</code>```

That will turn your function into a (large) vector gj(t) = g(x_j, t),   for j = 1, 1, ...., N. As a result, you will obtain a non-linear system of ODEs

```<code>dgj(t)/dt = Qj(g1(t), g2(t), ..., gN(t))
j = 1 ... N
</code>```

After that use something like Runge-Kutta to integrate numerically the ODE system.

Body:
computational science stack exchange is where you can ask and hope for an answer. Or you could try its physics cousin. The equation, you quote, is integro-differential equation, fairly non-linear... Fokker-Plank looking equation. Definitely not the typical Fokker-Plank.

What you can try is to discretize the space part of the function g(x,t)  using finite differences or finite-elements. After all, 0 < x < x_max and you have boundary conditions. You also have to discretize the corresponding integration. So maybe finite elements might be more appropriate? Finite elements means you can write g(x, t) as a series of a well chosen basis of compactly supported simple enough functions Bj(x) : j = 1...N in the interval [0, x_max]

g(x,t) = sum_j=1:N  gj(t)*Bj(x)

That will turn your function into a (large) vector gj(t) = g(x_j, t),   for j = 1, 1, ...., N. As a result, you will obtain a non-linear system of ODEs

dgj(t)/dt = Qj(g1(t), g2(t), ..., gN(t))
j = 1 ... N

After that use something like Runge-Kutta to integrate numerically the ODE system.


问:
Convert the tuples in a list to a dictionary and calculate the frequency
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

```<code>jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
</code>```

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

```<code>for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length
</code>```

答:
You can try:

```<code>dict_results = {}
jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
for jump in jumps:
    name, length = jump
    if name in dict_results:
        dict_results[name].append(length)
    else:
        dict_results[name] = [length]

for key, val in dict_results.items():
    dict_results[key] = sum(val) / len(val)

print(dict_results)
</code>```

Output

```<code>{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}
</code>```

Body:
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length

Body:
You can try:

dict_results = {}
jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
for jump in jumps:
    name, length = jump
    if name in dict_results:
        dict_results[name].append(length)
    else:
        dict_results[name] = [length]

for key, val in dict_results.items():
    dict_results[key] = sum(val) / len(val)

print(dict_results)

Output

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}


问:
Joining most recent record based on the date in another record
I have two tables - let's call them week and contract, like so:

```<code>Week                                    Contract
emp_id | starting   | data1 |  ...   emp_id | from_date  | data2 | ...
-------|------------|-------|--      -------|------------|-------|--
12     | 2019-01-08 | abcd  |        12     | 2018-08-01 | efgh  |
12     | 2019-01-15 | abcd  |        13     | 2018-10-02 | efgh  |
12     | 2019-01-22 | abcd  |        13     | 2019-01-15 | ijkl  |
13     | 2019-01-08 | abcd  |        13     | 2019-03-19 | mnop  |
13     | 2019-01-15 | abcd  |        14     | 2017-02-02 | efgh  |
13     | 2019-01-22 | abcd  |        15     | 2018-01-19 | efgh  |
</code>```

The week.starting field is a date (datetime with time set to midnight) that's at fairly regular intervals. The specific combination of (emp_id, starting) is unique. The from_date field is also a date that records the starting period where the contract record applies. This can be in the future, so we can't just do a MAX(from) and get the right contract for each employee. Currently, (emp_id, from_date) is unique, but I don't want to rely on this. week.starting and contract.from_date can be identical.

I want a query that returns the entire week record, and for each, the record for whatever contract was active at the time - that is, the record where from_date is largest while still less than or equal to week.starting. Getting this contract if I have a specific week in mind is a pretty straightforward greatest n-per-group problem:

```<code>SELECT * FROM contract
WHERE contract.emp_id = @emp_id AND contract.from_date <= @starting
ORDER BY contract.from_date DESC
LIMIT 1
</code>```

But I can't work out how to do this as part of a query to get every record in week. My specific combination of obstacles means I haven't been able to find an answer, despite this being a common set of problems. I don't appear to be able to pass week.starting into a subquery, and I don't appear to be able to use LIMIT in a join either. My best attempt so far ended up joining all contracts that were less than a given week.

What query will return the result I'm looking for?

```<code>emp_id | starting   | from_date  | data1 | data2 | ...
-------|------------|------------|-------|-------|--
12     | 2019-01-08 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-15 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-22 | 2018-08-01 | abcd  | efgh  |
13     | 2019-01-08 | 2018-10-02 | abcd  | efgh  |
13     | 2019-01-15 | 2019-01-15 | abcd  | ijkl  |
13     | 2019-01-22 | 2019-01-15 | abcd  | ijkl  |
</code>```

答:
In Postgres, you can use a lateral join:</p>

```<code>select w.*, c.*
from weeks w left join lateral
     (select c.*
      from contract c
      where c.emp_id = w.emp_id and
            c.from_date <= w.starting
      order by c.from_date desc
      fetch first 1 row only
     ) c;
</code>```

Body:
I have two tables - let's call them week and contract, like so:

Week                                    Contract
emp_id | starting   | data1 |  ...   emp_id | from_date  | data2 | ...
-------|------------|-------|--      -------|------------|-------|--
12     | 2019-01-08 | abcd  |        12     | 2018-08-01 | efgh  |
12     | 2019-01-15 | abcd  |        13     | 2018-10-02 | efgh  |
12     | 2019-01-22 | abcd  |        13     | 2019-01-15 | ijkl  |
13     | 2019-01-08 | abcd  |        13     | 2019-03-19 | mnop  |
13     | 2019-01-15 | abcd  |        14     | 2017-02-02 | efgh  |
13     | 2019-01-22 | abcd  |        15     | 2018-01-19 | efgh  |

The week.starting field is a date (datetime with time set to midnight) that's at fairly regular intervals. The specific combination of (emp_id, starting) is unique. The from_date field is also a date that records the starting period where the contract record applies. This can be in the future, so we can't just do a MAX(from) and get the right contract for each employee. Currently, (emp_id, from_date) is unique, but I don't want to rely on this. week.starting and contract.from_date can be identical.

I want a query that returns the entire week record, and for each, the record for whatever contract was active at the time - that is, the record where from_date is largest while still less than or equal to week.starting. Getting this contract if I have a specific week in mind is a pretty straightforward greatest n-per-group problem:

SELECT * FROM contract
WHERE contract.emp_id = @emp_id AND contract.from_date <= @starting
ORDER BY contract.from_date DESC
LIMIT 1

But I can't work out how to do this as part of a query to get every record in week. My specific combination of obstacles means I haven't been able to find an answer, despite this being a common set of problems. I don't appear to be able to pass week.starting into a subquery, and I don't appear to be able to use LIMIT in a join either. My best attempt so far ended up joining all contracts that were less than a given week.

What query will return the result I'm looking for?

emp_id | starting   | from_date  | data1 | data2 | ...
-------|------------|------------|-------|-------|--
12     | 2019-01-08 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-15 | 2018-08-01 | abcd  | efgh  |
12     | 2019-01-22 | 2018-08-01 | abcd  | efgh  |
13     | 2019-01-08 | 2018-10-02 | abcd  | efgh  |
13     | 2019-01-15 | 2019-01-15 | abcd  | ijkl  |
13     | 2019-01-22 | 2019-01-15 | abcd  | ijkl  |

Body:
In Postgres, you can use a lateral join:

select w.*, c.*
from weeks w left join lateral
     (select c.*
      from contract c
      where c.emp_id = w.emp_id and
            c.from_date <= w.starting
      order by c.from_date desc
      fetch first 1 row only
     ) c;


问:
how to use not between clause in codeigniter
I don't know what wrong with this query. I am getting error. Can please any one tell me about this.

```<code>$this->db->where("ac.booking_date", $booking_date);
$this->db->where(''.$booking_date .' NOT BETWEEN ac.booking_date AND ac.end_date', null, false);
</code>```

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '10:00 NOT BETWEEN ac.booking_date AND ac.end_date ORDER BY ac.id DESC' at line 7

SELECT ac.*, p.first_name, p.last_name FROM anb_crm_bookings ac LEFT JOIN anb_crm_users_personal_info p ON p.user_id = ac.created_by WHERE ac.email = 'devid00@Gmail.com' AND ac.record_id = '36841' AND ac.booking_date = '2019-05-29 10:00' AND 2019-05-29 10:00 NOT BETWEEN ac.booking_date AND ac.end_date ORDER BY ac.id DESC

Filename: models/BookingModel.php

Line Number: 245

答:
you're forgetting quotes in the 2nd WHERE.
   Replace it with the following code</p>

```<code> $this->db->where("ac.booking_date", $booking_date);
 $this->db->where('"'.$booking_date .'" NOT BETWEEN ac.booking_date AND ac.end_date', null, false);
</code>```

Body:
I don't know what wrong with this query. I am getting error. Can please any one tell me about this.

$this->db->where("ac.booking_date", $booking_date);
$this->db->where(''.$booking_date .' NOT BETWEEN ac.booking_date AND ac.end_date', null, false);

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '10:00 NOT BETWEEN ac.booking_date AND ac.end_date ORDER BY ac.id DESC' at line 7

SELECT ac.*, p.first_name, p.last_name FROM anb_crm_bookings ac LEFT JOIN anb_crm_users_personal_info p ON p.user_id = ac.created_by WHERE ac.email = 'devid00@Gmail.com' AND ac.record_id = '36841' AND ac.booking_date = '2019-05-29 10:00' AND 2019-05-29 10:00 NOT BETWEEN ac.booking_date AND ac.end_date ORDER BY ac.id DESC

Filename: models/BookingModel.php

Line Number: 245

Body:
you're forgetting quotes in the 2nd WHERE.
   Replace it with the following code

 $this->db->where("ac.booking_date", $booking_date);
 $this->db->where('"'.$booking_date .'" NOT BETWEEN ac.booking_date AND ac.end_date', null, false);


问:
How to send data from dialog back to parent container with react?
I have a react-big-calendar (The parent container), I have also a select which, the events of the calendar are fetched according to this select ( doctor name ) and I have a button when I click on it, the dialog will be appears (another component), on this dialog, I have a form to add an event after the select, when I post my API, I save it on local storage, but the event added doesn't appears on my calendar just after refresh the page and reselect the doctor name.
But I want, when I click on the save button, will be added directly on the calendar and it will be appeared on the calendar.

My code of calendar is :

```<code>   import Popup from './Popup';
export default class Calendar extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
      open: false,
}}
componentDidMount = () => {
    fetch(process.env.REACT_APP_API_BACKEND_YET+'get_liste_praticien.php')
      .then(Response => Response.json())
      .then(data => {
        this.setState ({ praticiens : data })
        localStorage.setItem('Liste de praticiens ', JSON.stringify(this.state.praticiens))
    })
}
fetchData = (nom,identifiant_user) => {
    this.setState({
      events: [],
      evtStorage:[],
      prevEvents:[],
      evtBackend:[]
    })
      fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning')
        .then(Response => Response.json())
        .then(data => {
          let evts = data.ListeResult;
          for (let i = 0; i < evts.length; i++) {
            evts[i].start = moment(evts[i].start).toDate();
            evts[i].end = moment(evts[i].end).toDate();
           if(evts[i].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evts[i])
          }
          this.setState({
            evtBackend: evts,
            events:  evts
          })
          localStorage.setItem("Liste de planning de " + nom, JSON.stringify(this.state.events));
        })
        const evtCached1 = JSON.parse(localStorage.getItem('Liste récente de planning de ' + nom));
        if(evtCached1 !== null) {
          for (let j = 0; j < evtCached1.length; j++) {
            evtCached1[j].start = moment(evtCached1[j].start).toDate();
            evtCached1[j].end = moment(evtCached1[j].end).toDate();
            if(evtCached1[j].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evtCached1[j]);
          }
          this.setState({
            events:this.state.events,
          });
          localStorage.removeItem("Liste de planning de " + nom);
        }}
// For the select
handlePraticienChange = id_user => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    },() => {
      this.state.praticiens.map((praticien)=> {
          if(this.state.id_user === praticien.id_user){
            this.setState ({ nom_user: praticien.nom_user})
           this.fetchData(praticien.nom_user, praticien.identifiant_user);
          }
      })
      }
    );
  }
// for the popup
 ModalAjoutb = (ref) => {
    if (ref) {
      this.ajoutb = ref.handleAjouterb;
    } else {
      this.ajoutb = null;
    }
  }
render() {

    return (
<div>
    <button className="bp3-button bp3-icon-add-to-artifact .bp3-fill" tabIndex="0" onClick={() => this.ajoutb(this.state.id_user, this.state.events)}>Add event</button>
    <Select  onChange={this.handlePraticienChange} value={this.state.id_user}>
        {this.state.praticiens.map((praticien) =>
            <Option key={praticien.id_user} value={praticien.id_user}>{praticien.nom_user}</Option>
        )}
    </Select>
    <DragAndDropCalendar
        selectable
        localizer={localizer}
        events={this.state.events}
        views={['month','week','day']}
        defaultView="week"
        culture = 'fr'
    />
    <Popup ref={this.ModalAjoutb} id_user={this.state.id_user} events={this.state.events} />
</div>
);
}}
</code>```

My code of dialog is :

```<code>export default class Popup extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
}}
handleAjouterb = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user,
    }, () => {
        this.fetchingPopup(this.state.id_user, this.state.identifiant_user, this.state.nom_user)
    });
  }
fetchingPopup = (id_user, identifiant_user, nom_user) =>{
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(id_user === praticiensCached[j].id_user){
        identifiant_user = praticiensCached[j].identifiant_user;
        this.setState ({ nom_user: praticiensCached[j].nom_user })
    }
}
handleValider = event => {
    event.preventDefault();
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(this.state.id_user === praticiensCached[j].id_user)
        this.state.identifiant_user = praticiensCached[j].identifiant_user;
    }

      const formData = new FormData();

      formData.append('identifiant_user', this.state.identifiant_user);
      formData.append('heuredebut', this.state.tranchesC[0].startC);
      formData.append('heurefin', this.state.tranchesC[0].endC);
      formData.append('libelleconge', this.state.libelle);
      axios({
        method: 'post',
        url: process.env.REACT_APP_API_BACKEND+'add_event_docteur',
        data: formData,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        }
      })
      .then(() => {
        fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning/start='+moment().startOf('isoweek').subtract(14,'days').toJSON()+'&end='+moment().endOf('isoweek').add(2,'months').toJSON()+'&identifiant_user='+this.state.identifiant_user)
          .then(Response => Response.json())
          .then(data => {
            let evts = data.ListeResult;
            for (let i = 0; i < evts.length; i++) {
              evts[i].start = moment(evts[i].start).toDate();
              evts[i].end = moment(evts[i].end).toDate();
              this.state.events.push(evts[i])
            }
            this.setState({
              events:  this.state.events
            }, ()=> {
              localStorage.setItem('Liste récente de planning de ' + this.state.nom_user, JSON.stringify(this.state.events));
              localStorage.removeItem("Liste de planning de " + this.state.nom_user);
              localStorage.setItem("Liste de planning de " + this.state.nom_user, JSON.stringify(this.state.events));
            })
          })
       })
}

render() {

    return (
<div>
    <Dialog
        icon="application"
        onClose={this.handleClose}
        title="Organisation des plannings du docteur"
        {...this.state}
        isOpen={this.state.openPopupAjout}>
           <Input id="libelle" style={{ width: '480px' }} value={this.state.libelle} onChange={this.handleInputChange('libelle')}/>
            <label className="pt-label .modifier"><strong>Date</strong></label>
            <LocaleProvider locale={fr_FR}>
                <RangePicker id="date" name= "date"  locale="fr" placeholder={["Date de début","Date de fin"]} separator="-" onChange={this.handleDateCChange}
                    value={this.state.dateIC} format="DD/MM/YYYY" allowClear={false}/>
            </LocaleProvider>
            <label className="pt-label .modifier"> <strong>Heure de début</strong></label>
            <Time value={el.startC} onChange={time => this.handleKeyboardStartCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton   onClick={() => this.openDialogC(i, el.startC, "startC")}><i  style={{fontSize:'18px'}} className="zmdi zmdi-alarm" /></IconButton>  </InputAdornment>}
            />
            <label className="pt-label .modifier"> <strong>Heure de fin</strong></label>
            <Time value={el.endC} onChange={time => this.handleKeyboardEndCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton  onClick={() => this.openDialogC(i, el.endC, "endC")}><i  style={{fontSize:'18px'}} className="zmdi zmdi-alarm" /></IconButton></InputAdornment> }/>

            <Clock maxWidth="xs" open={this.state.isOpenC} onBackdropClick={this.closeDialogC}>
            <TimePicker  mode="24h" value={this.createDateFromTextValueC(this.state.datePickerValueC)} onChange={this.handleDialogCChange}/>
            <DialogActions> <ButtonOk onClick={this.closeDialogC} color="primary"> Ok </ButtonOk></DialogActions>
            </Clock>
                <AnchorButton style={{display:'inline-block'}} intent={Intent.SUCCESS} onClick={this.handleValider}>Valider</AnchorButton>

</div>
);
}}
</code>```

I want to refresh the list of my events and appear my  event added on the calendar afer post form on the popup and not after the  refresh of the page and I will reselect the doctor.

How can I fix it ?

答:
Are you looking for something like this</p>

```<code>class ComponentB extends React.Component{
  render(){
    this.props.setInLocalStorage();
    const value = localStorage.getItem("testA");
    return <div>
  This is componentB{value}
  </div>}
}
class ComponentA extends React.Component{
 setInLocalStorage = ()=>{
   localStorage.setItem('testA', 'Hello');
}
render(){
  return <ComponentB setInLocalStorage={this.setInLocalStorage}/>
}
}

</code>```

Body:
I have a react-big-calendar (The parent container), I have also a select which, the events of the calendar are fetched according to this select ( doctor name ) and I have a button when I click on it, the dialog will be appears (another component), on this dialog, I have a form to add an event after the select, when I post my API, I save it on local storage, but the event added doesn't appears on my calendar just after refresh the page and reselect the doctor name.
But I want, when I click on the save button, will be added directly on the calendar and it will be appeared on the calendar.

My code of calendar is :

   import Popup from './Popup';
export default class Calendar extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
      open: false,
}}
componentDidMount = () => {
    fetch(process.env.REACT_APP_API_BACKEND_YET+'get_liste_praticien.php')
      .then(Response => Response.json())
      .then(data => {
        this.setState ({ praticiens : data })
        localStorage.setItem('Liste de praticiens ', JSON.stringify(this.state.praticiens))
    })
}
fetchData = (nom,identifiant_user) => {
    this.setState({
      events: [],
      evtStorage:[],
      prevEvents:[],
      evtBackend:[]
    })
      fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning')
        .then(Response => Response.json())
        .then(data => {
          let evts = data.ListeResult;
          for (let i = 0; i < evts.length; i++) {
            evts[i].start = moment(evts[i].start).toDate();
            evts[i].end = moment(evts[i].end).toDate();
           if(evts[i].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evts[i])
          }
          this.setState({
            evtBackend: evts,
            events:  evts
          })
          localStorage.setItem("Liste de planning de " + nom, JSON.stringify(this.state.events));
        })
        const evtCached1 = JSON.parse(localStorage.getItem('Liste récente de planning de ' + nom));
        if(evtCached1 !== null) {
          for (let j = 0; j < evtCached1.length; j++) {
            evtCached1[j].start = moment(evtCached1[j].start).toDate();
            evtCached1[j].end = moment(evtCached1[j].end).toDate();
            if(evtCached1[j].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evtCached1[j]);
          }
          this.setState({
            events:this.state.events,
          });
          localStorage.removeItem("Liste de planning de " + nom);
        }}
// For the select
handlePraticienChange = id_user => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    },() => {
      this.state.praticiens.map((praticien)=> {
          if(this.state.id_user === praticien.id_user){
            this.setState ({ nom_user: praticien.nom_user})
           this.fetchData(praticien.nom_user, praticien.identifiant_user);
          }
      })
      }
    );
  }
// for the popup
 ModalAjoutb = (ref) => {
    if (ref) {
      this.ajoutb = ref.handleAjouterb;
    } else {
      this.ajoutb = null;
    }
  }
render() {

    return (

    <button className="bp3-button bp3-icon-add-to-artifact .bp3-fill" tabIndex="0" onClick={() => this.ajoutb(this.state.id_user, this.state.events)}>Add event</button>
    <Select  onChange={this.handlePraticienChange} value={this.state.id_user}>
        {this.state.praticiens.map((praticien) =>
            <Option key={praticien.id_user} value={praticien.id_user}>{praticien.nom_user}</Option>
        )}
    </Select>
    <DragAndDropCalendar
        selectable
        localizer={localizer}
        events={this.state.events}
        views={['month','week','day']}
        defaultView="week"
        culture = 'fr'
    />
    <Popup ref={this.ModalAjoutb} id_user={this.state.id_user} events={this.state.events} />

);
}}

My code of dialog is :

export default class Popup extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
}}
handleAjouterb = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user,
    }, () => {
        this.fetchingPopup(this.state.id_user, this.state.identifiant_user, this.state.nom_user)
    });
  }
fetchingPopup = (id_user, identifiant_user, nom_user) =>{
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(id_user === praticiensCached[j].id_user){
        identifiant_user = praticiensCached[j].identifiant_user;
        this.setState ({ nom_user: praticiensCached[j].nom_user })
    }
}
handleValider = event => {
    event.preventDefault();
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(this.state.id_user === praticiensCached[j].id_user)
        this.state.identifiant_user = praticiensCached[j].identifiant_user;
    }

      const formData = new FormData();

      formData.append('identifiant_user', this.state.identifiant_user);
      formData.append('heuredebut', this.state.tranchesC[0].startC);
      formData.append('heurefin', this.state.tranchesC[0].endC);
      formData.append('libelleconge', this.state.libelle);
      axios({
        method: 'post',
        url: process.env.REACT_APP_API_BACKEND+'add_event_docteur',
        data: formData,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        }
      })
      .then(() => {
        fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning/start='+moment().startOf('isoweek').subtract(14,'days').toJSON()+'&end='+moment().endOf('isoweek').add(2,'months').toJSON()+'&identifiant_user='+this.state.identifiant_user)
          .then(Response => Response.json())
          .then(data => {
            let evts = data.ListeResult;
            for (let i = 0; i < evts.length; i++) {
              evts[i].start = moment(evts[i].start).toDate();
              evts[i].end = moment(evts[i].end).toDate();
              this.state.events.push(evts[i])
            }
            this.setState({
              events:  this.state.events
            }, ()=> {
              localStorage.setItem('Liste récente de planning de ' + this.state.nom_user, JSON.stringify(this.state.events));
              localStorage.removeItem("Liste de planning de " + this.state.nom_user);
              localStorage.setItem("Liste de planning de " + this.state.nom_user, JSON.stringify(this.state.events));
            })
          })
       })
}

render() {

    return (

    <Dialog
        icon="application"
        onClose={this.handleClose}
        title="Organisation des plannings du docteur"
        {...this.state}
        isOpen={this.state.openPopupAjout}>
           <Input id="libelle" style={{ width: '480px' }} value={this.state.libelle} onChange={this.handleInputChange('libelle')}/>
            Date
            <LocaleProvider locale={fr_FR}>
                <RangePicker id="date" name= "date"  locale="fr" placeholder={["Date de début","Date de fin"]} separator="-" onChange={this.handleDateCChange}
                    value={this.state.dateIC} format="DD/MM/YYYY" allowClear={false}/>
            </LocaleProvider>
             Heure de début
            <Time value={el.startC} onChange={time => this.handleKeyboardStartCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton   onClick={() => this.openDialogC(i, el.startC, "startC")}></IconButton>  </InputAdornment>}
            />
             Heure de fin
            <Time value={el.endC} onChange={time => this.handleKeyboardEndCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton  onClick={() => this.openDialogC(i, el.endC, "endC")}></IconButton></InputAdornment> }/>

            <Clock maxWidth="xs" open={this.state.isOpenC} onBackdropClick={this.closeDialogC}>
            <TimePicker  mode="24h" value={this.createDateFromTextValueC(this.state.datePickerValueC)} onChange={this.handleDialogCChange}/>
            <DialogActions> <ButtonOk onClick={this.closeDialogC} color="primary"> Ok </ButtonOk></DialogActions>
            </Clock>
                <AnchorButton style={{display:'inline-block'}} intent={Intent.SUCCESS} onClick={this.handleValider}>Valider</AnchorButton>

);
}}

I want to refresh the list of my events and appear my  event added on the calendar afer post form on the popup and not after the  refresh of the page and I will reselect the doctor.

How can I fix it ?

Body:
Are you looking for something like this

class ComponentB extends React.Component{
  render(){
    this.props.setInLocalStorage();
    const value = localStorage.getItem("testA");
    return <div>
  This is componentB{value}
  </div>}
}
class ComponentA extends React.Component{
 setInLocalStorage = ()=>{
   localStorage.setItem('testA', 'Hello');
}
render(){
  return <ComponentB setInLocalStorage={this.setInLocalStorage}/>
}
}


问:
Searching for literal string with Select-String and extracting part of string
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

```<code> Select-String -Path C:\file.inf -Pattern "$DeviceID"
</code>```

But it won't take the string as is, it's having a problem with the "\V":

```
Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand
```

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

答:
Select-String, by default, uses the .NET regex engine. To do simple string matching, use the -SimpleMatch switch parameter:

```<code>Select-String -Path C:\file.inf -pattern "$DeviceID" -SimpleMatch
</code>```

Body:
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

 Select-String -Path C:\file.inf -Pattern "$DeviceID"

But it won't take the string as is, it's having a problem with the "\V":

Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

Body:
Select-String, by default, uses the .NET regex engine. To do simple string matching, use the -SimpleMatch switch parameter:

Select-String -Path C:\file.inf -pattern "$DeviceID" -SimpleMatch


问:
Are there git hub projects available for reference to bring existing user Db to identity server 4? If there is one, point me to that
I have users Db built in Sql server and Have lot of columns based on application requirements. How do i use this users table in Identity server 4? Are there any git hub reference project to do this?</p>

答:
Create your own user class by inheriting from IdentityUser. There you can add your own properties and override the existing ones (to map them to your column names).

```<code>public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        IsActive = true;
    }

    // these two properties are your custom ones
    public int? StaffId { get; set; }
    public bool IsActive { get; set; }

    // here you map an Identity property to a column you already have
    [Column("LockoutEndDateUtc")]
    public override DateTimeOffset? LockoutEnd { get; set; }
}
</code>```

Body:
Create your own user class by inheriting from IdentityUser. There you can add your own properties and override the existing ones (to map them to your column names).

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        IsActive = true;
    }

    // these two properties are your custom ones
    public int? StaffId { get; set; }
    public bool IsActive { get; set; }

    // here you map an Identity property to a column you already have
    [Column("LockoutEndDateUtc")]
    public override DateTimeOffset? LockoutEnd { get; set; }
}


问:
How to pass custom model build in cross_val_predict
I want to do xgboost survival model with output_margin = True in predict. However, sklearn don't have any method to pass new parameters for predict, but it does have it for fit.

so i have written following class

```<code>class PredictWithOutputMargin:
    def __init__(self, model):
        self.model = model

    def predict(self, X):
        return self.model.predict(self, X, output_margin=True)

    def fit(self, X, y, **kwargs):
        return self.model.fit(X, y, **kwargs)

    def get_params(self, deep = False):
        return self.model.get_params(deep)
</code>```

then I am passing it to

```<code>from sklearn.model_selection import cross_val_predict as cvp

model = PredictWithOutputMargin(model_instance)
cv_score = cvp(model, train_x, train_y, cv=cv, n_jobs=-1, method=method)
</code>```

Here method is predict and cv is 5.

However, when I run code I get following error.

TypeError: __init__() got an unexpected keyword argument 'base_score'

Any idea how to pass it ?

答:
Most likely (in the absence of the full error dump it is just a guess) the problem is in the implementation of clone in sklearn. This function is used by the cross validation function to create copies of the input model and use those to spawn training in parallel threads. The way clone works is that it retrieves all parameters from the model and creates an object of the same type with those parameters (see here). So in your case it tries to call PredictWithOutputMargin(parameters_of_sklearn_model), which does to match your constructor.

I guess, the way to overcome this particular issue is to return {'mode': self.model} in PredictWithOutputMargin.get_params(). But I do not know if this will generate problems somewhere on another stage.

Body:
I want to do xgboost survival model with output_margin = True in predict. However, sklearn don't have any method to pass new parameters for predict, but it does have it for fit.

so i have written following class

class PredictWithOutputMargin:
    def __init__(self, model):
        self.model = model

    def predict(self, X):
        return self.model.predict(self, X, output_margin=True)

    def fit(self, X, y, **kwargs):
        return self.model.fit(X, y, **kwargs)

    def get_params(self, deep = False):
        return self.model.get_params(deep)

then I am passing it to

from sklearn.model_selection import cross_val_predict as cvp

model = PredictWithOutputMargin(model_instance)
cv_score = cvp(model, train_x, train_y, cv=cv, n_jobs=-1, method=method)

Here method is predict and cv is 5.

However, when I run code I get following error.

TypeError: __init__() got an unexpected keyword argument 'base_score'

Any idea how to pass it ?


问:
Explicit Log Level instead of MinimumLevel for Serilog
Is there any way I can configure exactly ONE log level per file in serilog?

I know I can configure one file per "MinimumLevel", but that is not what I need.

答:
I had a similar requirement. After some research, I added the following in the Startup class of my .net core 2.2 web api:

```<code>Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error)
        .WriteTo.RollingFile("C:\\Temp\\erros-logs.txt"))
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information)
        .WriteTo.RollingFile("C:\\Temp\\info-logs.txt"))
    .CreateLogger();
</code>```

If you are reading the settings from appsettings.json file and you want to use the above, you should transfer your logic from the file.

My answer is heavily inspired from the following post:
Restrict to level

Body:
I had a similar requirement. After some research, I added the following in the Startup class of my .net core 2.2 web api:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error)
        .WriteTo.RollingFile("C:\\Temp\\erros-logs.txt"))
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information)
        .WriteTo.RollingFile("C:\\Temp\\info-logs.txt"))
    .CreateLogger();

If you are reading the settings from appsettings.json file and you want to use the above, you should transfer your logic from the file.

My answer is heavily inspired from the following post:
Restrict to level


答:
Code:

```<code>jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

res = {}
for name, length in jumps:
    res[name] = [length] if name not in res else res[name] + [length]
avg_results = {k: sum(v) / len(v) for k, v in res.items()}
</code>```

Output:

```<code>{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}
</code>```

Title: Convert the tuples in a list to a dictionary and calculate the frequency

Body:
Code:

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

res = {}
for name, length in jumps:
    res[name] = [length] if name not in res else res[name] + [length]
avg_results = {k: sum(v) / len(v) for k, v in res.items()}

Output:

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}


问:
How to handle post a BigInteger in JSONObject in grails controller?
Here is my example:

```<code>class MyController {

    def index() {
        JSONObject json = request.JSON
        log.info('{}', json)
        respond json
    }

}
</code>```

How do I handle BigInteger in json? like this:

```<code>curl -H 'content-type: application/json' -d '{"largeNum": 99999999999999999999999}' http://localhost:8080/
</code>```

The JSONObject will conver this largeNum to Double like this:

```<code>{"largeNum":9.999999999999999E22}
</code>```

But I want to get a BigInteger, how to?

答:
Thank you guys. I push a PR to solve this issue: https://github.com/grails/grails-core/pull/11334

Waiting the upstream to be merged.

Body:
Here is my example:

class MyController {

    def index() {
        JSONObject json = request.JSON
        log.info('{}', json)
        respond json
    }

}

How do I handle BigInteger in json? like this:

curl -H 'content-type: application/json' -d '{"largeNum": 99999999999999999999999}' http://localhost:8080/

The JSONObject will conver this largeNum to Double like this:

{"largeNum":9.999999999999999E22}

But I want to get a BigInteger, how to?


问:
In which cases avplayer should play? Like play() function, set player rate
I set player to pause and i am setting player rate after the pause. After setting player rate avplayer starting the playing without play() method, so i want to know in which other cases that avplayer should play without play() method.

I find that when we set rate or seek to specific time than it is play but i want to know is there other cases when avplayer should play.

答: Please check https://github.com/teamSolutionAnalysts/sa-plug-avplayer which is very easy plug and play module, lets you play video easily and you tube embedded url supported.</p>


问:
Android ROOM save Map<String, Object>
I have a model like that

```<code>@Entity(tableName = "allrates")
class Data(
        @ColumnInfo(name = "rates")
        @SerializedName("rates")
        @Expose
        var rates: Map<String, Rates>,

        @ColumnInfo(name = "start")
        @SerializedName("start_at")
        @Expose
        var startDate: String,

        @ColumnInfo(name = "end")
        @SerializedName("end_at")
        @Expose
        var endDate: String,

        @SerializedName("base")
        @Expose
        var base: String,

        @PrimaryKey(autoGenerate = true)
        var id: Int
)
</code>```

And my problem is when I trying to insert in the database, doesn't show me any error but when I do the ´get´ is always returning me a null. So probably, my problem is in the ´Converter´ but I not sure about that.

And this is my converter

```<code>class mapConverter {
    @TypeConverter
    fun fromString(value: String): Map<String, Rates> {
        val mapType = object : TypeToken<Map<String, Rates>>() {

        }.type
        return Gson().fromJson(value, mapType)
    }

    @TypeConverter
    fun fromStringMap(map: Map<String, Rates>): String {
        val gson = Gson()
        return gson.toJson(map)
    }
}
</code>```

And here goes the DAO

```<code>@Dao
abstract class RatesDao {

    @Query("SELECT * FROM allrates")
    abstract fun loadRates(): LiveData<Data>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract fun insertRates(rates: Data)
}
</code>```

Connexion with ROOM

```<code>@Database(entities = [(Data::class)], version = 1, exportSchema = false)
@TypeConverters(mapConverter::class)
abstract class AppDatabase : RoomDatabase() {

    companion object {
        private var sInstance: AppDatabase? = null
        private const val DATABASE_NAME: String = "RatesList"

        fun getInstance(context: Context): AppDatabase {
            if (sInstance == null) {
                synchronized(AppDatabase::class) {
                    sInstance = Room.databaseBuilder(context.applicationContext,
                            AppDatabase::class.java, DATABASE_NAME)
                            .build()
                }
            }
            return sInstance as AppDatabase
        }
    }

    abstract fun ratesDao(): RatesDao
}
</code>```

答:
You are writing your code in Kotlin, so add this line @JvmStatic to MapConverter class as follows:

```<code>class  MapConverter {
    companion object{
        @JvmStatic
        @TypeConverter
        fun fromString(value: String): Map<String, String> {
            val mapType = object : TypeToken<Map<String, String>>() {}.type
            return Gson().fromJson(value, mapType)
        }
        @TypeConverter
        @JvmStatic
        fun fromStringMap(map: Map<String, String>): String {
            val gson = Gson()
            return gson.toJson(map)
        }
    }
}
</code>```

Title: Android ROOM save Map<String, Object>

Body:
I have a model like that

@Entity(tableName = "allrates")
class Data(
        @ColumnInfo(name = "rates")
        @SerializedName("rates")
        @Expose
        var rates: Map<String, Rates>,

        @ColumnInfo(name = "start")
        @SerializedName("start_at")
        @Expose
        var startDate: String,

        @ColumnInfo(name = "end")
        @SerializedName("end_at")
        @Expose
        var endDate: String,

        @SerializedName("base")
        @Expose
        var base: String,

        @PrimaryKey(autoGenerate = true)
        var id: Int
)

And my problem is when I trying to insert in the database, doesn't show me any error but when I do the ´get´ is always returning me a null. So probably, my problem is in the ´Converter´ but I not sure about that.

And this is my converter

class mapConverter {
    @TypeConverter
    fun fromString(value: String): Map<String, Rates> {
        val mapType = object : TypeToken<Map<String, Rates>>() {

        }.type
        return Gson().fromJson(value, mapType)
    }

    @TypeConverter
    fun fromStringMap(map: Map<String, Rates>): String {
        val gson = Gson()
        return gson.toJson(map)
    }
}

And here goes the DAO

@Dao
abstract class RatesDao {

    @Query("SELECT * FROM allrates")
    abstract fun loadRates(): LiveData<Data>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract fun insertRates(rates: Data)
}

Connexion with ROOM

@Database(entities = [(Data::class)], version = 1, exportSchema = false)
@TypeConverters(mapConverter::class)
abstract class AppDatabase : RoomDatabase() {

    companion object {
        private var sInstance: AppDatabase? = null
        private const val DATABASE_NAME: String = "RatesList"

        fun getInstance(context: Context): AppDatabase {
            if (sInstance == null) {
                synchronized(AppDatabase::class) {
                    sInstance = Room.databaseBuilder(context.applicationContext,
                            AppDatabase::class.java, DATABASE_NAME)
                            .build()
                }
            }
            return sInstance as AppDatabase
        }
    }

    abstract fun ratesDao(): RatesDao
}

Body:
You are writing your code in Kotlin, so add this line @JvmStatic to MapConverter class as follows:

class  MapConverter {
    companion object{
        @JvmStatic
        @TypeConverter
        fun fromString(value: String): Map<String, String> {
            val mapType = object : TypeToken<Map<String, String>>() {}.type
            return Gson().fromJson(value, mapType)
        }
        @TypeConverter
        @JvmStatic
        fun fromStringMap(map: Map<String, String>): String {
            val gson = Gson()
            return gson.toJson(map)
        }
    }
}


问:
Xamarin Forms Collection view ItemsSource Binding not updating the UI
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

```<code>    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }
</code>```

View Model Property which is using for ItemsSource Binding:

```<code>   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }
</code>```

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.

答: In this case try to extend the MainPage from INotifyPropertyChanged and instead of RaisePropertyChanged("CountryNames") in set property, use OnPropertyChanged()

Body:
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }

View Model Property which is using for ItemsSource Binding:

   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.


问:
How to add my own image with message like emoticons
okay...

I have asked this question about this but there is a new thing that i want to ask..

like emoticons I want to add my own image  with the iphone message ...

I am thankful if anybody can give me the idea about how to do this???

is this possible??

答: You can't control the behavior of the Mail application. You cannot achieve this behavior unless you are providing your own email entry form.</p>

ContentLicense: CC BY-SA 3.0


问:
Why isn't the code working (here) when I try to change values of a list using 'for' loop?
Let's say there's this random list:

```<code>st=['smthg','xyz','random','000','666']
</code>```

I want to change the values of the indices 1 to 3 using this for loop:

```<code>for anythg in st:
      st[1:3]='whtevr'
</code>```

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

```<code>'t','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',
</code>```

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

```<code>for i in range(1,4):
    st[i]='whtevr'
</code>```

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

答:
When assigning a value to a list slice, it expects the right hand expression to be an iterable. And it then replaces that slice with the iterable. When you try assigning a string, it is treated as a list of characters.

For example,

```<code>l = [1,2,3,4,5]
l[1:3] = 'abc'
print(l)
# [1, 'a', 'b', 'c', 4, 5]
</code>```

In your case, this insertion of 'whtevr' caused an infinite loop.

Body:
Let's say there's this random list:

st=['smthg','xyz','random','000','666']

I want to change the values of the indices 1 to 3 using this for loop:

for anythg in st:
      st[1:3]='whtevr'

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

't','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

for i in range(1,4):
    st[i]='whtevr'

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
When assigning a value to a list slice, it expects the right hand expression to be an iterable. And it then replaces that slice with the iterable. When you try assigning a string, it is treated as a list of characters.

For example,

l = [1,2,3,4,5]
l[1:3] = 'abc'
print(l)
# [1, 'a', 'b', 'c', 4, 5]

In your case, this insertion of 'whtevr' caused an infinite loop.


问:
PHPMailer and anonymous TLS connections
I'm using phpmailer to establish a TLS connection on port 25.
I cannot use a username/password, so it's a anonymous connection.

The server responds with the following:

```<code>250-SIZE
                                      250-PIPELINING
                                      250-DSN
                                      250-ENHANCEDSTATUSCODES
                                      250-XXXXXXXA
                                      250-XXXXXXXXXXXXXB
                                      250-AUTH NTLM
                                      250-XXXXXXXXXXXXXXXXXC
                                      250-8BITMIME
                                      250-BINARYMIME
                                      250-XXXXXXXD
                                      250-XXXXXXE
                                      250-XXXXF
                                      250 XXXXXXG
</code>```

When the STARTTLS-command is sent by phpmailer, the server responds:

```<code>CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 500 5.3.3 Unrecognized command
SMTP ERROR: STARTTLS command failed: 500 5.3.3 Unrecognized command
</code>```

So apparently the anonymous TLS isn't offered by the server.
Strange thing is, if I connect to the server via telnet, it's working.

Is this a phpmailer-issue? Or just some strange behaviour of the server???

答:
Hope following hack will help you :)

Here is my PHPMailer object

```<code>$phpmailer
</code>```

Comment line

```<code>$phpmailer->SMTPSecure = 'tls';
</code>```

And add

```<code>$phpmailer->SMTPOptions = array(
    'ssl' => array(
        'verify_peer'       => false,
        'verify_peer_name'  => false,
        'allow_self_signed' => true
    )
);
</code>```

Title: PHPMailer and anonymous TLS connections

Body:
I'm using phpmailer to establish a TLS connection on port 25.
I cannot use a username/password, so it's a anonymous connection.

The server responds with the following:

250-SIZE
                                      250-PIPELINING
                                      250-DSN
                                      250-ENHANCEDSTATUSCODES
                                      250-XXXXXXXA
                                      250-XXXXXXXXXXXXXB
                                      250-AUTH NTLM
                                      250-XXXXXXXXXXXXXXXXXC
                                      250-8BITMIME
                                      250-BINARYMIME
                                      250-XXXXXXXD
                                      250-XXXXXXE
                                      250-XXXXF
                                      250 XXXXXXG

When the STARTTLS-command is sent by phpmailer, the server responds:

CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 500 5.3.3 Unrecognized command
SMTP ERROR: STARTTLS command failed: 500 5.3.3 Unrecognized command

So apparently the anonymous TLS isn't offered by the server.
Strange thing is, if I connect to the server via telnet, it's working.

Is this a phpmailer-issue? Or just some strange behaviour of the server???

Body:
Hope following hack will help you :)

Here is my PHPMailer object

$phpmailer

Comment line

$phpmailer->SMTPSecure = 'tls';

And add

$phpmailer->SMTPOptions = array(
    'ssl' => array(
        'verify_peer'       => false,
        'verify_peer_name'  => false,
        'allow_self_signed' => true
    )
);


问:
How can create and send a mail by python code without creating a mail template in xml in odoo
Is it possible to send an email without a mail template ? I need to send an email from python code without creating the mail template by xml.</p>

答:
Yes it is possible.You can pass the email values within the python code itself.</p>

```<code>values = {}
email_to = 'receiver mail id'
email_from = 'sender mail id'
values['email_to'] = email_to
values['email_from'] = email_from  // Not necessary
values['subject'] = YOUR MAIL SUBJECT
values['body'] = You Email Body
self.env['mail.mail'].sudo().create(values).send() // Creating and sendimg the mail.
</code>```

Body:
Yes it is possible.You can pass the email values within the python code itself.

values = {}
email_to = 'receiver mail id'
email_from = 'sender mail id'
values['email_to'] = email_to
values['email_from'] = email_from  // Not necessary
values['subject'] = YOUR MAIL SUBJECT
values['body'] = You Email Body
self.env['mail.mail'].sudo().create(values).send() // Creating and sendimg the mail.


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
Others already explained the finalize method.

Note however, that best practices is to design a "close"/ "clean-up"/ "termination" method to close/ clean-up the object and ask the developer to call this method explicitly. Finalizers should only be used as a safety net. (See "Item 7: Avoid finalizers" of "Effective Java" by Joshua Bloch)

Update:

In this case also consider to implement AutoCloseable to support try-with-resources blocks.


问:
Why isn't my css applied unless i clean browser cache?
I'm making a simple website for a school project. It was going well until i added php to the code. Now it doesn't want to apply my css changes every time for some reason. I validated html, css and php on some sites and everything seems to be clean. Then i came across a article that said i have to clear the cache for the css to get applied. It worked (using chrome) though now i have to clean it after every css change or it wont get applied. Only thing that is coming to my mind is that I'm working in PhpStorm but checking the code using xampp and not the PhpStorm built-in browsers, though it worked perfectly until the php. Is there a better way out then clearing cache after every single css change?</p>

答:
You could edit your server settings but I’d just get in a habit of doing a “Hard Refresh” instead of a refresh.

When developing websites I always use Hard Refresh over regular refresh to avoid something old getting pulled from the cache. Simply press Ctrl + shift + r for a hard refresh  or see the link above for a list of shortcuts on different systems and browsers.


问:
Wordpress changing themes based on user agent
I've created two seperate themes. One for mobile, one for desktop. I've managed to change the theme with the function shown below. Changing the theme works, but the function still loads the CSS, HTML, JS and PHP code from the original and main theme.

Both the desktop and mobile theme have the same file structure and linking.

The folder structure is as follows

```<code>project
      |
      wp_content
               |
               themes
                    |
                    desktop
                    mobile
</code>```

function change_theme($current_theme)
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'CostumizedAgent') !== false) {
        return 'mobile';
    } else {
        return $current_theme;
    }
}
add_filter('stylesheet', 'change_theme');
add_filter('template', 'change_theme');
```

I'd expect to load the themes actual files, not the files from the main theme. Any suggestions?

答:
Try this. wp_is_mobile() function helps to detect device</p>

```<code>add_filter('body_class','mobile_theme_body_class');
function mobile_theme_body_class( $classes ){
    if ( wp_is_mobile() ){
        return 'mobile';
    } else {
        return 'desktop';
    }
    return $classes;
}
</code>```

Body:
I've created two seperate themes. One for mobile, one for desktop. I've managed to change the theme with the function shown below. Changing the theme works, but the function still loads the CSS, HTML, JS and PHP code from the original and main theme.

Both the desktop and mobile theme have the same file structure and linking.

The folder structure is as follows

project
      |
      wp_content
               |
               themes
                    |
                    desktop
                    mobile

function change_theme($current_theme)
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'CostumizedAgent') !== false) {
        return 'mobile';
    } else {
        return $current_theme;
    }
}
add_filter('stylesheet', 'change_theme');
add_filter('template', 'change_theme');

I'd expect to load the themes actual files, not the files from the main theme. Any suggestions?

Body:
Try this. wp_is_mobile() function helps to detect device

add_filter('body_class','mobile_theme_body_class');
function mobile_theme_body_class( $classes ){
    if ( wp_is_mobile() ){
        return 'mobile';
    } else {
        return 'desktop';
    }
    return $classes;
}


问:
How can I check the extension of a file?
I'm working on a certain program where I need to do different things depending on the extension of the file. Could I just use this?</p>

```<code>if m == *.mp3
   ...
elif m == *.flac
   ...
</code>```

答:
```<code>file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')
</code>```

Body:
I'm working on a certain program where I need to do different things depending on the extension of the file. Could I just use this?

if m == *.mp3
   ...
elif m == *.flac
   ...


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答: phimuemue's answer sums it up, I'll just add that, as a workaround, you can create a wrapper class that contains only one member - a pointer to c1, and then overload its operator <. Then you could sort a vector of object of that class.</p>

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !