问:
RSA Interoperability between C# and Java
I am working on API that will perform a certain handshake with [Java,C#] agents by giving them RSA key parameters [Exponent,Modulus,D]. I managed to make both agents encrypt and decrypt data given the parameters.

I tried to test the interoperability "when given the same parameters" between both. Java agent can seamlessly decrypt C# encrypted data
but I can't get it to work the other way around "to decrypt java-encrypted data with C#"

Here is a brief code to demonstrate the problem

→ Java ←

RSAParameters.java

```<code>class RSAParameters
{
    public BigInteger Exponent;
    public BigInteger Modulus;
    public BigInteger P;
    public BigInteger Q;
    public BigInteger DP;
    public BigInteger DQ;
    public BigInteger InverseQ;
    public BigInteger D;

    public RSAParameters(){}

    public RSAParameters(String ExponentString,String ModulusString,String DString)
    {
        this.Exponent = new BigInteger(1, Base64.getDecoder().decode(ExponentString.trim()));
        this.Modulus  = new BigInteger(1, Base64.getDecoder().decode(ModulusString.trim()));
        this.D        = new BigInteger(1, Base64.getDecoder().decode(DString.trim()));
    }

    public RSAParameters(String ExponentString,String ModulusString)
    {
        this.Exponent = new BigInteger(1, Base64.getDecoder().decode(ExponentString.trim()));
        this.Modulus  = new BigInteger(1, Base64.getDecoder().decode(ModulusString.trim()));
    }
}
</code>```

RSA.java

```<code>public class RSA
{

    public static final RSAParameters HandshakeSharedRSAParameters = new RSAParameters(
            "AQAB",
            "vsn+4HB74ypJ4dqetNWUpKueFAb9V0Vbb1TISWklNa4d1xSmDvF3eZ8bGSciU1PvvPgPVFHh+85ArL/jLqCbMuk8Bx2+y3UJVxXPXpazzv0qPTHd3UXyKeJa/LW+wD+J1Yjy823nT7D8NYOpdt8l9agIO5Me9JiebtxLbljcLMk=",
            "en19YeNV5rbT0Gln03n8gOyeBQWnyUwCNCwemuMivKAZEGl1Y8qrhi4cW73AT/dnx88LKHuZtuzooQBhfyImASGVPXMHYVf4I+f/ZbsYe+ZByyQ/OBlxOYrQxGoDW13us9S+biMyQVQ7MA2TQBmv52e1+LyX7RIsCzxQyUuYFTE="
    );
    public static String Encrypt(String PlainText,RSAParameters RSAParameters)  throws Exception
    {
        KeyFactory factory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        RSAPublicKeySpec RSAPublicKeySpec = new RSAPublicKeySpec(RSAParameters.Modulus, RSAParameters.Exponent);
        PublicKey PublicKey = factory.generatePublic(RSAPublicKeySpec);
        cipher.init(Cipher.ENCRYPT_MODE, PublicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(PlainText.getBytes()));
    }
}
</code>```

Main.java

```<code>public class Main
{
    public static void main(String[] args) throws Exception
    {
        String PlainTextToEncrypt = "hello android";
        String Encrypted = RSA.Encrypt(PlainTextToEncrypt,RSA.HandshakeSharedRSAParameters);
        System.out.println("Encrypted" +":  "+Encrypted);
        //Encrypted changes every execution
        //iDIsNj4QiVWlE8ck48uV0w3tnV5D2ro+3SOMkXan2D4feU6nV5TIVqJGLvMWKvkC+duN9jJzSWTR0CAsK2O2IDx88/9/ycpL0Tk9fumEY2KOINEOXASGxjZvzZ0lCf4AeP9koUp2MHZD8agcYDLe7PLVhA+x8kkAWXMUfyvIS4E=
     }
 }
</code>```

→ C# ←

RSA.cs

```<code>public class RSA
{
    public static readonly RSAParameters HandshakeSharedRSAParameters = new RSAParameters()
    {
        Exponent = Convert.FromBase64String("AQAB"),
        Modulus=Convert.FromBase64String("vsn+4HB74ypJ4dqetNWUpKueFAb9V0Vbb1TISWklNa4d1xSmDvF3eZ8bGSciU1PvvPgPVFHh+85ArL/jLqCbMuk8Bx2+y3UJVxXPXpazzv0qPTHd3UXyKeJa/LW+wD+J1Yjy823nT7D8NYOpdt8l9agIO5Me9JiebtxLbljcLMk="),
        P = Convert.FromBase64String("0l6/pEuwqlpHzjYFb3R9eOa+bQMcidn1h6qKR8DLyDPqA2eCgsBj7fvQvLnl9u6QJMzZdZg8fZP56ZP8nUGG3w=="),
        Q = Convert.FromBase64String("6Cv3YUcsnD1ub6lsqAZaEQrazHtf2HBiIboQlA5sMihThEPyL7Tsc85a8Ln9hFysje6MhNtUF6zyIpAU6NaJVw=="),
        DP = Convert.FromBase64String("zf61jf4H+mf5FDXV0LOzAaaBJWH8mgfx42zdhzGE2n/rUHYVWE9oCuugFI28X7ZvM3ncHsh5w0YZW93raVl25Q=="),
        DQ = Convert.FromBase64String("DsIsuYxSs6PcD1EPzSaKNycffXwiPZn3QvmW8DJygkW5+WBwVsQDe+EUOtU33mAdv+/4EsH2eILP6Y6LJbnthQ=="),
        InverseQ = Convert.FromBase64String("sBvjeZ0HbGT8/JfaPRe8eewHliWp/kpQNLiAGBE2CyFIB0mnkBXa+Vs52niLcMpGI1MLMSmdkDZo2/y+KIFcyg=="),
        D = Convert.FromBase64String("en19YeNV5rbT0Gln03n8gOyeBQWnyUwCNCwemuMivKAZEGl1Y8qrhi4cW73AT/dnx88LKHuZtuzooQBhfyImASGVPXMHYVf4I+f/ZbsYe+ZByyQ/OBlxOYrQxGoDW13us9S+biMyQVQ7MA2TQBmv52e1+LyX7RIsCzxQyUuYFTE=")
    };
    public static String Decrypt(String EncryptedText, RSAParameters RSAParameters)
    {
        RSACryptoServiceProvider CryptoServiceProvider = new RSACryptoServiceProvider();
        CryptoServiceProvider.ImportParameters(RSAParameters);
        return Encoding.Unicode.GetString(CryptoServiceProvider.Decrypt(Convert.FromBase64String(EncryptedText), false));
    }
}
</code>```

c# demo

```<code>String AndroidEncrypted = "iDIsNj4QiVWlE8ck48uV0w3tnV5D2ro+3SOMkXan2D4feU6nV5TIVqJGLvMWKvkC+duN9jJzSWTR0CAsK2O2IDx88/9/ycpL0Tk9fumEY2KOINEOXASGxjZvzZ0lCf4AeP9koUp2MHZD8agcYDLe7PLVhA+x8kkAWXMUfyvIS4E=";
Console.WriteLine(RSA.Decrypt(AndroidEncrypted,RSA.HandshakeSharedRSAParameters));
//Expected -> hello android
//Output -> 敨汬湡牤楯�
</code>```

答:
You are forgetting about the character decoding in C#. I would always standardize on UTF-8. This is the default character set on Android but not in Windows / .NET - where it is UTF-16LE (assuming a little endian system such as Windows on Intel or ARM).

In Windows, do:

```<code>Encoding.UTF8.GetBytes(plaintext);
</code>```

You're better off to use StandardCharsets.UTF_8 in Android as well, because if you'd ever use this on a system that has a different character encoding (e.g. Windows, with Windows-1252) then your code would suddenly fail again if you don't.

So always indicate the character encoding in e.g. String#getBytes(StandardCharsets.UTF_8) and new String(byte[] bytes, StandardCharsets.UTF_8).

Note that cryptographic operation must be valid if you get any output at all for RSA. RSA PKCS#1 always validates the padding after decryption, and you'd expect that to fail with an exception if the keys or padding scheme is incorrect.

Body:
I am working on API that will perform a certain handshake with [Java,C#] agents by giving them RSA key parameters [Exponent,Modulus,D]. I managed to make both agents encrypt and decrypt data given the parameters.

I tried to test the interoperability "when given the same parameters" between both. Java agent can seamlessly decrypt C# encrypted data
but I can't get it to work the other way around "to decrypt java-encrypted data with C#"

Here is a brief code to demonstrate the problem

→ Java ←

RSAParameters.java

class RSAParameters
{
    public BigInteger Exponent;
    public BigInteger Modulus;
    public BigInteger P;
    public BigInteger Q;
    public BigInteger DP;
    public BigInteger DQ;
    public BigInteger InverseQ;
    public BigInteger D;

    public RSAParameters(){}

    public RSAParameters(String ExponentString,String ModulusString,String DString)
    {
        this.Exponent = new BigInteger(1, Base64.getDecoder().decode(ExponentString.trim()));
        this.Modulus  = new BigInteger(1, Base64.getDecoder().decode(ModulusString.trim()));
        this.D        = new BigInteger(1, Base64.getDecoder().decode(DString.trim()));
    }

    public RSAParameters(String ExponentString,String ModulusString)
    {
        this.Exponent = new BigInteger(1, Base64.getDecoder().decode(ExponentString.trim()));
        this.Modulus  = new BigInteger(1, Base64.getDecoder().decode(ModulusString.trim()));
    }
}

RSA.java

public class RSA
{

    public static final RSAParameters HandshakeSharedRSAParameters = new RSAParameters(
            "AQAB",
            "vsn+4HB74ypJ4dqetNWUpKueFAb9V0Vbb1TISWklNa4d1xSmDvF3eZ8bGSciU1PvvPgPVFHh+85ArL/jLqCbMuk8Bx2+y3UJVxXPXpazzv0qPTHd3UXyKeJa/LW+wD+J1Yjy823nT7D8NYOpdt8l9agIO5Me9JiebtxLbljcLMk=",
            "en19YeNV5rbT0Gln03n8gOyeBQWnyUwCNCwemuMivKAZEGl1Y8qrhi4cW73AT/dnx88LKHuZtuzooQBhfyImASGVPXMHYVf4I+f/ZbsYe+ZByyQ/OBlxOYrQxGoDW13us9S+biMyQVQ7MA2TQBmv52e1+LyX7RIsCzxQyUuYFTE="
    );
    public static String Encrypt(String PlainText,RSAParameters RSAParameters)  throws Exception
    {
        KeyFactory factory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        RSAPublicKeySpec RSAPublicKeySpec = new RSAPublicKeySpec(RSAParameters.Modulus, RSAParameters.Exponent);
        PublicKey PublicKey = factory.generatePublic(RSAPublicKeySpec);
        cipher.init(Cipher.ENCRYPT_MODE, PublicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(PlainText.getBytes()));
    }
}

Main.java

public class Main
{
    public static void main(String[] args) throws Exception
    {
        String PlainTextToEncrypt = "hello android";
        String Encrypted = RSA.Encrypt(PlainTextToEncrypt,RSA.HandshakeSharedRSAParameters);
        System.out.println("Encrypted" +":  "+Encrypted);
        //Encrypted changes every execution
        //iDIsNj4QiVWlE8ck48uV0w3tnV5D2ro+3SOMkXan2D4feU6nV5TIVqJGLvMWKvkC+duN9jJzSWTR0CAsK2O2IDx88/9/ycpL0Tk9fumEY2KOINEOXASGxjZvzZ0lCf4AeP9koUp2MHZD8agcYDLe7PLVhA+x8kkAWXMUfyvIS4E=
     }
 }

→ C# ←

RSA.cs

public class RSA
{
    public static readonly RSAParameters HandshakeSharedRSAParameters = new RSAParameters()
    {
        Exponent = Convert.FromBase64String("AQAB"),
        Modulus=Convert.FromBase64String("vsn+4HB74ypJ4dqetNWUpKueFAb9V0Vbb1TISWklNa4d1xSmDvF3eZ8bGSciU1PvvPgPVFHh+85ArL/jLqCbMuk8Bx2+y3UJVxXPXpazzv0qPTHd3UXyKeJa/LW+wD+J1Yjy823nT7D8NYOpdt8l9agIO5Me9JiebtxLbljcLMk="),
        P = Convert.FromBase64String("0l6/pEuwqlpHzjYFb3R9eOa+bQMcidn1h6qKR8DLyDPqA2eCgsBj7fvQvLnl9u6QJMzZdZg8fZP56ZP8nUGG3w=="),
        Q = Convert.FromBase64String("6Cv3YUcsnD1ub6lsqAZaEQrazHtf2HBiIboQlA5sMihThEPyL7Tsc85a8Ln9hFysje6MhNtUF6zyIpAU6NaJVw=="),
        DP = Convert.FromBase64String("zf61jf4H+mf5FDXV0LOzAaaBJWH8mgfx42zdhzGE2n/rUHYVWE9oCuugFI28X7ZvM3ncHsh5w0YZW93raVl25Q=="),
        DQ = Convert.FromBase64String("DsIsuYxSs6PcD1EPzSaKNycffXwiPZn3QvmW8DJygkW5+WBwVsQDe+EUOtU33mAdv+/4EsH2eILP6Y6LJbnthQ=="),
        InverseQ = Convert.FromBase64String("sBvjeZ0HbGT8/JfaPRe8eewHliWp/kpQNLiAGBE2CyFIB0mnkBXa+Vs52niLcMpGI1MLMSmdkDZo2/y+KIFcyg=="),
        D = Convert.FromBase64String("en19YeNV5rbT0Gln03n8gOyeBQWnyUwCNCwemuMivKAZEGl1Y8qrhi4cW73AT/dnx88LKHuZtuzooQBhfyImASGVPXMHYVf4I+f/ZbsYe+ZByyQ/OBlxOYrQxGoDW13us9S+biMyQVQ7MA2TQBmv52e1+LyX7RIsCzxQyUuYFTE=")
    };
    public static String Decrypt(String EncryptedText, RSAParameters RSAParameters)
    {
        RSACryptoServiceProvider CryptoServiceProvider = new RSACryptoServiceProvider();
        CryptoServiceProvider.ImportParameters(RSAParameters);
        return Encoding.Unicode.GetString(CryptoServiceProvider.Decrypt(Convert.FromBase64String(EncryptedText), false));
    }
}

c# demo

String AndroidEncrypted = "iDIsNj4QiVWlE8ck48uV0w3tnV5D2ro+3SOMkXan2D4feU6nV5TIVqJGLvMWKvkC+duN9jJzSWTR0CAsK2O2IDx88/9/ycpL0Tk9fumEY2KOINEOXASGxjZvzZ0lCf4AeP9koUp2MHZD8agcYDLe7PLVhA+x8kkAWXMUfyvIS4E=";
Console.WriteLine(RSA.Decrypt(AndroidEncrypted,RSA.HandshakeSharedRSAParameters));
//Expected -> hello android
//Output -> 敨汬湡牤楯�

Body:
You are forgetting about the character decoding in C#. I would always standardize on UTF-8. This is the default character set on Android but not in Windows / .NET - where it is UTF-16LE (assuming a little endian system such as Windows on Intel or ARM).

In Windows, do:

Encoding.UTF8.GetBytes(plaintext);

You're better off to use StandardCharsets.UTF_8 in Android as well, because if you'd ever use this on a system that has a different character encoding (e.g. Windows, with Windows-1252) then your code would suddenly fail again if you don't.

So always indicate the character encoding in e.g. String#getBytes(StandardCharsets.UTF_8) and new String(byte[] bytes, StandardCharsets.UTF_8).

Note that cryptographic operation must be valid if you get any output at all for RSA. RSA PKCS#1 always validates the padding after decryption, and you'd expect that to fail with an exception if the keys or padding scheme is incorrect.


来源: stackexchange

问:
is there a way to get rid of the word "show all posh with "blablabla" label in blogger?
screenshoot

as we know, on the blogger platform we do not include posts into sub of the page, finally I use label tricks embedded on the page so that when visitors click will be directed to all posts labeled in accordance with the page.
but I have trouble eliminating this text "show POST WITH "blablabla" LABELS."

答:
Search for <data:view.search.resultsMessageHtml/> and remove the parent div of it.

It looks a bit like this:

```<code><span class='query-info query-success'><data:view.search.resultsMessageHtml/></span><a class='show-more' expr:href='data:blog.homepageUrl'><data:messages.showAll/></a>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Search for <data:view.search.resultsMessageHtml/> and remove the parent div of it.

It looks a bit like this:

<span class='query-info query-success'><data:view.search.resultsMessageHtml/></span><a class='show-more' expr:href='data:blog.homepageUrl'><data:messages.showAll/></a>


问:
A Little RegEx Help Please - Part 2
Here's the input string:

```<code>loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')
</code>```

With this RegExp: (?<=')[^']+.xml(?=')

... we get this:

```<code>http://www.something.com/videos/JohnsAwesomeCaption.xml
</code>```

... which is exactly what I wanted. BUT this time I'd like to select the complete string EXCEPT for the above. Basically an inverse selection. The output should look like this:

```<code>loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')
</code>```

Thanks!

答:
Try this if you have to do the task in Regex:

Replace

```<code>(.+)(?<=')[^']+\.xml(?=')(.+)
</code>```

with

```<code>$1$2
</code>```

ContentLicense: CC BY-SA 3.0

Title: A Little RegEx Help Please - Part 2

Body:
Here's the input string:

loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', 'http://www.something.com/videos/JohnsAwesomeCaption.xml', '/videos/video-splash-image.gif')

With this RegExp: (?<=')[^']+.xml(?=')

... we get this:

http://www.something.com/videos/JohnsAwesomeCaption.xml

... which is exactly what I wanted. BUT this time I'd like to select the complete string EXCEPT for the above. Basically an inverse selection. The output should look like this:

loadMedia('mediacontainer1', 'http://www.something.com/videos/JohnsAwesomeVideo.flv', '', '/videos/video-splash-image.gif')

Thanks!

Body:
Try this if you have to do the task in Regex:

Replace

(.+)(?<=')[^']+\.xml(?=')(.+)

with

$1$2


问:
Is there a cleaner way to apply a function that requires multiple dataframe columns to grouped data?
Let's say I have a function 'f' that requires three arguments: one dataframe and two columns.

If I want to use 'func' on grouped data to create a new column. Here's a setup:

```<code> import pandas as pd

 def f(x,y,z):
    return sum(x[y]**2) + sum(x[z]**3) - 50

 my_df = pd.DataFrame({'state':['Alabama','Alaska','Arizona','Alaska'],'a':[1,2,3,4],'b':[4,5,6,7]})
</code>```

The actual function I'm trying to apply is a lot more complicated but this example should do fine. I've been doing this:

```<code>x = my_df.groupby('state').apply(f,'a','b').rename('new_col')

my_df = my_df.merge(x, on = 'state', how = 'left')
</code>```

Normally I would just use transform, but transform throws an error because it can only be used on one column at a time.

```<code>my_df.groupby('state').transform(f,'a','b')

KeyError: ('a', 'occurred at index a')
</code>```

Is there a cleaner way to do this? I really wish there was a way to use apply and get a transformed result that has length equal to the original (ungrouped) dataframe.

Desired result:

```<code>     state  a  b  new_col
0  Alabama  1  4       15
1   Alaska  2  5      438
2  Arizona  3  6      175
3   Alaska  4  7      438
</code>```

答:
if I am creating a new column that I want to pass values of columns on the same row I always use apply calling a function.
In your case you could have done

```<code>def f(row):
    return row["a"]**2 + row["b"]**3 - 50

my_df['new_col'] = my_df.apply(f, axis=1 )
</code>```

you will get the same results

Body:
Let's say I have a function 'f' that requires three arguments: one dataframe and two columns.

If I want to use 'func' on grouped data to create a new column. Here's a setup:

 import pandas as pd

 def f(x,y,z):
    return sum(x[y]**2) + sum(x[z]**3) - 50

 my_df = pd.DataFrame({'state':['Alabama','Alaska','Arizona','Alaska'],'a':[1,2,3,4],'b':[4,5,6,7]})

The actual function I'm trying to apply is a lot more complicated but this example should do fine. I've been doing this:

x = my_df.groupby('state').apply(f,'a','b').rename('new_col')

my_df = my_df.merge(x, on = 'state', how = 'left')

Normally I would just use transform, but transform throws an error because it can only be used on one column at a time.

my_df.groupby('state').transform(f,'a','b')

KeyError: ('a', 'occurred at index a')

Is there a cleaner way to do this? I really wish there was a way to use apply and get a transformed result that has length equal to the original (ungrouped) dataframe.

Desired result:

     state  a  b  new_col
0  Alabama  1  4       15
1   Alaska  2  5      438
2  Arizona  3  6      175
3   Alaska  4  7      438

Body:
if I am creating a new column that I want to pass values of columns on the same row I always use apply calling a function.
In your case you could have done

def f(row):
    return row["a"]**2 + row["b"]**3 - 50

my_df['new_col'] = my_df.apply(f, axis=1 )

you will get the same results


问:
typescript, overriding method in a child class: could be instantiated with a different subtype of constraint '{}'
Trying to override a method in a child class, with a generic return type, and coming up with this error. I've been reading could be instantiated with a different subtype of constraint 'object' but I can't wrap my ahead around to my scenario. Any advise?

```<code>Type '{ deployments: { [deploymentId: string]: string[]; }; }' is not assignable to type 'SomeInterface'.
  '{ deployments: { [deploymentId: string]: string[]; }; }' is assignable to the constraint of type 'SomeInterface', but 'SomeInterface' could be instantiated with a different subtype of constraint '{}'.(2322)
</code>```

```<code>class SomeClass {
    testGenericMethod<T>(): T {
        throw new Error('Implement this.')
    }
}

interface SomeInterface {
  deployments: { [deploymentId: string]: Array<string> }
}

class ImplementSomeClass extends SomeClass {
    testGenericMethod<SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}
</code>```

Playground Link

答:
You are using a generic variable <SomeInterface> which overrides the interface definition in the scope of your function.

Use another generic variable. For instance, if it needs still to be a SomeInterface:

```<code>class ImplementSomeCLass {
    testGenericMethod<T extends SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}
</code>```

Remember that in function definition, the generic types are variables. You can assign them default values

```<code>testGenericMethod<T = SomeInterface>(): SomeInterface {/** **/}
</code>```

or you can constraint them to some types:

```<code>testGenericMethod<T extends SomeInterface>() : SomeInterface {/** **/}
</code>```

In the former case, you can call your function with any type:

```<code>const myInterface = testGenericMethod<any>();
</code>```

In the later case, you can use any type satisfying the constraint:

```<code>const myInterface = testGenericMethod<SomeInterface & MyOtherInterface>();
</code>```

Body:
Trying to override a method in a child class, with a generic return type, and coming up with this error. I've been reading could be instantiated with a different subtype of constraint 'object' but I can't wrap my ahead around to my scenario. Any advise?

Type '{ deployments: { [deploymentId: string]: string[]; }; }' is not assignable to type 'SomeInterface'.
  '{ deployments: { [deploymentId: string]: string[]; }; }' is assignable to the constraint of type 'SomeInterface', but 'SomeInterface' could be instantiated with a different subtype of constraint '{}'.(2322)

class SomeClass {
    testGenericMethod<T>(): T {
        throw new Error('Implement this.')
    }
}

interface SomeInterface {
  deployments: { [deploymentId: string]: Array<string> }
}

class ImplementSomeClass extends SomeClass {
    testGenericMethod<SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}

Playground Link

Body:
You are using a generic variable <SomeInterface> which overrides the interface definition in the scope of your function.

Use another generic variable. For instance, if it needs still to be a SomeInterface:

class ImplementSomeCLass {
    testGenericMethod<T extends SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}

Remember that in function definition, the generic types are variables. You can assign them default values

testGenericMethod<T = SomeInterface>(): SomeInterface {/** **/}

or you can constraint them to some types:

testGenericMethod<T extends SomeInterface>() : SomeInterface {/** **/}

In the former case, you can call your function with any type:

const myInterface = testGenericMethod<any>();

In the later case, you can use any type satisfying the constraint:

const myInterface = testGenericMethod<SomeInterface & MyOtherInterface>();


问:
Is "git checkout -b branchName" the same as "git checkout --track origin/branchName"?
Is git checkout -b branchName the same as git checkout --track origin/branchName?   I'm trying to begin contributing to a remote branch from my local machine.  Are these commands equivalent?  If not, how do they differ?

答:
If I'm understanding your question correctly, you want to create a branch in your local working directory.  In that case you want git checkout -b branchName

EDIT:

Then, do your work and commit the work to your new branch (with "git commit").  You can make several commits to the new branch or just one.  Once you want it to be reviewed, do git push -u origin. Then follow the pull request process you have been given, if any.  Otherwise just contact the person you're working with and notify them that you pushed a branch and give the name.


问:
Batched writes (for denormalized data) in Firebase Realtime Database using Flutter?
Looking for the equivalent of ref.updateChildValues which is used in Swift, but for Flutter.

I have denormalised data in the Realtime Database, so looking to update data in a batch across specific child nodes.

Would appreciate any guidance! Thank you!

答: In Flutter that method is called update, same as in Firebase's web SDK. Just like in the iOS version, you pass in a Map<String, dynamic> with  the values to update. The keys in this map being the name/path of each location to update, and the values then being the value to write to that location.


问:
Node.JS + Express parse CSV file on server
Essentially, what I have is a form where a user will upload a CSV file.

<form action="/upload" method="POST" enctype="multipart/form-data">

        <input type="file" class="custom-file-input" id="customFile" name="file" required>
        Choose file

    <input type="submit" class="btn btn-primary btn-block">
</form>
```

<p>FYI: I'm using getbootstrap.com as my style sheet.</p>

<p>Now, the form sends a POST request to <code>/upload</code> which is where my node.js code is. What I need is for the server to parse this CSV file and extract the data. I've got no idea what to do as all the different NPM packages such as Multer are using a system where the save the file locally and then parse it.</p>

<p>Edit: Forgot to mention this, but temporary local CSV hosting is not an option.
I need the client to upload server to process it and push to a DB, can't save the file locally anywhere.</p>

<p>Edit 2: I've used multer and the memory processing option and have gotten the following.</p>

```const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(req, res) {
  response.sendFile(__dirname + "/views/index.html");
});
app.post("/upload", upload.single('file'), async (req, res) => {
  res.send(req.file)
});
const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});

```

<p>Now once I upload the file, I'm getting the following response (this is what req.file is).</p>

```{"fieldname":"file","originalname":"tech.csv","encoding":"7bit","mimetype":"application/octet-stream","buffer":{"type":"Buffer","data":[67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101]},"size":56}

```

<p>So It's pretty clear that our data happens to be </p>

```67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101
```

<p>but how do I process that? The csv file data was </p>

```CLASS ID,TECH #,FIRST NAME,LAST NAME
6O,6O01,Anish,Anne
```

So how do I go from the information provided in the buffer data attribute to the actual data?

答:
All you have to use is Multer. Multer will return a buffer object which you can then make a string with the .toString() attribute.

Code:

```<code>const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(request, response) {
  response.sendFile(__dirname + "/views/index.html");
});

app.post("/upload", upload.single('file'), async (req, res) => {
  var b = req.file["buffer"]
  console.log(b.toString())
  res.send(b.toString())
});

const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});

</code>```

Body:
Essentially, what I have is a form where a user will upload a CSV file.

<form action="/upload" method="POST" enctype="multipart/form-data">

        <input type="file" class="custom-file-input" id="customFile" name="file" required>
        Choose file

    <input type="submit" class="btn btn-primary btn-block">
</form>

FYI: I'm using getbootstrap.com as my style sheet.

Now, the form sends a POST request to /upload which is where my node.js code is. What I need is for the server to parse this CSV file and extract the data. I've got no idea what to do as all the different NPM packages such as Multer are using a system where the save the file locally and then parse it.

Edit: Forgot to mention this, but temporary local CSV hosting is not an option.
I need the client to upload server to process it and push to a DB, can't save the file locally anywhere.

Edit 2: I've used multer and the memory processing option and have gotten the following.

const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(req, res) {
  response.sendFile(__dirname + "/views/index.html");
});
app.post("/upload", upload.single('file'), async (req, res) => {
  res.send(req.file)
});
const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});

