问:
What is wrong with this x86 assembly bubble sort program?
I need to figure out why nothing is swapping in this program. The program obtains an integer array containing 4,5,1,3,2 from a separate C program and it will return it sorted.

I have tried modifying some of the jump commands but nothing has worked.

```<code>.global myarray

.data
myarray:
    lea (%rdi),%r8      #load array to register
    mov %rsi,%r12       #load array size to register
    mov $0,%r10             #initialize index
sort:
    mov (%r8, %r10, 8), %rax    #store array[i] in rax
    inc %r10            #i++
    mov (%r8, %r10, 8), %rdx    #store array[i+1] in rdx
    cmp %rax, %rdx      #see if rdx is less than rax
    jle swap            #if rdx < rax, swap them
swap:
    cmp %r12, %r10      #check if still in array bounds
    je  check           #if we are at the end, check if sorted
    dec %r10            #i--
    mov %rdx, (%r8, %r10, 8)    #move array[i+1] into array[i]
    inc %r10            #i++
    mov %rax, (%r8, %r10, 8)    #move array[i] into array[i+1]
    jmp     check
check:
    mov $0, %r14        #temporary index in r14
    mov (%r8, %r10, 8), %eax    #temporarily store array[i] in eax
    inc %r14            #i++
    mov (%r8, %r10, 8), %ebx    #temporarily store array[i+1] in ebx
    cmp %eax, %ebx      #check if ebx is less than eax
    jle sort            #if ebx < eax, swap
    cmp %r12, %r14      #check if still in array bounds
    ret
</code>```

Expected results are the array being returned sorted; 1,2,3,4,5

答:
```<code>mov %rsi,%r12           #load array size to register
mov $0,%r10             #initialize index
</code>```

In an array with 5 elements you can only compare 4 pairs. It would be convenient to decrement %r12. At the same time you'll have a way out for when the array has but 1 element:

```<code>mov %rsi,%r12             #load array size to register
dec %r12
jz  NothingToDo
mov $0,%r10               #initialize index
</code>```

```<code>cmp %rax, %rdx          #see if rdx is less than rax
jle swap                #if rdx < rax, swap them
swap:
</code>```

If LessOrEqual the jump goes to swap, but else the code falls through in swap. That makes no sense!

Below is the code that makes the biggest number bubble to the top.

```<code>sort:
    mov (%r8, %r10, 8), %rax    #store array[i] in rax
    inc %r10                    #i++
    mov (%r8, %r10, 8), %rdx    #store array[i+1] in rdx
    cmp %rdx, %rax
    jle NoSwap
    dec %r10                    #i--
    mov %rdx, (%r8, %r10, 8)    #move array[i+1] into array[i]
    inc %r10                    #i++
    mov %rax, (%r8, %r10, 8)    #move array[i] into array[i+1]
NoSwap:
    cmp %r12, %r10              #check if still in array bounds
    jb  sort
</code>```

This inner loop code must be repeated a number of times but each time you lower the limit in %r12. (*)

```<code>jmp     check
check:
</code>```

This too is a useless jmp!

```<code>check:
mov $0, %r14        #temporary index in r14
mov (%r8, %r10, 8), %eax    #temporarily store array[i] in eax
inc %r14            #i++
mov (%r8, %r10, 8), %ebx    #temporarily store array[i+1] in ebx
cmp %eax, %ebx      #check if ebx is less than eax
jle sort            #if ebx < eax, swap
cmp %r12, %r14      #check if still in array bounds
</code>```

And this part of the code can not be salvaged. What happens here is beyond comprehension.

(*)

```<code>    mov     %rdi,%r8
    mov     %rsi,%r12
    dec     %r12
    jz      NothingToDo
OuterLoop:
    mov     $0,%r10
    ...
    dec     %r12
    jnz     OuterLoop
NothingToDo:
    ret
</code>```

Body:
I need to figure out why nothing is swapping in this program. The program obtains an integer array containing 4,5,1,3,2 from a separate C program and it will return it sorted.

I have tried modifying some of the jump commands but nothing has worked.

.global myarray

.data
myarray:
    lea (%rdi),%r8      #load array to register
    mov %rsi,%r12       #load array size to register
    mov $0,%r10             #initialize index
sort:
    mov (%r8, %r10, 8), %rax    #store array[i] in rax
    inc %r10            #i++
    mov (%r8, %r10, 8), %rdx    #store array[i+1] in rdx
    cmp %rax, %rdx      #see if rdx is less than rax
    jle swap            #if rdx < rax, swap them
swap:
    cmp %r12, %r10      #check if still in array bounds
    je  check           #if we are at the end, check if sorted
    dec %r10            #i--
    mov %rdx, (%r8, %r10, 8)    #move array[i+1] into array[i]
    inc %r10            #i++
    mov %rax, (%r8, %r10, 8)    #move array[i] into array[i+1]
    jmp     check
check:
    mov $0, %r14        #temporary index in r14
    mov (%r8, %r10, 8), %eax    #temporarily store array[i] in eax
    inc %r14            #i++
    mov (%r8, %r10, 8), %ebx    #temporarily store array[i+1] in ebx
    cmp %eax, %ebx      #check if ebx is less than eax
    jle sort            #if ebx < eax, swap
    cmp %r12, %r14      #check if still in array bounds
    ret

Expected results are the array being returned sorted; 1,2,3,4,5

Body:
mov %rsi,%r12           #load array size to register
mov $0,%r10             #initialize index

In an array with 5 elements you can only compare 4 pairs. It would be convenient to decrement %r12. At the same time you'll have a way out for when the array has but 1 element:

mov %rsi,%r12             #load array size to register
dec %r12
jz  NothingToDo
mov $0,%r10               #initialize index

cmp %rax, %rdx          #see if rdx is less than rax
jle swap                #if rdx < rax, swap them
swap:

If LessOrEqual the jump goes to swap, but else the code falls through in swap. That makes no sense!

Below is the code that makes the biggest number bubble to the top.

sort:
    mov (%r8, %r10, 8), %rax    #store array[i] in rax
    inc %r10                    #i++
    mov (%r8, %r10, 8), %rdx    #store array[i+1] in rdx
    cmp %rdx, %rax
    jle NoSwap
    dec %r10                    #i--
    mov %rdx, (%r8, %r10, 8)    #move array[i+1] into array[i]
    inc %r10                    #i++
    mov %rax, (%r8, %r10, 8)    #move array[i] into array[i+1]
NoSwap:
    cmp %r12, %r10              #check if still in array bounds
    jb  sort

This inner loop code must be repeated a number of times but each time you lower the limit in %r12. (*)

jmp     check
check:

This too is a useless jmp!

check:
mov $0, %r14        #temporary index in r14
mov (%r8, %r10, 8), %eax    #temporarily store array[i] in eax
inc %r14            #i++
mov (%r8, %r10, 8), %ebx    #temporarily store array[i+1] in ebx
cmp %eax, %ebx      #check if ebx is less than eax
jle sort            #if ebx < eax, swap
cmp %r12, %r14      #check if still in array bounds

And this part of the code can not be salvaged. What happens here is beyond comprehension.

(*)

    mov     %rdi,%r8
    mov     %rsi,%r12
    dec     %r12
    jz      NothingToDo
OuterLoop:
    mov     $0,%r10
    ...
    dec     %r12
    jnz     OuterLoop
NothingToDo:
    ret


来源: stackexchange

问:
How does comparing two chars (within a string) work in Python
I am starting to learn Python and looked at following website: https://www.w3resource.com/python-exercises/string/
I work on #4 which is "Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself."

```<code>str="restart"
char=str[0]
print(char)

strcpy=str
i=1
for i in range(len(strcpy)):
  print(strcpy[i], "\n")
  if strcpy[i] is char:
    strcpy=strcpy.replace(strcpy[i], '$')
print(strcpy)
</code>```

I would expect "resta$t" but the actual result is: $esta$t

Thank you for your help!

答:
There are two issues, first, you are not starting iteration where you think you are:

i = 1 # great, i is 1
for i in range(5):
    print(i)
0
1
2
3
4
```

<p><code>i</code> has been overwritten by the value tracking the loop. </p>

<p>Second, the <code>is</code> does not mean value equivalence. That is reserved for the <code>==</code> operator. Simpler types such as <code>int</code> and <code>str</code> can make it seem like <code>is</code> works in this fashion, but other types do not behave this way:</p>

<pre class="lang-py prettyprint-override"><code>a, b = 5, 5

a is b
True

a, b = "5", "5"
a is b
True

a==b
True

### This doesn't work
a, b = [], []

a is b
False

a == b
True
</code>```

As @Kevin pointed out in the comments, 99% of the time, is is not the operator you want.

As far as your code goes, str.replace will replace all instances of the argument supplied with the second arg, unless you give it an optional number of instances to replace. To avoid replacing the first character, grab the first char separately, like val = somestring[0], then replace the rest using a slice, no need for iteration:

somestr = 'restart' # don't use str as a variable name

val = somestr[0] # val is 'r'

# somestr[1:] gives 'estart'
x = somestr[1:].replace(val, '$')

