问:
UWP App: WebView: How to allow window.external.notify from within a app-local web page
For my UWP app, I would like to allow the user to submit a search term from a web page stored in the app's LocalState folder into my UWP app... So I am trying to use WebView.ScriptNotify.

The web page itself is stored in ms-appx-web:///[SomeFolder]/[SomePage.html].
The WebView can open the page. It executes JavaScript.

When I try to call window.external.notify, the JS Engine gives me the error TypeError: Object doesn't support property or method 'notify'.

I have registered ms-appx-web:///[SomeFolder]/* as a Content URI in the app manifest and given it "Allow for web only" access, since the app has access to Known Folders (Documents, Photos etc)...

Where am I going wrong here???

App's Target Build is 17763.

答:
And of course there was a workaround. Never Mind ScriptNotify, the solution is a WindowsRuntimComponent... Here are two descriptions:

https://www.suchan.cz/2016/01/hacking-uwp-webview-part-2-bypassing-window-external-notify-whitelist/

http://blog.damiendelaire.com/2016/06/communicating-back-and-forth-with.html

Worked as described.


来源: stackexchange

问:
Sorting a dictionary by its sub value
I currently have a dictionary in Python3 that looks like this

```<code>{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }
</code>```

Is there a way that I can arrange the nested dictionary that it becomes

```<code>{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}
</code>```

答:
since python 3.6 the dictionaries are insertion ordered so you can use:

```<code> d = {'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }

d = {k : dict(sorted(v.items(), key=lambda x: x[1])) for k, v in d.items()}
d
</code>```

output:

```<code>{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}}
</code>```

you can use OrderedDict if you want insertion order to be  guaranteed across other implementations of Python

ContentLicense: CC BY-SA 4.0

Title: Sorting a dictionary by its sub value

Body:
I currently have a dictionary in Python3 that looks like this

{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }

Is there a way that I can arrange the nested dictionary that it becomes

{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}

Body:
since python 3.6 the dictionaries are insertion ordered so you can use:

 d = {'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }

d = {k : dict(sorted(v.items(), key=lambda x: x[1])) for k, v in d.items()}
d

output:

{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}}

you can use OrderedDict if you want insertion order to be  guaranteed across other implementations of Python


问:
'@media' doesn't affect my Jumbotron header
Hello I've just started web development a few days ago.
I want my web page's header to be responsive so its width, height, font-size be flexible.

```<code><header class="text-white">
<div class="jumbotron bgimg text-white">
  <h1 class="display-4">
    <i class="fa fas fa-star"></i>
    Hello, World!<i class="fa fas fa-star fa-1x"></i></h1>
  <p class="lead">This is my webpage</p>
  <hr class="my-4">
  <p class="lead">Web page details.</p>
  <a class="btn btn-primary" href="./file.zip" download="" role="button">Download!</a>
</div>
</code>```

So I wrote the code like this so that my letter size will be printed small on a small mobile device. My problem is it stays the same and my background image randomly cropped.
Is it because I set display-4 on h1?

```<code>@media (max-width: 400px) {
  #headerh1 {
    width: 100%;
    height: 10%;
    font-size: 2em;
  }
}
</code>```

Thank you, for always.

答:
The selector #headerh1 {...} should be header h1 {...} (no ID but tag, space between header and h1)

If that doesn't select the element, there is another more specific css rule in your code, so you'll have to increase css specifity, for example by writing (note the spaces and "not-spaces"...):

```<code>header.text-white div.jumbotron.bgimg.text-white h1.display-4 { ... }
</code>```

Body:
Hello I've just started web development a few days ago.
I want my web page's header to be responsive so its width, height, font-size be flexible.

    Hello, World!

This is my webpage

Web page details.

  Download!

So I wrote the code like this so that my letter size will be printed small on a small mobile device. My problem is it stays the same and my background image randomly cropped.
Is it because I set display-4 on h1?

@media (max-width: 400px) {
  #headerh1 {
    width: 100%;
    height: 10%;
    font-size: 2em;
  }
}

Thank you, for always.

Body:
The selector #headerh1 {...} should be header h1 {...} (no ID but tag, space between header and h1)

If that doesn't select the element, there is another more specific css rule in your code, so you'll have to increase css specifity, for example by writing (note the spaces and "not-spaces"...):

header.text-white div.jumbotron.bgimg.text-white h1.display-4 { ... }


问:
Yii unique validation on two columns of different tables ie. composite unique validation
I have two tables table1 and table2 each having a column named email along with different other columns. What I want is a validator which looks for uniqueness in email field of both the columns. I found an extension which checks multiple columns of SAME table. How can I extend it so that it works for multiple columns?

答:
In Yii2

Short:

```<code>['common_attr', 'unique'],
['common_attr', 'unique', 'targetClass' => AnotherClass::class],
</code>```

Verbose:

```<code>class One extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => Two::class],
        ];
    }
}

class Two extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => One::class],
        ];
    }
}
</code>```

Also, you can use a multiple unique key with targetAttribute:

```<code>[
    'common_attr',
    'unique',
    'targetClass' => One::class,
    'targetAttribute' => ['common_attr', 'one_more_attr']
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Yii2

Short:

['common_attr', 'unique'],
['common_attr', 'unique', 'targetClass' => AnotherClass::class],

Verbose:

class One extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => Two::class],
        ];
    }
}

class Two extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => One::class],
        ];
    }
}

Also, you can use a multiple unique key with targetAttribute:

[
    'common_attr',
    'unique',
    'targetClass' => One::class,
    'targetAttribute' => ['common_attr', 'one_more_attr']
]


问:
Breakpoint not hitting
I ported an application from VC6 to VS 2008. I rebuilt the application in release build.  The Pdb file is available in the folder where exe is located.  But when I loaded the application and put break point I am getting the following message

"The breakpoint will not currently be hit.No symbols have been loaded for this document"

What would be the cause of the issue?

答:
The debugger could not find code associated with the source location you put the breakpoint at.

There can be a number of reasons for this. The one I've most often found was a section of code that was truly not compiled in. (either because of preprocessor conditionals or dead-code removal).

I imagine there can be other reasons too (e.g. inlining, though in theory, the compiler could generate the proper mapping for all the inlines. I don't know what VS2008 does here).

Are you sure you're putting the breakpoint in a code path that is supposed to be executed ?

Title: Breakpoint not hitting


问:
How to install mono in centOS7 aarch64
How to install mono in centOS 7 aarch64? The official download page only support x86_x64.

Does mono support RHEL 7 arm64?

official download page

Can this package be installed into centOS7 aarch64?

If yes, how to install or build it?

Thank you for your help.

答:
How to install mono in centOS 7 aarch64

mono aarch64 is in the EPEL.repo : 17 mono packages  https://dl.fedoraproject.org/pub/epel/7/aarch64/Packages/m/

EPEL : Extra packages for Enterprise Linux https://fedoraproject.org/wiki/EPEL

Title: How to install mono in centOS7 aarch64


答:
Or maybe try adding an id to the header :)

```<code><header id="headerh1" class="text-white">
</code>```

Title: '@media' doesn't affect my Jumbotron header

Body:
Or maybe try adding an id to the header :)

<header id="headerh1" class="text-white">


问:
Make a VStack fill the width of the screen in SwiftUI
Given this code:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(alignment: .leading) {
      Text("Title")
        .font(.title)

      Text("Content")
        .lineLimit(nil)
        .font(.body)

      Spacer()
    }
    .background(Color.red)
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
#endif
```
<hr />
<p>It results in this interface:</p>
<p><img src="https://i.stack.imgur.com/B87Ym.png" alt="preview" /></p>
<p>How can I make the <code>VStack</code> fill the width of the screen even if the labels/text components don't need the full width?</p>
<hr />
<p>A trick I've found is to insert an <em>empty</em> <code>HStack</code> in the structure like so:</p>
<pre class="lang-swift prettyprint-override"><code>VStack(alignment: .leading) {
  HStack {
    Spacer()
  }
  Text("Title")
    .font(.title)

  Text("Content")
    .lineLimit(nil)
    .font(.body)

  Spacer()
}
</code>```

Which yields the desired design:

Is there a better way?

答:
Login Page design using SwiftUI

```<code>import SwiftUI

struct ContentView: View {

    @State var email: String = "william@gmail.com"
    @State var password: String = ""
    @State static var labelTitle: String = ""

