问:
Why don't Parameters<Func> extend unknown[] (Array<unknown>) in ts strict mode
The title pretty much says it all really. I have this code:

```<code>  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true
</code>```

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.

答:
With the --strictFunctionTypes compiler option enabled, function type parameters are checked contravariantly. "Contra-variant" means that the subtype relationship of the function varies in the opposite direction from that of function parameters.  So if A extends B, then (x: B)=>void extends (x: A)=>void and not vice-versa.

This is a type safety issue due to the nature of "substitutability" in TypeScript, also known as behavioral subtyping.  If A extends B is true, you should be able to use an A as a B.  If you can't, then A extends B is not true.

If you turn off --strict then the compiler uses the pre-TS-2.6 behavior of checking function parameters bivariantly, which is unsafe, but was allowed for reasons of productivity.  That might be off-topic here, but you can read more about it in the TypeScript FAQ entry for "Why are function parameters bivariant?"

Anyway, if you need a function type that accepts any number unknown parameters, you cannot safely use a function that only a specific subtype of unknown.  Observe:

```<code>const t: testArgsF = (b, s) => (b ? s.trim() : s).length
const u: unknownArgsF = t; // error!

u(1, 2, 3); // explosion at runtime! s.trim is not a function
</code>```

If testArgsF extends unknownArgsF were true, then you would be able to assign t to u above without error, leading immediately to runtime errors when u happily accepts a non-string second argument.

You can see that the only safe way to subtype/implement a function type is for the subtype/implementation to accept arguments that are the same or wider than those expected by the supertype/call-signature.  That's why --strictFunctionTypes was introduced to the language.

If you change unknown to any (using anyArgsF instead of unknownArgsF) then the compiler will not complain because any is intentionally unsound in TypeScript.  The type any is considered to be assignable both to and from every other type; that's unsafe because, for example string extends any and any extends number are both true while string extends number is false.  The substitution principle above is therefore not enforced when any is involved.  Annotating a value as the any type is equivalent to loosening or turning off type checking for that value.   That doesn't save you from the runtime error; it just silences the compiler's error:

```<code>const a: anyArgsF = t; // okay, type checking with any is disabled/loosened
a(1, 2, 3); // same explosion at runtime!
</code>```

In the case where testNoArgsF extends unknownArgsF is true, this is also a consequence of substitutability.  You can use a function that takes no arguments as if it were just about any function type, since it will (usually) end up ignoring any arguments passed into it:

```<code>const n: testNoArgsF = () => 1;
const u2: unknownArgsF = n; // okay
u2(1, 2, 3); // okay at runtime, since `n` ignores its arguments
</code>```

This is explained in the TypeScript FAQ entry "Why are functions with fewer parameters assignable to functions that take more parameters?".

Okay, hope that helps; good luck!

Playground link to code

Body:
The title pretty much says it all really. I have this code:

  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.

Body:
With the --strictFunctionTypes compiler option enabled, function type parameters are checked contravariantly. "Contra-variant" means that the subtype relationship of the function varies in the opposite direction from that of function parameters.  So if A extends B, then (x: B)=>void extends (x: A)=>void and not vice-versa.

This is a type safety issue due to the nature of "substitutability" in TypeScript, also known as behavioral subtyping.  If A extends B is true, you should be able to use an A as a B.  If you can't, then A extends B is not true.

If you turn off --strict then the compiler uses the pre-TS-2.6 behavior of checking function parameters bivariantly, which is unsafe, but was allowed for reasons of productivity.  That might be off-topic here, but you can read more about it in the TypeScript FAQ entry for "Why are function parameters bivariant?"

Anyway, if you need a function type that accepts any number unknown parameters, you cannot safely use a function that only a specific subtype of unknown.  Observe:

const t: testArgsF = (b, s) => (b ? s.trim() : s).length
const u: unknownArgsF = t; // error!

u(1, 2, 3); // explosion at runtime! s.trim is not a function

If testArgsF extends unknownArgsF were true, then you would be able to assign t to u above without error, leading immediately to runtime errors when u happily accepts a non-string second argument.

You can see that the only safe way to subtype/implement a function type is for the subtype/implementation to accept arguments that are the same or wider than those expected by the supertype/call-signature.  That's why --strictFunctionTypes was introduced to the language.

If you change unknown to any (using anyArgsF instead of unknownArgsF) then the compiler will not complain because any is intentionally unsound in TypeScript.  The type any is considered to be assignable both to and from every other type; that's unsafe because, for example string extends any and any extends number are both true while string extends number is false.  The substitution principle above is therefore not enforced when any is involved.  Annotating a value as the any type is equivalent to loosening or turning off type checking for that value.   That doesn't save you from the runtime error; it just silences the compiler's error:

const a: anyArgsF = t; // okay, type checking with any is disabled/loosened
a(1, 2, 3); // same explosion at runtime!

In the case where testNoArgsF extends unknownArgsF is true, this is also a consequence of substitutability.  You can use a function that takes no arguments as if it were just about any function type, since it will (usually) end up ignoring any arguments passed into it:

const n: testNoArgsF = () => 1;
const u2: unknownArgsF = n; // okay
u2(1, 2, 3); // okay at runtime, since `n` ignores its arguments

This is explained in the TypeScript FAQ entry "Why are functions with fewer parameters assignable to functions that take more parameters?".

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/?#code/C4TwDgpgBMEM7AHIHsCCAnA5nAYlAvFABQCUBAfFAHYCuAtgEYToDcAUKJDPMBtnoSIBDLAEYAXFAbJkAGwhCqAGigjMAJkkJ0ASyqYy+SrUbN2naDSoBrKsgDuVPrgLEAdB7VxJV2w6oA2gC6hsb0TKwc4NCKIM4C7p5Y3qpUIMGh1OFmbFFcsAgAkoWuBbzJeBAAHrBUACZwqXEVUAD8MOg00JIAZkKycBAsUAD0Ix1dedBlxSWEAAoiQnQQsOhwADxl8ZTVtQ1Qi+jLq8ybvnaOO2xQbRMQN1C9-YPDY-e571bVkADGsHVxFNuEUAGqlHjxKB7CD1RoXfxQ9rATrdKB9AZDUbjDGDKAbAC0UHsAAsQK02O8IAA3WEwEnIGiYElAiwg4DgwhlFBQmFwqAIq4tZGop7ol5Y94oya5X7IKgIGCSbYtQQMFRwTJEBh3OBuFE6OikMWatzyfTAElsOUK4ACnw2S5OVUwN7jZjoZDoACEbBoRFEKnUKgAzCQ3dCqmBZMg4Dp5ao7Z0qMBDRBvVA9Qa6FAdI07HahOirP941RZfLFUJJLEoVyI8hrEIQGwhAGg6Hw9jI9HY2XE1Bk6mVr6K7bqMqeDyXcajFBROwbYqaJoBY7ES6qA2my2V+2oMGoGHt82B0O0xq9L9oAADKg33OYOzoeC54CNNT0WHvoA" rel="noreferrer">Playground link to code


来源: stackexchange

问:
Get result and state instead of just state from State Monad
I have this code:
runState (do { put 5; return 'X' }) 1 and the effect is: ('X',5). I would like to extract both result - 'X' and current state - 5 in a do block, then do something with them. However when I use the get function like: z <- get it sets the result to the current state destroying the value 5. How can I accomplish this?

答:
You may do this:

```<code>foo = do
    x <- do
        put 5
        return 'X'
    five <- get
    {- ... whatever you want ... -}
</code>```

In whatever you want, the variable x will be 'X', and the variable five will be 5.

ContentLicense: CC BY-SA 4.0

Body:
You may do this:

foo = do
    x <- do
        put 5
        return 'X'
    five <- get
    {- ... whatever you want ... -}

In whatever you want, the variable x will be 'X', and the variable five will be 5.


问:
Import Custom Module in Python [Although it works in PyCharm]
I see the question has already been asked thousands times, but I'm utterly confused.

I'm trying to run hello.py which import utils.common into hello.py

from utils.common import function

And I get the following error:

ModuleNotFoundError: No module named 'utils'

So my structure is the following:

```<code>── gig
    ├── __init__.py
    ├── src
    │   ├── __init__.py
    │   ├── hello
    │   │   ├── __init__.py
    │   │   └── hello.py
    │   └── utils
    │       ├── __init__.py
    │       ├── common.py
</code>```

Provided __init__.py in gig and in src as well, nothing changes though.

P.S. Imports work fine in PyCharm, the issue arises in docker container or when I try to run it locally from terminal.

Any pointers are very much appreciated.

Cheers,

Giga

答: usually your full import path: gig.src.utils.common should work.

Body:
I see the question has already been asked thousands times, but I'm utterly confused.

I'm trying to run hello.py which import utils.common into hello.py

from utils.common import function

And I get the following error:

ModuleNotFoundError: No module named 'utils'

So my structure is the following:

── gig
    ├── __init__.py
    ├── src
    │   ├── __init__.py
    │   ├── hello
    │   │   ├── __init__.py
    │   │   └── hello.py
    │   └── utils
    │       ├── __init__.py
    │       ├── common.py

Provided __init__.py in gig and in src as well, nothing changes though.

P.S. Imports work fine in PyCharm, the issue arises in docker container or when I try to run it locally from terminal.

Any pointers are very much appreciated.

Cheers,

Giga


问:
Manipulating large dataset with dcast
Apologies if this is a repeat question but I could not find the specific answer I am looking for. I have a dataframe with counts of different species caught on a given trip. A simplified example with 5 trips and 4 species is below:

```<code>trip = c(1,1,1,2,2,3,3,3,3,4,5,5)
species = c("a","b","c","b","d","a","b","c","d","c","c","d")
count = c(5,7,3,1,8,10,1,4,3,1,2,10)

dat = cbind.data.frame(trip, species, count)
dat

> dat
   trip species count
1     1       a     5
2     1       b     7
3     1       c     3
4     2       b     1
5     2       d     8
6     3       a    10
7     3       b     1
8     3       c     4
9     3       d     3
10    4       c     1
11    5       c     2
12    5       d    10
</code>```