print(val+x)
# resta$t
```

<p>If you still want to iterate, you can do that over the slice as well:</p>

<pre class="lang-py prettyprint-override"><code># collect your letters into a list
letters = []
char = somestr[0]

for letter in somestr[1:]: # No need to track an index here
    if letter == char: # don't use is, use == for value comparison
       letter = '$' # change letter to a different value if it is equal to char
    letters.append(letter)

# Then use join to concatenate back to a string
print(char + ''.join(letters))
# resta$t
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am starting to learn Python and looked at following website: https://www.w3resource.com/python-exercises/string/
I work on #4 which is "Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself."

str="restart"
char=str[0]
print(char)

strcpy=str
i=1
for i in range(len(strcpy)):
  print(strcpy[i], "\n")
  if strcpy[i] is char:
    strcpy=strcpy.replace(strcpy[i], '$')
print(strcpy)

I would expect "resta$t" but the actual result is: $esta$t

Thank you for your help!

Body:
There are two issues, first, you are not starting iteration where you think you are:

i = 1 # great, i is 1
for i in range(5):
    print(i)
0
1
2
3
4

i has been overwritten by the value tracking the loop.

Second, the is does not mean value equivalence. That is reserved for the == operator. Simpler types such as int and str can make it seem like is works in this fashion, but other types do not behave this way:

a, b = 5, 5

a is b
True

a, b = "5", "5"
a is b
True

a==b
True

### This doesn't work
a, b = [], []

a is b
False

a == b
True

As @Kevin pointed out in the comments, 99% of the time, is is not the operator you want.

As far as your code goes, str.replace will replace all instances of the argument supplied with the second arg, unless you give it an optional number of instances to replace. To avoid replacing the first character, grab the first char separately, like val = somestring[0], then replace the rest using a slice, no need for iteration:

somestr = 'restart' # don't use str as a variable name

val = somestr[0] # val is 'r'

# somestr[1:] gives 'estart'
x = somestr[1:].replace(val, '$')

print(val+x)
# resta$t

If you still want to iterate, you can do that over the slice as well:

# collect your letters into a list
letters = []
char = somestr[0]

for letter in somestr[1:]: # No need to track an index here
    if letter == char: # don't use is, use == for value comparison
       letter = '$' # change letter to a different value if it is equal to char
    letters.append(letter)

# Then use join to concatenate back to a string
print(char + ''.join(letters))
# resta$t


问:
How can I account for user time-zone while displaying timestamps from a mySQL database?
I have a chat program where when a user sends a chat, an automatic time-stamp is created in mySQL. When the chat log is displayed, I need to adjust all of the time-stamps based on the time zone each user is in...

ie.

Someone in California sees:

```<code>Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 10:01 AM)
</code>```

Someone in Chicago sees:

```<code>Bob: Hi (May 30 2019 12:00 AM)
Rob: Bye (May 30 2019 12:01 AM)
</code>```

Meaning I can't store the timestamps in the database accounting for timezone, otherwise all users would see something like this:

(Assuming bob is in California and Rob is in Chicago, and the messages were sent 1 minutes apart)

```<code>Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 12:01 AM)
</code>```

So when I pull out my date/times, here is the php code I use:

```<code>if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    echo "<label style = 'font-size:1.1vw';>".date('M j Y g:i A', strtotime($row['time']))."</label>"."<br>";
}

} else {

}
$conn->close();
</code>```

A PHP solution would be most ideal for me, but I am open to implementing javascript or jQuery solutions as well.

(P.S - I have no idea what time zone mySQL is storing, but it is not my current time zone... so a time-offset solution that goes off of my current time zone needs some kind of a workaround).

答:
Presumably each user has a preferred timezone stored somewhere? Then it's a simple matter of adjusting at the database level using that value. You don't provide any sample code, but assuming you've got a user object with America/Los Angeles stored as their preferred timezone, you could do something like this:

```<code>SELECT message_body, CONVERT_TZ(message_time, 'SYSTEM', ?) AS message_time FROM messages;
</code>```

And pass in the current user's timezone as a parameter from PHP

Body:
I have a chat program where when a user sends a chat, an automatic time-stamp is created in mySQL. When the chat log is displayed, I need to adjust all of the time-stamps based on the time zone each user is in...

ie.

Someone in California sees:

Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 10:01 AM)

Someone in Chicago sees:

Bob: Hi (May 30 2019 12:00 AM)
Rob: Bye (May 30 2019 12:01 AM)

Meaning I can't store the timestamps in the database accounting for timezone, otherwise all users would see something like this:

(Assuming bob is in California and Rob is in Chicago, and the messages were sent 1 minutes apart)

Bob: Hi (May 30 2019 10:00 AM)
Rob: Bye (May 30 2019 12:01 AM)

So when I pull out my date/times, here is the php code I use:

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    echo "".date('M j Y g:i A', strtotime($row['time'])).""."
";
}

} else {

}
$conn->close();

A PHP solution would be most ideal for me, but I am open to implementing javascript or jQuery solutions as well.

(P.S - I have no idea what time zone mySQL is storing, but it is not my current time zone... so a time-offset solution that goes off of my current time zone needs some kind of a workaround).

Body:
Presumably each user has a preferred timezone stored somewhere? Then it's a simple matter of adjusting at the database level using that value. You don't provide any sample code, but assuming you've got a user object with America/Los Angeles stored as their preferred timezone, you could do something like this:

SELECT message_body, CONVERT_TZ(message_time, 'SYSTEM', ?) AS message_time FROM messages;

And pass in the current user's timezone as a parameter from PHP


问:
What is the best way to pass contextual information from a web app to bot-framework
I have a web application where users can raise or view IT tickets. I developed a chat bot using  Microsoft Bot Framework and C# to support specific cases. I embedded the bot with my website using an iframe from this documentation. Now i want to pass contextual information to my bot. For example when a user clicks on the web-chat i want to pass the user name and ticket it. What is the best way to do this?

I am aware that you can get specific channel data from several channels such as Slack or Facebook but is there a way to create my own custom channel?

答:
In WebChat v4 you can add data to any outgoing activity's channel data through a custom store middleware; however, this approach does not work with the embedded iFrame. You have to either use a CDN or React.

For more details, take at the Send Backchannel Welcome Event Web Chat sample and this StackOverflow Question.

Custom store without arrow functions

function(ref) {
  const dispatch = ref.dispatch;
  return function (next) {
    return function(action) {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
          dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
          });
        return next(action);
    }
  }
}
```


问:
Why doesn't readline() return original text?
I'm trying to read files and collect the data inside the files. I am looking inside my directory, moving towards the folder, and looking there.

I would like to read every line in the file.

I have read that my output looks like binary. I've tried looking around on stackoverflow. I have also made sure the file I am reading is a txt file.

```<code>import os

def ratio(filename):

    cwd = str(os.getcwd())
    cwd = cwd[:-8]
    cwd = cwd + "Equities\\" + str(filename) + ".txt"
    file = open(cwd, "r")
    line_1=str(file.readline(4))
    print(line_1)
</code>```

The readline(4) should return:

Current assets

My readline(4) function returns:

ÿþA\000

答:
If you are trying to read a specific line try:

```<code>lines=file.readlines()
text = lines[4]
</code>```

readline reads one line at a time. You can use readlines instead to read all the lines at once into a list.

As I mentioned in my comment readline(4) only reads 4 bytes from the first line, not the fourth line.

Body:
I'm trying to read files and collect the data inside the files. I am looking inside my directory, moving towards the folder, and looking there.

I would like to read every line in the file.

I have read that my output looks like binary. I've tried looking around on stackoverflow. I have also made sure the file I am reading is a txt file.

import os

def ratio(filename):

    cwd = str(os.getcwd())
    cwd = cwd[:-8]
    cwd = cwd + "Equities\\" + str(filename) + ".txt"
    file = open(cwd, "r")
    line_1=str(file.readline(4))
    print(line_1)

The readline(4) should return:

Current assets

My readline(4) function returns:

ÿþA\000

Body:
If you are trying to read a specific line try:

lines=file.readlines()
text = lines[4]

readline reads one line at a time. You can use readlines instead to read all the lines at once into a list.

As I mentioned in my comment readline(4) only reads 4 bytes from the first line, not the fourth line.


问:
Avoid UI locking/freezing when assigning datasource?
I'm using MVP pattern, so I have a View that has almost no logic in it and a Presenter that knows how to react to the user's interactions with the view.
Everytime I need to get data from a service or such my code does so asynchronously, the problem I'm having is that lets say I get 10,000 items that need to be databound to a Grid, when I assign those (marshalling them through the UI thread) my UI locks for short periods of time (because of the Grid control/CurrencyManager locking the thread I think)

Does anybody know possible ways to avoid this?

I've tried assigning the data in incremental chunks with a timer, but still ends making the UI freeze randomly

Cheers

答: You should use some sort of virtual data mode for your grid. This will remove such kind of problem definitively.</p>

ContentLicense: CC BY-SA 3.0


问:
How to use std::find to find a string from the first elements of a vector< pair < string, string > > type?
I tried the following code :

```<code>    auto it = find(v.begin(),v.end(), name, [](const pair<string, string> &a,const string b)
                           {
                               return a.first == b;
                           }); // name contains the string to find.
</code>```

But this gives me compilation error. Help me find out my mistake.

答:
The overload you are trying to call does not exist. You want to use find_if:</p>

```<code>auto it = std::find_if(v.begin(),v.end(), [&](const pair<string, string> &a)
{
    return a.first == name;
}); // name contains the string to find.
</code>```

Body:
I tried the following code :

    auto it = find(v.begin(),v.end(), name, [](const pair<string, string> &a,const string b)
                           {
                               return a.first == b;
                           }); // name contains the string to find.

But this gives me compilation error. Help me find out my mistake.

Body:
The overload you are trying to call does not exist. You want to use find_if:

auto it = std::find_if(v.begin(),v.end(), [&](const pair<string, string> &a)
{
    return a.first == name;
}); // name contains the string to find.


问:
Why is compare-and-swap (CAS) algorithm a good choice for lock-free synchronization?
CAS belongs to the read-modify-write (RMW) family, a set of algorithms that allow you to perform complex transactions atomically.

Specifically, Wikipedia says that

CAS is used to implement synchronization primitives like semaphores and mutexes, as well as more sophisticated lock-free and wait-free algorithms. [...] CAS can implement more of these algorithms than atomic read, write, or fetch-and-add, and assuming a fairly large amount of memory, [...] it can implement all of them.