    var body: some View {
        VStack(alignment: .center){
            //Label
            Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
            //TextField
            TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .foregroundColor(.blue)
                .frame(minHeight: 40)
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            TextField("Password", text: $password) //Placeholder
                .textContentType(.newPassword)
                .frame(minHeight: 40)
                .foregroundColor(.blue) // Text color
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            //Button
            Button(action: {

            }) {
                HStack {
                    Image(uiImage: UIImage(named: "Login")!)
                        .renderingMode(.original)
                        .font(.title)
                        .foregroundColor(.blue)
                    Text("Login")
                        .font(.title)
                        .foregroundColor(.white)
                }

                .font(.headline)
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
                .cornerRadius(40)
                .padding(.horizontal, 20)

                .frame(width: 200, height: 50, alignment: .center)
            }
            Spacer()

        }.padding(10)

            .frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
            .background(Color.gray)

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Body:
Given this code:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(alignment: .leading) {
      Text("Title")
        .font(.title)

      Text("Content")
        .lineLimit(nil)
        .font(.body)

      Spacer()
    }
    .background(Color.red)
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
#endif

It results in this interface:

How can I make the VStack fill the width of the screen even if the labels/text components don't need the full width?

A trick I've found is to insert an empty HStack in the structure like so:

VStack(alignment: .leading) {
  HStack {
    Spacer()
  }
  Text("Title")
    .font(.title)

  Text("Content")
    .lineLimit(nil)
    .font(.body)

  Spacer()
}

Which yields the desired design:

Is there a better way?

Body:
Login Page design using SwiftUI

import SwiftUI

struct ContentView: View {

    @State var email: String = "william@gmail.com"
    @State var password: String = ""
    @State static var labelTitle: String = ""

    var body: some View {
        VStack(alignment: .center){
            //Label
            Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
            //TextField
            TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .foregroundColor(.blue)
                .frame(minHeight: 40)
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            TextField("Password", text: $password) //Placeholder
                .textContentType(.newPassword)
                .frame(minHeight: 40)
                .foregroundColor(.blue) // Text color
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            //Button
            Button(action: {

            }) {
                HStack {
                    Image(uiImage: UIImage(named: "Login")!)
                        .renderingMode(.original)
                        .font(.title)
                        .foregroundColor(.blue)
                    Text("Login")
                        .font(.title)
                        .foregroundColor(.white)
                }

                .font(.headline)
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
                .cornerRadius(40)
                .padding(.horizontal, 20)

                .frame(width: 200, height: 50, alignment: .center)
            }
            Spacer()

        }.padding(10)

            .frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
            .background(Color.gray)

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
Jekyll cannot find include files from within a collection
Sorry if this has been answered before, I've tried searching and haven't found anything.

I am using Jekyll 3.8.5 (the version supported by github pages). I have an include file youtube.html which is located inside my jekyll _includes directory. I am trying to reference the file from a file within a collection and it is just erroring - stating that it could not find the file within [collection]/_includes which is clearly wrong and should just be _includes.

Any idea how to fix the path so it can correctly find the include file?

You can see my implementation here: https://github.com/dtsn/jungleskipper/blob/feature/members/_members/jonas-brisbane.md

I did try this in jekyll 4 without a problem.

答:
I think the issue comes from the fact that you set post as a collection in your _config.yml

Remove

```<code>posts:
    title: Posts
    output: true
    layout: post
</code>```

Body:
I think the issue comes from the fact that you set post as a collection in your _config.yml

Remove

posts:
    title: Posts
    output: true
    layout: post


问:
.NET Private Key Rsa Encryption
I need to encrypt a string using an RSA 1.5 algorithm. I have been provided with a private key. However, I cannot for the life of me figure out how to add this key to the class. It seems as tho the key needs to be of type RSAParameter stuct. However this requires a set of values I have not been given such as Modulus, Exponent, P, Q, etc.. All I have is the private key. Can anyone help?</p>

答:
I guess that is what are you looking for:

```<code>    // Import ASymmetric RSA Key from a system file.
    public static RSAParameters ImportRSAKey(String fileName)
    {

        // Create a stream to a the specified system file.
        Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        // Extract/Deserialize the key from the file.
        IFormatter soapFormatter = new SoapFormatter();
        RSAParameters rsaParameter =
           (RSAParameters) soapFormatter.Deserialize(fileStream);

        // Close the file stream.
        fileStream.Close();

        return rsaParameter;

    }
</code>```

To generate a new key, you can use RSACryptoServiceProvider.ExportParameters method.

Refer to the following:

RSAParameters Structure

Title: .NET Private Key Rsa Encryption

Body:
I guess that is what are you looking for:

    // Import ASymmetric RSA Key from a system file.
    public static RSAParameters ImportRSAKey(String fileName)
    {

        // Create a stream to a the specified system file.
        Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        // Extract/Deserialize the key from the file.
        IFormatter soapFormatter = new SoapFormatter();
        RSAParameters rsaParameter =
           (RSAParameters) soapFormatter.Deserialize(fileStream);

        // Close the file stream.
        fileStream.Close();

        return rsaParameter;

    }

To generate a new key, you can use RSACryptoServiceProvider.ExportParameters method.

Refer to the following:

RSAParameters Structure


问:
postgres error that sequence doesn't exist but nextval returns value for sequence
I am trying to alter a table and need to drop primary key column and then recreate it. This is slightly more complicated because I need to insert a column that is 4th from last, the last 3 columns need to stay last.

I ma executing the following script:

```<code>DO$$
BEGIN

ALTER TABLE logging.audit_study
    DROP CONSTRAINT audit_study_pkey,
    DROP COLUMN indication,
    ADD COLUMN indication INT,
    ADD COLUMN audit_study_id_tmp INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    ADD COLUMN aud_action_tmp VARCHAR,
    ADD COLUMN transaction_id_tmp BIGINT DEFAULT (TXID_CURRENT());

UPDATE logging.audit_study SET audit_study_id_tmp = audit_study_id;
UPDATE logging.audit_study SET aud_action_tmp = aud_action;
UPDATE logging.audit_study SET transaction_id_tmp = transaction_id;

ALTER TABLE logging.audit_study
    DROP COLUMN audit_study_id,
    DROP COLUMN aud_action,
    DROP COLUMN transaction_id;

ALTER TABLE logging.audit_study RENAME audit_study_id_tmp TO audit_study_id;
ALTER TABLE logging.audit_study RENAME aud_action_tmp TO aud_action;
ALTER TABLE logging.audit_study RENAME transaction_id_tmp TO transaction_id;

PERFORM SETVAL('logging.audit_study_audit_study_id_tmp_seq', (SELECT MAX(audit_study_id)+1 FROM logging.audit_study), true);

END $$
</code>```

I get the following error:

```<code>[42P01] ERROR: relation "logging.audit_study_audit_study_id_tmp_seq" does not exist Where: PL/pgSQL function inline_code_block line 26 at PERFORM
</code>```

However, if i execute

```<code>SELECT nextval('logging.audit_study_audit_study_id_tmp_seq')
</code>```

I get an integer back for the next sequence. The sequence is also listed in the table properties.

I can't seem to understand why during this script, the sequence seems to disappear.

答: Dropping a primary key column declared as SERIAL data type (that creates automatically the related sequence) also drops the related sequence.</p>

Body:
I am trying to alter a table and need to drop primary key column and then recreate it. This is slightly more complicated because I need to insert a column that is 4th from last, the last 3 columns need to stay last.

I ma executing the following script:

DO$$
BEGIN

ALTER TABLE logging.audit_study
    DROP CONSTRAINT audit_study_pkey,
    DROP COLUMN indication,
    ADD COLUMN indication INT,
    ADD COLUMN audit_study_id_tmp INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    ADD COLUMN aud_action_tmp VARCHAR,
    ADD COLUMN transaction_id_tmp BIGINT DEFAULT (TXID_CURRENT());

UPDATE logging.audit_study SET audit_study_id_tmp = audit_study_id;
UPDATE logging.audit_study SET aud_action_tmp = aud_action;
UPDATE logging.audit_study SET transaction_id_tmp = transaction_id;

ALTER TABLE logging.audit_study
    DROP COLUMN audit_study_id,
    DROP COLUMN aud_action,
    DROP COLUMN transaction_id;

ALTER TABLE logging.audit_study RENAME audit_study_id_tmp TO audit_study_id;
ALTER TABLE logging.audit_study RENAME aud_action_tmp TO aud_action;
ALTER TABLE logging.audit_study RENAME transaction_id_tmp TO transaction_id;

PERFORM SETVAL('logging.audit_study_audit_study_id_tmp_seq', (SELECT MAX(audit_study_id)+1 FROM logging.audit_study), true);

END $$

I get the following error:

[42P01] ERROR: relation "logging.audit_study_audit_study_id_tmp_seq" does not exist Where: PL/pgSQL function inline_code_block line 26 at PERFORM

However, if i execute

SELECT nextval('logging.audit_study_audit_study_id_tmp_seq')

I get an integer back for the next sequence. The sequence is also listed in the table properties.

I can't seem to understand why during this script, the sequence seems to disappear.


答:
Using merge and renaming your t vector as tt (see the PS of Andrie) :

```<code>merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]
</code>```

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

```<code>z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)
</code>```

Title: Merge or combine by rownames

Body:
In the example below I have two datasets (Z and A). I want to merge or combine these sets by the ILMN numbers. If there is no match, fill in NA.

z <- matrix(c(0,0,1,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,"RND1","WDR", "PLAC8","TYBSA","GRA","TAF"), nrow=6,
    dimnames=list(c("ILMN_1651838","ILMN_1652371","ILMN_1652464","ILMN_1652952","ILMN_1653026","ILMN_1653103"),c("A","B","C","D","symbol")))

t<-matrix(c("GO:0002009", 8, 342, 1, 0.07, 0.679, 0, 0, 1, 0,
        "GO:0030334", 6, 343, 1, 0.07, 0.065, 0, 0, 1, 0,
        "GO:0015674", 7, 350, 1, 0.07, 0.065, 1, 0, 0, 0), nrow=10, dimnames= list(c("GO.ID","LEVEL","Annotated","Significant","Expected","resultFisher","ILMN_1652464","ILMN_1651838","ILMN_1711311","ILMN_1653026")))

The result will be like this:

             [,1]         [,2]         [,3]         [,4]
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674"  NA
LEVEL        "8"          "6"          "7"           NA
Annotated    "342"        "343"        "350"         NA
Significant  "1"          "1"          "1"           NA
Expected     "0.07"       "0.07"       "0.07"        NA
resultFisher "0.679"      "0.065"      "0.065"       NA
ILMN_1652464 "0"          "0"          "1"           PLAC8
ILMN_1651838 "0"          "0"          "0"           RND1
ILMN_1711311 "1"          "1"          "0"           NA
ILMN_1653026 "0"          "0"          "0"           GRA

Body:
Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)


问:
Error when POSTing to react app after SAML auth
Completely stumped on an issue I'm dealing with, and I feel like I've looked everywhere, just can't wrap my head around it.

I've got an app that's built as follows:

React frontend, built using Create React App

A separate API, running on a separate server, which the frontend interacts with via RESTful calls

Auth0 handling auth, using a SAML connection. Authentication is successful against the SAML connection.

App is hosted on Heroku, and uses the @mars/create-react-app buildback.

The issue I'm experiencing is that after the SAML authentication, there is a redirect back to my app as a POST. My app doesn't know what to do with said POST, and I'm unsure why.

The ideal scenario I'm looking for is:

User visits domain.com/login

User is redirected to SAML IdP, which asks for login

User logs in with IdP, and is sent back to my app, preferably just to the path /explorer. This should all be straight GET.

I'm happy to post any code related, but unsure what would be the most helpful. Despite me having set the SAML protocol binding to "redirect" on Auth0, it continues to post back to my app. I might simply be misunderstanding that piece, however.

Again, happy to post whatever code would help, just unsure what's most useful to see. Like I said, it seems that auth is working, just that after the authentication, there's a POST back to my root, and my app has zero clue what to do with it. There is no nginx config to speak of.

Thanks for any tips or hints about where to look.

答: Quick followup. Solved this (I think) by spinning up a simple Express server to serve the React app with, and routed POST / to index.html, which seems to have worked for now.


问:
Hyperlink Screen Tip
I'm using the code below to create a list of filenames from a given folder.

```<code>Public Sub ListFilesInFolder(SourceFolder As Scripting.folder, IncludeSubfolders As Boolean)

    Dim fName As String
    Dim Lastrow As Long

    On Error Resume Next

    For Each FileItem In SourceFolder.Files
' display file properties
        Cells(iRow, 3).Formula = FileItem.Name
        Cells(iRow, 4).Formula = FileItem.Path
        iRow = iRow + 1 ' next row number

    Next FileItem

    Range("C17").CurrentRegion.Select
    Selection.Sort Key1:=Range("C17"), Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

    With ActiveSheet
        Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
        Lastrow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End With

        If IncludeSubfolders Then
            For Each SubFolder In SourceFolder.SubFolders
                ListFilesInFolder SubFolder, True
                Next SubFolder
            End If
            Set FileItem = Nothing
            Set SourceFolder = Nothing
            Set FSO = Nothing

    For iRow = 17 To Lastrow
        Cells(iRow, 2).Formula = iRow - 16
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(iRow, 2), Address:="", _
                                   TextToDisplay:=CStr(iRow - 16)
    Next

End Sub
</code>```

Column B contains a unique incremental ID formatted as a hyperlink.

Column C Contains the file names, and

Column D contains the file path

When I hover over the hyperlink the 'Screen tip' which appears is the file path, but I'd like to change this so that the 'Screen tip' is the incremental unique ID.

I've read numerous posts about this and tried to change both the 'Text to display' and the 'Screen tip' text but I've been unsuccessful.

I just wondered whether someone may be able to look at this please and offer some guidance on how I may be able to change this.

答:
You can add the ScreenTip at the end of the Code String after TextToDisplay, example below:

```<code>ActiveSheet.Hyperlinks.Add Anchor:=Cells(1, 1), Address:="", TextToDisplay:=Cstr("texthaschanged"), ScreenTip:="Table Of Contents"
</code>```

Title: Hyperlink Screen Tip

Body:
I'm using the code below to create a list of filenames from a given folder.

Public Sub ListFilesInFolder(SourceFolder As Scripting.folder, IncludeSubfolders As Boolean)

    Dim fName As String
    Dim Lastrow As Long

    On Error Resume Next

    For Each FileItem In SourceFolder.Files
' display file properties
        Cells(iRow, 3).Formula = FileItem.Name
        Cells(iRow, 4).Formula = FileItem.Path
        iRow = iRow + 1 ' next row number

    Next FileItem

    Range("C17").CurrentRegion.Select
    Selection.Sort Key1:=Range("C17"), Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal

    With ActiveSheet
        Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
        Lastrow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End With

        If IncludeSubfolders Then
            For Each SubFolder In SourceFolder.SubFolders
                ListFilesInFolder SubFolder, True
                Next SubFolder
            End If
            Set FileItem = Nothing
            Set SourceFolder = Nothing
            Set FSO = Nothing

    For iRow = 17 To Lastrow
        Cells(iRow, 2).Formula = iRow - 16
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(iRow, 2), Address:="", _
                                   TextToDisplay:=CStr(iRow - 16)
    Next

End Sub

Column B contains a unique incremental ID formatted as a hyperlink.

Column C Contains the file names, and

Column D contains the file path

When I hover over the hyperlink the 'Screen tip' which appears is the file path, but I'd like to change this so that the 'Screen tip' is the incremental unique ID.

I've read numerous posts about this and tried to change both the 'Text to display' and the 'Screen tip' text but I've been unsuccessful.

I just wondered whether someone may be able to look at this please and offer some guidance on how I may be able to change this.

Body:
You can add the ScreenTip at the end of the Code String after TextToDisplay, example below:

ActiveSheet.Hyperlinks.Add Anchor:=Cells(1, 1), Address:="", TextToDisplay:=Cstr("texthaschanged"), ScreenTip:="Table Of Contents"


问:
Ignoring specific characters with Elasticsearch asciifolding
In my analyzer, I have added the asciifolding filter. In most cases this works very well, but when working with the danish language, I would like to not normalize the øæå characters, since "rød" and "rod" are very different words.

We are using the hosted elastic cloud cluster, so if possible a solution that does not require any non-standard deployments through the cloud platform.

Is there any way to do asciifolding, but whitelist certain characters?

Currently running on ES version 6.8

答:
You should probably be using the ICU Folding Token Filter.

From the documentation:

Case folding of Unicode characters based on UTR#30, like the
  ASCII-folding token filter on steroids.

It let's you do everything that the AsciiFolding filter does, but in addition to this, it also allows you to ignore a range of characters through the unicodeSetFilter property.

In this case, you want to ignore æ,ø,å,Æ,Ø,Å:

```<code>"unicodeSetFilter": "[^æøåÆØÅ]"
</code>```

Complete example:

```<code>PUT icu_sample
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "danish_analyzer": {
            "tokenizer": "icu_tokenizer",
            "filter": [
              "danish_folding",
              "lowercase"
            ]
          }
        },
        "filter": {
          "danish_folding": {
            "type": "icu_folding",
            "unicodeSetFilter": "[^æøåÆØÅ]"
          }
        }
      }
    }
  }
}
</code>```

Body:
You should probably be using the ICU Folding Token Filter.

From the documentation:

Case folding of Unicode characters based on UTR#30, like the
  ASCII-folding token filter on steroids.

It let's you do everything that the AsciiFolding filter does, but in addition to this, it also allows you to ignore a range of characters through the unicodeSetFilter property.

In this case, you want to ignore æ,ø,å,Æ,Ø,Å:

"unicodeSetFilter": "[^æøåÆØÅ]"

Complete example:

PUT icu_sample
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "danish_analyzer": {
            "tokenizer": "icu_tokenizer",
            "filter": [
              "danish_folding",
              "lowercase"
            ]
          }
        },
        "filter": {
          "danish_folding": {
            "type": "icu_folding",
            "unicodeSetFilter": "[^æøåÆØÅ]"
          }
        }
      }
    }
  }
}