Now once I upload the file, I'm getting the following response (this is what req.file is).

{"fieldname":"file","originalname":"tech.csv","encoding":"7bit","mimetype":"application/octet-stream","buffer":{"type":"Buffer","data":[67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101]},"size":56}

So It's pretty clear that our data happens to be

67,76,65,83,83,32,73,68,44,84,69,67,72,32,35,44,70,73,82,83,84,32,78,65,77,69,44,76,65,83,84,32,78,65,77,69,13,10,54,79,44,54,79,48,49,44,65,110,105,115,104,44,65,110,110,101

but how do I process that? The csv file data was

CLASS ID,TECH #,FIRST NAME,LAST NAME
6O,6O01,Anish,Anne

So how do I go from the information provided in the buffer data attribute to the actual data?

Body:
All you have to use is Multer. Multer will return a buffer object which you can then make a string with the .toString() attribute.

Code:

const express = require("express");
const app = express();
var bodyParser = require("body-parser");
var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", function(request, response) {
  response.sendFile(__dirname + "/views/index.html");
});

app.post("/upload", upload.single('file'), async (req, res) => {
  var b = req.file["buffer"]
  console.log(b.toString())
  res.send(b.toString())
});

const listener = app.listen(process.env.PORT, function() {
  console.log("Your app is listening on port " + listener.address().port);
});