https://en.wikipedia.org/wiki/Compare-and-swap#Overview

So it seems that a CAS algorithm is the "one size fits all" product of its category. Why is that so? What do other RMW algorithms lack of? If CAS is the best tool, what are the other algorithms for?

答:
CAS belongs to a class of objects called "consensus objects", each of which has a consensus number; the maximum number of threads for which a given consensus object can solve the consensus problem.

The consensus problem goes like this: for some number of threads n, propose some value p and decide on one of the proposed values d such that n threads agrees on d.

CAS is the most "powerful" consensus object because its consensus number is infinite. That is, CAS can be used to solve the consensus problem among a theoretically infinite number of threads. It even does it in a wait-free manner.

This can't be done with atomic registers, test-and-set, fetch-add, stacks since they all have finite consensus numbers. There are proofs for these consensus numbers but that is another story...

The significance of all of this is that it can be proven that there exists a wait-free implementation of an object for n threads using a consensus object with a consensus number of at least n. CAS is especially powerful because you can use it to implement wait-free objects for an arbitrary number of threads.

As to why other RMW operations are useful? Some problems in multiprocessing don't really involve solving the consensus problem for some arbitrary number of threads. For example, mutual exclusion can be solved using less powerful RMW operations like test-and-set (a simple TAS lock), fetch-add (ticket lock) or atomic swap (CLH lock).

More information on consensus for shared memory at Wikipedia Consensus (computer_science) section: In_shared-memory_systems

Also, there's a whole chapter on consensus and universal constructions in Herlihy and Shavit's The Art of Multiprocessor Programming (WorldCat) that I highly recommend.


问:
how to create a rect button in xaml
hai guys
i need your help to create a rectangle button with xaml.

if we create a default button will rounded rectangle button.
and i not found corner radius setting..
please help me..

答: Take a look at the MSDN example for creating fancy buttons here. Also take a look at the answer to this question.</p>

ContentLicense: CC BY-SA 2.5

Title: how to create a rect button in xaml


问:
How to properly use Google Drive Rest API?
I have an application where I want to upload the SQLite database file to the user's google drive account.

As Google Android API will stop working I thought to implement REST API, implementing REST API requires authentication. I am using Google Sign-in, but REST API Requires some type of access token. How to get that?

I created an account in the developer console, enabled the Drive API, plus added the Scope for drive/auth.

I achieved the login functionality using the official documentation, https://developers.google.com/identity/sign-in/android/sign-in

Using this code I can get the email of the user as well as create a DriveService,

```<code>    GoogleSignInOptions googleSignInOptions = new
    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(DriveScopes.DRIVE))
                .requestEmail()
                .build();

    googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);

    Intent googleSignInIntent = googleSignInClient.getSignInIntent();
    startActivityForResult(googleSignInIntent, REQUEST_CODE_SIGN_IN);
</code>```

In on activity result, I can get the user account, using the account I create a DriveServiceHelper

```<code>    mDriveServiceHelper = new DriveServiceHelper(getGoogleDriveService(getApplicationContext(), googleSignInAccount, "appName"));

</code>```

Now the thing is when I try to create folder It shows me an error about (UserRecoverableAuthIOException),

See the code using which I create Folder

```<code>public Task<GoogleDriveFileHolder> createFolder(final String folderName, @Nullable final String folderId) {
        return Tasks.call(mExecutor, new Callable<GoogleDriveFileHolder>() {
            @Override
            public GoogleDriveFileHolder call() {
                GoogleDriveFileHolder googleDriveFileHolder = new GoogleDriveFileHolder();

                List<String> root;
                if (folderId == null) {
                    root = Collections.singletonList("root");
                } else {

                    root = Collections.singletonList(folderId);
                }
                File metadata = new File()
                        .setParents(root)
                        .setMimeType(DriveFolder.MIME_TYPE)
                        .setName(folderName);

                File googleFile = null;
                googleFile = mDriveService.files().create(metadata).execute();
                googleDriveFileHolder.setId(googleFile.getId());
                return googleDriveFileHolder;
            }
        });
    }
</code>```

I tried solving the error, using various discussion threads available in StackOverflow none of them worked, can anyone guide me through this?

答:
Given an android.accounts.Account, you can use AccountManager.blockingGetAuthToken, set this token in a GoogleCredential, and then pass that in as the HttpRequestInitializer to Drive.Builder.

```<code>String token = AccountManager.get(context)
    .blockingGetAuthToken(<android.accounts.Account>, "oauth2:" + DriveScopes.DRIVE, false);
GoogleCredential credential = new GoogleCredential().setAccessToken(token);
Drive service = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
    .setApplicationName("app name")
    .build();
</code>```

Eventually this token will expire, at which point you will need to call AccountManager.invalidateAuthToken and acquire a new one

If you have included the play-services-auth library then you can pass this credential instead:

```<code>GoogleAccountCredential credential = GoogleAccountCredential
    .usingOAuth2(context, Collections.singleton(DriveScopes.DRIVE))
    .setSelectedAccount(googleAccount.getAccount());
</code>```

Body:
I have an application where I want to upload the SQLite database file to the user's google drive account.

As Google Android API will stop working I thought to implement REST API, implementing REST API requires authentication. I am using Google Sign-in, but REST API Requires some type of access token. How to get that?

I created an account in the developer console, enabled the Drive API, plus added the Scope for drive/auth.

I achieved the login functionality using the official documentation, https://developers.google.com/identity/sign-in/android/sign-in

Using this code I can get the email of the user as well as create a DriveService,

    GoogleSignInOptions googleSignInOptions = new
    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(DriveScopes.DRIVE))
                .requestEmail()
                .build();

    googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);

    Intent googleSignInIntent = googleSignInClient.getSignInIntent();
    startActivityForResult(googleSignInIntent, REQUEST_CODE_SIGN_IN);

In on activity result, I can get the user account, using the account I create a DriveServiceHelper

    mDriveServiceHelper = new DriveServiceHelper(getGoogleDriveService(getApplicationContext(), googleSignInAccount, "appName"));

Now the thing is when I try to create folder It shows me an error about (UserRecoverableAuthIOException),

See the code using which I create Folder

public Task<GoogleDriveFileHolder> createFolder(final String folderName, @Nullable final String folderId) {
        return Tasks.call(mExecutor, new Callable<GoogleDriveFileHolder>() {
            @Override
            public GoogleDriveFileHolder call() {
                GoogleDriveFileHolder googleDriveFileHolder = new GoogleDriveFileHolder();

                List<String> root;
                if (folderId == null) {
                    root = Collections.singletonList("root");
                } else {

                    root = Collections.singletonList(folderId);
                }
                File metadata = new File()
                        .setParents(root)
                        .setMimeType(DriveFolder.MIME_TYPE)
                        .setName(folderName);

                File googleFile = null;
                googleFile = mDriveService.files().create(metadata).execute();
                googleDriveFileHolder.setId(googleFile.getId());
                return googleDriveFileHolder;
            }
        });
    }

I tried solving the error, using various discussion threads available in StackOverflow none of them worked, can anyone guide me through this?

Body:
Given an android.accounts.Account, you can use AccountManager.blockingGetAuthToken, set this token in a GoogleCredential, and then pass that in as the HttpRequestInitializer to Drive.Builder.

String token = AccountManager.get(context)
    .blockingGetAuthToken(<android.accounts.Account>, "oauth2:" + DriveScopes.DRIVE, false);
GoogleCredential credential = new GoogleCredential().setAccessToken(token);
Drive service = new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
    .setApplicationName("app name")
    .build();

Eventually this token will expire, at which point you will need to call AccountManager.invalidateAuthToken and acquire a new one

If you have included the play-services-auth library then you can pass this credential instead:

GoogleAccountCredential credential = GoogleAccountCredential
    .usingOAuth2(context, Collections.singleton(DriveScopes.DRIVE))
    .setSelectedAccount(googleAccount.getAccount());


问:
How can i insert row into table sqlalchemy object?
i have table object that its name is tags and i don't know how to insert new row into it

this is my table object :

```<code>tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
    db.Column('Post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True)
)
</code>```

i tried to use this query for test :

```<code>db.session.add(tags(
        post_id = 1,
        tag_id = 2
))
</code>```

But I encountered this error :

```<code>TypeError: 'Table' object is not callable
</code>```

答:
I encourage you to use SQLAlchemy ORM approach. In your case it would be something like this:

```<code>from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Tags(Base):
    __tablename__ = 'tags'

    tag_id = Column(Integer, ForeignKey('tags.id'), primary_key=True)
    post_id = Column(Integer, ForeignKey('posts.id'), primary_key=True)

session.add(Tags(tag_id=1, post_id=2))
session.commit()
</code>```

Check SQLAlchemy site, they have great docs, recipes and examples!

Body:
i have table object that its name is tags and i don't know how to insert new row into it

this is my table object :

tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
    db.Column('Post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True)
)

i tried to use this query for test :

db.session.add(tags(
        post_id = 1,
        tag_id = 2
))

But I encountered this error :

TypeError: 'Table' object is not callable

Body:
I encourage you to use SQLAlchemy ORM approach. In your case it would be something like this:

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Tags(Base):
    __tablename__ = 'tags'

    tag_id = Column(Integer, ForeignKey('tags.id'), primary_key=True)
    post_id = Column(Integer, ForeignKey('posts.id'), primary_key=True)

session.add(Tags(tag_id=1, post_id=2))
session.commit()

Check SQLAlchemy site, they have great docs, recipes and examples!


问:
How can I test a word2vec over development data?
In a computer assignment, it's requested to implement word2vec algorithm to generate dense vectors for some words using a neural network. I implemented the neural network and trained it over training data. First, how can I test it over the test data? The question asks to draw a plot showing the perplexity for the training and test data during training (epochs). I can do that for the loss, which is something like this:

```<code>EPOCH: 0 LOSS: 27030.09155006593
EPOCH: 0 P_LOSS: 24637.964948774144
EPOCH: 0 PP: inf
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:121: RuntimeWarning: overflow encountered in double_scalars
EPOCH: 1 LOSS: 25349.086587261085
EPOCH: 1 P_LOSS: 22956.95998596929
EPOCH: 1 PP: inf
EPOCH: 2 LOSS: 24245.455581381622
EPOCH: 2 P_LOSS: 21853.32898008983
EPOCH: 2 PP: inf
EPOCH: 3 LOSS: 23312.976009712416
EPOCH: 3 P_LOSS: 20920.849408420647
</code>```

Which I gained by the following code:

```<code>    # CYCLE THROUGH EACH EPOCH
    for i in range(0, self.epochs):

        self.loss = 0
        self.loss_prob = 0
        # CYCLE THROUGH EACH TRAINING SAMPLE
        for w_t, w_c in training_data:

            # FORWARD PASS
            y_pred, h, u = self.forward_pass(w_t)

            # CALCULATE ERROR
            EI = np.sum([np.subtract(y_pred, word) for word in w_c], axis=0)

            # BACKPROPAGATION
            self.backprop(EI, h, w_t)

            # CALCULATE LOSS
            self.loss += -np.sum([u[word.index(1)] for word in w_c]) + len(w_c) * np.log(np.sum(np.exp(u)))
            self.loss_prob += -2*np.log(len(w_c)) -np.sum([u[word.index(1)] for word in w_c]) + (len(w_c) * np.log(np.sum(np.exp(u))))

        print('EPOCH:',i, 'LOSS:', self.loss)
        print('EPOCH:',i, 'P_LOSS:', self.loss_prob)
        print('EPOCH:',i, 'PP:', 2**self.loss_prob)
</code>```

However, I don't know how to find the perplexity for the training and development data in each epoch. Based on this question, it's said perplexity is 2**loss. However, as I tried this formula, I gained INF. Could you guide me how can I calculate perplexity? Can I do it in the current code, or should I apply a function over whole development data?

答:
You can solve the INF problem using decimal.</p>

```<code>import decimal
decimal.Decimal(2)**decimal.Decimal(loss)
</code>```

Body:
In a computer assignment, it's requested to implement word2vec algorithm to generate dense vectors for some words using a neural network. I implemented the neural network and trained it over training data. First, how can I test it over the test data? The question asks to draw a plot showing the perplexity for the training and test data during training (epochs). I can do that for the loss, which is something like this:

EPOCH: 0 LOSS: 27030.09155006593
EPOCH: 0 P_LOSS: 24637.964948774144
EPOCH: 0 PP: inf
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:121: RuntimeWarning: overflow encountered in double_scalars
EPOCH: 1 LOSS: 25349.086587261085
EPOCH: 1 P_LOSS: 22956.95998596929
EPOCH: 1 PP: inf
EPOCH: 2 LOSS: 24245.455581381622
EPOCH: 2 P_LOSS: 21853.32898008983
EPOCH: 2 PP: inf
EPOCH: 3 LOSS: 23312.976009712416
EPOCH: 3 P_LOSS: 20920.849408420647

Which I gained by the following code:

    # CYCLE THROUGH EACH EPOCH
    for i in range(0, self.epochs):

        self.loss = 0
        self.loss_prob = 0
        # CYCLE THROUGH EACH TRAINING SAMPLE
        for w_t, w_c in training_data:

            # FORWARD PASS
            y_pred, h, u = self.forward_pass(w_t)

            # CALCULATE ERROR
            EI = np.sum([np.subtract(y_pred, word) for word in w_c], axis=0)

            # BACKPROPAGATION
            self.backprop(EI, h, w_t)

            # CALCULATE LOSS
            self.loss += -np.sum([u[word.index(1)] for word in w_c]) + len(w_c) * np.log(np.sum(np.exp(u)))
            self.loss_prob += -2*np.log(len(w_c)) -np.sum([u[word.index(1)] for word in w_c]) + (len(w_c) * np.log(np.sum(np.exp(u))))

        print('EPOCH:',i, 'LOSS:', self.loss)
        print('EPOCH:',i, 'P_LOSS:', self.loss_prob)
        print('EPOCH:',i, 'PP:', 2**self.loss_prob)

However, I don't know how to find the perplexity for the training and development data in each epoch. Based on this question, it's said perplexity is 2**loss. However, as I tried this formula, I gained INF. Could you guide me how can I calculate perplexity? Can I do it in the current code, or should I apply a function over whole development data?

Body:
You can solve the INF problem using decimal.

import decimal
decimal.Decimal(2)**decimal.Decimal(loss)


问:
How to return data from firestore in json?
I'm trying to create a function (on server side) able to return data from firestore
but it always return me undefined

I tried to display it before returning it and I can see the value in my terminal.

```<code>exports.get_client = (ref)=> {
    ref.collection("clients/").get().then(function(coll) {
        let a= []
            coll.forEach(element => {
              a.push({"User": element.id, "data": element.data()})
              return a
            })
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}
</code>```

I expected [ { User: 'test@test.com',
    data:
     { email: 'test@test.com',
       family_name: 'test2',
       first_name: 'test' } } ]
but I had undefined.

答:
Your return a line is just returning from the lambda function that you passed to forEach.  It's not actually returning anything from the function get_client.  If you have a value to return from get_client, you will have to do that outside of the lambda

```<code>exports.get_client = (ref)=> {
    return ref.collection("clients/").get().then(function(coll) {
        let a= []
        coll.forEach(element => {
            a.push({"User": element.id, "data": element.data()})
        })
        return a
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}
</code>```

Body:
I'm trying to create a function (on server side) able to return data from firestore
but it always return me undefined

I tried to display it before returning it and I can see the value in my terminal.