问:
Cannot open database in unit test but db created
In unit test I would like to test db CRUD functions in real db environment.

The db is created, but when I call savechanges() I got the exception:

Microsoft.Data.SqlClient.SqlException: 'Cannot open database "..." requested by the login. The login failed. Login failed for user '....'.

Why? The context is the same.

```<code>services.AddDbContext<Context>(options =>
                  options.UseSqlServer(string.Format(Configuration["ConnectionString"],
                     Configuration["DbServer"],
                     Configuration["DbName"] + "_" + Guid.NewGuid().ToString(),
                     Configuration["DbUserName"],
                     Configuration["DbPassword"])));

public override void SetupDatabase(IApplicationBuilder app)
{
  using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
  {
     serviceScope.ServiceProvider.GetService<Context>().Database.Migrate();
  }
}
</code>```

答:
I had the same problem and solved it by moving Guid.NewGuid().ToString() out of the AddDbContext scope.

It seems AddDbContext is called multiple times and having it inside of AddDbContext causes the connection string to change each time.

Body:
In unit test I would like to test db CRUD functions in real db environment.

The db is created, but when I call savechanges() I got the exception:

Microsoft.Data.SqlClient.SqlException: 'Cannot open database "..." requested by the login. The login failed. Login failed for user '....'.

Why? The context is the same.

services.AddDbContext<Context>(options =>
                  options.UseSqlServer(string.Format(Configuration["ConnectionString"],
                     Configuration["DbServer"],
                     Configuration["DbName"] + "_" + Guid.NewGuid().ToString(),
                     Configuration["DbUserName"],
                     Configuration["DbPassword"])));

public override void SetupDatabase(IApplicationBuilder app)
{
  using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
  {
     serviceScope.ServiceProvider.GetService<Context>().Database.Migrate();
  }
}


问:
os.FileInfo mock not matching
in one of my golang Projects i went to mock the os.FileInfo for testcases.

I am not sure if I understand the interface handling of golang correctly.
As far as I know the following piece of code should work, but I get an Compilererror saying that the interface does not match.

I modified this go-doc example a bit in case you want to test it out yourself.