I am only interested in the counts of species b for each trip. So I want to manipulate this data frame so I end up with one that looks like this:

```<code>trip2 = c(1,2,3,4,5)
species2 = c("b","b","b","b","b")
count2 = c(7,1,1,0,0)

dat2 = cbind.data.frame(trip2, species2, count2)
dat2

> dat2
  trip2 species2 count2
1     1        b      7
2     2        b      1
3     3        b      1
4     4        b      0
5     5        b      0
</code>```

I want to keep all trips, including trips where species b was not observed. So I can't just subset the data by species b. I know I can cast the data so species are the columns and then just remove the columns for the other species like so:

```<code>library(dplyr)
library(reshape2)
test = dcast(dat, trip ~ species, value.var = "count", fun.aggregate = sum)
test

> test
  trip  a b c  d
1    1  5 7 3  0
2    2  0 1 0  8
3    3 10 1 4  3
4    4  0 0 1  0
5    5  0 0 2 10
</code>```

However, my real dataset has several hundred species caught on thousands of trips, and if I try to cast that many species to columns R  chokes. There are way too many columns. Is there a way to specify in dcast that I only want to cast species b? Or is there another way to do this that doesn't require casting the data? Thank you.

答:
Here is a data.table approach which I suspect will be very fast for you:

```<code>library(data.table)
setDT(dat)
result <- dat[,.(species = "b", count = sum(.SD[species == "b",count])),by = trip]
result
   trip species count
1:    1       b     7
2:    2       b     1
3:    3       b     1
4:    4       b     0
5:    5       b     0
</code>```

Title: Manipulating large dataset with dcast

Body:
Apologies if this is a repeat question but I could not find the specific answer I am looking for. I have a dataframe with counts of different species caught on a given trip. A simplified example with 5 trips and 4 species is below:

trip = c(1,1,1,2,2,3,3,3,3,4,5,5)
species = c("a","b","c","b","d","a","b","c","d","c","c","d")
count = c(5,7,3,1,8,10,1,4,3,1,2,10)

dat = cbind.data.frame(trip, species, count)
dat

> dat
   trip species count
1     1       a     5
2     1       b     7
3     1       c     3
4     2       b     1
5     2       d     8
6     3       a    10
7     3       b     1
8     3       c     4
9     3       d     3
10    4       c     1
11    5       c     2
12    5       d    10

I am only interested in the counts of species b for each trip. So I want to manipulate this data frame so I end up with one that looks like this:

trip2 = c(1,2,3,4,5)
species2 = c("b","b","b","b","b")
count2 = c(7,1,1,0,0)

dat2 = cbind.data.frame(trip2, species2, count2)
dat2

> dat2
  trip2 species2 count2
1     1        b      7
2     2        b      1
3     3        b      1
4     4        b      0
5     5        b      0

I want to keep all trips, including trips where species b was not observed. So I can't just subset the data by species b. I know I can cast the data so species are the columns and then just remove the columns for the other species like so:

library(dplyr)
library(reshape2)
test = dcast(dat, trip ~ species, value.var = "count", fun.aggregate = sum)
test

> test
  trip  a b c  d
1    1  5 7 3  0
2    2  0 1 0  8
3    3 10 1 4  3
4    4  0 0 1  0
5    5  0 0 2 10

However, my real dataset has several hundred species caught on thousands of trips, and if I try to cast that many species to columns R  chokes. There are way too many columns. Is there a way to specify in dcast that I only want to cast species b? Or is there another way to do this that doesn't require casting the data? Thank you.

Body:
Here is a data.table approach which I suspect will be very fast for you:

library(data.table)
setDT(dat)
result <- dat[,.(species = "b", count = sum(.SD[species == "b",count])),by = trip]
result
   trip species count
1:    1       b     7
2:    2       b     1
3:    3       b     1
4:    4       b     0
5:    5       b     0


问:
Can't push old elements up one place in an array
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.  </p>

```<code> public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }
</code>```

答: Your for loop should be loop from end to first and you should set newElement after loop

Body:
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.

 public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }


问:
SSRS KeepWithGroup Property
Scenario: I have my SSRS report laid out like this:

```<code> Static Row Group       (KeepWithGroup = After)   <--  Static Rowgroup is associated to RowGroup1

  RowGroup1
      subRowGroup1
        subRowGroup2
  RowGroup2
</code>```

My report is structured in such a way where the Static Row Group which is a header is associated to rowgroup1. So after each iteration of RowGroup1 my headers displays.  RowGroup2 serves as a totals page
for the sum of my RowGroup1.  Is there a way to Call the Static rowgroup after BOTH RowGroups? The only option i have at the moment is to insert those rows as a copy above RowGroup2 Since it occurs only once, but I've been tasked with seeing if I can reuse the same static group. Any help would be appreciate thanks!

答:
SSRS doesn't have a built-in feature for this exact scenario. In other words, you would need to make a copy of the Static Row Group to make it show up again by RowGroup2.

If the concern had to do with limiting the complexity of the report, you may consider moving the calculations to be fields in the dataset. Then both static rows can reference those same fields and the expressions are maintained all in one place.

Title: SSRS KeepWithGroup Property

Body:
Scenario: I have my SSRS report laid out like this:

 Static Row Group       (KeepWithGroup = After)   <--  Static Rowgroup is associated to RowGroup1

  RowGroup1
      subRowGroup1
        subRowGroup2
  RowGroup2

My report is structured in such a way where the Static Row Group which is a header is associated to rowgroup1. So after each iteration of RowGroup1 my headers displays.  RowGroup2 serves as a totals page
for the sum of my RowGroup1.  Is there a way to Call the Static rowgroup after BOTH RowGroups? The only option i have at the moment is to insert those rows as a copy above RowGroup2 Since it occurs only once, but I've been tasked with seeing if I can reuse the same static group. Any help would be appreciate thanks!


问:
Python not writing whole output into file
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)
</code>```

Content of writing.txt

```<code>/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&
</code>```

Output of internallinks.txt

```<code>www.icom.org.cn/icom/faculty/viewer/?id=470&
</code>```

Output of command print (combined) before with is closed

```<code>PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>
</code>```

答:
In the while loop, you are re-assigning the out_str variable to the current value of combined. Instead, for your desired output, you should be appending the new value ,i.e. combined to out_str.
Just replace

```<code>for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = "".join(combined)
</code>```

with

```<code>for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = out_str + combined
</code>```

and your code should be fine.

Body:
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)

Content of writing.txt

/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&

Output of internallinks.txt

www.icom.org.cn/icom/faculty/viewer/?id=470&

Output of command print (combined) before with is closed

PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>

Body:
In the while loop, you are re-assigning the out_str variable to the current value of combined. Instead, for your desired output, you should be appending the new value ,i.e. combined to out_str.
Just replace

for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = "".join(combined)

with

for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = out_str + combined

and your code should be fine.


问:
Why Controls.Find doesn't work with ToolStripMenuItem?
I am using the following method to access a controls properties via the control name:

```<code>var ctrl = frm.Controls.Find("textbox1", true).FirstOrDefault();
ctrl.Enabled = Convert.ToBoolean(ctrlperm.Value.ToString());
</code>```

and it is working fine, But it doesn't seem to work with ToolStripMenuItem because when I'm trying to use it with ToolStripMenuItem I get error message:

Object reference not set to an instance of an object

another problem is that when I'm using this code I don't really know the type of the control that i'm dealing with, meaning that it might be a ToolStripMenuItem or any other control, so Is there a unified way to access any control via its name?

答: In response to @Claudio P, what if thee menuItem doesn't have an owner so therefore it has no control.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using the following method to access a controls properties via the control name:

var ctrl = frm.Controls.Find("textbox1", true).FirstOrDefault();
ctrl.Enabled = Convert.ToBoolean(ctrlperm.Value.ToString());

and it is working fine, But it doesn't seem to work with ToolStripMenuItem because when I'm trying to use it with ToolStripMenuItem I get error message:

Object reference not set to an instance of an object

another problem is that when I'm using this code I don't really know the type of the control that i'm dealing with, meaning that it might be a ToolStripMenuItem or any other control, so Is there a unified way to access any control via its name?


问:
How to trigger another button when I press enter key inside my form
I have a search bar where if I type anything it processes the answer or the output in another Modal. and then, if I click [search] button, then the modal triggers. Now I want that if I press enter inside the box, it will trigger the button.

```<code> <form class="form-inline" >
        <input class="form-control mr-sm-1" onkeyup="SearchFunction()" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">

        <a class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-
target="#resultsModal">Search</a>
      </form>
</code>```

I am very very weak at javascript. please give me suggestions on how can I  make it possible.

答:
```<code><form class="form-inline" id="myForm">
        <input class="form-control mr-sm-1" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">

        <a class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-
target="#resultsModal">Search</a>
      </form>

<script type="text/javascript">
    var form = document.getElementById("myForm");
    function handleForm(event) { event.preventDefault(); }
    form.addEventListener('submit', submit);

    function submit(event) {
        event.preventDefault()
        console.log('code here')
    }