exports.get_client = (ref)=> {
    ref.collection("clients/").get().then(function(coll) {
        let a= []
            coll.forEach(element => {
              a.push({"User": element.id, "data": element.data()})
              return a
            })
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}

I expected [ { User: 'test@test.com',
    data:
     { email: 'test@test.com',
       family_name: 'test2',
       first_name: 'test' } } ]
but I had undefined.

Body:
Your return a line is just returning from the lambda function that you passed to forEach.  It's not actually returning anything from the function get_client.  If you have a value to return from get_client, you will have to do that outside of the lambda

exports.get_client = (ref)=> {
    return ref.collection("clients/").get().then(function(coll) {
        let a= []
        coll.forEach(element => {
            a.push({"User": element.id, "data": element.data()})
        })
        return a
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}


问:
The movie game - skipping "The" at the beginning of a movie
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

```<code>def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()
</code>```

答:
You can replace the Part of the string In The case You Mentioned THE with an empty string ,
use
The following Code to Remove the word You want from the string

```<code>str="The Incredibles"
str.replace("The","")
</code>```

Body:
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()

Body:
You can replace the Part of the string In The case You Mentioned THE with an empty string ,
use
The following Code to Remove the word You want from the string

str="The Incredibles"
str.replace("The","")


问:
Controlling dynamic properties in Shady according to video frames not time
I am trying to use Shady to present a sequence of image frames. I'm controlling the flow from another machine, so that I first instruct the machine running Shady to present the first frame, and later on to run the rest of the frames.
I create a World instance, and attach to it an animation callback function. Within this callback I listen for communications from the other machine (using UDP).
First I receive a command to load a given sequence (stored as a numpy array), and I do

```<code>def loadSequence(self, fname):
    yy = np.load(fname)
    pages = []
    sz = yy.shape[0]
    for j in range(yy.shape[1]/yy.shape[0]):
         pages.append(yy[:, j*sz:(j+1)*sz])
    deltax, deltay = (self.screen_px[0] - sz) / 2, (self.screen_px[1] - sz) / 2
    if (self.sequence is None):
        self.sequence = self.wind.Stimulus(pages, 'sequence', multipage=True, anchor=Shady.LOCATION.UPPER_LEFT, position=[deltax, deltay], visible=False)
    else:
        self.sequence.LoadPages(pages, visible=False)
</code>```

When I receive the command to show the first frame, I then do:

```<code>def showFirstFrame(self, pars):
    self.sequence.page = 0 if (pars[0] == 0) else (len(self.sequence.pages) - 1)
    self.sequence.visible = True
</code>```

But what do I do now to get the other frames to be be displayed? In the examples I see, s.page is set as a function of time, but I need to show all frames, regardless of time. So I was thinking of doing something along these lines:

```<code>def showOtherFrames(self, pars, ackClient):
    direction, ack = pars[0], pars[2]
    self.sequence.page = range(1, len(self.sequence.pages)) if (direction == 0) else range(len(self.sequence.pages)-2, -1, -1)
</code>```

But this won't work. Alternatively I thought of defining a function that takes t as argument, but ignores it and uses instead a counter kept in a global variable, but I'd like to understand what is the proper way of doing this.

答:
When you make s.page a dynamic property, the function assigned to it must take one argument (t), but you can still just use any variables in the space when defining that function, and not even use the time argument at all.

So, for example, you could do something as simple as:

```<code>w = Shady.World(...)
s = w.Stimulus(...)
s.page = lambda t: w.framesCompleted
</code>```

which will set the page property to the current frame count. That sounds like it could be useful for your problem.

Body:
I am trying to use Shady to present a sequence of image frames. I'm controlling the flow from another machine, so that I first instruct the machine running Shady to present the first frame, and later on to run the rest of the frames.
I create a World instance, and attach to it an animation callback function. Within this callback I listen for communications from the other machine (using UDP).
First I receive a command to load a given sequence (stored as a numpy array), and I do

def loadSequence(self, fname):
    yy = np.load(fname)
    pages = []
    sz = yy.shape[0]
    for j in range(yy.shape[1]/yy.shape[0]):
         pages.append(yy[:, j*sz:(j+1)*sz])
    deltax, deltay = (self.screen_px[0] - sz) / 2, (self.screen_px[1] - sz) / 2
    if (self.sequence is None):
        self.sequence = self.wind.Stimulus(pages, 'sequence', multipage=True, anchor=Shady.LOCATION.UPPER_LEFT, position=[deltax, deltay], visible=False)
    else:
        self.sequence.LoadPages(pages, visible=False)

When I receive the command to show the first frame, I then do:

def showFirstFrame(self, pars):
    self.sequence.page = 0 if (pars[0] == 0) else (len(self.sequence.pages) - 1)
    self.sequence.visible = True

But what do I do now to get the other frames to be be displayed? In the examples I see, s.page is set as a function of time, but I need to show all frames, regardless of time. So I was thinking of doing something along these lines:

def showOtherFrames(self, pars, ackClient):
    direction, ack = pars[0], pars[2]
    self.sequence.page = range(1, len(self.sequence.pages)) if (direction == 0) else range(len(self.sequence.pages)-2, -1, -1)

But this won't work. Alternatively I thought of defining a function that takes t as argument, but ignores it and uses instead a counter kept in a global variable, but I'd like to understand what is the proper way of doing this.

Body:
When you make s.page a dynamic property, the function assigned to it must take one argument (t), but you can still just use any variables in the space when defining that function, and not even use the time argument at all.

So, for example, you could do something as simple as:

w = Shady.World(...)
s = w.Stimulus(...)
s.page = lambda t: w.framesCompleted

which will set the page property to the current frame count. That sounds like it could be useful for your problem.


问:
iOS: Destination point given distance and bearing from start point
Given a start point, initial bearing, and distance, this will calculate the destination point and final bearing travelling along a (shortest distance) great circle arc:

```<code>var lat2 =

Math.asin( Math.sin(lat1)*Math.cos(d/R) +
Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );

var lon2 =

lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
       Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
</code>```

This code is in JavaScript.
I'dd like the same thing for iOS, so in objective-c.

Anyone knows about a class that would do the trick?

答:
I'm not translating your Javascript, this is just a routine I found somewhere for a project of mine that does the same thing:</p>

```<code>- (CLLocationCoordinate2D) NewLocationFrom:(CLLocationCoordinate2D)startingPoint
                         atDistanceInMiles:(float)distanceInMiles
                     alongBearingInDegrees:(double)bearingInDegrees {

    double lat1 = DEG2RAD(startingPoint.latitude);
    double lon1 = DEG2RAD(startingPoint.longitude);

    double a = 6378137, b = 6356752.3142, f = 1/298.257223563;  // WGS-84 ellipsiod
    double s = distanceInMiles * 1.61 * 1000;  // Convert to meters
    double alpha1 = DEG2RAD(bearingInDegrees);
    double sinAlpha1 = sin(alpha1);
    double cosAlpha1 = cos(alpha1);

    double tanU1 = (1 - f) * tan(lat1);
    double cosU1 = 1 / sqrt((1 + tanU1 * tanU1));
    double sinU1 = tanU1 * cosU1;
    double sigma1 = atan2(tanU1, cosAlpha1);
    double sinAlpha = cosU1 * sinAlpha1;
    double cosSqAlpha = 1 - sinAlpha * sinAlpha;
    double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
    double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
    double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

    double sigma = s / (b * A);
    double sigmaP = 2 * kPi;

    double cos2SigmaM;
    double sinSigma;
    double cosSigma;

    while (abs(sigma - sigmaP) > 1e-12) {
        cos2SigmaM = cos(2 * sigma1 + sigma);
        sinSigma = sin(sigma);
        cosSigma = cos(sigma);
        double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        sigmaP = sigma;
        sigma = s / (b * A) + deltaSigma;
    }

    double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
    double lat2 = atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f) * sqrt(sinAlpha * sinAlpha + tmp * tmp));
    double lambda = atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
    double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
    double L = lambda - (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

    double lon2 = lon1 + L;

    // Create a new CLLocationCoordinate2D for this point
    CLLocationCoordinate2D edgePoint = CLLocationCoordinate2DMake(RAD2DEG(lat2), RAD2DEG(lon2));

    return edgePoint;
}
</code>```

Body:
Given a start point, initial bearing, and distance, this will calculate the destination point and final bearing travelling along a (shortest distance) great circle arc:

var lat2 =

Math.asin( Math.sin(lat1)*Math.cos(d/R) +
Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );

var lon2 =

lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
       Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));

This code is in JavaScript.
I'dd like the same thing for iOS, so in objective-c.

Anyone knows about a class that would do the trick?

Body:
I'm not translating your Javascript, this is just a routine I found somewhere for a project of mine that does the same thing:

- (CLLocationCoordinate2D) NewLocationFrom:(CLLocationCoordinate2D)startingPoint
                         atDistanceInMiles:(float)distanceInMiles
                     alongBearingInDegrees:(double)bearingInDegrees {

    double lat1 = DEG2RAD(startingPoint.latitude);
    double lon1 = DEG2RAD(startingPoint.longitude);

    double a = 6378137, b = 6356752.3142, f = 1/298.257223563;  // WGS-84 ellipsiod
    double s = distanceInMiles * 1.61 * 1000;  // Convert to meters
    double alpha1 = DEG2RAD(bearingInDegrees);
    double sinAlpha1 = sin(alpha1);
    double cosAlpha1 = cos(alpha1);

    double tanU1 = (1 - f) * tan(lat1);
    double cosU1 = 1 / sqrt((1 + tanU1 * tanU1));
    double sinU1 = tanU1 * cosU1;
    double sigma1 = atan2(tanU1, cosAlpha1);
    double sinAlpha = cosU1 * sinAlpha1;
    double cosSqAlpha = 1 - sinAlpha * sinAlpha;
    double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
    double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
    double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

    double sigma = s / (b * A);
    double sigmaP = 2 * kPi;

    double cos2SigmaM;
    double sinSigma;
    double cosSigma;

    while (abs(sigma - sigmaP) > 1e-12) {
        cos2SigmaM = cos(2 * sigma1 + sigma);
        sinSigma = sin(sigma);
        cosSigma = cos(sigma);
        double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        sigmaP = sigma;
        sigma = s / (b * A) + deltaSigma;
    }

    double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
    double lat2 = atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f) * sqrt(sinAlpha * sinAlpha + tmp * tmp));
    double lambda = atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
    double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
    double L = lambda - (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

    double lon2 = lon1 + L;

    // Create a new CLLocationCoordinate2D for this point
    CLLocationCoordinate2D edgePoint = CLLocationCoordinate2DMake(RAD2DEG(lat2), RAD2DEG(lon2));

    return edgePoint;
}


问:
XML Deserialization not working past the first element
I am attempting to use XML deserialization to convert a XML response from a host into C# objects.  The root element is converted into its object and the 2nd element appears to be converted, but it's an empty element anyway.  Beyond that, non of the other elements are converted.  What am I missing?

I have tried many different variations of objects for each element and arrays of elements (even though an array is not needed.  I even found that you can paste the XML into the editor in Visual Studio and it will create the serialized objects (edit, paste special, Paste XML As Classes), but I have not been able to get anything to work!

Here's how the XML looks:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite/DTD MySite PaymentService v1//EN" "http://dtd.mysite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
    <reply>
        <orderStatus orderCode="ExampleOrder1">
            <reference id="YourReference">https://payments-test.mysite.com/app/hpp/integration/wpg/corporate?OrderKey=NGPPTESTMERCH1%5Ejsxml3835829684&Ticket=00146321872957902pqKhCTUf0vajKCw-X5HqZA</reference>
        </orderStatus>
    </reply>
</paymentService>
</code>```

-OR-

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite//DTD MySite PaymentService v1//EN" "http://dtd.MySite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
   <reply>
      <orderStatus orderCode="ExampleOrder1">
         <error code="2">
            <![CDATA[Invalid address: Postal code is missing or empty.]]>
        </error>
      </orderStatus>
   </reply>
</paymentService>
</code>```

Here are the objects:

```<code>   [Serializable]
   [XmlRoot(ElementName = "paymentService")]
   public partial class PaymentResponse
   {
      [XmlAttribute()]
      public string version { get; set; }

      [XmlAttribute()]
      public string merchantCode { get; set; }

      [XmlElement("reply")]
      public Reply reply { get; set; }
   }
   [Serializable]
   public partial class Reply
   {
      [XmlElement("orderStatus")]
      public OrderStatus orderStatus {get; set; }
   }
   [Serializable]
   public partial class OrderStatus
   {
         [XmlAttribute()]
         public string orderCode {get; set; }

         [XmlElement(ElementName = "reference",IsNullable =true)]
         public Reference reference {get; set; }

         [XmlElement(ElementName = "error",IsNullable =true)]
         public Error error {get; set; }
   }
</code>```

Here's the call to do the deserialization:

```<code>XmlSerializer serializer = new XmlSerializer(typeof(PaymentResponse));
        PaymentResponse response = (PaymentResponse)serializer.Deserialize(reader);
</code>```

The only thing that is returned in the merchantcode and version from PaymentResponse.

答:
You might have to tell the serializer about what to do about with the your non-primative types.

Try changing this

```<code>[XmlElement(ElementName = "reference",IsNullable =true)]
public Reference reference {get; set; }

[XmlElement(ElementName = "error",IsNullable =true)]
public Error error {get; set; }
</code>```

to this

```<code>[XmlElement(ElementName = "reference", Type = typeof(Reference), IsNullable = true)]
public Reference reference {get; set; }

[XmlElement(ElementName = "error", Type = typeof(Error), IsNullable = true)]
public Error error {get; set; }
</code>```

Good Luck!

Body:
I am attempting to use XML deserialization to convert a XML response from a host into C# objects.  The root element is converted into its object and the 2nd element appears to be converted, but it's an empty element anyway.  Beyond that, non of the other elements are converted.  What am I missing?

I have tried many different variations of objects for each element and arrays of elements (even though an array is not needed.  I even found that you can paste the XML into the editor in Visual Studio and it will create the serialized objects (edit, paste special, Paste XML As Classes), but I have not been able to get anything to work!

Here's how the XML looks:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite/DTD MySite PaymentService v1//EN" "http://dtd.mysite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
    <reply>
        <orderStatus orderCode="ExampleOrder1">
            <reference id="YourReference">https://payments-test.mysite.com/app/hpp/integration/wpg/corporate?OrderKey=NGPPTESTMERCH1%5Ejsxml3835829684&Ticket=00146321872957902pqKhCTUf0vajKCw-X5HqZA</reference>
        </orderStatus>
    </reply>
</paymentService>

-OR-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite//DTD MySite PaymentService v1//EN" "http://dtd.MySite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
   <reply>
      <orderStatus orderCode="ExampleOrder1">
         <error code="2">
            <![CDATA[Invalid address: Postal code is missing or empty.]]>
        </error>
      </orderStatus>
   </reply>
</paymentService>

Here are the objects:

   [Serializable]
   [XmlRoot(ElementName = "paymentService")]
   public partial class PaymentResponse
   {
      [XmlAttribute()]
      public string version { get; set; }

      [XmlAttribute()]
      public string merchantCode { get; set; }

      [XmlElement("reply")]
      public Reply reply { get; set; }
   }
   [Serializable]
   public partial class Reply
   {
      [XmlElement("orderStatus")]
      public OrderStatus orderStatus {get; set; }
   }
   [Serializable]
   public partial class OrderStatus
   {
         [XmlAttribute()]
         public string orderCode {get; set; }

         [XmlElement(ElementName = "reference",IsNullable =true)]
         public Reference reference {get; set; }

         [XmlElement(ElementName = "error",IsNullable =true)]
         public Error error {get; set; }
   }

Here's the call to do the deserialization:

XmlSerializer serializer = new XmlSerializer(typeof(PaymentResponse));
        PaymentResponse response = (PaymentResponse)serializer.Deserialize(reader);

The only thing that is returned in the merchantcode and version from PaymentResponse.

Body:
You might have to tell the serializer about what to do about with the your non-primative types.

Try changing this

[XmlElement(ElementName = "reference",IsNullable =true)]
public Reference reference {get; set; }

[XmlElement(ElementName = "error",IsNullable =true)]
public Error error {get; set; }

to this

[XmlElement(ElementName = "reference", Type = typeof(Reference), IsNullable = true)]
public Reference reference {get; set; }

[XmlElement(ElementName = "error", Type = typeof(Error), IsNullable = true)]
public Error error {get; set; }

Good Luck!


问:
How to pipe a default file on node request error?
I'm using nodejs with the request package.

Situation:

My frontend sends a file request to my node server through a HTTP GET

The server check if the user is authenticated

The server requests the file on AWS S3 like so:

```<code>request(req.query.url)
   .on('error', (e) => {
    // Some code here?
    res.sendFile(path.join(__dirname, '../assets/favicon.png'))
   })
   .pipe(res)
</code>```

Problem: Sometimes it doesn't find the file or can't connect to AWS S3 or whatever the error is, I would like to send  a default file if that happens. How could I achieve this?

答:
Wouldn`t it be a little cleaner if you start using try/catch instead of promises?
like:</p>

```<code>try {
    response = request(req.query.url)
    pipe(res)
catch (e) {
    console.log("just so you can know why it failed")
    pipe(default)
}
</code>```

Body:
I'm using nodejs with the request package.

Situation:

My frontend sends a file request to my node server through a HTTP GET

The server check if the user is authenticated

The server requests the file on AWS S3 like so:

request(req.query.url)
   .on('error', (e) => {
    // Some code here?
    res.sendFile(path.join(__dirname, '../assets/favicon.png'))
   })
   .pipe(res)

Problem: Sometimes it doesn't find the file or can't connect to AWS S3 or whatever the error is, I would like to send  a default file if that happens. How could I achieve this?

Body:
Wouldn`t it be a little cleaner if you start using try/catch instead of promises?
like:

try {
    response = request(req.query.url)
    pipe(res)
catch (e) {
    console.log("just so you can know why it failed")
    pipe(default)
}


问:
handleSubmit function not successfully firing using Formik
I am using Formik + Yup to construct a form but can't seem to get passed a basic issue, I feel like I'm missing something obvious.  My handleSubmit function wont fire on button click - even something simple like a console log.  If I add a pure function to the onClick button handler it fires, but Formik doesn't seem to be passing down my handleSubmit constructed with the withFormik HOC.

I've tried adding the handler to the Form component, doesn't work there either.

```<code>const formikEnhancer = withFormik({
  mapPropsToValues: props => ({
    firstName: props.firstName || '',
    ...
  }),
  validationSchema: yup.object().shape({
    firstName: yup.string().required('Please enter your first name'),
   ...
  }),
  handleSubmit: (values, formikBag) => {
    console.log('test');
    }
  },
});

const BusinessFundingForm = ({
  values,
  isSubmitting,
  errors,
  handleBlur,
  handleChange,
  handleSubmit,
  touched,
  data,
}) => {

  return (
        <Form className="form" id="form-id">
          <Row>
            <Col xs={12} sm={6}>
              <InputField
                id="first-name"
                type="text"
                name="firstName"
                value={values.firstName}
                onChange={handleChange}
                onBlur={handleBlur}
                placeholder="First Name"
                label="First Name"
              />
              {errors.firstName &&
                touched.firstName && <Error>{errors.firstName}</Error>}
            </Col>
           ...
          </Row>

          <Row>
            <ButtonWrapper>
              <Button
                type="submit"
                tall
                onClick={handleSubmit}
                varianttype={
                  isSubmitting ||
                  (!!errors.firstName ||
                    formHelpers.isEmpty(values.firstName))
                    ? 'disabled'
                    : 'outline'
                }
                disabled={
                  isSubmitting ||
                  (!!errors.firstName ||
                    formHelpers.isEmpty(values.firstName))
                }
                text="Submit →"
              />
            </ButtonWrapper>
          </Row>
        </Form>
      </FormGrid>
    </Element>
  );
};

export default formikEnhancer(BusinessFundingForm);

</code>```

For brevity's sake I deleted all the properties except the firstName property

答:
Sometimes there are errors on the page which prevent Formik from triggering handleSubmit thus its good to check if there are no errors by outputting errors on the screen or console.

To overcome these type of scenarios during development you can always use:
```{JSON.stringify(errors, null, 2)}``` as a DOM node so that you are constantly aware of the issue on the UI and then remove it or comment it during committing to your branch.

Also I trust there are no syntax errors on your code because your handleSubmit seems to have extra closing brace.

Body:
I am using Formik + Yup to construct a form but can't seem to get passed a basic issue, I feel like I'm missing something obvious.  My handleSubmit function wont fire on button click - even something simple like a console log.  If I add a pure function to the onClick button handler it fires, but Formik doesn't seem to be passing down my handleSubmit constructed with the withFormik HOC.

I've tried adding the handler to the Form component, doesn't work there either.

const formikEnhancer = withFormik({
  mapPropsToValues: props => ({
    firstName: props.firstName || '',
    ...
  }),
  validationSchema: yup.object().shape({
    firstName: yup.string().required('Please enter your first name'),
   ...
  }),
  handleSubmit: (values, formikBag) => {
    console.log('test');
    }
  },
});

const BusinessFundingForm = ({
  values,
  isSubmitting,
  errors,
  handleBlur,
  handleChange,
  handleSubmit,
  touched,
  data,
}) => {

  return (
        <Form className="form" id="form-id">
          <Row>
            <Col xs={12} sm={6}>
              <InputField
                id="first-name"
                type="text"
                name="firstName"
                value={values.firstName}
                onChange={handleChange}
                onBlur={handleBlur}
                placeholder="First Name"
                label="First Name"
              />
              {errors.firstName &&
                touched.firstName && <Error>{errors.firstName}</Error>}
            </Col>
           ...
          </Row>

          <Row>
            <ButtonWrapper>
              <Button
                type="submit"
                tall
                onClick={handleSubmit}
                varianttype={
                  isSubmitting ||
                  (!!errors.firstName ||
                    formHelpers.isEmpty(values.firstName))
                    ? 'disabled'
                    : 'outline'
                }
                disabled={
                  isSubmitting ||
                  (!!errors.firstName ||
                    formHelpers.isEmpty(values.firstName))
                }
                text="Submit →"
              />
            </ButtonWrapper>
          </Row>
        </Form>
      </FormGrid>
    </Element>
  );
};

export default formikEnhancer(BusinessFundingForm);

For brevity's sake I deleted all the properties except the firstName property

Body:
Sometimes there are errors on the page which prevent Formik from triggering handleSubmit thus its good to check if there are no errors by outputting errors on the screen or console.

To overcome these type of scenarios during development you can always use:
<pre>{JSON.stringify(errors, null, 2)}</pre> as a DOM node so that you are constantly aware of the issue on the UI and then remove it or comment it during committing to your branch.

Also I trust there are no syntax errors on your code because your handleSubmit seems to have extra closing brace.


问:
How can I route my Angular API Calls through the hosting server?
I have an application with an angular 7 front end and a dotnet core 2.2 API. The API exists on a protected corporate server, while the angular front end exists on a hosting server. The front end hosting server's ip is whitelisted on the API server's firewall, but because the API calls are coming from the user's IP instead of the hosting server's IP, all of the requests are being blocked.

For example, if User 1 has IP A and makes a request from the frontend application, it hits the API server with IP A, instead of IP B (the frontend server's IP). The request is then blocked because only IP B is whitelisted.

Is there a way around this? Can I force the request to come from the front end server's IP?

答:
What you can do is you can send the operation details from angular app to your hosted server. Then based on the operation details figure out which API needs to be called. The call that API from dotnet core. And send the result back to your client. So you hosting server acts as a gateway between the API and client.

It also depends on what hosting you are doing. If you have an option you can write this gateway in NodeJS if there are limitations regarding the platform.


问:
Oracle SQL query question
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

```<code>SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;
</code>```

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.

答:
Try this:</p>

```<code>WITH avgData AS
SELECT a.*,
             RANK() OVER(ORDER BY avg_cost) RN
  FROM
    (
        SELECT  DeptNo,
                    AVG(projcost) avg_cost,
                    projects.ROWNUM rn
        FROM    projects,
                    clinicians
        WHERE   clinicians.Clinicianno = projects.Clinicianno
        GROUP BY DeptNo
    ) a
SELECT *
  FROM avgData
 WHERE RN = 1
</code>```

Title: Oracle SQL query question

Body:
I'm trying to complete this Oracle SQL query with no luck.

"List the department that has the least average cost. (Hint: SELECT  MIN(AVG(cost)) is valid as long as no other column is combined in the SELECT statement. You can combine the above as a subquery with another query)"

I'm able to get it to display the Depts with their average cost, but when I try to work in MIN it breaks. This is what I have so far.

SELECT DeptNo, AVG(projcost) FROM projects, clinicians WHERE clinicians.Clinicianno = projects.Clinicianno GROUP BY DeptNo;

That will give me the depts and their AVG, but when I change AVG(projcost) to be MIN(AVG(projcost) it breaks. The hint is to make it a subquery but I can't figure out how to do that yet. Any help would be much appreciated.

Body:
Try this:

WITH avgData AS
SELECT a.*,
             RANK() OVER(ORDER BY avg_cost) RN
  FROM
    (
        SELECT  DeptNo,
                    AVG(projcost) avg_cost,
                    projects.ROWNUM rn
        FROM    projects,
                    clinicians
        WHERE   clinicians.Clinicianno = projects.Clinicianno
        GROUP BY DeptNo
    ) a
SELECT *
  FROM avgData
 WHERE RN = 1


问:
How to order content by FilePath in Hugo?
I'm trying to order content based on the FilePath. I want the FilePath to take precedence over the link title. I'm creating a documentation site with tutorials that will have sequenced content. I'd like the file structure to match the sequence of the tutorial (e.g. 01_getting_started.md, 2_setup.md, etc). I'd prefer to rely on the file path naming instead of defining the sequence information twice (in the filepath and in the weight front matter).

https://gohugo.io/templates/lists/#order-content

答:
Update: @Jura has an even more terse solution:

```<code>{{ range sort site.RegularPages "File.Path" }}
  {{ . }}
{{ end }}
</code>```

Given the following content:

```<code>content/
├── 01_getting_started.md
├── 02_setup.md
└── 03_configuration.md
</code>```

Then this template code:

```<code>{{ $pages := slice }}

{{ range site.RegularPages }}
  {{ $pages = $pages | append (dict "page" . "file_path" .File.Path) }}
{{ end }}

{{ range sort $pages "file_path" }}
  {{ .page }}
{{ end }}
</code>```

Will output the pages, ordered by file path:

```<code>  Page(/01_getting_started.md)

  Page(/02_setup.md)

  Page(/03_configuration.md)
</code>```

It works by creating an empty slice (aka an array). It loops through all pages, appending a dictionary (aka a map) of the page object and its file path to the slice. Then the slice is sorted by file path in ascending order, and looped through.

You can then treat .page like the usual .. So .page.Title would be equivalent to .Title.

Body:
Update: @Jura has an even more terse solution:

{{ range sort site.RegularPages "File.Path" }}
  {{ . }}
{{ end }}

Given the following content:

content/
├── 01_getting_started.md
├── 02_setup.md
└── 03_configuration.md

Then this template code:

{{ $pages := slice }}

{{ range site.RegularPages }}
  {{ $pages = $pages | append (dict "page" . "file_path" .File.Path) }}
{{ end }}

{{ range sort $pages "file_path" }}
  {{ .page }}
{{ end }}

Will output the pages, ordered by file path:

  Page(/01_getting_started.md)

  Page(/02_setup.md)

  Page(/03_configuration.md)

It works by creating an empty slice (aka an array). It loops through all pages, appending a dictionary (aka a map) of the page object and its file path to the slice. Then the slice is sorted by file path in ascending order, and looped through.

You can then treat .page like the usual .. So .page.Title would be equivalent to .Title.


问:
SVG textpath rendering appears reversed in Firefox
I'm trying to render text along a curved path in an SVG. It renders as expected in Chrome, Safari, and Edge, but it renders differently in Firefox.

jsfiddle: http://jsfiddle.net/hLyq1ug6/

```<code><svg width="320" height="320" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background: blue"><path d="m57.8,160 a102.2,102.2 0 1 1 204.4,0" fill="red" id="curvedTextPath5cf008a181659"></path><text x="160" y="185.5" style="fill: #ffffff; font-size: 35pt"><textPath xlink:href="#curvedTextPath5cf008a181659" startOffset="0" text-anchor="middle">Hello</textPath></text></svg>
</code>```

Expected:

Firefox:

答:
I've removed the x and the y attributes from the text. If you need to offset the text use startOffset="50%"I hope it helps.

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background: blue">
<path d="m57.8,160 a102.2,102.2 0 1 1 204.4,0" fill="red" id="curvedTextPath5cf008a181659"></path>
<text style="fill: #ffffff; font-size: 35pt">
<textPath xlink:href="#curvedTextPath5cf008a181659" startOffset="50%" text-anchor="middle">Hello</textPath>
</text>
</svg>```

Body:
I'm trying to render text along a curved path in an SVG. It renders as expected in Chrome, Safari, and Edge, but it renders differently in Firefox.

jsfiddle: http://jsfiddle.net/hLyq1ug6/

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background: blue"><path d="m57.8,160 a102.2,102.2 0 1 1 204.4,0" fill="red" id="curvedTextPath5cf008a181659"></path><text x="160" y="185.5" style="fill: #ffffff; font-size: 35pt"><textPath xlink:href="#curvedTextPath5cf008a181659" startOffset="0" text-anchor="middle">Hello</textPath></text></svg>

Expected:

Firefox:


问:
How to spread the inner array elements of an array?
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

```<code>[1,2,[3,4],[5,6]]
</code>```

Output:

```<code>[1,2,3,4,5,6]
</code>```

How do I convert the first array into 2nd one?

答:
You could take a generator for the array which checks the lement and for arrays, it returns the nested elements.

function* flat() {
    var i = 0;
    while (i < this.length) {
        if (Array.isArray(this[i])) {
            this[i][Symbol.iterator] = flat;
            yield* this[i];
        } else {
            yield this[i];
        }
        i++;
    }
}

var array = [1, 2, [3, 4], [5, 6], [7, [8, 9]]];
array[Symbol.iterator] = flat;

console.log([...array]);```

Body:
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

[1,2,[3,4],[5,6]]

Output:

[1,2,3,4,5,6]

How do I convert the first array into 2nd one?


问:
Fastest method to find a complex type in a list (Vector, Array, Dictionary, whatever is faster)
Hail, Stack!

I need to know the best method to find an item inside a list (Vector, Array, Dictionary, whatever is faster) of complex type (extensions of Objects and Sprites).

I've used "Needle in Haystack" method, but it seems that it isn't fast enough.

E.g.
Suppose that I have a collection of Sprites (a pool, in fact).

Each sprite will be added to the stage and perform some action. After that, it will die.

I don't want to pay the cost to dispose it (garbage collect) and create another (new) one every time so I'll keep the dead sprites in a collection.

Sometimes times I'll call a method that will add a sprite to the stage.

This sprite can be a old one, if it is already dead, or a new one, if the pool don't have any free sprite.

One of the scenarios that pushed me to this question was a Particle System.

A "head" particle leaving a "trail" of particles every frame and exploding into a flashy multitude of particles... Every frame...

Some times this counts up to 50.000 PNGs with motion, rotation, alpha, event dispatching, scale, etc...

But, this is JUST ONE scenario...

At the moment I'm trying to use a Object Pool with a Linked List...

Hopes that it will be faster that running a whole Array/Vector or create new instances every frame an let them dye with Garbage Collection.

Someone knows a better/faster way to do it?

答:
I'd say Vector, but there seems to be some mixed results.

Vector.<> vs array

http://impossiblearts.com/blog/2008/06/fp10-vector-vs-array/


问:
Assertion error when selecting item in DropdownButton
I have created an app in Flutter to use for my company's inventory. One of the widgets in the app is a DropdownButton that is populated with elements from Firebase Cloud Firestore. All the menu items are loading properly, but when I select an item I get a red screen.

I am fairly new to Flutter so I mostly copied the code from a tutorial, so I find it odd that it does not work.

```<code>class _ReviewChangesScreenState extends State<ReviewChangesScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  DocumentSnapshot job;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Review Changes'),
        ),
        body: Column(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Form(
                key: _formKey,
                child: StreamBuilder(
                  stream: Firestore.instance.collection('jobs').snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
                    return new DropdownButton(
                      value: job,
                      onChanged: (val) {
                        setState(() {
                          job = val;
                        });
                      },
                      items: snapshot.data.documents
                          .map<DropdownMenuItem<DocumentSnapshot>>(
                              (DocumentSnapshot document) {
                        return new DropdownMenuItem<DocumentSnapshot>(
                          child: Text(document.data['jobCode']),
                          value: document,
                        );
                      }).toList(),
                    );
                  },
                )),
          ),
        ]));
  }
}
</code>```

This is the error I receive when I try to select an item in the menu.

```<code>I/flutter ( 7320): The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter ( 7320): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#22b54):
I/flutter ( 7320): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 609 pos 15: 'items == null ||
I/flutter ( 7320): items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==
I/flutter ( 7320): value).length == 1': is not true.

</code>```

Flutter doctor output:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.5.4-hotfix.2, on Microsoft Windows [Version 10.0.17763.529],
    locale en-CA)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] Connected device (1 available)

</code>```

I'm really stumped on what the issue is.

答:
The error tells you that your items or value parameters of the Dropdown constructor doesn't satisfy the requirements of the Dropdown. Take a look at the code:

https://github.com/flutter/flutter/blob/v1.5.4-hotfix.2/packages/flutter/lib/src/material/dropdown.dart#L609

assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1)
```

In human translation:

items must not be null

items must contain at least 1 element

value must not be null

items must contain a element that has a value of value

Your input data, violate one of these conditions.

Body:
I have created an app in Flutter to use for my company's inventory. One of the widgets in the app is a DropdownButton that is populated with elements from Firebase Cloud Firestore. All the menu items are loading properly, but when I select an item I get a red screen.

I am fairly new to Flutter so I mostly copied the code from a tutorial, so I find it odd that it does not work.

class _ReviewChangesScreenState extends State<ReviewChangesScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  DocumentSnapshot job;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Review Changes'),
        ),
        body: Column(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Form(
                key: _formKey,
                child: StreamBuilder(
                  stream: Firestore.instance.collection('jobs').snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
                    return new DropdownButton(
                      value: job,
                      onChanged: (val) {
                        setState(() {
                          job = val;
                        });
                      },
                      items: snapshot.data.documents
                          .map<DropdownMenuItem<DocumentSnapshot>>(
                              (DocumentSnapshot document) {
                        return new DropdownMenuItem<DocumentSnapshot>(
                          child: Text(document.data['jobCode']),
                          value: document,
                        );
                      }).toList(),
                    );
                  },
                )),
          ),
        ]));
  }
}