```<code>package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

type file interface{
    Name() string
}

func readFiles() []file{
    files, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    return files
}

func main() {
    files := readFiles()

    for _, file := range files {
        fmt.Println(file.Name())
    }
}
</code>```

Following at the golang doc, the ioutil.ReadDir(".") should Return a slice of os.FileInfo which should be a specialisation of my selfwritten file interface.

Can anyone help me out of this hell of misconceptions and entanglements, please?

Thank you very much guys!

答:
To elaborate on the other answer and comments, os.FileInfo does fulfill the file interface you've defined, but a slice of os.FileInfo does not implicitly convert to a slice of your file interface. A simple fix would be to have your readFiles do the conversion explicitly, e.g.

```<code>func readFiles() []file{
    fileInfos, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    files := make([]file, len(fileInfos))
    for i, fi := range fileInfos {
        files[i] = fi
    }

    return files
}
</code>```

Title: os.FileInfo mock not matching

Body:
in one of my golang Projects i went to mock the os.FileInfo for testcases.

I am not sure if I understand the interface handling of golang correctly.
As far as I know the following piece of code should work, but I get an Compilererror saying that the interface does not match.

I modified this go-doc example a bit in case you want to test it out yourself.

package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

type file interface{
    Name() string
}

func readFiles() []file{
    files, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    return files
}

func main() {
    files := readFiles()

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Following at the golang doc, the ioutil.ReadDir(".") should Return a slice of os.FileInfo which should be a specialisation of my selfwritten file interface.

Can anyone help me out of this hell of misconceptions and entanglements, please?

Thank you very much guys!

Body:
To elaborate on the other answer and comments, os.FileInfo does fulfill the file interface you've defined, but a slice of os.FileInfo does not implicitly convert to a slice of your file interface. A simple fix would be to have your readFiles do the conversion explicitly, e.g.

func readFiles() []file{
    fileInfos, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    files := make([]file, len(fileInfos))
    for i, fi := range fileInfos {
        files[i] = fi
    }

    return files
}


问:
read specific single element value from xml using vb
I am trying to read specific element value from below xml:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document Version="7.700000" VersionSeemage="7.7.0.101">
<Server Type="CLitServerModifiable">
    <CLitInfo>
        <Neutral>
            <GroupInfoPropSet>
                <GroupInfo.List/>
                <GroupInfo.Guid Value="a126be064a25ce3f"/>
            </GroupInfoPropSet>
        </Neutral>
    </CLitInfo>
</Server>
</Document>
</code>```

I need only this string a126be064a25ce3f. As I am very new to this. I tried below code:

```<code>Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
Dim str As String = doc.SelectSingleNode("DocumentSmg/Server[Type='CLitServerModifiable']/CLitBOMInfo/Neutral/GroupInfoPropSet/GroupInfo.List/GroupInfo.Guid").InnerText
 MsgBox(str)
</code>```

It returns nothing

答:
Using XElement

```<code>    Dim xe As XElement
    xe = XElement.Load("test.xml")
    Dim thisGUID As String = xe...<GroupInfo.Guid>.@Value
</code>```

for testing you can use literals

```<code>    Dim xe As XElement
    '  for testing use a literal
    xe = <Document Version="7.700000" VersionSeemage="7.7.0.101">
             <Server Type="CLitServerModifiable">
                 <CLitInfo>
                     <Neutral>
                         <GroupInfoPropSet>
                             <GroupInfo.List/>
                             <GroupInfo.Guid Value="a126be064a25ce3f"/>
                         </GroupInfoPropSet>
                     </Neutral>
                 </CLitInfo>
             </Server>
         </Document>

    Dim thisGUID As String = xe...<GroupInfo.Guid>.@Value
</code>```

Body:
I am trying to read specific element value from below xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document Version="7.700000" VersionSeemage="7.7.0.101">
<Server Type="CLitServerModifiable">
    <CLitInfo>
        <Neutral>
            <GroupInfoPropSet>
                <GroupInfo.List/>
                <GroupInfo.Guid Value="a126be064a25ce3f"/>
            </GroupInfoPropSet>
        </Neutral>
    </CLitInfo>
</Server>
</Document>

I need only this string a126be064a25ce3f. As I am very new to this. I tried below code:

Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
Dim str As String = doc.SelectSingleNode("DocumentSmg/Server[Type='CLitServerModifiable']/CLitBOMInfo/Neutral/GroupInfoPropSet/GroupInfo.List/GroupInfo.Guid").InnerText
 MsgBox(str)

It returns nothing

Body:
Using XElement

    Dim xe As XElement
    xe = XElement.Load("test.xml")
    Dim thisGUID As String = xe...<GroupInfo.Guid>.@Value

for testing you can use literals

    Dim xe As XElement
    '  for testing use a literal
    xe = <Document Version="7.700000" VersionSeemage="7.7.0.101">
             <Server Type="CLitServerModifiable">
                 <CLitInfo>
                     <Neutral>
                         <GroupInfoPropSet>
                             <GroupInfo.List/>
                             <GroupInfo.Guid Value="a126be064a25ce3f"/>
                         </GroupInfoPropSet>
                     </Neutral>
                 </CLitInfo>
             </Server>
         </Document>

    Dim thisGUID As String = xe...<GroupInfo.Guid>.@Value


问:
Algorithm to generate all possible populations for a 5-Likert Scale in R (cumulative frequency per level by 0.1)
I would like to generate all possible populations in a 5-likert scale which values are the cumulative frequency by 0.1 in each level), e.g.:

```<code>[1] [2]  [3]  [4]  [5]
1    0    0    0    0
0    1    0    0    0
         ...
0    0    0    0    1
0.9  0.1  0    0    0
0.9  0   0.1   0    0
         ...
0.8 0.2   0    0    0
0.8  0    0.2  0    0
         ...
0.8 0.1  0.1   0    0
</code>```

and so on...

I have tried with some rudimentary loops like:

```<code>fin <- NULL
for (i in 1:10) {
  a <- c(1-(i/10),0,0,0,0)
  fin <- c(fin,a)
  for (j in 1:10) {
    b <- c(a[1],(j/10),0,0,0)
    fin <- c(fin,b)
    for (k in 1:10) {
      c <- c(a[1],b[2],k/10,0,0)
      fin <- c(fin,c)
      for (l in 1:10) {
        d <- c(a[1],b[2],c[3],l/10,0)
        fin <- c(fin,d)
        for (m in 1:10) {
          e <- c(a[1],b[2],c[3],d[4],m/10)
          fin <- c(fin,e)
        }
      }
    }
  }
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))
head(dat)