</script>
</code>```

Body:
I have a search bar where if I type anything it processes the answer or the output in another Modal. and then, if I click [search] button, then the modal triggers. Now I want that if I press enter inside the box, it will trigger the button.

 <form class="form-inline" >
        <input class="form-control mr-sm-1" onkeyup="SearchFunction()" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">

        Search
      </form>

I am very very weak at javascript. please give me suggestions on how can I  make it possible.


问:
(In general) should ASP.NET MVC be used as the backend for an Angular app?
Most of my experience is in the Java stack/community. But I was just moved onto a brand new project for a brand new webapp that will use a .NET stack.

One of my superiors suggested that we implement this brand new webapp using an Angular frontend and a ASP.NET MVC backend. I know that it is possible for an Angular frontend to use an ASP.NET MVC backend. But I also know that one of the main draws of ASP.NET MVC is the Razor view engine, which we would not be using. Furthermore, Wikipedia says that ASP.NET MVC is discontinued. Therefore my question - is it recommended to use ASP.NET MVC as the backend for an Angular app?

答:
yes, using angular as a front end and asp.net mvc as a backend is a good combination.
You can use asp.net web api (with EFCore + SQlServer database )to build your rest services and use angular to consume it in frontend.


问:
Creating a list or tuple out of one word-per-line in vim
I come across the following pattern quite frequently, where I have to copy-paste a bunch of items (usually in excel) into something like a SQL query and often the simplest way to do this is copy-paste the data into vim and then run a macro/command on it to format it. Here is an example of input data:

This involves three steps for me:

Delete empty lines: :g!/\S/d

Add quotes around it and a , separator: :% s/\v(\S+)/"\1",

Put it onto one line and add a wrapping [...] or (...): ggVG (select all), J (condense-all), 0i(CTRL-o$)

Is there a way I can put all this into a function or macro, or what's the best way that I could take the above input and enter some keyboard shortcut, such as ⌘s and it formats everything in the above way?

While it might seem overkill, this is something that I can do pretty easily and quickly (without really thinking) in an editor like TextMate where I can use a multi-cursor.

答:
I figured another option:

```<code>:%s/\v(\w+)\n+/"\1",/g | norm $x | exec "norm! I(\<Esc>A)"
</code>```

As a command line option:

```<code>vim -c ':%s/\v(\w+)\n+/"\1",/g | norm $x | s/.*/(&)/g' -c wq target.txt

-c ........... vim command line (interactive shell)
\v ........... very magic (simple regex system)
\w+ .......... one or more words per line
\n+ .......... one or more line breaks
() ........... regex group
\1 ........... repeat the first regex group
normal $x .... deletes the last character of the remaining single line
</code>```

Once I am using only the words \w+ inside the regex group, the line breaks are ignored in the substitution. In the last substitution we dont need more % because at this point we have a single line.

Body:
I figured another option:

:%s/\v(\w+)\n+/"\1",/g | norm $x | exec "norm! I(\<Esc>A)"

As a command line option:

vim -c ':%s/\v(\w+)\n+/"\1",/g | norm $x | s/.*/(&)/g' -c wq target.txt

-c ........... vim command line (interactive shell)
\v ........... very magic (simple regex system)
\w+ .......... one or more words per line
\n+ .......... one or more line breaks
() ........... regex group
\1 ........... repeat the first regex group
normal $x .... deletes the last character of the remaining single line

Once I am using only the words \w+ inside the regex group, the line breaks are ignored in the substitution. In the last substitution we dont need more % because at this point we have a single line.


答:
Use, pd.merge to left merge the dataframes df1 & df2 on column Sname, Then using Series.fillna fill the NaN values in PSMark column from PhySci column and assign the PSMark column to PhySci:

```<code>df  = pd.merge(df1, df2, on='Sname', how='left')
df = df.assign(PhySci=df.pop('PSMark').fillna(df['PhySci']).astype(int))
</code>```

Result:

```<code># print(df)

  Sname  Tamil  English  Maths  Science  Sscience  PhySci
0   Abu     35       65     64       98        36       0
1  Eric     70       54     65       32        58      25
2  Mani     56       25     32       32        78      32
3   Ram     80       24     68       54        76      54
4   Tom     40       26     56       69        42      69
5   Eva     50       18     56       87        56      87
</code>```

Title: update join pandas - python

Body:
How to achieve update join on pandas native statement (.apply())?
I want to update PSMark from Dataframe2 on PhySci in Dataframe1

Dataframe1 (tbl_ex):

|    | Sname   |   Tamil |   English |   Maths |   Science |   Sscience |   PhySci |
|---:|:--------|--------:|----------:|--------:|----------:|-----------:|---------:|
|  0 | Abu     |      35 |        65 |      64 |        98 |         36 |        0 |
|  1 | Eric    |      70 |        54 |      65 |        32 |         58 |       25 |
|  2 | Mani    |      56 |        25 |      32 |        32 |         78 |       10 |
|  3 | Ram     |      80 |        24 |      68 |        54 |         76 |        0 |
|  4 | Tom     |      40 |        26 |      56 |        69 |         42 |       65 |
|  5 | Eva     |      50 |        18 |      56 |        87 |         56 |        0 |

Dataframe2 (tbl_fy):

|    | Sname   |   PSMark |
|---:|:--------|---------:|
|  0 | Tom     |       69 |
|  1 | Ram     |       54 |
|  2 | Mani    |       32 |
|  3 | Eva     |       87 |
|  4 | Sam     |       89 |

I achieved this with sqldf module

q="""
    UPDATE tbl_ex
    SET
      PhySci = (SELECT tbl_fy.PSMark
                            FROM tbl_fy
                            WHERE tbl_fy.Sname = tbl_ex.Sname )
    WHERE
    EXISTS (
        SELECT *
        FROM tbl_fy
        WHERE tbl_fy.Sname = tbl_ex.Sname );
    """

sqldf.run(q)
print(tbl_ex.to_markdown())

Final Result from tbl_ex:

|    | Sname   |   Tamil |   English |   Maths |   Science |   Sscience |   PhySci |
|---:|:--------|--------:|----------:|--------:|----------:|-----------:|---------:|
|  0 | Abu     |      35 |        65 |      64 |        98 |         36 |        0 |
|  1 | Eric    |      70 |        54 |      65 |        32 |         58 |       25 |
|  2 | Mani    |      56 |        25 |      32 |        32 |         78 |       32 |
|  3 | Ram     |      80 |        24 |      68 |        54 |         76 |       54 |
|  4 | Tom     |      40 |        26 |      56 |        69 |         42 |       69 |
|  5 | Eva     |      50 |        18 |      56 |        87 |         56 |       87 |

Body:
Use, pd.merge to left merge the dataframes df1 & df2 on column Sname, Then using Series.fillna fill the NaN values in PSMark column from PhySci column and assign the PSMark column to PhySci:

df  = pd.merge(df1, df2, on='Sname', how='left')
df = df.assign(PhySci=df.pop('PSMark').fillna(df['PhySci']).astype(int))

Result:

# print(df)

  Sname  Tamil  English  Maths  Science  Sscience  PhySci
0   Abu     35       65     64       98        36       0
1  Eric     70       54     65       32        58      25
2  Mani     56       25     32       32        78      32
3   Ram     80       24     68       54        76      54
4   Tom     40       26     56       69        42      69
5   Eva     50       18     56       87        56      87


问:
Define a custom date format and converter with Spring Data Elasticsearch
I'm currently migrating from Spring Data Elasticsearch 3.2.x to 4.0.0.

I'm removing a JacksonEntityMapper, that defined a custom ZonedDateTimeDeserializer, to use the ElasticsearchEntityMapper

I have a ZonedDateTime field defined as follows:

```<code>    @Field(type = Date, format = DateFormat.date_time)
    private final ZonedDateTime loggedIn;