This is the error I receive when I try to select an item in the menu.

I/flutter ( 7320): The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter ( 7320): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#22b54):
I/flutter ( 7320): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 609 pos 15: 'items == null ||
I/flutter ( 7320): items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==
I/flutter ( 7320): value).length == 1': is not true.

Flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.5.4-hotfix.2, on Microsoft Windows [Version 10.0.17763.529],
    locale en-CA)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] Connected device (1 available)

I'm really stumped on what the issue is.

Body:
The error tells you that your items or value parameters of the Dropdown constructor doesn't satisfy the requirements of the Dropdown. Take a look at the code:

https://github.com/flutter/flutter/blob/v1.5.4-hotfix.2/packages/flutter/lib/src/material/dropdown.dart#L609

assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1)

In human translation:

items must not be null

items must contain at least 1 element

value must not be null

items must contain a element that has a value of value

Your input data, violate one of these conditions.


问:
c# windows shutdown control
Please read - this is not a duplicate.

I have a Windows service that runs under the LocalSystem acct.  I am in need of restoring certain files prior to shutdown.  I am able to intercept the Shutdown action at which point I initiate my restore process but the shutdown happens before I am able to complete.
I have enabled Shutdown privileges, added calls to AbortShutdown (Win32) and several other (ie shutdown /a) options but they do not work.  I believe it is because the shutdown or restart has already been initiated and I have read that these functions only stop a shutdown while it is scheduled.