a <- NULL
for (i in 1:111110) {
  if(rowSums(dat[i,])==1)
  {b <- dat[i,]
  a <- c(a,b)}
  else{
    next
    }
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))
</code>```

I know it is not smart neither efficient but rows where sum = 1 are some of the cases I want to have, but it is insufficient.

I really appreciate any help. Thanks in advance.

答:
Create vector containing all allowed values

```<code>values <- seq(0, 1, by=0.1)
values
</code>```

Returns:

```<code>[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
</code>```

Using base R expand.grid to get all possible combinations of these values for five variables:

```<code>df <- expand.grid(A1 = values, A2 = values, A3 = values, A4 = values, A5 = values)
</code>```

Calculate row wise sum using rowSums:

```<code>df$TestSum <- rowSums(df)
</code>```

Keep only rows where the TestSum is 1 (and also only keep the first 5 columns, we don't need the TestSum column anymore):

```<code>result <- df[df$TestSum == 1, 1:5]

head(result)
</code>```

Returns:

```<code>    A1  A2 A3 A4 A5
11 1.0 0.0  0  0  0
21 0.9 0.1  0  0  0
31 0.8 0.2  0  0  0
41 0.7 0.3  0  0  0
51 0.6 0.4  0  0  0
61 0.5 0.5  0  0  0
</code>```

Body:
I would like to generate all possible populations in a 5-likert scale which values are the cumulative frequency by 0.1 in each level), e.g.:

[1] [2]  [3]  [4]  [5]
1    0    0    0    0
0    1    0    0    0
         ...
0    0    0    0    1
0.9  0.1  0    0    0
0.9  0   0.1   0    0
         ...
0.8 0.2   0    0    0
0.8  0    0.2  0    0
         ...
0.8 0.1  0.1   0    0

and so on...

I have tried with some rudimentary loops like:

fin <- NULL
for (i in 1:10) {
  a <- c(1-(i/10),0,0,0,0)
  fin <- c(fin,a)
  for (j in 1:10) {
    b <- c(a[1],(j/10),0,0,0)
    fin <- c(fin,b)
    for (k in 1:10) {
      c <- c(a[1],b[2],k/10,0,0)
      fin <- c(fin,c)
      for (l in 1:10) {
        d <- c(a[1],b[2],c[3],l/10,0)
        fin <- c(fin,d)
        for (m in 1:10) {
          e <- c(a[1],b[2],c[3],d[4],m/10)
          fin <- c(fin,e)
        }
      }
    }
  }
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))
head(dat)

a <- NULL
for (i in 1:111110) {
  if(rowSums(dat[i,])==1)
  {b <- dat[i,]
  a <- c(a,b)}
  else{
    next
    }
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))

I know it is not smart neither efficient but rows where sum = 1 are some of the cases I want to have, but it is insufficient.

I really appreciate any help. Thanks in advance.

Body:
Create vector containing all allowed values

values <- seq(0, 1, by=0.1)
values

Returns:

[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

Using base R expand.grid to get all possible combinations of these values for five variables:

df <- expand.grid(A1 = values, A2 = values, A3 = values, A4 = values, A5 = values)

Calculate row wise sum using rowSums:

df$TestSum <- rowSums(df)

Keep only rows where the TestSum is 1 (and also only keep the first 5 columns, we don't need the TestSum column anymore):

result <- df[df$TestSum == 1, 1:5]

head(result)

Returns:

    A1  A2 A3 A4 A5
11 1.0 0.0  0  0  0
21 0.9 0.1  0  0  0
31 0.8 0.2  0  0  0
41 0.7 0.3  0  0  0
51 0.6 0.4  0  0  0
61 0.5 0.5  0  0  0


问:
Update multiple keys with values of a dictionary after a loop has run and updated values that are used to update the dictionary
I am trying to update a dictionary that is initialized at the start of the method/function and later the corresponding values of the keys should be updated with the counter variables in the function. But, for some reasons my dictionary is not getting updated. Please advise.

Code:

```<code>def quizresult(quiz_df):
maxmarks=10.0
noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
quiz_result={'noofpresent':None,'lessthan50':None,'between50and60':None,'between60and70':None,'between70and80':None,'greaterthan80':None}
for i in range(len(quiz_df)):

    noofpresent=len(quiz_df.index)
    if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
        lessthanfifty += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
        betweenfiftyandsixty += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
        betweensixtyandseventy += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
        betweenseventyandeighty += 1
    if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
        greaterthaneighty += 1
quiz_result.update({'noofpresent':noofpresent,'lessthan50':lessthanfifty,'between50and60':betweenfiftyandsixty,'between60and70':betweensixtyandseventy,'between70and80':betweenseventyandeighty,'greaterthan80':greaterthaneighty})

return quiz_result
</code>```

P.S: Indentation is not an issue here. I get following message:

"SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  after removing the cwd from sys.path."

答:
You can manually do the following to update the values of the dict with the counter variables.
For example,

```<code>quiz_result['noofpresent'] = noofpresent #You can do the following for all other keys.
</code>```

Edit:

Can you try the following code and tell me what happens. Please preserve the indentaion. As well as that also make sure that the len(quiz_df) > 0.

```<code>def quizresult(quiz_df):
    maxmarks=10.0
    noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
    quiz_result={'noofpresent':0,'lessthan50':0,'between50and60':0,'between60and70':0,'between70and80':0,'greaterthan80':0}
    for i in range(len(quiz_df)):

        noofpresent=len(quiz_df.index)
        if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
            lessthanfifty += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
            betweenfiftyandsixty += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
            betweensixtyandseventy += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
            betweenseventyandeighty += 1
        if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
            greaterthaneighty += 1
    quiz_result.update(noofpresent =noofpresent ,lessthan50=lessthanfifty ,between50and60=betweenfiftyandsixty,between60and70=betweensixtyandseventy, between70and80=betweenseventyandeighty,greaterthan80= greaterthaneighty)

return quiz_result
</code>```

I am certain that your error is to do with a loop not running or the condtiional statements inside the loop fails and hence doesnt increment the values

Body:
I am trying to update a dictionary that is initialized at the start of the method/function and later the corresponding values of the keys should be updated with the counter variables in the function. But, for some reasons my dictionary is not getting updated. Please advise.

Code:

def quizresult(quiz_df):
maxmarks=10.0
noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
quiz_result={'noofpresent':None,'lessthan50':None,'between50and60':None,'between60and70':None,'between70and80':None,'greaterthan80':None}
for i in range(len(quiz_df)):

    noofpresent=len(quiz_df.index)
    if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
        lessthanfifty += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
        betweenfiftyandsixty += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
        betweensixtyandseventy += 1
    if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
        betweenseventyandeighty += 1
    if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
        greaterthaneighty += 1
quiz_result.update({'noofpresent':noofpresent,'lessthan50':lessthanfifty,'between50and60':betweenfiftyandsixty,'between60and70':betweensixtyandseventy,'between70and80':betweenseventyandeighty,'greaterthan80':greaterthaneighty})

return quiz_result

P.S: Indentation is not an issue here. I get following message:

"SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  after removing the cwd from sys.path."

Body:
You can manually do the following to update the values of the dict with the counter variables.
For example,

quiz_result['noofpresent'] = noofpresent #You can do the following for all other keys.

Edit:

Can you try the following code and tell me what happens. Please preserve the indentaion. As well as that also make sure that the len(quiz_df) > 0.

def quizresult(quiz_df):
    maxmarks=10.0
    noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
    quiz_result={'noofpresent':0,'lessthan50':0,'between50and60':0,'between60and70':0,'between70and80':0,'greaterthan80':0}
    for i in range(len(quiz_df)):

        noofpresent=len(quiz_df.index)
        if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
            lessthanfifty += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
            betweenfiftyandsixty += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
            betweensixtyandseventy += 1
        if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
            betweenseventyandeighty += 1
        if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
            greaterthaneighty += 1
    quiz_result.update(noofpresent =noofpresent ,lessthan50=lessthanfifty ,between50and60=betweenfiftyandsixty,between60and70=betweensixtyandseventy, between70and80=betweenseventyandeighty,greaterthan80= greaterthaneighty)

return quiz_result

I am certain that your error is to do with a loop not running or the condtiional statements inside the loop fails and hence doesnt increment the values


问:
Is it possible to dynamically convert currency symbol from currency code like 'EUR' or 'GBP'?
I would like to get currencies symbols depending on currency codes supplied. For example if given 'EUR', I would like to get € dynamically and if I have 'USD' I get $ automatically in PHP.

NB: I'm actually working on e107 framework

答:
if you can use third party libraries, maybe this :
https://github.com/symfony/Intl
 Can solve your problem, witht the synthax :

```<code>Intl::getCurrencyBundle()->getCurrencySymbol('USD')
</code>```

For example.

Body:
if you can use third party libraries, maybe this :
https://github.com/symfony/Intl
 Can solve your problem, witht the synthax :

Intl::getCurrencyBundle()->getCurrencySymbol('USD')

For example.


问:
What is the use of where keyword in a generic function's signature?
I refactored this snippet:

```<code>remark.observeOn(mainThread())
      .subscribe { remark ->
          remark_box.visible = remark.isNotEmpty()
          remark_tv.text = remark
      }
      .addTo(CompositeDisposable())
</code>```

using this extension, but I get lost from what is : Disposable where T : Observable<String>
Please somebody could shed some light on that?

```<code>remark.bindTo(remark_tv)
      .addTo(CompositeDisposable())
</code>```

and

```<code>fun <T> T.bindTo(textView: TextView): Disposable where T : Observable<String> {
    return observeOn(mainThread())
        .subscribe { remark ->
            textView.text = remark
        }
}
</code>```

答:
: Disposable Signifies that your function's return type is Disposable.

and where T : Observable<String> part specifies an upper bound on the generic type parameter T. in simple terms it means T must be a subtype of Observable<String>.

When working with generic types, you can specify a single upper bound as

```<code>// This function can only be called with types implementing Collection<Int>
fun <T: Collection<Int>> someFun(first: T, second: T)

// If you try to call it as following, it will not compile
someFun(listOfStrings, listOfStrings)
</code>```

but if you need to specify multiple upper bounds then you have to use the where clause as

```<code>// This function can only be called with types implementing Iterable<Int>
// as well as Serializable
fun <T> someFun(first: T, second: T): Int where  T: Iterable<Int>,T: Serializable

// This does not work, you can not comma separate the upper bounds
fun <T: Iterable<Int>, Serializable> someFun(first: T, second: T): Int
</code>```

As the documentation states

Only one upper bound can be specified inside the angle brackets. If
  the same type parameter needs more than one upper bound, we need a
  separate where-clause.

Body:
I refactored this snippet:

remark.observeOn(mainThread())
      .subscribe { remark ->
          remark_box.visible = remark.isNotEmpty()
          remark_tv.text = remark
      }
      .addTo(CompositeDisposable())

using this extension, but I get lost from what is : Disposable where T : Observable<String>
Please somebody could shed some light on that?

remark.bindTo(remark_tv)
      .addTo(CompositeDisposable())

and

fun <T> T.bindTo(textView: TextView): Disposable where T : Observable<String> {
    return observeOn(mainThread())
        .subscribe { remark ->
            textView.text = remark
        }
}

Body:
: Disposable Signifies that your function's return type is Disposable.

and where T : Observable<String> part specifies an upper bound on the generic type parameter T. in simple terms it means T must be a subtype of Observable<String>.

When working with generic types, you can specify a single upper bound as

// This function can only be called with types implementing Collection<Int>
fun <T: Collection<Int>> someFun(first: T, second: T)

// If you try to call it as following, it will not compile
someFun(listOfStrings, listOfStrings)

but if you need to specify multiple upper bounds then you have to use the where clause as

// This function can only be called with types implementing Iterable<Int>
// as well as Serializable
fun <T> someFun(first: T, second: T): Int where  T: Iterable<Int>,T: Serializable

// This does not work, you can not comma separate the upper bounds
fun <T: Iterable<Int>, Serializable> someFun(first: T, second: T): Int

As the documentation states

Only one upper bound can be specified inside the angle brackets. If
  the same type parameter needs more than one upper bound, we need a
  separate where-clause.


答:
Are you sure your indentation is correct? I ran the following piece of code and got the expected dictionary (0.0 as dict values):</p>

```<code>In [1]: def quizresult(quiz_df):
   ...:     maxmarks=10.0
   ...:     noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
   ...:     quiz_result={'noofpresent':None,'lessthan50':None,'between50and60':None,'between60and70':None,'between70and80':None,'greaterthan80':None}
   ...:     for i in range(len(quiz_df)):
   ...:
   ...:         noofpresent=len(quiz_df.index)
   ...:         if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
   ...:             lessthanfifty += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
   ...:             betweenfiftyandsixty += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
   ...:             betweensixtyandseventy += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
   ...:             betweenseventyandeighty += 1
   ...:         if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
   ...:             greaterthaneighty += 1
   ...:     quiz_result.update({'noofpresent':noofpresent,'lessthan50':lessthanfifty,'between50and60':betweenfiftyandsixty,'between60and70':betweensixtyandseventy,'between70and80':betweenseventyandeighty,'greaterthan80':greaterthaneighty})
   ...:
   ...:     return quiz_result
   ...:

In [2]: quizresult([])
Out[2]:
{'noofpresent': 0.0,
 'lessthan50': 0.0,
 'between50and60': 0.0,
 'between60and70': 0.0,
 'between70and80': 0.0,
 'greaterthan80': 0.0}
</code>```

Title: Update multiple keys with values of a dictionary after a loop has run and updated values that are used to update the dictionary

Body:
Are you sure your indentation is correct? I ran the following piece of code and got the expected dictionary (0.0 as dict values):

In [1]: def quizresult(quiz_df):
   ...:     maxmarks=10.0
   ...:     noofpresent,lessthanfifty,betweenfiftyandsixty,betweensixtyandseventy,betweenseventyandeighty,greaterthaneighty=0.0,0.0,0.0,0.0,0.0,0.0
   ...:     quiz_result={'noofpresent':None,'lessthan50':None,'between50and60':None,'between60and70':None,'between70and80':None,'greaterthan80':None}
   ...:     for i in range(len(quiz_df)):
   ...:
   ...:         noofpresent=len(quiz_df.index)
   ...:         if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.5:
   ...:             lessthanfifty += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.5 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.6):
   ...:             betweenfiftyandsixty += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.6 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.7):
   ...:             betweensixtyandseventy += 1
   ...:         if((float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.7 and (float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)<0.8):
   ...:             betweenseventyandeighty += 1
   ...:         if(float(quiz_df.loc[i,'Grade/10.00'])/maxmarks)>=0.8:
   ...:             greaterthaneighty += 1
   ...:     quiz_result.update({'noofpresent':noofpresent,'lessthan50':lessthanfifty,'between50and60':betweenfiftyandsixty,'between60and70':betweensixtyandseventy,'between70and80':betweenseventyandeighty,'greaterthan80':greaterthaneighty})
   ...:
   ...:     return quiz_result
   ...:

In [2]: quizresult([])
Out[2]:
{'noofpresent': 0.0,
 'lessthan50': 0.0,
 'between50and60': 0.0,
 'between60and70': 0.0,
 'between70and80': 0.0,
 'greaterthan80': 0.0}


问:
Change global variable from event function
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
</code>```

CSS

```<code>.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}
</code>```

Javascript

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};
</code>```

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

答:
The problem with your solution is that the for loop you have written assigns event listeners for setting an 'X' on the board to every single square BEFORE there is even a single click on the board. This means your if logic will never assign an 'O', since all clicks will call chasviX()

You should instead use a forEach() function of an NodeList like your action variable:

```<code> var gameState = false;
 action.forEach(function(act) {
    act.addEventListener("click", function(event) {
        // If gameState is false(logical 0), place an 'X' on the board
        // Otherwise, place a 'O'
        event.target.textContent = gameState ? 'X' : 'O';
        // Invert state at the end
        gameState = !gameState;
    });
})
</code>```

Body:
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

Body:
The problem with your solution is that the for loop you have written assigns event listeners for setting an 'X' on the board to every single square BEFORE there is even a single click on the board. This means your if logic will never assign an 'O', since all clicks will call chasviX()

You should instead use a forEach() function of an NodeList like your action variable:

 var gameState = false;
 action.forEach(function(act) {
    act.addEventListener("click", function(event) {
        // If gameState is false(logical 0), place an 'X' on the board
        // Otherwise, place a 'O'
        event.target.textContent = gameState ? 'X' : 'O';
        // Invert state at the end
        gameState = !gameState;
    });
})


问:
java regex : getting a substring from a string which can vary
I have a String like - "Bangalore,India=Karnataka". From this String I would like to extract only the substring "Bangalore". In this case the regex can be - (.+),.*=.*. But the problem is, the String can sometimes come like only "Bangalore". Then in that case the above regex wont work. What will be the regex to get the substring "Bangalore" whatever the String be ?

答:
Try this regex, This will grab any grouping of characters at the start followed by a comma but not the comma itself.

^.*(?=,)


问:
IntelliJ IDEA Project with Angular and Spring Boot
i've created an IntelliJ 'Empty Project' and added 2 Modules: One for Spring Boot (Backend) and one for Angular CLI (Frontend). So far, so good.
File Structure of my Project

Now i added the project to GitLab and got problems when cloning the project, bc for some reason it sometimes only gets one module.
Also I got Problems with .gitignore file, bc this would need to be outside of a specific module in my root-project. The same for .gitlab-ci.yml.

I can't add anything into my project except for new modules. Or at least it is then only shown in the project structure like here:Hidden folders in my project

What i now would need is some kind of root module/project which has the Spring and ANgular Modules as childs. So that they can start separately. But still can have some project-level files.

Is there any way to achieve this in IntelliJ?

Thank you for your help :)

答: My suggestion would be to just create two separate projects, with different repos in GitLab. And then, you could open them separately in IntelliJ. From the workflow perspective, this approach would be more natural. For example, when you do work on the frontend, you keep your backend running, but do changes only in the frontend and vice-versa.</p>


问:
How can we play sound alarm after command is done on Mac terminal?
When we run a command that takes a while such as source compile or brew upgrade, we usually do other things such as web searching rather than watching the command running the whole time.

Is there any possible way that I can get notified once the command is done?

```<code>brew upgrade | afplay /System/Library/Sounds/Submarine.aiff -v 10
</code>```

I tried with afplay on Mac as above but the problem is a) stdout is not shown due to the pipe, b) it plays the sound right after the command starts to run rather than waiting until "brew upgrade" is finished.

Any suggestions please?

答:
To directly answer the question, this can be done without installing anything extra, and with just the system alert.

To play the system alert sound after you run "command":

```<code>command; printf "\a"
</code>```

Giorgio's answer is also good, as in"

```<code>command; say command is done
</code>```

To like the continuous alarm idea; I would do something like this to repeat the alarm every 10 seconds:

```<code>command; while :; sleep 10; do say command is done; done
</code>```

Or

```<code>command; while :; sleep 2; do printf "\a"; done
</code>```

Body:
When we run a command that takes a while such as source compile or brew upgrade, we usually do other things such as web searching rather than watching the command running the whole time.

Is there any possible way that I can get notified once the command is done?

brew upgrade | afplay /System/Library/Sounds/Submarine.aiff -v 10

I tried with afplay on Mac as above but the problem is a) stdout is not shown due to the pipe, b) it plays the sound right after the command starts to run rather than waiting until "brew upgrade" is finished.

Any suggestions please?

Body:
To directly answer the question, this can be done without installing anything extra, and with just the system alert.

To play the system alert sound after you run "command":

command; printf "\a"

Giorgio's answer is also good, as in"

command; say command is done

To like the continuous alarm idea; I would do something like this to repeat the alarm every 10 seconds:

command; while :; sleep 10; do say command is done; done

Or

command; while :; sleep 2; do printf "\a"; done


问:
Spring Controller - HashMap Return
I have a very basic REST controller...

```<code>@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
    String signKeyToken = signKeyService.generateNewToken();
    Map<String, String> data = new HashMap<>();
    data.put("signKey", signKeyToken);
    return new ResponseEntity<>(data, HttpStatus.OK);
}
</code>```

}

returns

```<code>{
"signKey": "_IjAY736MvwKZLtoJHrhNaD4MUL2r0Al"
}
</code>```

But because I want to return a json object to the frontend, instead of only a string I created an hashmap.
This code works fine but I feel like there should be a better way...

In this case I don't want to create models or anything. This is a simple return of a String. Do I really need to keep creating HashMaps in my controllers which only return some data that is not in any model?

Any help?

答:
You can do it as</p>

```<code>String signKeyToken = signKeyService.generateNewToken();
DataObj data = new DataObj(signKeyToken);
return new ResponseEntity<>(data, HttpStatus.OK);