问:
Mobx don't update observable array
I've store with obersable array :

@observable list = [];

And i've methode for remove an item in my array :

@

```<code>@action remove(_id) {
  const presentation = this.list.find(item => _id === item._id);
  this.list.remove(presentation);
  console.log(this.list.slice()); // Don't update, @action log : spliced 'PresentationsStore@2.list': index 2, added 0, removed 1
}

@action findUserPresentations(userId) {
  return this.list.filter(item => userId === item.userId);
}
</code>```

My console.log() work nice (return new array without item), but my container with @observable isn't update :

```<code>@observer
@inject('user', 'presentations')
class MyPresentationsContainer extends React.Component {

  get presentations() {
    return this.props.presentations.findUserPresentations(this.props.user.id);
  }

  render() {
    return (
      <MyPresentations
        presentations={this.presentations}
      />
    );
  }
}
</code>```

Anyone know if i need add other methode in remove(_id)  ?

Thank you !

答:
the filter method basically returns a new array.

You can do this:

this.list = this.list.filter(item => userId === item.userId);

Title: Mobx don't update observable array

Body:
I've store with obersable array :

@observable list = [];

And i've methode for remove an item in my array :

@

@action remove(_id) {
  const presentation = this.list.find(item => _id === item._id);
  this.list.remove(presentation);
  console.log(this.list.slice()); // Don't update, @action log : spliced 'PresentationsStore@2.list': index 2, added 0, removed 1
}

@action findUserPresentations(userId) {
  return this.list.filter(item => userId === item.userId);
}

My console.log() work nice (return new array without item), but my container with @observable isn't update :

@observer
@inject('user', 'presentations')
class MyPresentationsContainer extends React.Component {

  get presentations() {
    return this.props.presentations.findUserPresentations(this.props.user.id);
  }

  render() {
    return (
      <MyPresentations
        presentations={this.presentations}
      />
    );
  }
}

Anyone know if i need add other methode in remove(_id)  ?

Thank you !


答:
Do a match of your pattern, get the substring that matched, then do a replace of that exact substring with an empty string (or '', or whatever). If your language has the option to return the indices that matched rather than the text that matched it's even easier because you can just remove the text range identified by the indices.

Some languages provide a "regusb" (regular expression substitute) command that lets you replace a regular expression with another string, which lets you do the match-and-replace all in one step. Different languages may call that command by different names.

Title: A Little RegEx Help Please - Part 2