</code>```

However, the deserialization of this loses the zone information, so that a comparison between the field before and after being stored fails:

before

```<code>loggedIn=2020-06-01T09:50:27.389589+01:00[Europe/London]
</code>```

after

```<code>loggedIn=2020-06-01T09:50:27.389+01:00
</code>```

I expect the zone information to be lost as only the timezone offset is being stored. With the Jackson ZonedDateTimeDeserializer I was able to apply the Zone during the ZonedDateTime construction.

Ideally, I'd like to define a custom date format and converter classes to handle my scenario.

I've tried the following field configuration:

```<code>    @Field(type = Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ")
    private final ZonedDateTime loggedIn;
</code>```

With Reading/WritingConverters

```<code>@WritingConverter
public class ZonedDateTimeToStringConverter implements Converter<ZonedDateTime, String>  {

    @Override
    public String convert(ZonedDateTime source) {
        return source.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

@ReadingConverter
public class StringToZonedDateTimeConverter implements Converter<String, ZonedDateTime>  {

    @Override
    public ZonedDateTime convert(String source) {
        return ZonedDateTime.parse(source, DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.systemDefault()));
    }
}
</code>```

and configuration

```<code>public class ElasticConfiguration extends AbstractElasticsearchConfiguration {

    @Bean
    @Override
    public ElasticsearchCustomConversions elasticsearchCustomConversions() {
        return new ElasticsearchCustomConversions(List.of(new ZonedDateTimeToStringConverter(),
                                                          new StringToZonedDateTimeConverter()));
    }
}
</code>```

However, the reading of the field fails with an exception

```<code>Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {YearOfEra=2020, MonthOfYear=8, DayOfMonth=20, OffsetSeconds=3600},ISO resolved to 11:11:11.123 of type java.time.format.Parsed
    at java.base/java.time.LocalDate.from(LocalDate.java:396)
    at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:560)
    at org.springframework.data.elasticsearch.core.convert.ElasticsearchDateConverter.parse(ElasticsearchDateConverter.java:109)
    at org.springframework.data.elasticsearch.core.convert.ElasticsearchDateConverter.parse(ElasticsearchDateConverter.java:114)
    ...
</code>```

Looking at the exception, when comparing the parsing against the successful DateFormat.date_time read, I may have an error in the pattern. The TemporalAccessor for the DateFormat.date_time is {OffsetSeconds=3600, InstantSeconds=1597918271},ISO resolved to 2020-08-20T11:11:11.123, whereas my custom pattern parses to {YearOfEra=2020, MonthOfYear=8, DayOfMonth=20, OffsetSeconds=3600},ISO resolved to 11:11:11.123

But it also seems that the custom converters I specified aren't being picked up. Note. I have other customer converters specified that are being picked up so don't believe it's a configuration issue.

Any help would be appreciated, I'm not sure why the custom pattern fails, but think I could avoid it if the custom converters were picked up. I can workaround the issue for now, but ideally I'd like everything to be consistent before and after the upgrade.

答:
Don't use yyyy in a date pattern, change it to (see the Elasticsearch docs)

```<code>pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSSSSZ")
</code>```

By defining the property as FieldType.Dateinternally a converter is created for this property and used; the custom converters aren't needed

Body:
I'm currently migrating from Spring Data Elasticsearch 3.2.x to 4.0.0.

I'm removing a JacksonEntityMapper, that defined a custom ZonedDateTimeDeserializer, to use the ElasticsearchEntityMapper

I have a ZonedDateTime field defined as follows:

    @Field(type = Date, format = DateFormat.date_time)
    private final ZonedDateTime loggedIn;

However, the deserialization of this loses the zone information, so that a comparison between the field before and after being stored fails:

before

loggedIn=2020-06-01T09:50:27.389589+01:00[Europe/London]

after

loggedIn=2020-06-01T09:50:27.389+01:00

I expect the zone information to be lost as only the timezone offset is being stored. With the Jackson ZonedDateTimeDeserializer I was able to apply the Zone during the ZonedDateTime construction.

Ideally, I'd like to define a custom date format and converter classes to handle my scenario.

I've tried the following field configuration:

    @Field(type = Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ")
    private final ZonedDateTime loggedIn;

With Reading/WritingConverters

@WritingConverter
public class ZonedDateTimeToStringConverter implements Converter<ZonedDateTime, String>  {

    @Override
    public String convert(ZonedDateTime source) {
        return source.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

@ReadingConverter
public class StringToZonedDateTimeConverter implements Converter<String, ZonedDateTime>  {

    @Override
    public ZonedDateTime convert(String source) {
        return ZonedDateTime.parse(source, DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.systemDefault()));
    }
}

and configuration

public class ElasticConfiguration extends AbstractElasticsearchConfiguration {

    @Bean
    @Override
    public ElasticsearchCustomConversions elasticsearchCustomConversions() {
        return new ElasticsearchCustomConversions(List.of(new ZonedDateTimeToStringConverter(),
                                                          new StringToZonedDateTimeConverter()));
    }
}

However, the reading of the field fails with an exception

Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {YearOfEra=2020, MonthOfYear=8, DayOfMonth=20, OffsetSeconds=3600},ISO resolved to 11:11:11.123 of type java.time.format.Parsed
    at java.base/java.time.LocalDate.from(LocalDate.java:396)
    at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:560)
    at org.springframework.data.elasticsearch.core.convert.ElasticsearchDateConverter.parse(ElasticsearchDateConverter.java:109)
    at org.springframework.data.elasticsearch.core.convert.ElasticsearchDateConverter.parse(ElasticsearchDateConverter.java:114)
    ...

Looking at the exception, when comparing the parsing against the successful DateFormat.date_time read, I may have an error in the pattern. The TemporalAccessor for the DateFormat.date_time is {OffsetSeconds=3600, InstantSeconds=1597918271},ISO resolved to 2020-08-20T11:11:11.123, whereas my custom pattern parses to {YearOfEra=2020, MonthOfYear=8, DayOfMonth=20, OffsetSeconds=3600},ISO resolved to 11:11:11.123

But it also seems that the custom converters I specified aren't being picked up. Note. I have other customer converters specified that are being picked up so don't believe it's a configuration issue.

Any help would be appreciated, I'm not sure why the custom pattern fails, but think I could avoid it if the custom converters were picked up. I can workaround the issue for now, but ideally I'd like everything to be consistent before and after the upgrade.

Body:
Don't use yyyy in a date pattern, change it to (see the Elasticsearch docs)

pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSSSSZ")

By defining the property as FieldType.Dateinternally a converter is created for this property and used; the custom converters aren't needed


问:
How to do proper Git compatible hex sha packing/compression in Node.js
I'm currently trying to port a ruby code to javascript.
And i have this

```<code>ENTRY_FORMAT = "A7Z*H40"
mode = "100644"
fileName = "tree.js"
sha= "baae99010b237a699ff0aba02fd5310c18903b1b"
[mode, filename, sha].pack(ENTRY_FORMAT)
</code>```

Where MODE, entry.name and entry.oid are string

• A7 :
this encodes the first string, MODE , as a seven-byte string padded on the right with spaces

• Z* : this encodes the second string, entry.name , as an arbitrary-length null-padded string, that
is, it represents the string as-is with a null byte appended to the end

•H40 :this encodes a string of forty hexadecimal digits, entry.oid , by packing each pair of
digits into a single byte as we saw in Section 2.3.3, “Trees on disk”

Can i do this in javaScript ?

答:
I'll assume you meant mode was also a string.

let fileName = "file.js";
let sha = "baae99010b237a699ff0aba02fd5310c18903b1b";
let mode = '100664';

// encode all into bytes
let enc = new TextEncoder();
let modeArray = enc.encode(mode.padEnd(7));
let fileNameArray = enc.encode(fileName + '\0');
let shaArray = Uint8Array.from(sha.match(/../g), x => parseInt(x, 16));

// concatenate together
let array = new Uint8Array([...modeArray, ...fileNameArray, ...shaArray]);

console.log(array);```
</div>
</div>
</p>

<p>Node.js has <code>Buffer</code> class, which simplifies some of these operations:</p>

```let modeBuffer = Buffer.from(mode.padEnd(7));
let fileNameBuffer = Buffer.from(fileName + '\0');
let shaBuffer = Buffer.from(sha, 'hex');
let buffer = Buffer.concat([modeBuffer, fileNameBuffer, shaBuffer]);
// can fs.writeFile(file, buffer, ...)
```

Body:
I'm currently trying to port a ruby code to javascript.
And i have this

ENTRY_FORMAT = "A7Z*H40"
mode = "100644"
fileName = "tree.js"
sha= "baae99010b237a699ff0aba02fd5310c18903b1b"
[mode, filename, sha].pack(ENTRY_FORMAT)

Where MODE, entry.name and entry.oid are string

• A7 :
this encodes the first string, MODE , as a seven-byte string padded on the right with spaces

• Z* : this encodes the second string, entry.name , as an arbitrary-length null-padded string, that
is, it represents the string as-is with a null byte appended to the end

•H40 :this encodes a string of forty hexadecimal digits, entry.oid , by packing each pair of
digits into a single byte as we saw in Section 2.3.3, “Trees on disk”

Can i do this in javaScript ?

Body:
I'll assume you meant mode was also a string.

let fileName = "file.js";
let sha = "baae99010b237a699ff0aba02fd5310c18903b1b";
let mode = '100664';

// encode all into bytes
let enc = new TextEncoder();
let modeArray = enc.encode(mode.padEnd(7));
let fileNameArray = enc.encode(fileName + '\0');
let shaArray = Uint8Array.from(sha.match(/../g), x => parseInt(x, 16));

// concatenate together
let array = new Uint8Array([...modeArray, ...fileNameArray, ...shaArray]);

console.log(array);

Node.js has Buffer class, which simplifies some of these operations:

let modeBuffer = Buffer.from(mode.padEnd(7));
let fileNameBuffer = Buffer.from(fileName + '\0');
let shaBuffer = Buffer.from(sha, 'hex');
let buffer = Buffer.concat([modeBuffer, fileNameBuffer, shaBuffer]);
// can fs.writeFile(file, buffer, ...)


问:
SVG polygon to fill svg parent
I have an svg polygon and I am trying to get the polygon to fill to the size of the svg container. Changing the height and width attributes scales the polygon as expected however I do not want any of the whitespace between the polygon and svg. Is there a way to achieve this without having to re-do the points?</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>2</title>
    <g id="2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <polygon id="Rectangle" fill="#000000" points="6 4 14 4 14 12.6416575 10 16 6 12.6416575"></polygon>
    </g>
</svg>
</code>```

答:
You could adjust the viewBox instead e.g.

<svg width="20px" height="20px" viewBox="6 4 8 12" preserveAspectRatio="none" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background-color:red">
    <title>2</title>
    <g id="2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <polygon id="Rectangle" fill="#000000" points="6 4 14 4 14 12.6416575 10 16 6 12.6416575"></polygon>
    </g>
</svg>```

Title: SVG polygon to fill svg parent

Body:
I have an svg polygon and I am trying to get the polygon to fill to the size of the svg container. Changing the height and width attributes scales the polygon as expected however I do not want any of the whitespace between the polygon and svg. Is there a way to achieve this without having to re-do the points?

<?xml version="1.0" encoding="UTF-8"?>
<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>2</title>
    <g id="2" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <polygon id="Rectangle" fill="#000000" points="6 4 14 4 14 12.6416575 10 16 6 12.6416575"></polygon>
    </g>
</svg>


问:
Need to compare two columns and complete a third with data from one the sheets
I have to compare two columns from two sheets with some data. If the columns have the same data, i have to display the data of one the sheets (a third column).

I tried with a

If, Vlookup and Index

formula but its not working, at least for me.

On Sheet 1 i have the "G" Column (original data) and on Sheet 2 i have the "C" column. If both cells match, i need the data from the "A" column on Sheet 2 to be displayed.

Can anyone give me a hand?

Thanks!

答:
Assuming you want the result on Sheet 1, on Sheet 1 use formula like this:

```<code>=INDEX(SHEET2!A:A,MATCH(G1,SHEET2!C:C,0))
</code>```

I recommend you to limit the ranges (A:A and C:C) to match actual data tables to increase performance.

Body:
Assuming you want the result on Sheet 1, on Sheet 1 use formula like this:

=INDEX(SHEET2!A:A,MATCH(G1,SHEET2!C:C,0))

I recommend you to limit the ranges (A:A and C:C) to match actual data tables to increase performance.


问:
Error while linking a custom dynamic library Rust
In a directory I have a C file and its header

/home/test/c_pro

```<code>  f.c
  f.h
  libf.so
</code>```

I have compiled the f.c into a dll called libf.so using the following command

```<code>gcc -c -fPIC f.c -o f.o
gcc f.o -shared -o f.so
</code>```

I want to use this in my Rust project.

So in Rust project I have a build.rs

```<code>println!("cargo:rustc-link-search=/home/test/c_pro");
println!("cargo:rustc-link-lib=dylib=f")
</code>```

When I run a cargo build the build fails with the following errors

```<code>/home/test/c_pro/f.so: undefined reference to `EC_KEY_new_by_curve_name'
      collect2: error: ld returned 1 exit status
</code>```

In my f.c I do some imports from openssl

```<code>#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
</code>```

and use symbols from these libraries.

Any ideas as to why the build fails? I am following the official doc and am relying on 2 build parameters

cargo:rustc-link-search so that cargo can know that he has to do a look up in this directory as well.

cargo:rustc-link-lib=dylib  to tell what dynamic library to link to.

What am I missing here folks?
Thanks in advance.

EDIT+UPDATE:

I did as pointed out by @Uli Schlachter and it compiles but I get a runtime error stating that libf.so is not found.

```<code>ldd ./target/debug/test_f
    libf.so => not found.
</code>```

Any ideas?

答:
Compile your shared object with</p>

```<code>gcc -c -fPIC f.c -o f.o
gcc f.o -shared -o f.so -lssl
</code>```

Body:
In a directory I have a C file and its header

/home/test/c_pro

  f.c
  f.h
  libf.so

I have compiled the f.c into a dll called libf.so using the following command

gcc -c -fPIC f.c -o f.o
gcc f.o -shared -o f.so

I want to use this in my Rust project.

So in Rust project I have a build.rs

println!("cargo:rustc-link-search=/home/test/c_pro");
println!("cargo:rustc-link-lib=dylib=f")

When I run a cargo build the build fails with the following errors

/home/test/c_pro/f.so: undefined reference to `EC_KEY_new_by_curve_name'
      collect2: error: ld returned 1 exit status

In my f.c I do some imports from openssl

#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>

and use symbols from these libraries.

Any ideas as to why the build fails? I am following the official doc and am relying on 2 build parameters

cargo:rustc-link-search so that cargo can know that he has to do a look up in this directory as well.

cargo:rustc-link-lib=dylib  to tell what dynamic library to link to.

What am I missing here folks?
Thanks in advance.

EDIT+UPDATE:

I did as pointed out by @Uli Schlachter and it compiles but I get a runtime error stating that libf.so is not found.

ldd ./target/debug/test_f
    libf.so => not found.

Any ideas?

Body:
Compile your shared object with

gcc -c -fPIC f.c -o f.o
gcc f.o -shared -o f.so -lssl


问:
Django ModelForm multiple check boxes aren't working
I'm working on an application form by using the Django model and  ModelForm class, in the application, it has multiple checkboxes. when I submit the form it is showing the error that the selected choice isn't a valid choice. I used the CheckboxSelectMultiple widget to select checkboxes. If anyone knows plz help me.

```<code> Models.py

 from django.db import models
 from django.urls import reverse

class Application(models.Model):

   genres1=(
   ('classical','Classical'),
   ('rock','Rock'),
   ('musical Theater','Musical Theater'),
   ('country','country'),
   ('blues','Blues'),
   ('christian Contemporary','Christian Contemporary'),
   ('gospel','Gospel'),
   ('other','Other'),
   )

   languages1=(
    ('english','English'),
    ('spanish','Spanish'),
    ('german','German'),
    ('chinese','Chinese'),
    ('hindi','Hindi'),
    ('french','French'),
    ('russian','Russian'),
    ('turkish','Turkish'),
    )
   firstname=models.CharField(max_length=50)
   lastname=models.CharField(max_length=50)
   Email=models.EmailField()
   phonenumber=models.CharField(max_length=15)
   genres=models.CharField(max_length=50, choices=genres1)
   languages=models.CharField(max_length=50, choices=languages1)

def __str__(self):
    return self.firstname
</code>```

forms.py

```<code>from django import forms
from django.forms import ModelForm
from .models import Application

class application(ModelForm):
   genres1=(
   ('classical','Classical'),
   ('rock','Rock'),
   ('musical Theater','Musical Theater'),
   ('country','country'),
   ('blues','Blues'),
   ('christian Contemporary','Christian Contemporary'),
   ('gospel','Gospel'),
   ('other','Other'),
)

languages1=(
    ('english','English'),
    ('spanish','Spanish'),
    ('german','German'),
    ('chinese','Chinese'),
    ('hindi','Hindi'),
    ('french','French'),
    ('russian','Russian'),
    ('turkish','Turkish'),
)
 genres=forms.MultipleChoiceField(required=True,widget=forms.CheckboxSelectMultiple,choices=genres1)
 languages=forms.MultipleChoiceField(required=True,widget=forms.CheckboxSelectMultiple,
 choices=languages1)
 class Meta:
    model=Application
    fields = '__all__'
</code>```

views.py

```<code> from django.shortcuts import render,redirect, get_object_or_404
 from onlinetutors.models import Category,tutors
 from .forms import application
 from .models import Application

 def registration(request):
    if request.method == 'POST':
    form=application(request.POST)
    if form.is_valid():
        form.save()
        firstname=form.cleaned_data['firstname']
        lastname=form.cleaned_data['lastname']
        Email=form.cleaned_data['Email']
        phonenumber=form.cleaned_data['phonenumber']
        genres=form.cleaned_data['genres']
        languages=form.cleaned_data['languages']
        form=Application(firstname=firstname,lastname=lastname,Email= Email,phonenumber=phonenumber,
        languages=languages,genres=genres)

        form.save()
        return redirect("/thankyou/")
else:
    form=application()
return render(request,"registration.html",{"form":form})
</code>```

答: i think the problem might be occuring because you repeated generes1 and languages1 choices in the form.py. Try delete that that is genere1 and languages1 choices. The form.py will use the choices from the models.py. Not too sure but try that and see.</p>

Body:
I'm working on an application form by using the Django model and  ModelForm class, in the application, it has multiple checkboxes. when I submit the form it is showing the error that the selected choice isn't a valid choice. I used the CheckboxSelectMultiple widget to select checkboxes. If anyone knows plz help me.

 Models.py

 from django.db import models
 from django.urls import reverse

class Application(models.Model):

   genres1=(
   ('classical','Classical'),
   ('rock','Rock'),
   ('musical Theater','Musical Theater'),
   ('country','country'),
   ('blues','Blues'),
   ('christian Contemporary','Christian Contemporary'),
   ('gospel','Gospel'),
   ('other','Other'),
   )

   languages1=(
    ('english','English'),
    ('spanish','Spanish'),
    ('german','German'),
    ('chinese','Chinese'),
    ('hindi','Hindi'),
    ('french','French'),
    ('russian','Russian'),
    ('turkish','Turkish'),
    )
   firstname=models.CharField(max_length=50)
   lastname=models.CharField(max_length=50)
   Email=models.EmailField()
   phonenumber=models.CharField(max_length=15)
   genres=models.CharField(max_length=50, choices=genres1)
   languages=models.CharField(max_length=50, choices=languages1)

def __str__(self):
    return self.firstname

forms.py

from django import forms
from django.forms import ModelForm
from .models import Application

class application(ModelForm):
   genres1=(
   ('classical','Classical'),
   ('rock','Rock'),
   ('musical Theater','Musical Theater'),
   ('country','country'),
   ('blues','Blues'),
   ('christian Contemporary','Christian Contemporary'),
   ('gospel','Gospel'),
   ('other','Other'),
)

languages1=(
    ('english','English'),
    ('spanish','Spanish'),
    ('german','German'),
    ('chinese','Chinese'),
    ('hindi','Hindi'),
    ('french','French'),
    ('russian','Russian'),
    ('turkish','Turkish'),
)
 genres=forms.MultipleChoiceField(required=True,widget=forms.CheckboxSelectMultiple,choices=genres1)
 languages=forms.MultipleChoiceField(required=True,widget=forms.CheckboxSelectMultiple,
 choices=languages1)
 class Meta:
    model=Application
    fields = '__all__'

views.py

 from django.shortcuts import render,redirect, get_object_or_404
 from onlinetutors.models import Category,tutors
 from .forms import application
 from .models import Application

 def registration(request):
    if request.method == 'POST':
    form=application(request.POST)
    if form.is_valid():
        form.save()
        firstname=form.cleaned_data['firstname']
        lastname=form.cleaned_data['lastname']
        Email=form.cleaned_data['Email']
        phonenumber=form.cleaned_data['phonenumber']
        genres=form.cleaned_data['genres']
        languages=form.cleaned_data['languages']
        form=Application(firstname=firstname,lastname=lastname,Email= Email,phonenumber=phonenumber,
        languages=languages,genres=genres)

        form.save()
        return redirect("/thankyou/")
else:
    form=application()
return render(request,"registration.html",{"form":form})


问:
Arithmetic with big numbers in browser, suspiciously fast?
I am trying to learn Diffie-Hellman, and the reason for its security should be because the computations needed to brute-force it should be so expensive that it would just not be worth it. However typing

(2n**2048n-1n)%(2n**2048n)
```

in Google Chrome gives an instant result. How come?

Body:
I am trying to learn Diffie-Hellman, and the reason for its security should be because the computations needed to brute-force it should be so expensive that it would just not be worth it. However typing

(2n**2048n-1n)%(2n**2048n)

in Google Chrome gives an instant result. How come?

Body:
2n**2048n is "only" 617 digits in decimal:

32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656n

% isn't a particularly difficult operation, even on a pair of numbers that large.

I think it's the sheer number of computations, not the difficulty of one of them, that's the key thing in Diffie-Hellman (though I have to admit not being a crypto guy).


问:
REGEX password validation without special characters
I am using this regex to validate my password.
My password -

should be alphanumeric ONLY,

contains at least 8 characters,

at least 2 numbers

and at least 2 alphabet.

My regex is

```<code>^.*(?=.{8,})(?=.*\d*\d)(?=.*[a-zA-Z]*[a-zA-Z])(?!.*\W).*$
</code>```

but unfortunately it still matches if I try to put special characters at the beginning.
For example @password12, !password12.

答:
Because your pattern begins and ends with .*, it will match anything at the beginning or end of the string, including special characters.

You shouldn't be solving this problem with a single regular expression, it makes the code hard to read and hard to modify. Write one function for each rule using whatever makes sense for that rule, then your validation script becomes crystal clear:

```<code>if is_alpha_only(password) &&
   len(password) > = 8 &&
   has_2_or_more_numbers(password) &&
   has_2_or_more_alpha(password) ...
</code>```

Seriously, what's the point of cramming all of that into a single regular expression?

And why disallow special characters? There's simply no reason for that.

Body:
I am using this regex to validate my password.
My password -

should be alphanumeric ONLY,

contains at least 8 characters,

at least 2 numbers

and at least 2 alphabet.

My regex is

^.*(?=.{8,})(?=.*\d*\d)(?=.*[a-zA-Z]*[a-zA-Z])(?!.*\W).*$

but unfortunately it still matches if I try to put special characters at the beginning.
For example @password12, !password12.

Body:
Because your pattern begins and ends with .*, it will match anything at the beginning or end of the string, including special characters.

You shouldn't be solving this problem with a single regular expression, it makes the code hard to read and hard to modify. Write one function for each rule using whatever makes sense for that rule, then your validation script becomes crystal clear:

if is_alpha_only(password) &&
   len(password) > = 8 &&
   has_2_or_more_numbers(password) &&
   has_2_or_more_alpha(password) ...

Seriously, what's the point of cramming all of that into a single regular expression?

And why disallow special characters? There's simply no reason for that.


问:
What is Put after the Equal Sign in '&source= in the LinkedIn Share Code?
I'm trying to create a LinkedIn share code in my web app, but I want to understand what every part of the code means before implementing it. Take this code for example:

```<code>$('.lisharelink').click(function() {
  var shareurl = $(this).data('shareurl');
  window.open('https://www.linkedin.com/shareArticle?mini=true&url=' + escape(shareurl) + '&title=' + document.title + '&source=whatever&target=new', '_blank', 'width=300,height=200');
  return false;
});
</code>```

What should one put for '&source=? Where does one find the information to put here?

答:
The parameter source, like title and summary, is no longer acceptable for the LinkedIn share URL.  If you want to share now, the only parameter allowed is url, like so...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Sharing Documentation.

However, if we look at an archive.org version of the Original LinkedIn Share Documentation (click the "Customized URL" tab), you'll see they say...

SOURCE:

description: The url-encoded source of the content (e.g. your website or application name)

maxlength: 200

required: No

So, it seems like it could've been either a domain or application name, as long as it is URL-encoded and under 200 characters.

Of course, it is no longer supported by the LinkedIn API.  Just use url and you'll be set.  If you want to set the other fields in the share preview, you'll need to set your og: tags, as per LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Body:
I'm trying to create a LinkedIn share code in my web app, but I want to understand what every part of the code means before implementing it. Take this code for example:

$('.lisharelink').click(function() {
  var shareurl = $(this).data('shareurl');
  window.open('https://www.linkedin.com/shareArticle?mini=true&url=' + escape(shareurl) + '&title=' + document.title + '&source=whatever&target=new', '_blank', 'width=300,height=200');
  return false;
});

What should one put for '&source=? Where does one find the information to put here?

Body:
The parameter source, like title and summary, is no longer acceptable for the LinkedIn share URL.  If you want to share now, the only parameter allowed is url, like so...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Sharing Documentation.

However, if we look at an archive.org version of the Original LinkedIn Share Documentation (click the "Customized URL" tab), you'll see they say...

SOURCE:

description: The url-encoded source of the content (e.g. your website or application name)

maxlength: 200

required: No

So, it seems like it could've been either a domain or application name, as long as it is URL-encoded and under 200 characters.

Of course, it is no longer supported by the LinkedIn API.  Just use url and you'll be set.  If you want to set the other fields in the share preview, you'll need to set your og: tags, as per LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.


问:
Parsing Nested Arrays Data
How to parse the data of Nested JS Array to Objects? I've tried different approaches by using for loop and Dict datatype but it's not working.

Background :
I'm using chart.js library to show some data points in Radar Chart.Now i am trying to parse the nested arrays data and convert each array of module into single object and then pass it's data to visualization chart.

```<code>// Input-->
JavaScript_Array=
[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],
["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],
["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],
["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]]

//Expected Output

    Final_Array=[{label: "Module1",  data: [9,5,8],Questions:[Q1,Q2,Q3] },
                 {label: "Module2",  data: [5,9,1],Questions:[Q1,Q2,Q3]},
                 {label: "Module3",  data: [2,1,3],Questions:[Q1,Q2,Q3]},
                 {label: "Module4",  data: [3,4,2],Questions:[Q1,Q2,Q3]}]
</code>```

答:
You could reduce the array and group based on the label. Create an accumulator with each unique label as the key and the object you need in the output as value. If the label doesn't exist on the accumulator yet, add it. Then, update the respective keys of the object. Use Object.values() get the array of values from the grouped object:

const input=[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]];

const merged = input.reduce((acc, [q, label, n]) => {
  acc[label] = acc[label] || { label, data: [], Questions: [] };
  acc[label].data.push(n);
  acc[label].Questions.push(q);
  return acc
}, {})

const output = Object.values(merged)

console.log(output)```
</div>
</div>
</p>

<p>This is how the merged/ accumulator object looks like</p>

<pre class="lang-js prettyprint-override"><code>{
  "Module1": {
    label: "Module1",
    data: [9, 5, 8],
    Questions: ["Q1", "Q2", "Q3"]
  },
  "Module2": {
    ...
  },
  "Module3": {
    ...
  }
}
</code>```

Title: Parsing Nested Arrays Data

Body:
How to parse the data of Nested JS Array to Objects? I've tried different approaches by using for loop and Dict datatype but it's not working.

Background :
I'm using chart.js library to show some data points in Radar Chart.Now i am trying to parse the nested arrays data and convert each array of module into single object and then pass it's data to visualization chart.

// Input-->
JavaScript_Array=
[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],
["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],
["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],
["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]]

//Expected Output

    Final_Array=[{label: "Module1",  data: [9,5,8],Questions:[Q1,Q2,Q3] },
                 {label: "Module2",  data: [5,9,1],Questions:[Q1,Q2,Q3]},
                 {label: "Module3",  data: [2,1,3],Questions:[Q1,Q2,Q3]},
                 {label: "Module4",  data: [3,4,2],Questions:[Q1,Q2,Q3]}]

Body:
You could reduce the array and group based on the label. Create an accumulator with each unique label as the key and the object you need in the output as value. If the label doesn't exist on the accumulator yet, add it. Then, update the respective keys of the object. Use Object.values() get the array of values from the grouped object:

const input=[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]];

const merged = input.reduce((acc, [q, label, n]) => {
  acc[label] = acc[label] || { label, data: [], Questions: [] };
  acc[label].data.push(n);
  acc[label].Questions.push(q);
  return acc
}, {})

const output = Object.values(merged)

console.log(output)

This is how the merged/ accumulator object looks like

{
  "Module1": {
    label: "Module1",
    data: [9, 5, 8],
    Questions: ["Q1", "Q2", "Q3"]
  },
  "Module2": {
    ...
  },
  "Module3": {
    ...
  }
}


问:
http://localhost:3000/[object%20Object] not found 404
In my react app, this is an array of filenames I get from server side

```<code>const photos = ["01-1913.JPG", "01-1913.1.jpg", "01-1913.2.jpg"]
</code>```

and here is how I use it with JSX

```<code>            {
              photos.map(entry => {
                return (
                <div key={entry}>
                <PhotoItem key={entry} url={`${process.env.REACT_APP_NODE_SERVER}/${entry}`} />
                </div>
                )
                })
            }
</code>```

```<code>const PhotoItem = (url) => {
  return (
    <img
      src={url}
      onError={this.addDefaultSrc}
      alt="photoItem"
      style={{
        width: "500px",
        height: "600px",
        border: "1px solid #123C69",
      }}
    ></img>
  );
};
```
```

I can not figure out why I am not getting the photo (only the dummy photo from the onError event I've used) and if it has anything to do with the Object%object error. Any help would be appreciated.

答:
As mentioned in the comments, the PhotoItem component should look like this:

// Note that here props are named "props" instead of "url"
const PhotoItem = (props) => {
  return (

  );
};

```

<p>Note that the first argument that a react component receives is <code>props</code>. So even if you name it <code>url</code>, the value that you are looking for url lives in <code>url.url</code>.</p>

<p>I also recommend to deconstruct your <code>props</code> like this:</p>

<pre class="lang-js prettyprint-override"><code>const PhotoItem = ({url}) => {
  return (
    <img
      src={url}
      ...
    ></img>
  );
};

</code>```

Body:
In my react app, this is an array of filenames I get from server side

const photos = ["01-1913.JPG", "01-1913.1.jpg", "01-1913.2.jpg"]

and here is how I use it with JSX

            {
              photos.map(entry => {
                return (

                <PhotoItem key={entry} url={`${process.env.REACT_APP_NODE_SERVER}/${entry}`} />

                )
                })
            }

const PhotoItem = (url) => {
  return (

  );
};
```

I can not figure out why I am not getting the photo (only the dummy photo from the onError event I've used) and if it has anything to do with the Object%object error. Any help would be appreciated.

Body:
As mentioned in the comments, the PhotoItem component should look like this:

// Note that here props are named "props" instead of "url"
const PhotoItem = (props) => {
  return (
    <img
      src={props.url}
      onError={this.addDefaultSrc}
      alt="photoItem"
      style={{
        width: "500px",
        height: "600px",
        border: "1px solid #123C69",
      }}
    ></img>
  );
};

Note that the first argument that a react component receives is props. So even if you name it url, the value that you are looking for url lives in url.url.

I also recommend to deconstruct your props like this:

const PhotoItem = ({url}) => {
  return (
    <img
      src={url}
      ...
    ></img>
  );
};


问:
How to convert a Python .pyd file to a wheel on Windows?
I am wondering how to convert .pyd file to a Python Wheel?

Environment: on Windows, I have compiled a set of C++ files to a .pyd file using MSVC 2019 and CMake. I am using pybind11 to create a Python module.

I have tried every technique I can possibly think of over the past few months.

答:
Solved it by using the answer by @hoefling:

Created a setup.py file from said answer, filled in the blanks.

Then used this batch file:

```<code>@echo off
rem Build and install module. Run in a Visual Studio x64 prompt.
rem Out of the box, Python does not support building of wheels.
pip install wheel
rem Build wheel.
python setup.py bdist_wheel
rem Install wheel.
pip install --upgrade --force-reinstall dist/MyProject-0.0.1-cp37-cp37m-win_amd64.whl
pause
</code>```

The final boss to slay was working out, after a week, that if CMakeCache.txt  is present in the root directory, everything will fail with a huge 20-line nonsensical error message. CMake is a reasonable build system, but it sure has some absolutely horrific bugs - there's no other word for that sort of behavior.

Appendix A

Quote from Building C and C++ Extensions:

A C extension for CPython is a shared library (e.g. a .so file on Linux, .pyd on Windows), which exports an initialization function.

To be importable, the shared library must be available on PYTHONPATH, and must be named after the module name, with an appropriate extension. When using distutils, the correct filename is generated automatically.

The initialization function has the signature:

```<code>PyObject* PyInit_modulename(void)
</code>```

It returns either a fully-initialized module, or a PyModuleDef instance. See Initializing C modules for details.

So during development, it is not really that necessary to compile the .pyd file into a wheel for installation. As long as the .pyd file is available onPYTHONPATH, and it named correctly, then everything will just work.

Body:
Solved it by using the answer by @hoefling:

Created a setup.py file from said answer, filled in the blanks.

Then used this batch file:

@echo off
rem Build and install module. Run in a Visual Studio x64 prompt.
rem Out of the box, Python does not support building of wheels.
pip install wheel
rem Build wheel.
python setup.py bdist_wheel
rem Install wheel.
pip install --upgrade --force-reinstall dist/MyProject-0.0.1-cp37-cp37m-win_amd64.whl
pause

The final boss to slay was working out, after a week, that if CMakeCache.txt  is present in the root directory, everything will fail with a huge 20-line nonsensical error message. CMake is a reasonable build system, but it sure has some absolutely horrific bugs - there's no other word for that sort of behavior.

Appendix A

Quote from Building C and C++ Extensions:

A C extension for CPython is a shared library (e.g. a .so file on Linux, .pyd on Windows), which exports an initialization function.

To be importable, the shared library must be available on PYTHONPATH, and must be named after the module name, with an appropriate extension. When using distutils, the correct filename is generated automatically.

The initialization function has the signature:

PyObject* PyInit_modulename(void)

It returns either a fully-initialized module, or a PyModuleDef instance. See Initializing C modules for details.

So during development, it is not really that necessary to compile the .pyd file into a wheel for installation. As long as the .pyd file is available onPYTHONPATH, and it named correctly, then everything will just work.


问:
Why is 'scipy.sparse.linalg.spilu' less efficient than 'scipy.linalg.lu' for sparse matrix?
I posted this question on https://scicomp.stackexchange.com, but received no attention. As long as I get answer in one of them, I will inform in the other.

I have a matrix B which is sparse and try to utilize a function scipy.sparse.linalg.spilu specialized for sparse matrix to factorize B. Could you please explain why this function is significantly less efficient than the function scipy.linalg.lu for general matrix? Thank you so much!

```<code>import numpy as np
import scipy.linalg as la
import scipy.sparse.linalg as spla
import time
from scipy import sparse
from scipy.sparse import csc_matrix
A = np.random.randint(100, size=(10000, 10000))
B = np.triu(A, -100)

start = time.time()
(P, L, U) = la.lu(B)
end = time.time()
print('Time to decompose B with lu =', end - start)

start = time.time()
mtx = spla.spilu(csc_matrix(B))
end = time.time()
print('Time to decompose B with spilu =', end - start)
</code>```

The computation time is

```<code>Time to decompose B with lu = 4.7765138149261475
Time to decompose B with spilu = 14.165712594985962
</code>```

答:
```<code>(B==0).sum()
Out[5]: 49510694

B.shape
Out[6]: (10000, 10000)

(B==0).sum()/100000000
Out[7]: 0.49510694
</code>```

Your matrix B is not sparse at all. More than half of the elements in B are non-zeros. Of course spilu would be less efficient when dealing with such a dense matrix.

Body:
I posted this question on https://scicomp.stackexchange.com, but received no attention. As long as I get answer in one of them, I will inform in the other.

I have a matrix B which is sparse and try to utilize a function scipy.sparse.linalg.spilu specialized for sparse matrix to factorize B. Could you please explain why this function is significantly less efficient than the function scipy.linalg.lu for general matrix? Thank you so much!

import numpy as np
import scipy.linalg as la
import scipy.sparse.linalg as spla
import time
from scipy import sparse
from scipy.sparse import csc_matrix
A = np.random.randint(100, size=(10000, 10000))
B = np.triu(A, -100)

start = time.time()
(P, L, U) = la.lu(B)
end = time.time()
print('Time to decompose B with lu =', end - start)

start = time.time()
mtx = spla.spilu(csc_matrix(B))
end = time.time()
print('Time to decompose B with spilu =', end - start)

The computation time is

Time to decompose B with lu = 4.7765138149261475
Time to decompose B with spilu = 14.165712594985962

Body:
(B==0).sum()
Out[5]: 49510694

B.shape
Out[6]: (10000, 10000)

(B==0).sum()/100000000
Out[7]: 0.49510694

Your matrix B is not sparse at all. More than half of the elements in B are non-zeros. Of course spilu would be less efficient when dealing with such a dense matrix.


问:
Custom URL schemes
How does one handle custom URL schemes to allow one app to be directed to another? e.g. instagram://user?username=someusername which directs a user straight to the users profile via username.  I need to create something similar.

I've checked out application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool and application(_ application: UIApplication, handleOpen url: URL) -> Bool but they seem to have a red line through when attempting to implement so I assume they are deprecated. Also, they don't seem to get called when I open my app via url from a browser.

答:
From iOS 13 and above below function will no longer work.

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
</code>```

Updated function from iOS 13 and above

```<code> func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)
</code>```

Use this function in SceneDelegate class.

Credit: https://www.swiftdevcenter.com/custom-url-scheme-deep-link-ios-13-and-later-swift-5/

For more detail follow this tutorial

Title: Custom URL schemes

Body:
From iOS 13 and above below function will no longer work.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool

Updated function from iOS 13 and above

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)

Use this function in SceneDelegate class.

Credit: https://www.swiftdevcenter.com/custom-url-scheme-deep-link-ios-13-and-later-swift-5/

For more detail follow this tutorial


问:
Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support
I am trying to read a .xlsx with pandas, but get the follwing error:

```<code>data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)

Traceback (most recent call last):
  File "/Users/Vineeth/PycharmProjects/DataAnalysis1/try1.py", line 9, in <module>
    data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/util/_decorators.py", line 118, in wrapper
    return func(*args, **kwargs)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/io/excel.py", line 230, in read_excel
    io = ExcelFile(io, engine=engine)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/io/excel.py", line 263, in __init__
    raise ImportError(err_msg)
ImportError: Install xlrd >= 0.9.0 for Excel support
</code>```

I've also tried

```<code>data = pd.read_excel("DataAnalysis1/temp1.xlsx", low_memory=False).fillna(value=0)
</code>```

And I Still get the same error.

Background: I'm trying to extract an excel file with multiple worksheets as a dict of data frames.I installed xlrd version 0.9.0 and the latest version(1.1.0) but I still get the same error. Thanks!

答:
I had the same problem and none of the above answers worked. If you go into the settings (CTRL + ALT + s) and search for project interpreter you will see all of the installed packages. Click the + button at the top right and search for xlrd, then click install package at the bottom left.

I had already done the "pip install xlrd" command from the file location of my python.exe before this, so you may need to do that as well. (you can find the file location by searching it in windows search bar and right click -> open file location, then type cmd into the file explorer address bar)

Body:
I am trying to read a .xlsx with pandas, but get the follwing error:

data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)

Traceback (most recent call last):
  File "/Users/Vineeth/PycharmProjects/DataAnalysis1/try1.py", line 9, in <module>
    data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/util/_decorators.py", line 118, in wrapper
    return func(*args, **kwargs)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/io/excel.py", line 230, in read_excel
    io = ExcelFile(io, engine=engine)
  File "/Users/Vineeth/venv/lib/python2.7/site-packages/pandas/io/excel.py", line 263, in __init__
    raise ImportError(err_msg)
ImportError: Install xlrd >= 0.9.0 for Excel support

I've also tried

data = pd.read_excel("DataAnalysis1/temp1.xlsx", low_memory=False).fillna(value=0)

And I Still get the same error.

Background: I'm trying to extract an excel file with multiple worksheets as a dict of data frames.I installed xlrd version 0.9.0 and the latest version(1.1.0) but I still get the same error. Thanks!


问:
rails form - 2 fields with same id in a form - how to disable second field when first field is selected
I have in my rails form the following code:

```<code><label>Fruit: </label>  <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
                          ['Orange', 'Orange'],
                          ['Kiwi', 'Kiwi'],
                          ['Other', 'Other']
                          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
                                                                         {document.getElementById('otherTissue').style.display = 'block';
                                                                         } "}
                          ) %>

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10  %></span>
</code>```

User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.

The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.

I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.

Many many thanks for any suggestion provided.

答:
First, be aware that rails posts are based on fields' name, not ids.

In your case, you should use a virtual attribute to store the potential other fruit value.

Your model could look like:

```<code>attr_accessor :other_fruit

before_save :check_fruits

def check_fruits
  #if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column
  #BTW, why these capital letters?
  IST_FRUIT = other_fruit unless other_fruit.nil?
end
</code>```

And your form would be:

```<code><span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10  %></span>
</code>```

Body:
I have in my rails form the following code:

Fruit:   <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
                          ['Orange', 'Orange'],
                          ['Kiwi', 'Kiwi'],
                          ['Other', 'Other']
                          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
                                                                         {document.getElementById('otherTissue').style.display = 'block';
                                                                         } "}
                          ) %>

 If other, please state: <%= f.text_field :IST_FRUIT, :size => 10  %>

User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.

The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.

I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.

Many many thanks for any suggestion provided.

Body:
First, be aware that rails posts are based on fields' name, not ids.

In your case, you should use a virtual attribute to store the potential other fruit value.

Your model could look like:

attr_accessor :other_fruit

before_save :check_fruits

def check_fruits
  #if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column
  #BTW, why these capital letters?
  IST_FRUIT = other_fruit unless other_fruit.nil?
end

And your form would be:

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10  %></span>


问:
Table view cell with label and textField and equal space between each other
i want to create a table view with cells which have a textField.
What drives me crazy is the spacing between label and textField cause i want a equal spacing in all cells.

To better explain take a look at this screenshot.

So im searching for a good way to get the spacing between Second Label and Second textField and set this on the other cells, too.

Is there a way to do it in the storyboard and not by edit the constraint in code?

答:
I would suggest that:

use a horizontal stackview to hold the label and textField with some spacing in between, like 10.

set the label's width constraint to a fixed value.

the details are as follows:

add a horizontal stackview into the cell's contentView

set the stackview constraints to fill the contentView with some margins:
eg. leading: 20, trailing 20, top 10, bottom 10.

add a label and a textField into the stackview.

in the stackview's Attribute inspector, set the spacing to 10.

set the label's width constraint to 100, or 0.3:1 to the contentView's width

so the label will have a fixed width, fixed spacing between label and textField, and the textField will take all the horizontal space remain.


问:
How can I range check C++14 user defined literals?
Is there a way to persuade a good C++ compiler to warn about the overflow
in constructing a user defined type from a user defined literal as shown in the example
code below? At least (via Godbolt) GCC and Clang warn about the overflow in the equivalent intrinsic code, but MSVC doesn't. None care about the same error in the user defined code.

```<code>#include <iostream>

struct MyShort
{
  short  data;
  constexpr MyShort ( short arg ) : data ( arg ) {}
};

constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  return MyShort ( arg );
}

struct UseMyShort
{
  MyShort constexpr static  var1 = 100000_MyShort;
  short constexpr static    var2 = 100000;
};

int main ( int argc, char** argv )
{
  std::cout << UseMyShort::var1.data;
  std::cout << UseMyShort::var2;
}
</code>```

UPDATE: Thanks pyj and cigien. You gave me the clue. When the code is run at compile time, the compiler doesn't care about branches not taken, so
non-constexpr expressions are fine. If the compiler executes that path
it errors which is the desired outcome. I have adapted your solutions
to assert so the code also detects runtime errors when in debug mode. Updated code below. I've accepted cigien's answer because it looks like they took a penalty for a faulty draft, not a faulty idea.

```<code>#include <iostream>
#include <limits>
#include <assert.h>

template <class elem>
constexpr elem rangeCheck ( unsigned long long arg )
{
  if ( arg > std::numeric_limits<elem>::max() ) {
    assert ( false );
  }
  return elem(arg);
}

struct MyShort
{
  short  data;
  constexpr MyShort ( short arg ) : data ( arg ) {}
};

constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  return MyShort { rangeCheck<short> (arg) };
}

struct UseMyShort
{
// compile time error (GCC):-
// ... call to non-constexpr function ‘void __assert_fail(const char*, const char*, unsigned int, const char*)’
//     assert ( false );
//     ^
  MyShort constexpr static  var1 = 100000_MyShort;
  short constexpr static    var2 = 100000; // compile time warning (with GCC -Woverflow)
};

int main ( int, char** )
{
  std::cout << UseMyShort::var1.data;
  std::cout << UseMyShort::var2;
  MyShort const var4 = 100000_MyShort; // runtime error
  MyShort       var5 = 100000_MyShort; // runtime error
  return 0;
}

</code>```

答:
You can force a hard error by checking if the unsigned long long's value is narrowed when cast to a short value:

```<code>constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  if (static_cast<short>(arg) != arg)
  {
    std::cout << "oops";  // or some other non-constexpr code
  }
  return MyShort (arg);
}
</code>```

Here's a demo.

Body:
Is there a way to persuade a good C++ compiler to warn about the overflow
in constructing a user defined type from a user defined literal as shown in the example
code below? At least (via Godbolt) GCC and Clang warn about the overflow in the equivalent intrinsic code, but MSVC doesn't. None care about the same error in the user defined code.

#include <iostream>

struct MyShort
{
  short  data;
  constexpr MyShort ( short arg ) : data ( arg ) {}
};

constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  return MyShort ( arg );
}

struct UseMyShort
{
  MyShort constexpr static  var1 = 100000_MyShort;
  short constexpr static    var2 = 100000;
};

int main ( int argc, char** argv )
{
  std::cout << UseMyShort::var1.data;
  std::cout << UseMyShort::var2;
}

UPDATE: Thanks pyj and cigien. You gave me the clue. When the code is run at compile time, the compiler doesn't care about branches not taken, so
non-constexpr expressions are fine. If the compiler executes that path
it errors which is the desired outcome. I have adapted your solutions
to assert so the code also detects runtime errors when in debug mode. Updated code below. I've accepted cigien's answer because it looks like they took a penalty for a faulty draft, not a faulty idea.

#include <iostream>
#include <limits>
#include <assert.h>

template <class elem>
constexpr elem rangeCheck ( unsigned long long arg )
{
  if ( arg > std::numeric_limits<elem>::max() ) {
    assert ( false );
  }
  return elem(arg);
}

struct MyShort
{
  short  data;
  constexpr MyShort ( short arg ) : data ( arg ) {}
};

constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  return MyShort { rangeCheck<short> (arg) };
}