class DataObj {
    private String signKey;
    //setter,getter,constructor
}
</code>```

Title: Spring Controller - HashMap Return

Body:
I have a very basic REST controller...

@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/signKey", produces = "application/json")
public class SignKeyController {

@Autowired
private SignKeyService signKeyService;

@GetMapping(value = "/generate")
public ResponseEntity<?> generateSignKey() {
    String signKeyToken = signKeyService.generateNewToken();
    Map<String, String> data = new HashMap<>();
    data.put("signKey", signKeyToken);
    return new ResponseEntity<>(data, HttpStatus.OK);
}

}

returns

{
"signKey": "_IjAY736MvwKZLtoJHrhNaD4MUL2r0Al"
}

But because I want to return a json object to the frontend, instead of only a string I created an hashmap.
This code works fine but I feel like there should be a better way...

In this case I don't want to create models or anything. This is a simple return of a String. Do I really need to keep creating HashMaps in my controllers which only return some data that is not in any model?

Any help?

Body:
You can do it as

String signKeyToken = signKeyService.generateNewToken();
DataObj data = new DataObj(signKeyToken);
return new ResponseEntity<>(data, HttpStatus.OK);

class DataObj {
    private String signKey;
    //setter,getter,constructor
}


问:
VSCode not picking up ipykernel
I'm trying to use vscode with jupyter via the python extension.  My pipfile looks like this:

```<code>[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[packages]
opencv-python = "*"

[requires]
python_version = "3.6"

[dev-packages]
ipykernel = "*"
ipython = "*"
jupyter = "*"
</code>```

To start the ipython interpreter i follow these steps:

$ pipenv install

$ pipenv shell

$ code .

using the Python: Select interpreter, i select the pipenv environment

run code

when i got to the code block by pressing shift + enter, i see the errors:

Code block:

```<code>#%%
import cv2
</code>```

I have also tried using all dependencies in the [packages] section, reinstalling my pipenv from scratch, and repeating the above process.

Always the same error, what am i missing?

```<code>$ code -v
1.41.1
26076a4de974ead31f97692a0d32f90d735645c0
x64

</code>```

答:
Turns out that the python I had installed python3.x, but not python3.x-dev.

You can install this using:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update -y && sudo apt upgrade
sudo apt install python3.8 python3.8-dev
```

Upon opening vscode i then hit ctrl + shift + P and selected Python: Select Interpreter and selected the virtual env containing ipykernel.

Title: VSCode not picking up ipykernel

Body:
I'm trying to use vscode with jupyter via the python extension.  My pipfile looks like this:

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[packages]
opencv-python = "*"

[requires]
python_version = "3.6"

[dev-packages]
ipykernel = "*"
ipython = "*"
jupyter = "*"

To start the ipython interpreter i follow these steps:

$ pipenv install

$ pipenv shell

$ code .

using the Python: Select interpreter, i select the pipenv environment

run code

when i got to the code block by pressing shift + enter, i see the errors:

Code block:

#%%
import cv2

I have also tried using all dependencies in the [packages] section, reinstalling my pipenv from scratch, and repeating the above process.

Always the same error, what am i missing?

$ code -v
1.41.1
26076a4de974ead31f97692a0d32f90d735645c0
x64

Body:
Turns out that the python I had installed python3.x, but not python3.x-dev.

You can install this using:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update -y && sudo apt upgrade
sudo apt install python3.8 python3.8-dev

Upon opening vscode i then hit ctrl + shift + P and selected Python: Select Interpreter and selected the virtual env containing ipykernel.


问:
How to define a foreign key in an Django app model which is ignored if a sub-app is not installed
I have a base app which is used by sub-apps.
I have an AbstractUser defined in the base app and I need to add a relation to a sub-app model if the sub-app is installed.
I understand that my new field will be present in the user table in the database, but with a null value if the sub-app is note installed.
My problem is to reference the foreign key I had to a model that does not exists if the sub-apps is not installed.
Does I need to transfer the model from the sub-apps to the base app or is there another solution like a conditionnal foreign key constraint in my AbstractUser model.</p>

答: I think you need a stub sub-app to plug the hole if it's "not installed". All it does is declare the model so that there's a table in the database (but no records). You could later replace it with the real sub-app and populate the table through it.</p>


问:
Still having problems with jQuery background animate - works in safari and IE, nothing else!
I made a thread a few days ago about animating a background image. I was advised to use a certain plugin which worked ok. I was using jQuery 1.4.2 - however, I have since been having real issues with the coda slider on my website. I then decided to change to the newest jQuery (1.6.1) and the issue was resolved. On the other hand my background animations broke in some browsers.

The weird thing is it works in safari on a mac, and ie9, 8, 7 and even 6 with a transparent png fix. It doesn't work for me in firefox on mac or pc and opera on mac.

Has anyone else had any problems like this? I spent some time making this images and would love to get it sorted! There must be some way round this, or maybe the code I have written it just plain wrong!?

I have made a fiddle with the actual images and script. It's the first one I have made so i'm not 100% sure I have done it right, feel free to say if it needs tweaking...

You can find the jsfiddle here

Many Thanks : )