问:
Split whitespaces and search user input
I have an input field where users can search a database for a certain name. The database contains names such as "Doe, John".

If a user searches for "john" I think it's easy to implement. However, if he or she searches for "john Doe" I would like to implement the logic search for john or search for doe.

With RegEx I am completely lost. Is something like this even possible? However, with JS I would at least be able to consider this algorithm:

Split the input on a whitespace and create to arrays

Remove special characters

Filter the JSON object retrieved from the database

check, whether item includes the cleansed string-arrays

As for the JS-functions I tried something (in vain):

```<code>        let search = 'John Doe' //user input
        let data = ['Doe, John', 'Bean, Mister'] //data from database
        let split = search.split(" ") //split the whitespace into two arrays
        split = split.map(item => { return item.replace(/[^\w\s]+/gi, '')}) //remove dots, commas etc.
        let result = data.filter(item => { //filter each item from the data...
            split.forEach(element => {
            let found = item.match(new RegExp(element, "i")) // so here I get matches, but how can I move them up the let the filter method return true?
            return found.length
            }).length>0

        })
        console.log(result)
</code>```

Thanks to Taplars comment, I have used a map-method instead of a forEach:

```<code>let data = ['Doe, John', 'Bean, Mister']
    let split = search.split(" ")
    split = split.map(item => { return item.replace(/[^\w\s]+/gi, '')})
    let result = data.filter(item => {
      let filtered =   split.map(element => {
            let ret = item.match(new RegExp(element, "i"))
            return ret
        })
      console.log(item,filtered) //now I have two arrays, one with something meaningful and one with [null,null]. How can I remove empty arrays?
      return filtered.length>0
    })
    console.log(result)
</code>```

答:
Try the following:

Get the search expression and turn it into a series of regular expressions

Iterate through the data and check to see if some or all the expressions match

const data = ['Doe, John', 'Doe, Jane', 'Smith, John', 'Bean, Mister'] // data from database

function searchEvery(input) {
  const wordExpressions = input.split(/[^\w]+/g)
    .filter(word => word) // remove empty entries
    .map(word => new RegExp(word, 'i')); // convert to regular expression
  return data.filter(item => wordExpressions.every(exp => exp.test(item)));
}

function searchSome(input) {
  const wordExpressions = input.split(/[^\w]+/g)
    .filter(word => word) // remove empty entries
    .map(word => new RegExp(word, 'i')); // convert to regular expression
  return data.filter(item => wordExpressions.some(exp => exp.test(item)));
}

console.log(searchEvery('John Doe'))
console.log(searchEvery('John'))
console.log(searchEvery('Doe'))

console.log(searchSome('John Doe'))```

Title: Split whitespaces and search user input

Body:
I have an input field where users can search a database for a certain name. The database contains names such as "Doe, John".

If a user searches for "john" I think it's easy to implement. However, if he or she searches for "john Doe" I would like to implement the logic search for john or search for doe.

With RegEx I am completely lost. Is something like this even possible? However, with JS I would at least be able to consider this algorithm:

Split the input on a whitespace and create to arrays

Remove special characters

Filter the JSON object retrieved from the database

check, whether item includes the cleansed string-arrays

As for the JS-functions I tried something (in vain):

        let search = 'John Doe' //user input
        let data = ['Doe, John', 'Bean, Mister'] //data from database
        let split = search.split(" ") //split the whitespace into two arrays
        split = split.map(item => { return item.replace(/[^\w\s]+/gi, '')}) //remove dots, commas etc.
        let result = data.filter(item => { //filter each item from the data...
            split.forEach(element => {
            let found = item.match(new RegExp(element, "i")) // so here I get matches, but how can I move them up the let the filter method return true?
            return found.length
            }).length>0

        })
        console.log(result)

Thanks to Taplars comment, I have used a map-method instead of a forEach:

let data = ['Doe, John', 'Bean, Mister']
    let split = search.split(" ")
    split = split.map(item => { return item.replace(/[^\w\s]+/gi, '')})
    let result = data.filter(item => {
      let filtered =   split.map(element => {
            let ret = item.match(new RegExp(element, "i"))
            return ret
        })
      console.log(item,filtered) //now I have two arrays, one with something meaningful and one with [null,null]. How can I remove empty arrays?
      return filtered.length>0
    })
    console.log(result)


问:
Using Flask with CPU-bound requests that need to be parallelized onto multiple cores
A computational scientist where I work wrote a program that scores inputs using a machine learning model built with scikit-learn. My task is to make this ML scorer available as a microservice.

So I wrote a few lines of code using Flask to accomplish this. Mission achieved!

Well, not quite. Because this service is going to be beaten on pretty heavily at times, it needs to be able to crunch on several requests in parallel. (I.e., on multiple cores. We have about 20 on our server.) A solution that I can achieve with about ten minutes of effort is to just spin up ten or twenty of these little REST servers on different ports and round-robin to them using nginx as a reverse proxy.

Although this will work fine, I am sure, I think it would be more elegant to have a single Python server handling all the requests, rather than having twenty Python servers. So I started reading up on WSGI and uWSGI and a bunch of other things. But all that I have accomplished with all this reading and web surfing is ending up very confused.

So I'll ask here instead of trying to unravel this on my own: Should I just stick with the brute force approach I described above? Or is there something better that I might be doing?

But if doing something "better" is going to require days of effort wading through incomprehensible documentation, doing frustrating experimentation, and pulling out all of my hair, then I'd rather just stick with the dumb brute force approach that I already understand and that I know for sure will work.

Thanks.

答:
As suggested by tedivm, I used FastAPI and uvicorn to implement a working solution.

Here's a sample little server program which is named test_fast_api.py. It responds to both GET and POST requests (the POST requests should be in JSON) and the responses are in JSON:

```<code>from typing import List
from fastapi import FastAPI

app = FastAPI()

@app.get("/score/{seq}")
async def score(seq: str):
    return len(seq)

@app.get("/scores/{seqs}")
async def scores(seqs: str):
    return [len(seq) for seq in seqs.split(",")]

@app.post("/scores")
async def scores_post(seqs: List[str]):
    return [len(seq) for seq in seqs]
</code>```

This service can then be served by 10 processes like so:

```<code>$ uvicorn --workers 10 --port 12345 test_fast_api:app
</code>```

If this service were actually CPU-bound, running using 10 processes would allow it to make good use of 10 CPU cores.

Body:
As suggested by tedivm, I used FastAPI and uvicorn to implement a working solution.

Here's a sample little server program which is named test_fast_api.py. It responds to both GET and POST requests (the POST requests should be in JSON) and the responses are in JSON:

from typing import List
from fastapi import FastAPI

app = FastAPI()

@app.get("/score/{seq}")
async def score(seq: str):
    return len(seq)

@app.get("/scores/{seqs}")
async def scores(seqs: str):
    return [len(seq) for seq in seqs.split(",")]

@app.post("/scores")
async def scores_post(seqs: List[str]):
    return [len(seq) for seq in seqs]

This service can then be served by 10 processes like so:

$ uvicorn --workers 10 --port 12345 test_fast_api:app

If this service were actually CPU-bound, running using 10 processes would allow it to make good use of 10 CPU cores.


问:
Replace Text with jQuery if text exists
What I am trying to do in jQuery is to take the first comment, out of a group that is all hidden until the user clicks on a button, and output that first comment so it is visible.  I have this working, to a point.  I want it to happen when the page loads, so I have it in the document.ready, but it won't work.  So I attached it to a mousemove event, and it works.

But what I want to do now is if there is a comment, take the comment and show it like I have previously.  But if there isn't a comment, then show the words 'No Comment'.  Below is the code I'm using.

```<code>if ( jQuery('.dsq-commenter-name').length ){
          jQuery(document).mousemove(function() {
            jQuery('#comments p strong').text( jQuery('.dsq-commenter-name').text() );
            jQuery('#comments p span.comment_excerpt').text( jQuery('.dsq-comment-text').text() );
        });
      }
</code>```

This code isn't working.  If I take away the if statement, it works fine to replace the text, but if no comments at all, it just puts empty space instead of leaving the words 'No Comments'.  If I put the code directly into the console, it works.  So I'm not sure why it won't work when the page loads.  I'm assuming it has to be something with the if statement, but I've tried all kinds of things and can't get it to work.

EDIT:
Not shown in this code but I have everything in a jQuery(document).ready(function() {
and that doesn't seem to help.  But the comments are handled by Disqus, and so I'm thinking they are loaded later, so how would I go about attaching an event to them?

SECOND EDIT:
Okay I've fixed it, not sure if it is the best way to do it though.  Thanks to @Jacob, I decided the comments were loading after the code had already executed.  So I added on to the code using setTimeout, and so the function will run a second or so after the page loads, which works.  Again, not sure if this is the way to do it or not, so please correct me if I'm wrong or if you want to see the code.

答:
I'm not sure "length" is the best variable to check.  Try val:</p>

```<code>if (jquery('.dsq-commenter-name').val() != "") {  //or try != null
    //do stuff.
}
</code>```

Title: Replace Text with jQuery if text exists

Body:
What I am trying to do in jQuery is to take the first comment, out of a group that is all hidden until the user clicks on a button, and output that first comment so it is visible.  I have this working, to a point.  I want it to happen when the page loads, so I have it in the document.ready, but it won't work.  So I attached it to a mousemove event, and it works.

But what I want to do now is if there is a comment, take the comment and show it like I have previously.  But if there isn't a comment, then show the words 'No Comment'.  Below is the code I'm using.

if ( jQuery('.dsq-commenter-name').length ){
          jQuery(document).mousemove(function() {
            jQuery('#comments p strong').text( jQuery('.dsq-commenter-name').text() );
            jQuery('#comments p span.comment_excerpt').text( jQuery('.dsq-comment-text').text() );
        });
      }

This code isn't working.  If I take away the if statement, it works fine to replace the text, but if no comments at all, it just puts empty space instead of leaving the words 'No Comments'.  If I put the code directly into the console, it works.  So I'm not sure why it won't work when the page loads.  I'm assuming it has to be something with the if statement, but I've tried all kinds of things and can't get it to work.

EDIT:
Not shown in this code but I have everything in a jQuery(document).ready(function() {
and that doesn't seem to help.  But the comments are handled by Disqus, and so I'm thinking they are loaded later, so how would I go about attaching an event to them?

SECOND EDIT:
Okay I've fixed it, not sure if it is the best way to do it though.  Thanks to @Jacob, I decided the comments were loading after the code had already executed.  So I added on to the code using setTimeout, and so the function will run a second or so after the page loads, which works.  Again, not sure if this is the way to do it or not, so please correct me if I'm wrong or if you want to see the code.

Body:
I'm not sure "length" is the best variable to check.  Try val:

if (jquery('.dsq-commenter-name').val() != "") {  //or try != null
    //do stuff.
}


问:
Create a string list into a float list
I was reading from a file and was able to compute a list, but sadly it reads as :
['40\n', '35\n', '49\n', '53\n', '38\n', '39\n', '40\n', '37\n', '49\n', '34\n', '38\n', '43\n', '47\n', '\n']
when I would like it to read as:
['40', '35', '49', '53', '38', '39', '40', '37', '49', '34', '38', '43', '47']
I know I have to append it and/or slice it in order to turn in into floats. I am really stuck on this part. This is the one part that will make the rest of my code work. Any help is appreciated!

Title: Create a string list into a float list

Body:
'\n' is a linebreak. It can be ignored when there is a number before it. Thus you could do:

a = ['40\n', '35\n', '49\n', '53\n', '38\n', '39\n', '40\n', '37\n', '49\n', '34\n', '38\n', '43\n', '47\n', '\n']

[int(i) for i in a if i!='\n']
[40, 35, 49, 53, 38, 39, 40, 37, 49, 34, 38, 43, 47]

if you want floats, just do:

[float(i) for i in a if i!='\n']
[40.0, 35.0, 49.0, 53.0, 38.0, 39.0, 40.0, 37.0, 49.0, 34.0, 38.0,

43.0, 47.0]


问:
How to ignore one or more output bus pins for a module instantiation
I want to ignore one or more bits in an array argument for a module in SystemVerilog.

```<code>module x(in a, out [0:3] z);
...
endmodule