struct UseMyShort
{
// compile time error (GCC):-
// ... call to non-constexpr function ‘void __assert_fail(const char*, const char*, unsigned int, const char*)’
//     assert ( false );
//     ^
  MyShort constexpr static  var1 = 100000_MyShort;
  short constexpr static    var2 = 100000; // compile time warning (with GCC -Woverflow)
};

int main ( int, char** )
{
  std::cout << UseMyShort::var1.data;
  std::cout << UseMyShort::var2;
  MyShort const var4 = 100000_MyShort; // runtime error
  MyShort       var5 = 100000_MyShort; // runtime error
  return 0;
}

Body:
You can force a hard error by checking if the unsigned long long's value is narrowed when cast to a short value:

constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
  if (static_cast<short>(arg) != arg)
  {
    std::cout << "oops";  // or some other non-constexpr code
  }
  return MyShort (arg);
}

Here's a demo.


问:
How can I get a particular part of a String enclosed between 2 characters using Excel VBA?
I need to write a macro in excel which can help me get a particular part of a string. My string is as follows :

PAYPAL *VINAYAKAGGRAWAL 4029357733

I need to extract VINAYAKAGGRAWAL from the above string. Any help with vba macro or any excel formula to do this would help.

Thanks in advance.

答:
If your two characters are "*" and " " as in the string above, then you could use this in VBA:

```<code>Function GetString(s As String) As String
    GetString = Split(Split(s, "*")(1), " ")(0)
End Function
</code>```

Or use an in-cell formulae on the worksheet:

```<code>=TRIM(LEFT(RIGHT(D8,LEN(D8)-FIND("*",D8)),FIND(" ",RIGHT(D8,LEN(D8)-FIND("*",D8)))))
</code>```

where D8 would have the original string in

Body:
If your two characters are "*" and " " as in the string above, then you could use this in VBA:

Function GetString(s As String) As String
    GetString = Split(Split(s, "*")(1), " ")(0)
End Function

Or use an in-cell formulae on the worksheet:

=TRIM(LEFT(RIGHT(D8,LEN(D8)-FIND("*",D8)),FIND(" ",RIGHT(D8,LEN(D8)-FIND("*",D8)))))

where D8 would have the original string in


问:
Returning Optional<Student> or Optional.empty()
I'm playing a little bit with Optional to understand how it works. Let's say I have this class:

```<code>public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

and I want to return a Student by Id or Optional.empty if it doesn't find it. This is what I have so far:

```<code>public class Main {
    static List<Student> students = new ArrayList<>();

    public static void main(String[] args) {
        students.add(new Student(1, "name1"));
        students.add(new Student(2, "name2"));
        students.add(new Student(3, "name3"));

        System.out.println(getStudentById(1).get().getName());
    }

    public static Optional<Student> getStudentById(int id) {
        return students
                .stream()
                .filter( s -> s.getId() == id)
                .findFirst();
    }
}
</code>```

That works but I wanted to add this line:

```<code>.findFirst()
.orElse(Optional.empty());
</code>```

and I got this:
    Error:(23, 39) java: incompatible types: no instance(s) of type variable(s) T exist so that java.util.Optional conforms to com.company.Student

Also I'd like to know if that is the correct way to go over a list, I mean element by element or there is something better?

答:
If you read javadocs of Stream#findFirst() you will find that you already have what you need:

Returns an Optional describing the first element of this stream, or an
  empty Optional if the stream is empty. If the stream has no encounter
  order, then any element may be returned.

So just do

```<code>return students
            .stream()
            .filter( s -> s.getId() == id)
            .findFirst();
</code>```

Body:
I'm playing a little bit with Optional to understand how it works. Let's say I have this class:

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and I want to return a Student by Id or Optional.empty if it doesn't find it. This is what I have so far:

public class Main {
    static List<Student> students = new ArrayList<>();

    public static void main(String[] args) {
        students.add(new Student(1, "name1"));
        students.add(new Student(2, "name2"));
        students.add(new Student(3, "name3"));

        System.out.println(getStudentById(1).get().getName());
    }

    public static Optional<Student> getStudentById(int id) {
        return students
                .stream()
                .filter( s -> s.getId() == id)
                .findFirst();
    }
}

That works but I wanted to add this line:

.findFirst()
.orElse(Optional.empty());

and I got this:
    Error:(23, 39) java: incompatible types: no instance(s) of type variable(s) T exist so that java.util.Optional conforms to com.company.Student

Also I'd like to know if that is the correct way to go over a list, I mean element by element or there is something better?

Body:
If you read javadocs of Stream#findFirst() you will find that you already have what you need:

Returns an Optional describing the first element of this stream, or an
  empty Optional if the stream is empty. If the stream has no encounter
  order, then any element may be returned.

So just do

return students
            .stream()
            .filter( s -> s.getId() == id)
            .findFirst();