答:
Looks pretty.  Won't work generally.

The issue is that background-position-x and background-position-y are not W3C spec.  I know, I've run into the issue myself a few times.

You can get around this by manually creating a timer and manually rebuilding the background-position with its paired x/y values, but jQuery's animate won't work for you because background-position isn't a numeric value.

The background-position animate plugin didn't work for you?


答:
Use expand.grid to generate all combinations first and then filter (e.g. using dplyr) only those rows, where the sum is one:

```<code>levels <- seq(0,1, 0.1)

expand.grid(L1 = levels,
            L2 = levels,
            L3 = levels,
            L4 = levels,
            L5 = levels) %>%
  dplyr::mutate(sum = L1+L2+L3+L4+L5) %>%
  dplyr::filter(sum == 1) %>%
  dplyr::select(-sum)

</code>```

Title: Algorithm to generate all possible populations for a 5-Likert Scale in R (cumulative frequency per level by 0.1)

Body:
Use expand.grid to generate all combinations first and then filter (e.g. using dplyr) only those rows, where the sum is one:

levels <- seq(0,1, 0.1)

expand.grid(L1 = levels,
            L2 = levels,
            L3 = levels,
            L4 = levels,
            L5 = levels) %>%
  dplyr::mutate(sum = L1+L2+L3+L4+L5) %>%
  dplyr::filter(sum == 1) %>%
  dplyr::select(-sum)


问:
How to deploy a spring boot restful API with Azure pipeline
I have spring boot application that is connected to a mysql database. I have a repo in Azure Repo and a pipeline in Azure Pipeline. On Azure Portal I have made a Azure Mysql database and also a web app. How do I connect the web app and the pipeline? I thought I already connected them as I made the pipeline. I can't seem to be able to use my api as i get 404 back when calling it. All tutorials are focusing on how to deploy without the pipeline but that is not my case. What am I missing?</p>

答:
Beside what you have done above you also need to do below steps

1, First you need to create service connection to connect your azure subscription to your azure devops pipeline. Please check the detailed steps Sign in to Azure Pipelines and connect to Azure.

2, When you have your pipeline. You also need to customize your pipeline to build your java app with maven task or other build tasks. Please check Build Java apps for more information.

3, You also need to use Azure App Service Deploy task(in the release pipeline or build pipeline) to deploy your app to azure web app.

There is a tutorial provided by Microsoft with detailed steps to deploy java app to azure.


问:
Lookup values in pandas dataframe
```<code>Date        Ticker    Volume
2019-03-21    AAPL        10
2019-03-21    GOOG         5
2019-03-21     IBM         0
2019-03-25    AAPL         0
2019-03-25     IBM         0
2019-03-25    GOOG        12
2019-03-27    AAPL         0
2019-03-27     IBM        16
2019-03-27    GOOG        10
2019-03-28     IBM         9
2019-03-28    GOOG         0
2019-03-28    AAPL        10
</code>```

Suppose the data is ordered by date. How to exact the first row from each date. If the 'Volume' is 0, then take the next row until it's not 0.

```<code>Date        Ticker    volume
2019-03-21    AAPL        10
2019-03-25    GOOG        12
2019-03-27     IBM        16
2019-03-28     IBM         9
</code>```

I have tried by using lambda, but it seems not working.

```<code>df_new = df.groupby(['Date']).head(lambda x: 2 if df['Volume'] == 0 else 1).reset_index(0, drop=True)

TypeError: unorderable types: int() < function()
</code>```

If I have enough data and like to exact #2-5 rows (consecutive) from each date. Should I use range function?

答:
Using drop_duplicates

```<code>df1=df.loc[df.Volume!=0].drop_duplicates('Date')
Out[13]:
         Date Ticker  Volume
0  2019-03-21   AAPL      10
5  2019-03-25   GOOG      12
7  2019-03-27    IBM      16
9  2019-03-28    IBM       9
</code>```

Title: Lookup values in pandas dataframe

Body:
Date        Ticker    Volume
2019-03-21    AAPL        10
2019-03-21    GOOG         5
2019-03-21     IBM         0
2019-03-25    AAPL         0
2019-03-25     IBM         0
2019-03-25    GOOG        12
2019-03-27    AAPL         0
2019-03-27     IBM        16
2019-03-27    GOOG        10
2019-03-28     IBM         9
2019-03-28    GOOG         0
2019-03-28    AAPL        10

Suppose the data is ordered by date. How to exact the first row from each date. If the 'Volume' is 0, then take the next row until it's not 0.

Date        Ticker    volume
2019-03-21    AAPL        10
2019-03-25    GOOG        12
2019-03-27     IBM        16
2019-03-28     IBM         9

I have tried by using lambda, but it seems not working.

df_new = df.groupby(['Date']).head(lambda x: 2 if df['Volume'] == 0 else 1).reset_index(0, drop=True)

TypeError: unorderable types: int() < function()

If I have enough data and like to exact #2-5 rows (consecutive) from each date. Should I use range function?

Body:
Using drop_duplicates

df1=df.loc[df.Volume!=0].drop_duplicates('Date')
Out[13]:
         Date Ticker  Volume
0  2019-03-21   AAPL      10
5  2019-03-25   GOOG      12
7  2019-03-27    IBM      16
9  2019-03-28    IBM       9


问:
Getting MalformedJsonException error with Gson
I am trying to convert string to Map<Integer,String> using code:

```<code>public static <T, R> HashMap<T, R> strMapToHashmap(String strMap) {
    Gson gson = new GsonBuilder().create();
    Type type = new TypeToken<HashMap<T, R>>() {
    }.getType();
    return gson.fromJson(strMap, type);
}
</code>```

and getting below error:

```<code>Caused by: com.google.gson.stream.MalformedJsonException: Unexpected value at line 1 column 5 path $.
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:564)
    at com.google.gson.stream.JsonReader.peek(JsonReader.java:425)
    at com.google.gson.internal.bind.ObjectTypeAdapter.read(ObjectTypeAdapter.java:55)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)`