module tb;
  logic my_a;
  logic [1:3] my_z;
  // I want to stop having to do this next line:
  logic ignore_this_bit;
  x myx(.a(my_a), .z({ignore_this_bit, my_z}));
endmodule
</code>```

What is the proper syntax to do this? I have been doing it just as shown above with a declaration of ignore_this_bit and simply never connecting to that net. But it seems there should be a simpler way. Something like just using a comma and no variable name in the arguments for the module instantiation or maybe using something like 1'bX instead of an output argument bit, or something like that.

Is this affected by the fact that I am using big-endian bit ordering for the vectors here? (I hate it, but I am building code for an old CPU that uses that ordering and it's way easier to match my code to the existing than to fix it.)

This is a hard concept to search for, and I have tried. Does anyone have expertise that can help me know how to do this "the right way"? Thanks.

答:
You should not need to do anything here. This should just work truncating the MSB z[0]

```<code>x myx(.a(my_a), .z(my_z));
</code>```

Think of an output port as an implicit continuous assignment

```<code>assign my_z = myx.z;
</code>```

But if the MSB is not the bit you want to ignore, there is no simple solution. You might want to look at the net alias feature.

Body:
I want to ignore one or more bits in an array argument for a module in SystemVerilog.

module x(in a, out [0:3] z);
...
endmodule

module tb;
  logic my_a;
  logic [1:3] my_z;
  // I want to stop having to do this next line:
  logic ignore_this_bit;
  x myx(.a(my_a), .z({ignore_this_bit, my_z}));
endmodule

What is the proper syntax to do this? I have been doing it just as shown above with a declaration of ignore_this_bit and simply never connecting to that net. But it seems there should be a simpler way. Something like just using a comma and no variable name in the arguments for the module instantiation or maybe using something like 1'bX instead of an output argument bit, or something like that.

Is this affected by the fact that I am using big-endian bit ordering for the vectors here? (I hate it, but I am building code for an old CPU that uses that ordering and it's way easier to match my code to the existing than to fix it.)

This is a hard concept to search for, and I have tried. Does anyone have expertise that can help me know how to do this "the right way"? Thanks.

Body:
You should not need to do anything here. This should just work truncating the MSB z[0]

x myx(.a(my_a), .z(my_z));

Think of an output port as an implicit continuous assignment

assign my_z = myx.z;

But if the MSB is not the bit you want to ignore, there is no simple solution. You might want to look at the net alias feature.


问:
Swift: Change value of another ViewController with delegation programmatically
I am trying to change the value of one ViewController by clicking a button inside a second ViewController with delegation.
But so far it only prints a message, but doesn't change the value.

I have this class where I defined a view:

```<code>class CounterView: UIView {

    public var creditPointValue = Int()

    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = .cyan

        self.addSubview(label)
        label.text = "Credit Points: \(creditPointValue)"
        label.translatesAutoresizingMaskIntoConstraints = false;
        label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    }

    func changeCreditPointValue(value:Int){
        creditPointValue = creditPointValue + value
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

I am using that view inside this ViewController and I want to manipulate the variable "creditPointValue":

```<code>protocol AddCreditsDelegate {
    func addCreditsToCounter()
}

class ViewController: UIViewController {

    var delegate: AddCreditsDelegate?

    var counterView = CounterView()

    let label = UILabel()

    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white

        view.addSubview(button)
        button.backgroundColor = .red
        button.setTitle("View2", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

    override func viewDidAppear(_ animated: Bool) {
        view.addSubview(counterView)
        counterView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        counterView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        counterView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        //counterView.frame.size.height = 30
        counterView.bottomAnchor.constraint(equalTo: counterView.topAnchor, constant: 50).isActive = true

    }

    @objc func changeView(){
        delegate?.addCreditsToCounter()
        navigationController?.pushViewController(ViewController2(), animated: true)
    }
}
</code>```

And inside this second ViewController I am trying to change the value by clicking the button I added to the view:

```<code>class ViewController2: UIViewController {

    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(button)
               button.backgroundColor = .red
               button.setTitle("add Credits", for: .normal)
               button.translatesAutoresizingMaskIntoConstraints = false
               button.addTarget(self, action: #selector(addCreditsButton), for: .touchUpInside)
               button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
               button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

    @objc func addCreditsButton(){
        addCreditsToCounter()
    }
}

extension ViewController2 : AddCreditsDelegate{
    func addCreditsToCounter() {
        let vc = ViewController()
        vc.delegate = self
        vc.counterView.creditPointValue += 5
        print("pressed")
    }
}
</code>```

So far only the message "pressed" gets printed each time I click the button and I don't even know if I am going into the right direction with my approach trying to use delegation.

答:
You create a new instance here

```<code>  let vc = ViewController()
</code>```

instead you need

```<code>@objc func changeView() {
 let sec = ViewController2(),
 sec.delegate = self
 navigationController?.pushViewController( animated: true)
}
</code>```

Then declare this inside the SecondVC

```<code>weak var delegate:ViewController?
</code>```

Finally

```<code>    func addCreditsToCounter() {
        delegate?.counterView.creditPointValue += 5
        print("pressed")
    }
</code>```

Body:
I am trying to change the value of one ViewController by clicking a button inside a second ViewController with delegation.
But so far it only prints a message, but doesn't change the value.

I have this class where I defined a view:

class CounterView: UIView {

    public var creditPointValue = Int()

    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = .cyan

        self.addSubview(label)
        label.text = "Credit Points: \(creditPointValue)"
        label.translatesAutoresizingMaskIntoConstraints = false;
        label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    }

    func changeCreditPointValue(value:Int){
        creditPointValue = creditPointValue + value
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I am using that view inside this ViewController and I want to manipulate the variable "creditPointValue":

protocol AddCreditsDelegate {
    func addCreditsToCounter()
}

class ViewController: UIViewController {

    var delegate: AddCreditsDelegate?

    var counterView = CounterView()

    let label = UILabel()

    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white

        view.addSubview(button)
        button.backgroundColor = .red
        button.setTitle("View2", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

    override func viewDidAppear(_ animated: Bool) {
        view.addSubview(counterView)
        counterView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        counterView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        counterView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        //counterView.frame.size.height = 30
        counterView.bottomAnchor.constraint(equalTo: counterView.topAnchor, constant: 50).isActive = true

    }

    @objc func changeView(){
        delegate?.addCreditsToCounter()
        navigationController?.pushViewController(ViewController2(), animated: true)
    }
}

And inside this second ViewController I am trying to change the value by clicking the button I added to the view:

class ViewController2: UIViewController {

    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(button)
               button.backgroundColor = .red
               button.setTitle("add Credits", for: .normal)
               button.translatesAutoresizingMaskIntoConstraints = false
               button.addTarget(self, action: #selector(addCreditsButton), for: .touchUpInside)
               button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
               button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

    @objc func addCreditsButton(){
        addCreditsToCounter()
    }
}

extension ViewController2 : AddCreditsDelegate{
    func addCreditsToCounter() {
        let vc = ViewController()
        vc.delegate = self
        vc.counterView.creditPointValue += 5
        print("pressed")
    }
}

So far only the message "pressed" gets printed each time I click the button and I don't even know if I am going into the right direction with my approach trying to use delegation.

Body:
You create a new instance here

  let vc = ViewController()

instead you need

@objc func changeView() {
 let sec = ViewController2(),
 sec.delegate = self
 navigationController?.pushViewController( animated: true)
}

Then declare this inside the SecondVC

weak var delegate:ViewController?

Finally

    func addCreditsToCounter() {
        delegate?.counterView.creditPointValue += 5
        print("pressed")
    }


问:
SBCL "subst" efficiency
I just wrote a program that calls subst inside a loop, along with a number of other functions, and by far, the subst function calls take the most amount of time. Below is a notional snippet of code that contains the spirit of the program i wrote.

```<code>    (loop
       with bindings = ((symbol1 . 1) (sybmol2 . 2) ... (sybmoln . n))
       with x-copy
       for x in xs
       do
         ...
         (setq x-copy (copy-cpd x))
         (setf (cpd-identifiers1 x-copy) (subst-bindings bindings (cpd-identifiers1 x)))
         (setf (cpd-identifiers2 x-copy) (subst-bindings bindings (cpd-identifiers2 x)))
         ...)
</code>```

subst-bindings makes recursive calls to subst internally:

```<code>(defun subst-bindings (bindings generic)
  (cond ((null bindings) generic)
    (t (subst-bindings (cdr bindings)
               (subst (cdar bindings) (caar bindings) generic)))))
</code>```

I ran my actual code with the statistical profiler enabled, and I got these results:

```<code>           Self        Total        Cumul
  Nr  Count     %  Count     %  Count     %    Calls  Function
------------------------------------------------------------------------
   1   4585  45.8   6840  68.4   4585  45.8        -  (LABELS SB-IMPL::S :IN SUBST)
   2   2204  22.0   2205  22.1   6789  67.9        -  EQL
   3    489   4.9    489   4.9   7278  72.8        -  SUBST
   4    315   3.2   7537  75.4   7593  75.9        -  SUBST-BINDINGS
   5    150   1.5    235   2.3   7743  77.4        -  PPRINT-DISPATCH
   6    143   1.4    274   2.7   7886  78.9        -  SB-IMPL::%FIND-SYMBOL
   7    114   1.1    114   1.1   8000  80.0        -  SB-IMPL::%MAKE-STRING-OUTPUT-STREAM
   8    106   1.1    347   3.5   8106  81.1        -  SB-KERNEL:OUTPUT-SYMBOL-NAME
   9     94   0.9    113   1.1   8200  82.0        -  SB-IMPL::STRING-SOUT
  10     73   0.7    155   1.5   8273  82.7        -  SB-KERNEL::VALUES-SPECIFIER-TYPE-R
  11     70   0.7     70   0.7   8343  83.4        -  SB-KERNEL:UB32-BASH-COPY
  12     56   0.6     56   0.6   8399  84.0        -  SB-KERNEL:%SXHASH-SIMPLE-SUBSTRING
  13     51   0.5     51   0.5   8450  84.5        -  MAKE-CPD
  14     48   0.5    160   1.6   8498  85.0        -  GET-OUTPUT-STREAM-STRING
  15     48   0.5     48   0.5   8546  85.5        -  WRITE-STRING
  16     44   0.4     44   0.4   8590  85.9        -  SB-KERNEL:%COERCE-CALLABLE-TO-FUN
  17     43   0.4    741   7.4   8633  86.3        -  PRINC
  18     43   0.4     60   0.6   8676  86.8        -  POSITION
  19     39   0.4    151   1.5   8715  87.2        -  SB-IMPL::%WRITE-STRING
  20     39   0.4     46   0.5   8754  87.5        -  SB-KERNEL:STRING=*
  21     37   0.4    195   2.0   8791  87.9        -  SB-KERNEL::SPECIFIER-TYPE-R
  22     37   0.4    169   1.7   8828  88.3        -  OPERATE-FACTOR
  23     36   0.4     68   0.7   8864  88.6        -  SB-VM::GENERIC-+
  24     36   0.4     36   0.4   8900  89.0        -  COPY-LIST
  25     35   0.4    231   2.3   8935  89.4        -  SB-KERNEL:SPECIFIER-TYPE
  26     33   0.3    314   3.1   8968  89.7        -  SB-INT:%INTERN
  27     32   0.3   9146  91.5   9000  90.0        -  CANDIDATE-NODES
  28     31   0.3     31   0.3   9031  90.3        -  SB-IMPL::SETUP-PRINTER-STATE
  29     30   0.3     79   0.8   9061  90.6        -  COPY-SEQ
  30     30   0.3     45   0.4   9091  90.9        -  GET-FULLY-QUALIFIED-CPD-VARS
  31     30   0.3     30   0.3   9121  91.2        -  SB-IMPL::OUTPUT-SYMBOL
  32     28   0.3   1724  17.2   9149  91.5        -  GENERATE-CPD-VARS
  33     26   0.3     63   0.6   9175  91.8        -  SB-INT:EQUAL-BUT-NO-CAR-RECURSION
  34     25   0.3     25   0.3   9200  92.0        -  SB-IMPL::VECTOR-SUBSEQ-DISPATCH/SIMPLE-VECTOR
  35     24   0.2     24   0.2   9224  92.2        -  (SB-IMPL::OPTIMIZED-DATA-VECTOR-REF T)
  36     23   0.2     23   0.2   9247  92.5        -  SB-KERNEL:HAIRY-DATA-VECTOR-REF/CHECK-BOUNDS
  37     21   0.2    685   6.8   9268  92.7        -  (LABELS SB-IMPL::HANDLE-IT :IN SB-KERNEL:OUTPUT-OBJECT)
  38     20   0.2     70   0.7   9288  92.9        -  SB-IMPL::COMPUTE-SYMBOL-HASH
  39     19   0.2   1295  12.9   9307  93.1        -  COMBINE-SYMBOLS
  40     19   0.2    395   4.0   9326  93.3        -  INTERN
  41     19   0.2    104   1.0   9345  93.5        -  (FLET SB-IMPL::REPLACE-ALL :IN GET-OUTPUT-STREAM-STRING)
  42     19   0.2     19   0.2   9364  93.6        -  SB-C:RETURN-MULTIPLE
  43     19   0.2     19   0.2   9383  93.8        -  SB-KERNEL:VECTOR-SUBSEQ*
  44     18   0.2    133   1.3   9401  94.0        -  COPY-CPD
</code>```

The SBCL User manual describes how to interpret this table:

For each function, the table will show three absolute and relative
  sample counts. The Self column shows samples taken while directly
  executing that function. The Total column shows samples taken while
  executing that function or functions called from it (sampled to a
  platform-specific depth). The Cumul column shows the sum of all Self
  columns up to and including that line in the table.

As you can see, two of the first three entries are subst-related functions and the percentage of samples taken during these functions is disproportionately more than the rest of the function calls. This makes me wonder, is subst is implemented in an efficient way in sbcl? If not, are there any more efficient alternatives I could use to perform substitutions?

Thanks for your help

答:
Check out the standard functions sublis and nsublis. They use an assoc list for the substitutions.

```<code>CL-USER > (sublis '((x . 10) (y . 20))
                  '(* x (+ x y) (* y y)))
(* 10 (+ 10 20) (* 20 20))
</code>```

Style:

I would not write the substitution function in a recursive style.

```<code>(defun subst-bindings (bindings generic)
  (loop for (b v) in bindings
        do (setf generic (subst v b generic)))
  generic)
</code>```

Above ensures that it is actually a loop and the destructuring makes the code a bit shorter to read in this case. In portable Common Lisp tail recursive functions are not always converted to an efficient loop.

Title: SBCL "subst" efficiency

Body:
I just wrote a program that calls subst inside a loop, along with a number of other functions, and by far, the subst function calls take the most amount of time. Below is a notional snippet of code that contains the spirit of the program i wrote.

    (loop
       with bindings = ((symbol1 . 1) (sybmol2 . 2) ... (sybmoln . n))
       with x-copy
       for x in xs
       do
         ...
         (setq x-copy (copy-cpd x))
         (setf (cpd-identifiers1 x-copy) (subst-bindings bindings (cpd-identifiers1 x)))
         (setf (cpd-identifiers2 x-copy) (subst-bindings bindings (cpd-identifiers2 x)))
         ...)

subst-bindings makes recursive calls to subst internally:

(defun subst-bindings (bindings generic)
  (cond ((null bindings) generic)
    (t (subst-bindings (cdr bindings)
               (subst (cdar bindings) (caar bindings) generic)))))

I ran my actual code with the statistical profiler enabled, and I got these results:

           Self        Total        Cumul
  Nr  Count     %  Count     %  Count     %    Calls  Function
------------------------------------------------------------------------
   1   4585  45.8   6840  68.4   4585  45.8        -  (LABELS SB-IMPL::S :IN SUBST)
   2   2204  22.0   2205  22.1   6789  67.9        -  EQL
   3    489   4.9    489   4.9   7278  72.8        -  SUBST
   4    315   3.2   7537  75.4   7593  75.9        -  SUBST-BINDINGS
   5    150   1.5    235   2.3   7743  77.4        -  PPRINT-DISPATCH
   6    143   1.4    274   2.7   7886  78.9        -  SB-IMPL::%FIND-SYMBOL
   7    114   1.1    114   1.1   8000  80.0        -  SB-IMPL::%MAKE-STRING-OUTPUT-STREAM
   8    106   1.1    347   3.5   8106  81.1        -  SB-KERNEL:OUTPUT-SYMBOL-NAME
   9     94   0.9    113   1.1   8200  82.0        -  SB-IMPL::STRING-SOUT
  10     73   0.7    155   1.5   8273  82.7        -  SB-KERNEL::VALUES-SPECIFIER-TYPE-R
  11     70   0.7     70   0.7   8343  83.4        -  SB-KERNEL:UB32-BASH-COPY
  12     56   0.6     56   0.6   8399  84.0        -  SB-KERNEL:%SXHASH-SIMPLE-SUBSTRING
  13     51   0.5     51   0.5   8450  84.5        -  MAKE-CPD
  14     48   0.5    160   1.6   8498  85.0        -  GET-OUTPUT-STREAM-STRING
  15     48   0.5     48   0.5   8546  85.5        -  WRITE-STRING
  16     44   0.4     44   0.4   8590  85.9        -  SB-KERNEL:%COERCE-CALLABLE-TO-FUN
  17     43   0.4    741   7.4   8633  86.3        -  PRINC
  18     43   0.4     60   0.6   8676  86.8        -  POSITION
  19     39   0.4    151   1.5   8715  87.2        -  SB-IMPL::%WRITE-STRING
  20     39   0.4     46   0.5   8754  87.5        -  SB-KERNEL:STRING=*
  21     37   0.4    195   2.0   8791  87.9        -  SB-KERNEL::SPECIFIER-TYPE-R
  22     37   0.4    169   1.7   8828  88.3        -  OPERATE-FACTOR
  23     36   0.4     68   0.7   8864  88.6        -  SB-VM::GENERIC-+
  24     36   0.4     36   0.4   8900  89.0        -  COPY-LIST
  25     35   0.4    231   2.3   8935  89.4        -  SB-KERNEL:SPECIFIER-TYPE
  26     33   0.3    314   3.1   8968  89.7        -  SB-INT:%INTERN
  27     32   0.3   9146  91.5   9000  90.0        -  CANDIDATE-NODES
  28     31   0.3     31   0.3   9031  90.3        -  SB-IMPL::SETUP-PRINTER-STATE
  29     30   0.3     79   0.8   9061  90.6        -  COPY-SEQ
  30     30   0.3     45   0.4   9091  90.9        -  GET-FULLY-QUALIFIED-CPD-VARS
  31     30   0.3     30   0.3   9121  91.2        -  SB-IMPL::OUTPUT-SYMBOL
  32     28   0.3   1724  17.2   9149  91.5        -  GENERATE-CPD-VARS
  33     26   0.3     63   0.6   9175  91.8        -  SB-INT:EQUAL-BUT-NO-CAR-RECURSION
  34     25   0.3     25   0.3   9200  92.0        -  SB-IMPL::VECTOR-SUBSEQ-DISPATCH/SIMPLE-VECTOR
  35     24   0.2     24   0.2   9224  92.2        -  (SB-IMPL::OPTIMIZED-DATA-VECTOR-REF T)
  36     23   0.2     23   0.2   9247  92.5        -  SB-KERNEL:HAIRY-DATA-VECTOR-REF/CHECK-BOUNDS
  37     21   0.2    685   6.8   9268  92.7        -  (LABELS SB-IMPL::HANDLE-IT :IN SB-KERNEL:OUTPUT-OBJECT)
  38     20   0.2     70   0.7   9288  92.9        -  SB-IMPL::COMPUTE-SYMBOL-HASH
  39     19   0.2   1295  12.9   9307  93.1        -  COMBINE-SYMBOLS
  40     19   0.2    395   4.0   9326  93.3        -  INTERN
  41     19   0.2    104   1.0   9345  93.5        -  (FLET SB-IMPL::REPLACE-ALL :IN GET-OUTPUT-STREAM-STRING)
  42     19   0.2     19   0.2   9364  93.6        -  SB-C:RETURN-MULTIPLE
  43     19   0.2     19   0.2   9383  93.8        -  SB-KERNEL:VECTOR-SUBSEQ*
  44     18   0.2    133   1.3   9401  94.0        -  COPY-CPD

The SBCL User manual describes how to interpret this table:

For each function, the table will show three absolute and relative
  sample counts. The Self column shows samples taken while directly
  executing that function. The Total column shows samples taken while
  executing that function or functions called from it (sampled to a
  platform-specific depth). The Cumul column shows the sum of all Self
  columns up to and including that line in the table.

As you can see, two of the first three entries are subst-related functions and the percentage of samples taken during these functions is disproportionately more than the rest of the function calls. This makes me wonder, is subst is implemented in an efficient way in sbcl? If not, are there any more efficient alternatives I could use to perform substitutions?

Thanks for your help

Body:
Check out the standard functions sublis and nsublis. They use an assoc list for the substitutions.

CL-USER > (sublis '((x . 10) (y . 20))
                  '(* x (+ x y) (* y y)))
(* 10 (+ 10 20) (* 20 20))

Style:

I would not write the substitution function in a recursive style.

(defun subst-bindings (bindings generic)
  (loop for (b v) in bindings
        do (setf generic (subst v b generic)))
  generic)

Above ensures that it is actually a loop and the destructuring makes the code a bit shorter to read in this case. In portable Common Lisp tail recursive functions are not always converted to an efficient loop.


问:
Asp.Net Core produces 404 when API is separated into multiple projects
I am trying to break out reusable code for the APIs that I have to create, but there is one issue that has had me stumped for a few days now.  When all of the code resides in a single project, WebAPI and the common code exists within a folder called Core, everything works.

Now, if I take the code within Core and put it in its own project WebAPI.Core, the API starts, Swagger loads, but every request produces 404. I have narrowed down the problem, and it only occurs when Startup and Program are in different projects.  Is that the intended behavior, or did I do something wrong?

Here is the Startup which is located in the WebAPI.Core project:

```<code>public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApiVersioning(options =>
        {
            options.UseApiBehavior = false;
            options.ReportApiVersions = true;
            options.ApiVersionReader = new HeaderApiVersionReader("api-version");
            options.AssumeDefaultVersionWhenUnspecified = true;
        });
        services.AddMvc(options => { options.EnableEndpointRouting = false; });
        services.AddVersionedApiExplorer(options =>
        {
            options.GroupNameFormat = "'v'VVV";
            options.SubstituteApiVersionInUrl = true;
        });

        services
            .AddControllers(options => options.Filters.Add(new ErrorFilter()))
            .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
    }

    public void Configure(IApplicationBuilder app)
    {
        const string swagger = "Swagger";

        app.UseMvc(routes => routes.MapRoute("default", "/{controller}/{action}/{*id}", new {id = string.Empty}));
        app.UseRouting();
        app.UseEndpoints(builder => builder.MapControllers());

        var directory = Combine(Api.CurrentDirectory, swagger);

        if (Exists(directory))
        {
            Delete(directory, true);
        }

        CreateDirectory(directory);

        app.UseDefaultFiles().UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(directory),
            RequestPath = $"/{swagger}"
        });

        Api.Assembly.CreateDocuments(AppSettings["Title"], AppSettings["Description"], AppSettings["Name"], AppSettings["Email"], directory);

        app.UseSwaggerUI(setupAction =>
        {
            setupAction.RoutePrefix = string.Empty;

            foreach (var file in GetFiles(directory))
            {
                var fileName = GetFileNameWithoutExtension(file);
                setupAction.SwaggerEndpoint($"/{swagger}/{fileName}.json", fileName.Replace("-", " "));
            }
        });
    }
}
</code>```

Here is Api, the link between Startup and Program, also located in WebAPI.Core:

```<code>public static class Api
{
    public static void Run<TStartup>(this Assembly assembly, string[] args) where TStartup : Startup
    {
        Assembly = assembly;
        CurrentDirectory = GetDirectoryName(UnescapeDataString(new UriBuilder(assembly.CodeBase).Path));

        CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<TStartup>(); }).Build().Run();
    }

    public static Assembly Assembly { get; private set; }

    public static string CurrentDirectory { get; private set; }
}
</code>```

And finally, here is Program, located in WebAPI:

```<code>public static class Program
{
    public static void Main(string[] args)
    {
        GetExecutingAssembly().Run<Startup>(args);
    }
}
</code>```

答:
As was pointed out in one of the comments, I was missing a link to the API assembly.

from:

```<code> services.AddMvc(options => { options.EnableEndpointRouting = false; });
</code>```

to:

```<code>services.AddMvc(options => { options.EnableEndpointRouting = false; }).AddApplicationPart(Api.Assembly);
</code>```

and here is some extra information on AddApplicationPart.

Body:
I am trying to break out reusable code for the APIs that I have to create, but there is one issue that has had me stumped for a few days now.  When all of the code resides in a single project, WebAPI and the common code exists within a folder called Core, everything works.

Now, if I take the code within Core and put it in its own project WebAPI.Core, the API starts, Swagger loads, but every request produces 404. I have narrowed down the problem, and it only occurs when Startup and Program are in different projects.  Is that the intended behavior, or did I do something wrong?

Here is the Startup which is located in the WebAPI.Core project:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApiVersioning(options =>
        {
            options.UseApiBehavior = false;
            options.ReportApiVersions = true;
            options.ApiVersionReader = new HeaderApiVersionReader("api-version");
            options.AssumeDefaultVersionWhenUnspecified = true;
        });
        services.AddMvc(options => { options.EnableEndpointRouting = false; });
        services.AddVersionedApiExplorer(options =>
        {
            options.GroupNameFormat = "'v'VVV";
            options.SubstituteApiVersionInUrl = true;
        });

        services
            .AddControllers(options => options.Filters.Add(new ErrorFilter()))
            .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
    }

    public void Configure(IApplicationBuilder app)
    {
        const string swagger = "Swagger";

        app.UseMvc(routes => routes.MapRoute("default", "/{controller}/{action}/{*id}", new {id = string.Empty}));
        app.UseRouting();
        app.UseEndpoints(builder => builder.MapControllers());

        var directory = Combine(Api.CurrentDirectory, swagger);

        if (Exists(directory))
        {
            Delete(directory, true);
        }

        CreateDirectory(directory);

        app.UseDefaultFiles().UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(directory),
            RequestPath = $"/{swagger}"
        });

        Api.Assembly.CreateDocuments(AppSettings["Title"], AppSettings["Description"], AppSettings["Name"], AppSettings["Email"], directory);

        app.UseSwaggerUI(setupAction =>
        {
            setupAction.RoutePrefix = string.Empty;

            foreach (var file in GetFiles(directory))
            {
                var fileName = GetFileNameWithoutExtension(file);
                setupAction.SwaggerEndpoint($"/{swagger}/{fileName}.json", fileName.Replace("-", " "));
            }
        });
    }
}

Here is Api, the link between Startup and Program, also located in WebAPI.Core:

public static class Api
{
    public static void Run<TStartup>(this Assembly assembly, string[] args) where TStartup : Startup
    {
        Assembly = assembly;
        CurrentDirectory = GetDirectoryName(UnescapeDataString(new UriBuilder(assembly.CodeBase).Path));

        CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<TStartup>(); }).Build().Run();
    }

    public static Assembly Assembly { get; private set; }

    public static string CurrentDirectory { get; private set; }
}