My goal is to intercept the shutdown, abort it, complete my tasks and then shutdown.  I just need more time and the amount of time is dependent on the number and size of files I have to restore.

I am open to any suggestion and appreciate your time and consideration.
Thanks!

答:
Your goal is untenable. On Windows, the user has control over the shutdown process. If the user wants to shutdown the machine, it's not up to your software to contravene the user's intentions.

The burden is on you to make sure that your software can deal with a shutdown, whenever it happens. This usually means making sure that file operations are as atomic as possible, or using a "hot journal" file to recover (on the next system startup) in the event that atomic operations can't be completed.

The files that you speak of, that you have to restore before shutdown, should be "restored" (hard to tell exactly what you mean here) as soon as any operations are finished on them. Without further details, it hard to discuss the specific approaches.

Title: c# windows shutdown control


问:
Receiving "Cannot read property 'value' of undefined" in formControlName property
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}
</code>```

Here is my login.component.html:

```<code><mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">
            <table class="login-full-width" cellspacing="0">
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>
                    </td>
                </tr>
                <p>
                    Value: {{email.value}}
                </p>
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>
                    </td>
                </tr>
            </table>
        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>
</code>```

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

```<code><input matInput type="text" formControlName="email" placeholder="Email" required>
</code>```

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?

答:
There is no email property in your class. You have to access the form value through the form group, like so:</p>

```<code><p>
 Value: {{loginForm.get('email').value}}