</code>```

and the string I passed to it is:

```<code>{4=, 1=3:00 pm–4:00 pm, 7=, 6=2:00 am–3:00 am, 5=8:00 am–9:00 am, 3=1:00 am–2:00 am, 2=9:00 am–10:00 am}
</code>```

I couldn't find out what is wrong with it.

答:
Your string doesn't look like JSON. Try to pass

```<code>{
    "4": "",
    "1": "3:00 pm–4:00 pm",
    "7": "",
    "6": "2:00 am–3:00 am",
    "5": "8:00 am–9:00 am",
    "3": "1:00 am–2:00 am",
    "2": "9:00 am–10:00 am"
}
</code>```

I'm not sure if it's what you need , but Gson mainly used for parsing jsons

Body:
I am trying to convert string to Map<Integer,String> using code:

public static <T, R> HashMap<T, R> strMapToHashmap(String strMap) {
    Gson gson = new GsonBuilder().create();
    Type type = new TypeToken<HashMap<T, R>>() {
    }.getType();
    return gson.fromJson(strMap, type);
}

and getting below error:

Caused by: com.google.gson.stream.MalformedJsonException: Unexpected value at line 1 column 5 path $.
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:564)
    at com.google.gson.stream.JsonReader.peek(JsonReader.java:425)
    at com.google.gson.internal.bind.ObjectTypeAdapter.read(ObjectTypeAdapter.java:55)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)`

and the string I passed to it is:

{4=, 1=3:00 pm–4:00 pm, 7=, 6=2:00 am–3:00 am, 5=8:00 am–9:00 am, 3=1:00 am–2:00 am, 2=9:00 am–10:00 am}

I couldn't find out what is wrong with it.

Body:
Your string doesn't look like JSON. Try to pass

{
    "4": "",
    "1": "3:00 pm–4:00 pm",
    "7": "",
    "6": "2:00 am–3:00 am",
    "5": "8:00 am–9:00 am",
    "3": "1:00 am–2:00 am",
    "2": "9:00 am–10:00 am"
}

I'm not sure if it's what you need , but Gson mainly used for parsing jsons


问:
Showing error for multiple empty inputs vuejs vuetify
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

```<code>if (!this.externalIP || !this.externalHttpPort || !this.vendor) {
</code>```

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

```<code>  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }
</code>```

is there any other way of doing it? Also, Eslint show warning on indentations as well

答:
I'm using VeeValidate to handle all of Validation job, maybe you will be interested in it:
https://logaretm.github.io/vee-validate/</p>

Body:
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

if (!this.externalIP || !this.externalHttpPort || !this.vendor) {

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }

is there any other way of doing it? Also, Eslint show warning on indentations as well


问:
Getting Semester Averages with Grades using files in Python
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

```<code>last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades
</code>```

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

```<code>semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.
</code>```

Here's what I have so far. I'm terrible with files so I only know how to call a column.

```<code>def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())
</code>```

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

```<code>Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21
</code>```

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.

答:
ginkul's answer couldn't cover to handle multiple row of values

so I try to write code more generally like below:

```<code>def get_header():
    gb_data = open('gb_data.txt','r')
    header = gb_data.readline()
    return header.strip()

def get_content():
    gb_data = open('gb_data.txt','r')
    content = gb_data.readlines()
    del content[0]
    return content

hw_pos = []
project_pos = []
quiz_pos =  []

header_list = get_header()
header_list = header_list.split(", ")
header_list_index = enumerate(header_list)
for index, target in header_list_index:
    if target == "hw":
        hw_pos.append(index)
    elif target == "quiz":
        quiz_pos.append(index)
    elif target == "project":
        project_pos.append(index)

content_list = get_content()

avg_dict = {}

for element in content_list:
    element = element.strip().split(", ")

    name = element[0] + ', ' + element[1]
    hw_avg = sum([int(element[i]) for i in hw_pos]) / len(hw_pos)
    project_avg = sum([int(element[i]) for i in project_pos]) / len(project_pos)
    quiz_avg = sum([int(element[i]) for i in quiz_pos]) / len(quiz_pos)
    avg_dict.update({name:(hw_avg, project_avg, quiz_avg)})

for name, avg in avg_dict.items():
    print(name, "hw avg : ", round(avg[0], 2), "project avg : ", round(avg[1], 2), "quiz avg : ", round(avg[2], 2))
</code>```

save your all output to another text file

```<code>for name, avg in avg_dict.items():
    with open("avg.txt", "a") as f:
        dataline = name + " hw avg : " + str(round(avg[0], 2)) + \
        " project avg : " + str(round(avg[1], 2)) + " quiz avg : " + str(round(avg[2], 2)) + "\n"
        f.write(dataline)
</code>```

Body:
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.

Here's what I have so far. I'm terrible with files so I only know how to call a column.

def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.

Body:
ginkul's answer couldn't cover to handle multiple row of values

so I try to write code more generally like below:

def get_header():
    gb_data = open('gb_data.txt','r')
    header = gb_data.readline()
    return header.strip()

def get_content():
    gb_data = open('gb_data.txt','r')
    content = gb_data.readlines()
    del content[0]
    return content

hw_pos = []
project_pos = []
quiz_pos =  []

header_list = get_header()
header_list = header_list.split(", ")
header_list_index = enumerate(header_list)
for index, target in header_list_index:
    if target == "hw":
        hw_pos.append(index)
    elif target == "quiz":
        quiz_pos.append(index)
    elif target == "project":
        project_pos.append(index)

content_list = get_content()

avg_dict = {}

for element in content_list:
    element = element.strip().split(", ")

    name = element[0] + ', ' + element[1]
    hw_avg = sum([int(element[i]) for i in hw_pos]) / len(hw_pos)
    project_avg = sum([int(element[i]) for i in project_pos]) / len(project_pos)
    quiz_avg = sum([int(element[i]) for i in quiz_pos]) / len(quiz_pos)
    avg_dict.update({name:(hw_avg, project_avg, quiz_avg)})

for name, avg in avg_dict.items():
    print(name, "hw avg : ", round(avg[0], 2), "project avg : ", round(avg[1], 2), "quiz avg : ", round(avg[2], 2))

save your all output to another text file

for name, avg in avg_dict.items():
    with open("avg.txt", "a") as f:
        dataline = name + " hw avg : " + str(round(avg[0], 2)) + \
        " project avg : " + str(round(avg[1], 2)) + " quiz avg : " + str(round(avg[2], 2)) + "\n"
        f.write(dataline)


答:
Use boolean indexing with mask by Series.ne for not equal and then DataFrame.drop_duplicates:

```<code>df = df[df['Volume'].ne(0)].drop_duplicates('Date')
print (df)
         Date Ticker  Volume
0  2019-03-21   AAPL      10
5  2019-03-25   GOOG      12
7  2019-03-27    IBM      16
9  2019-03-28    IBM       9
</code>```

Alterntive with DataFrame.query:

```<code>df = df.query('Volume != 0').drop_duplicates('Date')
</code>```

EDIT:

For extract second/third/next columns use GroupBy.nth, only python counts from 0, so for second rows need 1, for third 2:

```<code>df1 = df[df['Volume'].ne(0)]
print (df1)
          Date Ticker  Volume
0   2019-03-21   AAPL      10
1   2019-03-21   GOOG       5
5   2019-03-25   GOOG      12
7   2019-03-27    IBM      16
8   2019-03-27   GOOG      10
9   2019-03-28    IBM       9
11  2019-03-28   AAPL      10

df2 = df1.groupby('Date').nth(1)
print (df2)
           Ticker  Volume
Date
2019-03-21   GOOG       5
2019-03-27   GOOG      10
2019-03-28   AAPL      10
</code>```

Or GroupBy.cumcount for mask:

```<code>df2 = df1[df1.groupby('Date').cumcount().eq(1)]
print (df2)
          Date Ticker  Volume
1   2019-03-21   GOOG       5
8   2019-03-27   GOOG      10
11  2019-03-28   AAPL      10
</code>```

Title: Lookup values in pandas dataframe

Body:
Use boolean indexing with mask by Series.ne for not equal and then DataFrame.drop_duplicates:

df = df[df['Volume'].ne(0)].drop_duplicates('Date')
print (df)
         Date Ticker  Volume
0  2019-03-21   AAPL      10
5  2019-03-25   GOOG      12
7  2019-03-27    IBM      16
9  2019-03-28    IBM       9

Alterntive with DataFrame.query:

df = df.query('Volume != 0').drop_duplicates('Date')

EDIT:

For extract second/third/next columns use GroupBy.nth, only python counts from 0, so for second rows need 1, for third 2:

df1 = df[df['Volume'].ne(0)]
print (df1)
          Date Ticker  Volume
0   2019-03-21   AAPL      10
1   2019-03-21   GOOG       5
5   2019-03-25   GOOG      12
7   2019-03-27    IBM      16
8   2019-03-27   GOOG      10
9   2019-03-28    IBM       9
11  2019-03-28   AAPL      10

df2 = df1.groupby('Date').nth(1)
print (df2)
           Ticker  Volume
Date
2019-03-21   GOOG       5
2019-03-27   GOOG      10
2019-03-28   AAPL      10

Or GroupBy.cumcount for mask:

df2 = df1[df1.groupby('Date').cumcount().eq(1)]
print (df2)
          Date Ticker  Volume
1   2019-03-21   GOOG       5
8   2019-03-27   GOOG      10
11  2019-03-28   AAPL      10