And finally, here is Program, located in WebAPI:

public static class Program
{
    public static void Main(string[] args)
    {
        GetExecutingAssembly().Run<Startup>(args);
    }
}

Body:
As was pointed out in one of the comments, I was missing a link to the API assembly.

from:

 services.AddMvc(options => { options.EnableEndpointRouting = false; });

to:

services.AddMvc(options => { options.EnableEndpointRouting = false; }).AddApplicationPart(Api.Assembly);

and here is some extra information on AddApplicationPart.


问:
HTML Input Gradient Text
Been looking for a solution but no prevail, so I thought I'd ask here.

I am trying to apply a linear gradient to the input field as I have for the buttons as seen in this picture.

I have played around with different CSS options but have not been able to succeed.

The best version is where the placeholder is styled, but the input value is not. If I try to style the input value then things go wrong.

And advice would be greatly appreciated.

button{
  background-color: dodgerblue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
  font-size: 32px
}

button i{
  background: -webkit-linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

input{
  background-color: dodgerblue;
  height: 60px;
  width: 360px;
  font-size: 32px
}

input::placeholder{
  background: -webkit-linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/*
input:focus {
    background: -webkit-linear-gradient(#ffffff70, #ffffff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button><i>X</i></button>

<hr />

<input placeholder="SEARCH"/></code>```

答:
You will need two background layer. One for the text and one for the background-color.

Unfortunately this won't work on Firefox due to known bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1571244

input {
  background-color: dodgerblue;
  color:transparent;
  height: 60px;
  width: 360px;
  font-size: 32px
}

input::placeholder {
  background: linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
          background-clip: text;
  -webkit-text-fill-color: transparent;
}

input:not(:placeholder-shown) {
  background:
    linear-gradient(#ffffff70, #ffffff),
    dodgerblue;
  -webkit-background-clip: text, padding-box;
          background-clip: text, padding-box;
  -webkit-text-fill-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder="SEARCH"></code>```

For firefox you can consider an extra div for the background:

input {
  color:transparent;
  height: 60px;
  width: 360px;
  font-size: 32px;
  background: linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
          background-clip: text;
  -webkit-text-fill-color: transparent;
}

.input {
  display:inline-block;
  background-color: dodgerblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input"><input placeholder="SEARCH"></div></code>```

Title: HTML Input Gradient Text

Body:
Been looking for a solution but no prevail, so I thought I'd ask here.

I am trying to apply a linear gradient to the input field as I have for the buttons as seen in this picture.

I have played around with different CSS options but have not been able to succeed.

The best version is where the placeholder is styled, but the input value is not. If I try to style the input value then things go wrong.

And advice would be greatly appreciated.

button{
  background-color: dodgerblue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
  font-size: 32px
}

button i{
  background: -webkit-linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

input{
  background-color: dodgerblue;
  height: 60px;
  width: 360px;
  font-size: 32px
}

input::placeholder{
  background: -webkit-linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/*
input:focus {
    background: -webkit-linear-gradient(#ffffff70, #ffffff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
*/

<button>X</button>

<input placeholder="SEARCH"/>

Body:
You will need two background layer. One for the text and one for the background-color.

Unfortunately this won't work on Firefox due to known bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1571244

input {
  background-color: dodgerblue;
  color:transparent;
  height: 60px;
  width: 360px;
  font-size: 32px
}

input::placeholder {
  background: linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
          background-clip: text;
  -webkit-text-fill-color: transparent;
}

input:not(:placeholder-shown) {
  background:
    linear-gradient(#ffffff70, #ffffff),
    dodgerblue;
  -webkit-background-clip: text, padding-box;
          background-clip: text, padding-box;
  -webkit-text-fill-color: transparent;
}

<input placeholder="SEARCH">

For firefox you can consider an extra div for the background:

input {
  color:transparent;
  height: 60px;
  width: 360px;
  font-size: 32px;
  background: linear-gradient(#ffffff70, #ffffff);
  -webkit-background-clip: text;
          background-clip: text;
  -webkit-text-fill-color: transparent;
}

.input {
  display:inline-block;
  background-color: dodgerblue;
}

<div class="input"><input placeholder="SEARCH"></div>


问:
How to find a user selection weather forward or backward in javascript?
I am new to javascript.I am trying to make an simple toggle up div With user selection direction ill place the toggle div.After some googling I found one working fiddle But not as expected See the below screenshot to see the difference

When I select Some text on the front of the paragraph It works fine Like this

But when I selected some text from bottom paragraph It is not Working as expected

JsFiddle

Actually I am working in React version Fiddle is in Jquery

This is my code

```<code>    import React from 'react'
import {render} from 'react-dom';

export default class App extends  React.Component{
    constructor(props){
        super(props);
        this.state = {
            display:'none'  ,
            top:'',
            bottom:'',
            left:'',
            right:'',
            diplayForDown:'none'

        };
        this.handleOnMouseDown = this.handleOnMouseDown.bind(this)
        this.onMounseUp = this.onMounseUp.bind(this)
        this.onMouseDwn = this.onMouseDwn.bind(this)
        this.triggerAlltime = this.triggerAlltime.bind(this)
    }

    handleOnMouseDown(){
        let sel = window.getSelection && window.getSelection();

        let r = sel.getRangeAt(0).getBoundingClientRect();
        let relative=document.body.parentNode.getBoundingClientRect();
        console.log('Relative ',relative);

    if(!sel.isCollapsed){

        console.log(sel,r);
        let display = 'block';

        let top = (r.bottom - relative.top - 80)+'px';
        let bottom = r.bottom+'px';
        let left =( r.left)+'px';
        let right = (r.right)+'px';
        console.log('This is Height',r.bottom-r.top);
        let selectionHeight = r.bottom - r.top;
        if(selectionHeight => 22.22){
            this.setState({
                display,
                top:top,
                bottom,
                left,
                right
            })
        }else{
            this.setState({
                display,
                top,
                bottom,
                left,
                right
            })
        }

    }else{
        this.setState({
            display:'none'
        })
    }

        console.log('Slected')
    }
    onMounseUp(e){
        e.preventDefault()
        let sel = window.getSelection && window.getSelection();
        if(!sel.isCollapsed){
            console.log('Moved Up')

        }
    }
    onMouseDwn(e){

        let sel = window.getSelection && window.getSelection();
        if(!sel.isCollapsed){
            console.log('Moved Down')
        }
    }
    getSelectionHtml() {
        let html = "";
        if (typeof window.getSelection != "undefined") {
            let sel = window.getSelection();
            if (sel.rangeCount) {
                let container = document.createElement("div");
                for (let i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().htmlText;
            }
        }

        console.log('html',html)
        return html;

    }
    lastCharRTL(txt) {
        return /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]$/.test(txt);
    }

    triggerAlltime(e){
        // console.log('Some Thinms')
        if(!window.getSelection().isCollapsed){
            //find the Direction Of Slelection
            let sel = window.getSelection();
            console.log(sel)
            let range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            let backwards = range.collapsed;
            range.detach();
            // get selection rects
            let rects = sel.getRangeAt(0).getClientRects();
            let n = rects.length - 1;
            let display = 'block';
            console.log(this.lastCharRTL(this.getSelectionHtml()))
            if (this.lastCharRTL(this.getSelectionHtml()))
                this.setState({
                   display:'none',
                    diplayForDown:'none',
                   top: rects[n].top + 10,
                   left: rects[n].left - 10
               })
            else if (backwards)
                this.setState({
                    display,
                    diplayForDown:'none',
                    top: rects[0].top + -68,
                    left: rects[0].left

                })
            else
                this.setState({
                    display:'none',
                    diplayForDown:'block',
                    top: rects[n].top + 40,
                    left: rects[n].right+-160

                })

        }else{
            this.setState({

                display:'none',
                diplayForDown:'none',

            })
        }
    }

    render(){
        return(
            <div  className="container">
                <div className="CenterCon">
                    <div contentEditable="true"  onMouseUp={this.triggerAlltime} onMouseDown={this.triggerAlltime} onKeyUp={this.triggerAlltime} onKeyDown={this.triggerAlltime} className="Edithis" >
                    <p>Test</p>
                    </div>
                </div>

                <div style={{top: this.state.top, bottom: this.state.bottom, left:this.state.left, right:this.state.right, display: this.state.display}} className="Toggle">
                    <ul>
                        <li>B</li>
                        <li>U</li>
                        <li>H</li>
                        <li>"</li>
                    </ul>
                    <div className="triangle">

                    </div>
                </div>

               {/*DownWard Toggle*/}

                <div style={{top: this.state.top, bottom: this.state.bottom, left: this.state.left, right: this.state.right, display: this.state.diplayForDown}} className="ToggleForDownWardSelection">
                    <div className="triangle-bottom" />
                    <ul>
                        <li>B</li>
                        <li>U</li>
                        <li>H</li>
                        <li>li</li>
                    </ul>
                </div>

            </div>

        )
    }
}

render(<App/>,document.getElementById('app'));
</code>```

答:
const isBackwards = () => {
  const selection = window.getSelection();
  let range = document.createRange();
  range.setStart(selection.anchorNode, selection.anchorOffset);
  range.setEnd(selection.focusNode, selection.focusOffset);

  let backwards = range.collapsed;
  range.detach();
  return backwards;
}
```

Body:
I am new to javascript.I am trying to make an simple toggle up div With user selection direction ill place the toggle div.After some googling I found one working fiddle But not as expected See the below screenshot to see the difference

When I select Some text on the front of the paragraph It works fine Like this

But when I selected some text from bottom paragraph It is not Working as expected

JsFiddle

Actually I am working in React version Fiddle is in Jquery

This is my code

    import React from 'react'
import {render} from 'react-dom';

export default class App extends  React.Component{
    constructor(props){
        super(props);
        this.state = {
            display:'none'  ,
            top:'',
            bottom:'',
            left:'',
            right:'',
            diplayForDown:'none'

        };
        this.handleOnMouseDown = this.handleOnMouseDown.bind(this)
        this.onMounseUp = this.onMounseUp.bind(this)
        this.onMouseDwn = this.onMouseDwn.bind(this)
        this.triggerAlltime = this.triggerAlltime.bind(this)
    }

    handleOnMouseDown(){
        let sel = window.getSelection && window.getSelection();

        let r = sel.getRangeAt(0).getBoundingClientRect();
        let relative=document.body.parentNode.getBoundingClientRect();
        console.log('Relative ',relative);

    if(!sel.isCollapsed){

        console.log(sel,r);
        let display = 'block';

        let top = (r.bottom - relative.top - 80)+'px';
        let bottom = r.bottom+'px';
        let left =( r.left)+'px';
        let right = (r.right)+'px';
        console.log('This is Height',r.bottom-r.top);
        let selectionHeight = r.bottom - r.top;
        if(selectionHeight => 22.22){
            this.setState({
                display,
                top:top,
                bottom,
                left,
                right
            })
        }else{
            this.setState({
                display,
                top,
                bottom,
                left,
                right
            })
        }

    }else{
        this.setState({
            display:'none'
        })
    }

        console.log('Slected')
    }
    onMounseUp(e){
        e.preventDefault()
        let sel = window.getSelection && window.getSelection();
        if(!sel.isCollapsed){
            console.log('Moved Up')

        }
    }
    onMouseDwn(e){

        let sel = window.getSelection && window.getSelection();
        if(!sel.isCollapsed){
            console.log('Moved Down')
        }
    }
    getSelectionHtml() {
        let html = "";
        if (typeof window.getSelection != "undefined") {
            let sel = window.getSelection();
            if (sel.rangeCount) {
                let container = document.createElement("div");
                for (let i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().htmlText;
            }
        }

        console.log('html',html)
        return html;

    }
    lastCharRTL(txt) {
        return /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]$/.test(txt);
    }

    triggerAlltime(e){
        // console.log('Some Thinms')
        if(!window.getSelection().isCollapsed){
            //find the Direction Of Slelection
            let sel = window.getSelection();
            console.log(sel)
            let range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            let backwards = range.collapsed;
            range.detach();
            // get selection rects
            let rects = sel.getRangeAt(0).getClientRects();
            let n = rects.length - 1;
            let display = 'block';
            console.log(this.lastCharRTL(this.getSelectionHtml()))
            if (this.lastCharRTL(this.getSelectionHtml()))
                this.setState({
                   display:'none',
                    diplayForDown:'none',
                   top: rects[n].top + 10,
                   left: rects[n].left - 10
               })
            else if (backwards)
                this.setState({
                    display,
                    diplayForDown:'none',
                    top: rects[0].top + -68,
                    left: rects[0].left

                })
            else
                this.setState({
                    display:'none',
                    diplayForDown:'block',
                    top: rects[n].top + 40,
                    left: rects[n].right+-160

                })

        }else{
            this.setState({

                display:'none',
                diplayForDown:'none',

            })
        }
    }

    render(){
        return(

Test

B

U

H

"

               {/*DownWard Toggle*/}

B

U

H

li

        )
    }
}

render(<App/>,document.getElementById('app'));


问:
Does HTML5 Canvas pixel size depend on the canvas size?
I'm drawing simple lines with the HTML5 canvas:

```<code>context = $('canvas')[0].getContext('2d');
context.moveTo(150, 20);
context.lineTo(300, 20);
context.stroke();
</code>```

When my canvas CSS changes from:

```<code>canvas {
    width: 500px;
    height: 500px;
}
</code>```

to

```<code>canvas {
    width: 1000px;
    height: 1000px;
}
</code>```

the stroke width and height also double! What gives?

答: Answered here: Resize HTML5 canvas to fit window</p>

Body:
I'm drawing simple lines with the HTML5 canvas:

context = $('canvas')[0].getContext('2d');
context.moveTo(150, 20);
context.lineTo(300, 20);
context.stroke();

When my canvas CSS changes from:

canvas {
    width: 500px;
    height: 500px;
}

to

canvas {
    width: 1000px;
    height: 1000px;
}

the stroke width and height also double! What gives?