</p>
</code>```

Body:
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}

Here is my login.component.html:

<mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">

                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>

                    Value: {{email.value}}

                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>

        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

<input matInput type="text" formControlName="email" placeholder="Email" required>

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?

Body:
There is no email property in your class. You have to access the form value through the form group, like so:

<p>
 Value: {{loginForm.get('email').value}}
</p>


问:
Tkinter open and close Toplevel windows
Iam new in Python, and my set goal is trying to create an application for myself to list and manipulate some data; in my case some coins.
I am self teaching code, but there are many thing I do not understand yet.

Iam organizing the code as best as I could, but I have reached some of my limits.

My code is showing a Tk window which is containing the data that you enter in a second window using Toplevel. When you use the ADD button it shows the window, but if you happen to close it and open it again, it shows an error. Iam sure it is because my instance of the window is destroyed but I would love to have your input about how I should solve this issue. What would you suggest ?

Thanks for your time !

from tkinter import *  # tkinter package import
from tkinter import ttk

window_size = '480x600+0+0'

############################ Window 1 configuration ############################
window = Tk()
window.title('Coin Collector')  # title of the window
window.geometry(window_size)  #taille de la fenetre
window.config(background='white')

#searchbar
search_bar_txt = Label(window, text='Search :')
search_bar_txt.place(height=40,width=70,x=1,y=1)
search_bar_entry = Entry(window)
search_bar_entry.place(height=40,width=410,x=71,y=1)

# tree view setup
tree=ttk.Treeview(window)
tree['columns']=('one','two','three')
tree.column('#0', width=29, minwidth=80)
tree.column('one', width=150, minwidth=80)
tree.column('two', width=150, minwidth=80)
tree.column('three', width=147, minwidth=80)

tree.heading('#0',text='#ID')
tree.heading('one', text='COIN')
tree.heading('two', text='YEAR')
tree.heading('three', text='PRICE')

tree.place(height= 510,x=0, y=50)

def show_window2():
    window_2.deiconify()

###### BUTTONS ########
Button_add = Button(window, text='ADD', command=show_window2)
Button_add.place(height=40, width=120, x=0, y=560)

Button_remove = Button(window, text='REMOVE')
Button_remove.place(height=40, width=120, x=120, y=560)

Button_edit = Button(window, text='EDIT')
Button_edit.place(height=40, width=120, x=240, y=560)

Button_exit = Button(window, text='EXIT', command=exit)
Button_exit.place(height=40, width=120, x=360, y=560)

############################ Window 2 configuration ############################
window_2 = Toplevel()
window_2.title('Edit coin')
window_2.geometry('300x500+480+0')
window_2.config(background='white')
window_2.iconify()
window_2.protocol('WM_DELETE_WINDOW', window_2.destroy);#Changes close button

#coin type
coin_type_txt = Label(window_2, text='Coin Name :')
coin_type_txt.place(x=0, y=0)
coin_type_value = Entry(window_2)
coin_type_value.place(height=30, width=165, x=130, y=0)

#coin year
coin_year_txt = Label(window_2, text='Coin year :')
coin_year_txt.place(x=0, y=35)
coin_year_value = Entry(window_2)
coin_year_value.place(height=30, width=165, x=130, y=35)

#coin price
coin_price_txt = Label(window_2, text='Coin price :')
coin_price_txt.place(x=0, y=70)
coin_price_value = Entry(window_2,width=10)
coin_price_value.place(height=30, width=165, x=130, y=70)

def save_coin(): #create function to execute when clicked
    tree.insert('','end',text='',values=(coin_type_value.get(),coin_year_value.get(),coin_price_value.get()))

#save coin
coin_save_button = Button(window_2, text='save', command=save_coin)
coin_save_button.place(height=40, width=300, x=0, y=460)

######FUNCTIONS######

def exit():
    window.destroy()

window.mainloop()

```

答:
The way I do this is to move the creation of the toplevel and its widgets into a function. Then you can check for whether the window exists or not when displaying it. If it doesn't exist because the user destroyed it, you can recreate it.

For example, your show_window would look something like this:

```<code>def show_window2():
    if not window_2.winfo_exists():
        create_window2()
    window_2.deiconify()
</code>```

Title: Tkinter open and close Toplevel windows

Body:
The way I do this is to move the creation of the toplevel and its widgets into a function. Then you can check for whether the window exists or not when displaying it. If it doesn't exist because the user destroyed it, you can recreate it.

For example, your show_window would look something like this:

def show_window2():
    if not window_2.winfo_exists():
        create_window2()
    window_2.deiconify()