问:
Minimizing ViewState size in ASP.Net, is there a difference between initializing control values in the constructor versus OnInit?
Ok I'm trying to understand how best to handle ViewState, for the programmatic setting of default values using C#. I understand that the construction of the ViewState hidden field is based on every value that is set after the OnInit event is triggered. What I'm not clear about is if there is a difference between using the control's constructor or the OnInit event to set default values.

```<code>public MyControl(){
    this.Text = "SomeDefaultValue";
}
</code>```

versus

```<code>protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue";
}
</code>```

I've seen some places that suggest testing the ViewState value for null in the get of the given property, like so:

```<code>public string Text {
    get {
        return this.ViewState["Text"] == null ?
            "SomeDefaultValue" :
            this.ViewState["Text"] as string;
    }
    set { this.ViewState["Text"] = value; }
}
</code>```

I don't like that because it makes clearing the value confusing.

So, Is there any functional difference between using the constructor vs OnInit to set default ViewState values?

答:
There is quite a detailed document on the ViewState over at MSDN:

...server controls don't begin tracking
  view state changes until right at the
  end of the initialization stage.
  Second, when adding dynamic controls
  that need to utilize view state, these
  controls will need to be added during
  the Page's Init event as opposed to
  the Load event.

Just from this alone, I would say, if you're utilising the ViewState, use OnInit.

Body:
Ok I'm trying to understand how best to handle ViewState, for the programmatic setting of default values using C#. I understand that the construction of the ViewState hidden field is based on every value that is set after the OnInit event is triggered. What I'm not clear about is if there is a difference between using the control's constructor or the OnInit event to set default values.

public MyControl(){
    this.Text = "SomeDefaultValue";
}

versus

protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue";
}

I've seen some places that suggest testing the ViewState value for null in the get of the given property, like so:

public string Text {
    get {
        return this.ViewState["Text"] == null ?
            "SomeDefaultValue" :
            this.ViewState["Text"] as string;
    }
    set { this.ViewState["Text"] = value; }
}

I don't like that because it makes clearing the value confusing.

So, Is there any functional difference between using the constructor vs OnInit to set default ViewState values?


来源: stackexchange

问:
How can I code a Javascript Alert to only populate once per web session?
I am creating a website for my final and have coded an "adult content" alert on my homepage. I am trying to get the site to populate that message only once per session but right now it populates every time you go to the homepage.

The class is HTML and CSS but we were asked to include one basic javascript code and the "alert" seemed most appropriate. I have tried googling this question different ways to get help but it's mostly providing information that is above a very very basic level of javascript.

This is my current code:

```<code><script>
alert("WARNING! Adult Language and Content! The following is intended for
immature adults only. Viewer Discretion is Advised.")
</script>
</code>```

This is the site:
http://mysite.du.edu/~mdarienz/index.html

Since this is for a final, I don't need the code to fix it but if you could maybe steer me in the right direction for how to approach it I would greatly appreciate it.

答:
You can store your data on session basis using the sessionStorage api provided by most of the browsers. So you can store a bool(or a number or a string) in the sessionStorage to check if you have shown the alert or not.

```<code><script type="text/javascript">
// check if api exists
if (sessionStorage !== undefined) {
    // check if you have any item with the key 'showAlert'
    if (sessionStorage.getItem("showAlert") == null) {
        alert("Show alert");
        // Set the item with the key 'showAlert' so that
        // this won't be executed later.
        sessionStorage.setItem("showAlert", false);
    }
}
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a website for my final and have coded an "adult content" alert on my homepage. I am trying to get the site to populate that message only once per session but right now it populates every time you go to the homepage.

The class is HTML and CSS but we were asked to include one basic javascript code and the "alert" seemed most appropriate. I have tried googling this question different ways to get help but it's mostly providing information that is above a very very basic level of javascript.

This is my current code:

This is the site:
http://mysite.du.edu/~mdarienz/index.html

Since this is for a final, I don't need the code to fix it but if you could maybe steer me in the right direction for how to approach it I would greatly appreciate it.

Body:
You can store your data on session basis using the sessionStorage api provided by most of the browsers. So you can store a bool(or a number or a string) in the sessionStorage to check if you have shown the alert or not.

<script type="text/javascript">
// check if api exists
if (sessionStorage !== undefined) {
    // check if you have any item with the key 'showAlert'
    if (sessionStorage.getItem("showAlert") == null) {
        alert("Show alert");
        // Set the item with the key 'showAlert' so that
        // this won't be executed later.
        sessionStorage.setItem("showAlert", false);
    }
}
</script>


问:
Is it possible to enable resizing without the title bar in JavaFX?
I removed the javaFx title bar using :

```<code>stage.initStyle(StageStyle.TRANSPARENT);
</code>```

Then I am trying to enable

```<code>stage.setResizable(true);
</code>```

to resize my application but it seems I cant be able to resize the window?
Please help. Thanks!

I already tried using :

```<code>tage.initStyle(StageStyle.UNDECORATED);
</code>```

答:
I suggest you add a button that sets your stage's setMaximized = true or false.
And add MinHeight and MinWidth

Body:
I removed the javaFx title bar using :

stage.initStyle(StageStyle.TRANSPARENT);

Then I am trying to enable

stage.setResizable(true);

to resize my application but it seems I cant be able to resize the window?
Please help. Thanks!

I already tried using :

tage.initStyle(StageStyle.UNDECORATED);


问:
Form button not being disabled
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

```<code>  <div id="wrapper">
    <section>
      <div class="page-container">
        <p class="profile-details">
          Please enter a username and password to create your profile
        </p>
        <form [formGroup]="profileDetailsForm">
          <div>
            <label for="username">Username</label>
            <input id="username" type="text" formControlName="username" size="50" />
          </div>
          <div>
            <label for="password">Password</label>
            <input id="password" type="password" formControlName="password" />
          </div>
          <div>
            <label for="confirmPassword">Confirm Password</label>
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />
            <p *ngIf="isConfirmPasswordFails" class="error">
              * Password and Confirm Password do not match, please try again.
            </p>
          </div>
          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>
      </div>
    </section>
  </div>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }
</code>```

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

答:
'false' is not a Boolean value. If your variable is boolean, it will automatically bind to [disable] that bool value.

Use this:

```<code><button (click)="onCreateProfile()" [disabled]="!passwordsMatch">CREATE PROFILE</button>
</code>```

Or, if this is a complex condition, you can call to a method like this

```<code><button (click)="onCreateProfile()" [disabled]="!isPasswordsMatch()">CREATE PROFILE</button>

isPasswordsMatch() {
    //More complex code here
    return this.passwordsMatch;
}
</code>```

Title: Form button not being disabled

Body:
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

          Please enter a username and password to create your profile

        <form [formGroup]="profileDetailsForm">

            Username
            <input id="username" type="text" formControlName="username" size="50" />

            Password
            <input id="password" type="password" formControlName="password" />

            Confirm Password
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />

              * Password and Confirm Password do not match, please try again.

          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

Body:
'false' is not a Boolean value. If your variable is boolean, it will automatically bind to [disable] that bool value.

Use this:

<button (click)="onCreateProfile()" [disabled]="!passwordsMatch">CREATE PROFILE</button>

Or, if this is a complex condition, you can call to a method like this

<button (click)="onCreateProfile()" [disabled]="!isPasswordsMatch()">CREATE PROFILE</button>

isPasswordsMatch() {
    //More complex code here
    return this.passwordsMatch;
}


问:
How do I change file name that contains a date automatically in python
I am trying to copy data from one excel file to another automatically using python, currently i have to manually update the date in the excel file name every morning. Is there a way to automatically update the date in the excel file name. I am very new to any form of programming, trying to learn to keep my job.

I have tried to use the time date function and declare this as a variable and copy this into code but no luck

```<code>import datetime

Filedate= (datetime.date.today()-datetime.timedelta(1))

exceldate= Filedate.strftime("%Y",)+Filedate.strftime("%m",)+Filedate.strftime("%d",)

import pyexcel as p

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Statsexceldate.xls",#CHANGE DATE #manual entry.
               dest_file_name='YieldX Daily Stats20190522.xlsx')#CHANGE DATE manual entry
</code>```

答:
I believe what you are trying to do is, open a excel file everyday, and rename its filename to current date, where the previous excel file will have the date of yesterday.

```<code>import datetime
import pyexcel as p

yesterday = (datetime.date.today()-datetime.timedelta(1)).strftime("%Y%m%d")

today = datetime.date.today().strftime("%Y%m%d")

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Stats" + yesterday + ".xls",
               dest_file_name='YieldX Daily Stats' + today + '.xlsx')
</code>```

The above code, when executed will change the name of the .xls file which was created yesterday (with its Timestamp), to the current date.

Example:-

If a file named YieldX Daily Stats20190530.xls existed yesterday, today its name will be modified to YieldX Daily Stats20190531.xls

Body:
I am trying to copy data from one excel file to another automatically using python, currently i have to manually update the date in the excel file name every morning. Is there a way to automatically update the date in the excel file name. I am very new to any form of programming, trying to learn to keep my job.

I have tried to use the time date function and declare this as a variable and copy this into code but no luck

import datetime

Filedate= (datetime.date.today()-datetime.timedelta(1))

exceldate= Filedate.strftime("%Y",)+Filedate.strftime("%m",)+Filedate.strftime("%d",)

import pyexcel as p

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Statsexceldate.xls",#CHANGE DATE #manual entry.
               dest_file_name='YieldX Daily Stats20190522.xlsx')#CHANGE DATE manual entry

Body:
I believe what you are trying to do is, open a excel file everyday, and rename its filename to current date, where the previous excel file will have the date of yesterday.

import datetime
import pyexcel as p

yesterday = (datetime.date.today()-datetime.timedelta(1)).strftime("%Y%m%d")

today = datetime.date.today().strftime("%Y%m%d")

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Stats" + yesterday + ".xls",
               dest_file_name='YieldX Daily Stats' + today + '.xlsx')

The above code, when executed will change the name of the .xls file which was created yesterday (with its Timestamp), to the current date.

Example:-

If a file named YieldX Daily Stats20190530.xls existed yesterday, today its name will be modified to YieldX Daily Stats20190531.xls


问:
Dotnet upgrade - 2.0 to 3.5 - performance
We have a number of winforms apps that are written in dotnet 2.0.  Are there any performance upgrades that we would expect when taking transistion to 3.5 runtime?  Any particular benefits we will get, besides the language features?</p>

答: There are performance enhancements with appdomain startup time (assembly loading), networking, drawing and presentation, and threading to name a few.</p>

OwnerDisplayName: mek

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Rex M

ContentLicense: CC BY-SA 2.5


问:
how many threads is too many in iphone/objective-c dev
I have a complex sync job that does several asyncronous calls for content over HTTP. Each time this content is received, it asks for the next bit and so on. These are all daisey-chained in a big over-all sync job with data on the server.

There are probably 12 steps in this job chain. It seems to get stuck after around the 5th async request, the request never comes back and it hangs for ever waiting for it. I think it may have to do with too many threads being spawned because if I fire off the one it hangs at at the beginning it returns fine.

In the way I imagine it in my head, the main thread asks for async content a. When it comes back in its own asynchronous time it spawns a new thread which then asks for aync content b. When it comes back in its own sweet time it spawns a new thread which then asks for content c. Isn't a new thread being created everytime an async request returns a result?

Am I daisy-chaining these requests right? I was quite good at threads in Java development but I'm a bit confused on how they work in Obj-C. Do I need to use a Thread pool of say 3 threads and reuse these?

Sorry for the high-level question but I'm sure some experts can help clear the cloud of mystery around this.

答:
NSOperationQueues are built on top of Grand Central Dispatch. If you need precise control over order of operations and the ability to dispatch synchronous requests you might want to use GCD directly. Using either, you don't really need to worry about thread creation/management. You simply queue your operations as needed by your app.

The Apple docs are fine on this IMHO but you can find a number of tutorials out there.

[EDIT: added link to Apple docs]

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html


问:
How to pass array object as a parameter in kendo datasource read methods?
I am trying to send array object to mvc controller from kendo datasource read methods and unable to bind parameter studentId in GetAllStudentDetails Methods.

```<code> var studentId=[1,2,3]
         var preSelectStudentDataSource = new kendo.data.DataSource({
                            transport: {
                                read: {
                                    url: '/Manage/Students/GetAllStudentDetails',
                                    dataType: "json",
                                    contentType: "application/json;charset=utf-8",
                                    data: { studentId: studentId}
                                }
                            },
                            schema: {
                                success: "success",
                                message: "message",
                                data: "data",
                                model: {
                                    id: "StudentId"
                                }
                            },
                            autoBind: true
                        })
</code>```

In Controller Side

```<code> public JsonResult GetAllStudentDetails(int[] studentId)
        {
            JsonResult result = null;
            // Code
            return result;
        }
</code>```

答:
Making traditional=true it work for me

```<code> var studentId=[1,2,3]
     var preSelectSegmentDataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: '/Manage/Students/GetAllStudentDetails',
                                dataType: "json",
                                traditional: true,
                                contentType: "application/json;charset=utf-8",
                                data: { studentId: studentId}
                            }
                        },
                        schema: {
                            success: "success",
                            message: "message",
                            data: "data",
                            model: {
                                id: "StudentId"
                            }
                        },
                        autoBind: true
                    })
</code>```

Or with JSON.stringify()

```<code> var preSelectedSegmentDataSource = new kendo.data.DataSource({
                    transport: {
                        read: {
                            url: '/Manage/Students/GetAllStudentDetails',
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json;charset=utf-8",

                        },
                        parameterMap: function (options, operation) {
                           var studentId=[1,2,3]
                            if (operation == "read") {

                                return JSON.stringify({ studentId: studentId});
                            }
                        }
                    },
                    schema: {
                        success: "success",
                        message: "message",
                        data: "data",
                        model: {
                            id: "StudentId"
                        }
                    },
                    autoBind: true
                })
</code>```

Body:
I am trying to send array object to mvc controller from kendo datasource read methods and unable to bind parameter studentId in GetAllStudentDetails Methods.

 var studentId=[1,2,3]
         var preSelectStudentDataSource = new kendo.data.DataSource({
                            transport: {
                                read: {
                                    url: '/Manage/Students/GetAllStudentDetails',
                                    dataType: "json",
                                    contentType: "application/json;charset=utf-8",
                                    data: { studentId: studentId}
                                }
                            },
                            schema: {
                                success: "success",
                                message: "message",
                                data: "data",
                                model: {
                                    id: "StudentId"
                                }
                            },
                            autoBind: true
                        })

In Controller Side

 public JsonResult GetAllStudentDetails(int[] studentId)
        {
            JsonResult result = null;
            // Code
            return result;
        }

Body:
Making traditional=true it work for me

 var studentId=[1,2,3]
     var preSelectSegmentDataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: '/Manage/Students/GetAllStudentDetails',
                                dataType: "json",
                                traditional: true,
                                contentType: "application/json;charset=utf-8",
                                data: { studentId: studentId}
                            }
                        },
                        schema: {
                            success: "success",
                            message: "message",
                            data: "data",
                            model: {
                                id: "StudentId"
                            }
                        },
                        autoBind: true
                    })

Or with JSON.stringify()

 var preSelectedSegmentDataSource = new kendo.data.DataSource({
                    transport: {
                        read: {
                            url: '/Manage/Students/GetAllStudentDetails',
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json;charset=utf-8",

                        },
                        parameterMap: function (options, operation) {
                           var studentId=[1,2,3]
                            if (operation == "read") {

                                return JSON.stringify({ studentId: studentId});
                            }
                        }
                    },
                    schema: {
                        success: "success",
                        message: "message",
                        data: "data",
                        model: {
                            id: "StudentId"
                        }
                    },
                    autoBind: true
                })


问:
make all the other widget flatbuttons chage their colour when one is pressed on flutter
i have some buttons that i need to be able to press only one and the rest should change their colour,

in order to make the code smaller i extracted the widget to make it reusable, but when i select a button it get the colour changed but it does not refresh the state of the other buttons.

if i dont extract the button method and make use of duplicate code inside the Row, then it works.

What im missing?

```<code>int numOfTime = 60;

class NumOfTime extends StatefulWidget {
  const NumOfTime({
    Key key,
  }) : super(key: key);

  @override
  _NumOfTimeState createState() => _NumOfTimeState();
}

class _NumOfTimeState extends State<NumOfTime> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
            margin: EdgeInsets.only(left: 15, top: 5),
            child: Text(
              'Δευτερόλεπτα',
              style: TextStyle(color: Colors.white),
            )),
        Container(
          margin: EdgeInsets.only(top: 2, left: 10, right: 10, bottom: 10),
          decoration: myBoxDecoration(),
          child: Row(
            children: <Widget>[
              Container(
                  padding: EdgeInsets.only(left: 10, right: 5),
                  child: Icon(Icons.timer)),
              CustomButton(
                number: 30,
              ),
              CustomButton(
                number: 45,
              ),
              CustomButton(
                number: 60,
              ),
              CustomButton(
                number: 75,
              ),
              CustomButton(
                number: 90,
              ),
              Container(
                padding: EdgeInsets.only(right: 10),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class CustomButton extends StatefulWidget {
  final int number;
  const CustomButton({
    Key key,
    final int number,
  }) : this.number = number;

  @override
  _CustomButtonState createState() => _CustomButtonState(number);
}

class _CustomButtonState extends State<CustomButton> {
  final int number;
  _CustomButtonState(this.number);

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: FlatButton(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
          disabledColor: number == numOfTime ? Colors.black : Colors.white,
          highlightColor: number == numOfTime ? Colors.black : Colors.white,
          color: number == numOfTime ? Colors.black : Colors.white,
          child: Text(
            '$number',
            style: TextStyle(
                color: number == numOfTime ? Colors.white : Colors.black,
                fontSize: 13),
          ),
          onPressed: () {
            numOfTime = number;
            setState(() {});
          }),
    );
  }
}
</code>```

i expect to see all the other buttons change their color back to white if one is selected.

i also tried to pass null onPressed to make it disabled, but i dont see any change.

答:
It's a common error, you have many options to solve this, I will show you the easy way with minimum modifications.

You need to refresh the parent widget ( the widget which contains the buttons) , because you need to refresh all of your buttons again.

So, this is your code fixed:

```<code>    class _NumOfTimeState extends State<NumOfTime> {
      _onPressed() {
        setState(() {});
      }

      @override
      Widget build(BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                margin: EdgeInsets.only(left: 15, top: 5),
                child: Text(
                  'Δευτερόλεπτα',
                  style: TextStyle(color: Colors.white),
                )),
            Container(
              margin: EdgeInsets.only(top: 2, left: 10, right: 10, bottom: 10),
              //decoration: myBoxDecoration(),
              child: Row(
                children: <Widget>[
                  Container(
                      padding: EdgeInsets.only(left: 10, right: 5),
                      child: Icon(Icons.timer)),
                  CustomButton(
                    number: 30,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 45,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 60,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 75,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 90,
                    onButtonPressed: _onPressed,
                  ),
                  Container(
                    padding: EdgeInsets.only(right: 10),
                  )
                ],
              ),
            ),
          ],
        );
      }
    }

    class CustomButton extends StatefulWidget {
      final int number;
      final VoidCallback onButtonPressed;
      const CustomButton({
        Key key,
        final int number,
        this.onButtonPressed,
      }) : this.number = number;

      @override
      _CustomButtonState createState() => _CustomButtonState(number);
    }

    class _CustomButtonState extends State<CustomButton> {
      final int number;
      _CustomButtonState(this.number);

      @override
      void initState() {
        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        return Expanded(
          flex: 1,
          child: FlatButton(
              shape:
                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
              disabledColor: number == numOfTime ? Colors.black : Colors.white,
              highlightColor: number == numOfTime ? Colors.black : Colors.white,
              color: number == numOfTime ? Colors.black : Colors.white,
              child: Text(
                '$number',
                style: TextStyle(
                    color: number == numOfTime ? Colors.white : Colors.black,
                    fontSize: 13),
              ),
              onPressed: () {
                numOfTime = number;
                widget.onButtonPressed();
              }),
        );
      }
    }
</code>```

Body:
i have some buttons that i need to be able to press only one and the rest should change their colour,

in order to make the code smaller i extracted the widget to make it reusable, but when i select a button it get the colour changed but it does not refresh the state of the other buttons.

if i dont extract the button method and make use of duplicate code inside the Row, then it works.

What im missing?

int numOfTime = 60;

class NumOfTime extends StatefulWidget {
  const NumOfTime({
    Key key,
  }) : super(key: key);

  @override
  _NumOfTimeState createState() => _NumOfTimeState();
}

class _NumOfTimeState extends State<NumOfTime> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
            margin: EdgeInsets.only(left: 15, top: 5),
            child: Text(
              'Δευτερόλεπτα',
              style: TextStyle(color: Colors.white),
            )),
        Container(
          margin: EdgeInsets.only(top: 2, left: 10, right: 10, bottom: 10),
          decoration: myBoxDecoration(),
          child: Row(
            children: <Widget>[
              Container(
                  padding: EdgeInsets.only(left: 10, right: 5),
                  child: Icon(Icons.timer)),
              CustomButton(
                number: 30,
              ),
              CustomButton(
                number: 45,
              ),
              CustomButton(
                number: 60,
              ),
              CustomButton(
                number: 75,
              ),
              CustomButton(
                number: 90,
              ),
              Container(
                padding: EdgeInsets.only(right: 10),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class CustomButton extends StatefulWidget {
  final int number;
  const CustomButton({
    Key key,
    final int number,
  }) : this.number = number;

  @override
  _CustomButtonState createState() => _CustomButtonState(number);
}

class _CustomButtonState extends State<CustomButton> {
  final int number;
  _CustomButtonState(this.number);

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: FlatButton(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
          disabledColor: number == numOfTime ? Colors.black : Colors.white,
          highlightColor: number == numOfTime ? Colors.black : Colors.white,
          color: number == numOfTime ? Colors.black : Colors.white,
          child: Text(
            '$number',
            style: TextStyle(
                color: number == numOfTime ? Colors.white : Colors.black,
                fontSize: 13),
          ),
          onPressed: () {
            numOfTime = number;
            setState(() {});
          }),
    );
  }
}

i expect to see all the other buttons change their color back to white if one is selected.

i also tried to pass null onPressed to make it disabled, but i dont see any change.

Body:
It's a common error, you have many options to solve this, I will show you the easy way with minimum modifications.

You need to refresh the parent widget ( the widget which contains the buttons) , because you need to refresh all of your buttons again.

So, this is your code fixed:

    class _NumOfTimeState extends State<NumOfTime> {
      _onPressed() {
        setState(() {});
      }

      @override
      Widget build(BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                margin: EdgeInsets.only(left: 15, top: 5),
                child: Text(
                  'Δευτερόλεπτα',
                  style: TextStyle(color: Colors.white),
                )),
            Container(
              margin: EdgeInsets.only(top: 2, left: 10, right: 10, bottom: 10),
              //decoration: myBoxDecoration(),
              child: Row(
                children: <Widget>[
                  Container(
                      padding: EdgeInsets.only(left: 10, right: 5),
                      child: Icon(Icons.timer)),
                  CustomButton(
                    number: 30,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 45,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 60,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 75,
                    onButtonPressed: _onPressed,
                  ),
                  CustomButton(
                    number: 90,
                    onButtonPressed: _onPressed,
                  ),
                  Container(
                    padding: EdgeInsets.only(right: 10),
                  )
                ],
              ),
            ),
          ],
        );
      }
    }

    class CustomButton extends StatefulWidget {
      final int number;
      final VoidCallback onButtonPressed;
      const CustomButton({
        Key key,
        final int number,
        this.onButtonPressed,
      }) : this.number = number;

      @override
      _CustomButtonState createState() => _CustomButtonState(number);
    }

    class _CustomButtonState extends State<CustomButton> {
      final int number;
      _CustomButtonState(this.number);

      @override
      void initState() {
        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        return Expanded(
          flex: 1,
          child: FlatButton(
              shape:
                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
              disabledColor: number == numOfTime ? Colors.black : Colors.white,
              highlightColor: number == numOfTime ? Colors.black : Colors.white,
              color: number == numOfTime ? Colors.black : Colors.white,
              child: Text(
                '$number',
                style: TextStyle(
                    color: number == numOfTime ? Colors.white : Colors.black,
                    fontSize: 13),
              ),
              onPressed: () {
                numOfTime = number;
                widget.onButtonPressed();
              }),
        );
      }
    }


问:
object MotorLatentCommandCursor can't be used in 'await' expression
use motor in Tornado to connect mongodb

i created a motor connect

```<code>import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await self.db.account.aggregate([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)
</code>```

when i got started ,i got this message:
"object MotorLatentCommandCursor can't be used in 'await' expression"

idk why ~ it's seems like nothing wrong

答:
In official documentation said: An object that can be used in an await expression. Can be a coroutine or an object with an await() method.
you can get more information from PEP 492: https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for

also you can use asgiref to wrap your function:

```<code>from asgiref.sync import sync_to_async
import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await sync_to_async(self.db.account.aggregate)([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)
</code>```

Body:
use motor in Tornado to connect mongodb

i created a motor connect

import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await self.db.account.aggregate([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)

when i got started ,i got this message:
"object MotorLatentCommandCursor can't be used in 'await' expression"

idk why ~ it's seems like nothing wrong

Body:
In official documentation said: An object that can be used in an await expression. Can be a coroutine or an object with an await() method.
you can get more information from PEP 492: https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for

also you can use asgiref to wrap your function:

from asgiref.sync import sync_to_async
import motor.motor_tornado
from tornado.web import RequestHandler
client = motor.motor_tornado.MotorClient('mongodb://xxx')

class BaseHandler(RequestHandler):
    @property
    def db(self):
        return client['realtime-test']

class Account(BaseHandler):
    async def get(self,*args,**kwargs):
        all_user = await sync_to_async(self.db.account.aggregate)([
            {'$match': {'status': 1}},
            {'$group': {'_id':''}}
        ])
        print(all_user)


问:
MYSQL Order by Clause is not working on Currencies table when column name is Date and column Data Type is Date and time
I have database table for currencies. I update currencies on daily basis by using google finance API along with date and time. My column name is Date and data type is datetime

I want to fetch currency rate of Dollar which is last updated on database on basis of date, instead of id of table.

Below queries shows always same result.

```<code>SELECT * FROM `currencyrates` WHERE CurrencyCode='USD' AND Rate > 0  ORDER BY 'Date' ASC

SELECT * FROM `currencyrates` WHERE CurrencyCode='USD' AND Rate > 0  ORDER BY 'Date' DESC
</code>```

It always shows records from 2015, instead it should show record of 2019 first because records exits in database i checked it by sorting in my SQL tool (SQLyog).

答:
*SELECT * FROM currencyrates WHERE CurrencyCode='USD' AND Rate >= 0  ORDER BY 'Date' ASC

SELECT * FROM currencyrates WHERE CurrencyCode='USD' AND Rate >= 0  ORDER BY 'Date' DESC*

Body:
I have database table for currencies. I update currencies on daily basis by using google finance API along with date and time. My column name is Date and data type is datetime

I want to fetch currency rate of Dollar which is last updated on database on basis of date, instead of id of table.

Below queries shows always same result.

SELECT * FROM `currencyrates` WHERE CurrencyCode='USD' AND Rate > 0  ORDER BY 'Date' ASC

SELECT * FROM `currencyrates` WHERE CurrencyCode='USD' AND Rate > 0  ORDER BY 'Date' DESC

It always shows records from 2015, instead it should show record of 2019 first because records exits in database i checked it by sorting in my SQL tool (SQLyog).


问:
Nested lists into smalls lists (splitted by category)
This is my code, which is inside of a function:

```<code>xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray
</code>```

It prints me a big list, with the following result:

```<code>[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]
</code>```

I am trying to split it up and get small subsets of the big list, something like:

```<code>Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]
</code>```

答:
You can join your texts back into one text and use regex to extract the needed information. It seems kind of structured (per line):

```<code>until 1st "-" : authors
after authors some unwanted stuf, followed by
year: 4 digit with spaces around it before next - and
from last "-" : publisher
</code>```

I would use this expression: r'^(?P<author>[^-]+)(.+?) (?P<year>\d{4}).*-(?P<pub>.+)$',re.M):

```<code>'^(?P<author>[^-]+)'       Capture from start of line till first - into group author
'(.+?)'                    Capture anything into not named group
'(?P<year>\d{4}).*-'       Capture anything with space + 4 digits + anything - into
                           group year
'(?P<pub>.+)$'             capture anythin beyond that until end of line into group pub
</code>```

And then iterate over your joined texts:

```<code>text=[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

# until 1st "-" : authors
# from last "-" : publisher
# year: 4 digit with spaces around it
import re

# re.M == multiline
pattern = re.compile(r'^(?P<author>[^-]+)(.+?) (?P<year>\d{4}).*-(?P<pub>.+)$',re.M)

t = '\n'.join(a for b in text for a in b)

auth = []
year = []
pub = []
for p in pattern.finditer(t):
    auth.append(p.group("author"))
    year.append(p.group("year"))
    pub.append(p.group("pub"))

print("Authors: ",auth)
print("Years: ",year)
print("Publishers: ",pub)
</code>```

Output:

```<code>Authors:  ['LR Hirsch, AM Gobin, AR Lowery, F Tam… ',
           'C Loo, A Lowery, N Halas, J West, R Drezek ',
           'SJ Oldenburg, JB Jackson, SL Westcott… ',
           'RD Averitt, SL Westcott, NJ Halas ',
           'LR Hirsch, JB Jackson, A Lee, NJ Halas… ',
           'SJ Oldenburg, RD Averitt, NJ Halas ',
           'AM Gobin, MH Lee, NJ Halas, WD James… ',
           'JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… ',
           'JB Jackson, NJ Halas ',
           'RD Averitt, D Sarkar, NJ Halas ']

Years:  ['2006', '2005', '1999', '1999', '2003', '2002', '2007', '2008', '2001', '1997']

Publishers:  [' Springer', ' ACS Publications', ' aip.scitation.org',
              ' osapublishing.org', ' ACS Publications', ' Google Patents',
              ' ACS Publications', ' ACS Publications', ' ACS Publications', ' APS']
</code>```

Your capturing can be enhanced fiddling around and omitting some whitespaces here and there - I suggest taking this as a start point and refine the patters over at http://regex101.com (set to python) until you are fully statisfied.

Body:
This is my code, which is inside of a function:

xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray

It prints me a big list, with the following result:

[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

I am trying to split it up and get small subsets of the big list, something like:

Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]

Body:
You can join your texts back into one text and use regex to extract the needed information. It seems kind of structured (per line):

until 1st "-" : authors
after authors some unwanted stuf, followed by
year: 4 digit with spaces around it before next - and
from last "-" : publisher

I would use this expression: r'^(?P<author>[^-]+)(.+?) (?P<year>\d{4}).*-(?P<pub>.+)$',re.M):

'^(?P<author>[^-]+)'       Capture from start of line till first - into group author
'(.+?)'                    Capture anything into not named group
'(?P<year>\d{4}).*-'       Capture anything with space + 4 digits + anything - into
                           group year
'(?P<pub>.+)$'             capture anythin beyond that until end of line into group pub

And then iterate over your joined texts:

text=[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

# until 1st "-" : authors
# from last "-" : publisher
# year: 4 digit with spaces around it
import re

# re.M == multiline
pattern = re.compile(r'^(?P<author>[^-]+)(.+?) (?P<year>\d{4}).*-(?P<pub>.+)$',re.M)

t = '\n'.join(a for b in text for a in b)

auth = []
year = []
pub = []
for p in pattern.finditer(t):
    auth.append(p.group("author"))
    year.append(p.group("year"))
    pub.append(p.group("pub"))

print("Authors: ",auth)
print("Years: ",year)
print("Publishers: ",pub)

Output:

Authors:  ['LR Hirsch, AM Gobin, AR Lowery, F Tam… ',
           'C Loo, A Lowery, N Halas, J West, R Drezek ',
           'SJ Oldenburg, JB Jackson, SL Westcott… ',
           'RD Averitt, SL Westcott, NJ Halas ',
           'LR Hirsch, JB Jackson, A Lee, NJ Halas… ',
           'SJ Oldenburg, RD Averitt, NJ Halas ',
           'AM Gobin, MH Lee, NJ Halas, WD James… ',
           'JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… ',
           'JB Jackson, NJ Halas ',
           'RD Averitt, D Sarkar, NJ Halas ']

Years:  ['2006', '2005', '1999', '1999', '2003', '2002', '2007', '2008', '2001', '1997']

Publishers:  [' Springer', ' ACS Publications', ' aip.scitation.org',
              ' osapublishing.org', ' ACS Publications', ' Google Patents',
              ' ACS Publications', ' ACS Publications', ' ACS Publications', ' APS']

Your capturing can be enhanced fiddling around and omitting some whitespaces here and there - I suggest taking this as a start point and refine the patters over at http://regex101.com (set to python) until you are fully statisfied.


问:
http-server with localhost:3000 gives ERR_INVALID_REDIRECT
I have installed http-server using the following command:

npm i -g http-server

Upon running the server I get the response saying Running on 127.0.0.1:8080

My call looks like this:

http-server -a 0.0.0.0 -c-1

If I go to 127.0.0.1:8080 or 10.1.1.72:8080 I get:

This page is not working.

127.0.0.1:8080 sent an invalid response

ERR_INVALID_REDIRECT

I have googled and searched everywhere with no answer as to what actually solves this. I'm not using XAMPP or IIS just a blank node server.

Node.js: 11.12.0

npm: 6.7.0

OS: Windows 10

I have checked my host files, there is nothing relevant there. I have no idea what would be causing this. I don't use .htaccess files or Web.config files either.

Notes

If I go to localhost:8080/index.html I can get to my app. This isn't supposed to work like that though.

答:
I'm having the exact same problem. Just installed both node and http-server globally. run http-server and it gives me the following error when accessing localhost:8080:

"ERR_INVALID_REDIRECT"

If I try to access the index.html page, it works. It doesn't even show directories listing, even with -d in the command line.

I got something, though: installing an older version of http-server and it loads the index.html automagically :)

This was the command/version: npm install -g http-server@0.8.5
Anything newer (0.9.0+) and it breaks again.

Edit:

Even then, it will only work on sub-folders, not on the root. For example:

http://localhost:8080/mypage/ will load index.html automatically.

http://localhost:8080/ won't


问:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64') after using df.drop command
I understand that the error is because I have NaN values in my csv, but I have the command df.dropna in many places in my code, so I don't understand why it is interpreting the code as still having NaN values.

Now it is making me write more because of my long code, you can just ignore this, it is gibberish, please refer to the above sentence for my question, I greatly appreciate your help for helping me solve it, thanks!

```<code>import numpy as np
import pandas as pd
import pickle
from collections import Counter
from sklearn import svm, model_selection as cross_validation, neighbors
from sklearn.ensemble import RandomForestClassifier, VotingClassifier

def process_data_for_lables(ticker):
    hm_days = 7
    df = pd.read_csv('sp500_joined_closes.csv', index_col=0)
    df.dropna(inplace=True)
    tickers = df.columns.values.tolist()
    df.fillna(0)

    for i in range (1,hm_days+1):
        df['{}_{}d'.format(ticker, i)] = (df[ticker].shift(-i)-df[ticker])/ df[ticker]

    df.fillna(0)
    return tickers, df
#process_data_for_lables('XOM')

def buy_sell_hold(*args):
    cols = [c for c in args]
    requirement = 0.02
    for col in cols:
        if col > requirement:
            return 1
        if col < -requirement:
            return-1
    return 0

def extract_featuresets(ticker):
    tickers, df = process_data_for_lables(ticker)
    df.dropna(inplace=True)
    df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
                                              df['{}_1d'.format(ticker)],
                                              df['{}_2d'.format(ticker)],
                                              df['{}_3d'.format(ticker)],
                                              df['{}_4d'.format(ticker)],
                                              df['{}_5d'.format(ticker)],
                                              df['{}_6d'.format(ticker)],
                                              df['{}_7d'.format(ticker)]))

    vals = df['{}_target'.format(ticker)].values.tolist()
    str_vals = [str(i) for i in vals]
    print('Data spread:', Counter(str_vals))
    df.fillna(0)

    df = df.replace([np.inf, -np.inf], np.nan)
    df.dropna(inplace=True)

    df_vals = df[[ticker for ticker in tickers]].pct_change()
    df_vals = df_vals.replace([np.inf, -np.inf], 0)
    df_vals.fillna(0)

    X = df_vals.values
    y = df['{}_target'.format(ticker)].values
    np.nan_to_num(X)
    return X, y, df
#extract_featuresets('XOM')

def do_ml(ticker):

    X, y, df = extract_featuresets(ticker)
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,
                                                                    y,
                                                                    test_size = 0.25)
    clf = neighbors.KNeighborsClassifier()
    clf.fit(X_train, y_train)
    confidence = clf.score(X_test, y_test)
    predictions = clf.predict(X_test)
    print('Predicted spread:', Counter(predictions))

    return confidence

do_ml('BAC')
</code>```

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float64').

答:
The first step in solving any problem is recognizing there is one.

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Are you sure that your processed dataframe contains NaN only? There might be the case where you have infinity.
You can check your dataframe, whether it contains infinity or NaN.
To check for NaN present or not, use:

```<code>df.isnull().any().any()
</code>```

If the output is true, you still have NaN present.

To check for infinity present or not, use:

```<code>df.isinfinity().any().any()
</code>```

If you find any of the command's output to be true, then perhaps you should try removing that type of values from the dataframe. Else, please make sure all the values are in range of dtype float64.

Please share your findings!

Body:
I understand that the error is because I have NaN values in my csv, but I have the command df.dropna in many places in my code, so I don't understand why it is interpreting the code as still having NaN values.

Now it is making me write more because of my long code, you can just ignore this, it is gibberish, please refer to the above sentence for my question, I greatly appreciate your help for helping me solve it, thanks!

import numpy as np
import pandas as pd
import pickle
from collections import Counter
from sklearn import svm, model_selection as cross_validation, neighbors
from sklearn.ensemble import RandomForestClassifier, VotingClassifier

def process_data_for_lables(ticker):
    hm_days = 7
    df = pd.read_csv('sp500_joined_closes.csv', index_col=0)
    df.dropna(inplace=True)
    tickers = df.columns.values.tolist()
    df.fillna(0)

    for i in range (1,hm_days+1):
        df['{}_{}d'.format(ticker, i)] = (df[ticker].shift(-i)-df[ticker])/ df[ticker]

    df.fillna(0)
    return tickers, df
#process_data_for_lables('XOM')

def buy_sell_hold(*args):
    cols = [c for c in args]
    requirement = 0.02
    for col in cols:
        if col > requirement:
            return 1
        if col < -requirement:
            return-1
    return 0

def extract_featuresets(ticker):
    tickers, df = process_data_for_lables(ticker)
    df.dropna(inplace=True)
    df['{}_target'.format(ticker)] = list(map(buy_sell_hold,
                                              df['{}_1d'.format(ticker)],
                                              df['{}_2d'.format(ticker)],
                                              df['{}_3d'.format(ticker)],
                                              df['{}_4d'.format(ticker)],
                                              df['{}_5d'.format(ticker)],
                                              df['{}_6d'.format(ticker)],
                                              df['{}_7d'.format(ticker)]))

    vals = df['{}_target'.format(ticker)].values.tolist()
    str_vals = [str(i) for i in vals]
    print('Data spread:', Counter(str_vals))
    df.fillna(0)

    df = df.replace([np.inf, -np.inf], np.nan)
    df.dropna(inplace=True)

    df_vals = df[[ticker for ticker in tickers]].pct_change()
    df_vals = df_vals.replace([np.inf, -np.inf], 0)
    df_vals.fillna(0)

    X = df_vals.values
    y = df['{}_target'.format(ticker)].values
    np.nan_to_num(X)
    return X, y, df
#extract_featuresets('XOM')

def do_ml(ticker):

    X, y, df = extract_featuresets(ticker)
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,
                                                                    y,
                                                                    test_size = 0.25)
    clf = neighbors.KNeighborsClassifier()
    clf.fit(X_train, y_train)
    confidence = clf.score(X_test, y_test)
    predictions = clf.predict(X_test)
    print('Predicted spread:', Counter(predictions))

    return confidence

do_ml('BAC')

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float64').

Body:
The first step in solving any problem is recognizing there is one.

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Are you sure that your processed dataframe contains NaN only? There might be the case where you have infinity.
You can check your dataframe, whether it contains infinity or NaN.
To check for NaN present or not, use:

df.isnull().any().any()

If the output is true, you still have NaN present.

To check for infinity present or not, use:

df.isinfinity().any().any()

If you find any of the command's output to be true, then perhaps you should try removing that type of values from the dataframe. Else, please make sure all the values are in range of dtype float64.

Please share your findings!


问:
Convert factor ddmmyyyy:ss:mm:hh to ddmmyyyy format in R
I have factor of date format 30APR2019:00:00:00, how can I convert it to date format ddmmyy in R?

答:
If you want the date back you can convert to date-time using as.POSIXct and then return date

```<code>as.Date(as.POSIXct("30APR2019:00:00:00", format = "%d%b%Y:%T"))
</code>```

If you want it in the specific format, we can use format

```<code>format(as.POSIXct("30APR2019:00:00:00", format = "%d%b%Y:%T"), "%d%m%Y")
</code>```

Body:
If you want the date back you can convert to date-time using as.POSIXct and then return date

as.Date(as.POSIXct("30APR2019:00:00:00", format = "%d%b%Y:%T"))

If you want it in the specific format, we can use format

format(as.POSIXct("30APR2019:00:00:00", format = "%d%b%Y:%T"), "%d%m%Y")


问:
I have a folder that contains multiple folders which contain images. I want to filter the images based on dimensions
This code displays the ImageName and FolderName properly, but the Dimension remains blank.And the data which is displayed properly is not getting saved in a csv file.

Also, If condition based on dimension is not working.

```<code>#-----------powershell script------------
foreach ($folder in $Folders) {
    $Images = Get-ChildItem  -Path $Folder -Filter *.png
    $Results = @()
    foreach ($image  in $Images) {
        $dimensions = $image.Dimensions
        # $dimensions = "$($image.Width) x $($image.Height)"
        If ($dimensions -ne '1000 x 1000') {

            $Results += [pscustomobject]@{
                ImageName  = $image
                FolderName = $Folder
                Dimension  = $dimensions
            }
        }
    }

    $Results | FT -auto

    # $ExcelData= Format-Table -property @{n="$image";e='$Folder'}
    $Results | Export-csv "C:\Users\M1036098\Documents\Imagelessthan1000pi.txt" -NoTypeInformation

}
</code>```

Dimension property in output remains blank

答:
So lets go over why this doesnt work. Get-ChildItem brings back the Object System.Io.FileInfo

System.IO.FileIonfo we can see from Microsoft there is no method or property named Dimensions.

So then lets get those dimensions...

First we are going to load the image into memory and get the size.

```<code>$Folders = @("C:\Test")

$Folders | %{
    $Folder = $_
    Get-ChildItem  -Path $_ -Filter *.png | %{
        try{
            $Image = New-Object System.Drawing.Bitmap "$($_.FullName)"
            [pscustomobject]@{
                ImageName  = $_.Name
                FolderName = $Folder
                Dimension  = "$($Image.Height) x $($Image.Width)"
            }
        }catch{
        }
    } | ?{
        $_.Dimension -ne "1000 x 1000"
    }
}
</code>```

Output looks like

```<code>ImageName     FolderName     Dimension
---------     ----------     ---------
Test1.png     C:\Test        1440 x 2560
Test2.png     C:\Test        1200 x 1200
</code>```

Edit : Adding function for Sonam. Based on a answer that was posted.

```<code>function Get-ImageDimension([string]$Path, [array]$ImageExtensions, [array]$ExcludeDimensions){

    Get-ChildItem -Path $Path -Include $ImageExtensions -Recurse | foreach-object{
        try{
            $image = [Drawing.Image]::FromFile($_);
            [pscustomobject]@{
                ImageName = $_.Name
                FolderName = $_.DirectoryName
                Dimension= "$($image.Width) x $($image.Height)"
            }
        }catch{
        }
    } | ?{
        $ExcludeDimensions -notcontains $_.Dimension
    }
}

Get-ImageDimension C:\Test\ -ImageExtensions *.png -ExcludeDimensions "1000 x 1000" | export-csv C:\Test\Test.csv
</code>```

Body:
This code displays the ImageName and FolderName properly, but the Dimension remains blank.And the data which is displayed properly is not getting saved in a csv file.

Also, If condition based on dimension is not working.

#-----------powershell script------------
foreach ($folder in $Folders) {
    $Images = Get-ChildItem  -Path $Folder -Filter *.png
    $Results = @()
    foreach ($image  in $Images) {
        $dimensions = $image.Dimensions
        # $dimensions = "$($image.Width) x $($image.Height)"
        If ($dimensions -ne '1000 x 1000') {

            $Results += [pscustomobject]@{
                ImageName  = $image
                FolderName = $Folder
                Dimension  = $dimensions
            }
        }
    }

    $Results | FT -auto

    # $ExcelData= Format-Table -property @{n="$image";e='$Folder'}
    $Results | Export-csv "C:\Users\M1036098\Documents\Imagelessthan1000pi.txt" -NoTypeInformation

}

Dimension property in output remains blank

Body:
So lets go over why this doesnt work. Get-ChildItem brings back the Object System.Io.FileInfo

System.IO.FileIonfo we can see from Microsoft there is no method or property named Dimensions.

So then lets get those dimensions...

First we are going to load the image into memory and get the size.

$Folders = @("C:\Test")

$Folders | %{
    $Folder = $_
    Get-ChildItem  -Path $_ -Filter *.png | %{
        try{
            $Image = New-Object System.Drawing.Bitmap "$($_.FullName)"
            [pscustomobject]@{
                ImageName  = $_.Name
                FolderName = $Folder
                Dimension  = "$($Image.Height) x $($Image.Width)"
            }
        }catch{
        }
    } | ?{
        $_.Dimension -ne "1000 x 1000"
    }
}

Output looks like

ImageName     FolderName     Dimension
---------     ----------     ---------
Test1.png     C:\Test        1440 x 2560
Test2.png     C:\Test        1200 x 1200

Edit : Adding function for Sonam. Based on a answer that was posted.

function Get-ImageDimension([string]$Path, [array]$ImageExtensions, [array]$ExcludeDimensions){

    Get-ChildItem -Path $Path -Include $ImageExtensions -Recurse | foreach-object{
        try{
            $image = [Drawing.Image]::FromFile($_);
            [pscustomobject]@{
                ImageName = $_.Name
                FolderName = $_.DirectoryName
                Dimension= "$($image.Width) x $($image.Height)"
            }
        }catch{
        }
    } | ?{
        $ExcludeDimensions -notcontains $_.Dimension
    }
}

Get-ImageDimension C:\Test\ -ImageExtensions *.png -ExcludeDimensions "1000 x 1000" | export-csv C:\Test\Test.csv


问:
Not able to import Python module
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

```<code>project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py
</code>```

This is my testing code

```<code>"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200
</code>```

But when i run it it shows:

```<code>Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'
</code>```

What am I doing wrong here.

答: The best solution would be to make your package installable, rather then fiddle with the PYTHONPATH. See guidelines to python packaging here: https://packaging.python.org/tutorials/packaging-projects/</p>

Title: Not able to import Python module

Body:
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py

This is my testing code

"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200

But when i run it it shows:

Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'

What am I doing wrong here.


问:
Rails query from three models using joins
I have the following models in my Rails application:

```<code>class Test
    has_many :tests_profiles
    has_many :class_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles
</code>```

I must query tests belonging to particular ClassProfile. My present helper function is like this:

```<code>def get_tests(class_profile)
        return Test.joins(:tests_profiles).where(tests_profiles: {class_profile_id: class_profile.id})
</code>```

In my erb file, I am looping through the result like this:

```<code><% tests = get_tests(class_profile) %>
    <% tests.each do |test| %>
        <th><%= test.name %></th>
    <% end %>
</code>```

But the problem here is I am getting all the tests names and not the only ones associated with that particular ClassProfile. How can I correct it so that it functions that way I want it to?

答:
You can use has_many through here:

```<code>class Test
    has_many :tests_profiles
    has_many :class_profiles, through: :tests_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles
    has_many :tests, through: :tests_profiles
</code>```

and use class_profile.tests.each do in the view

Body:
I have the following models in my Rails application:

class Test
    has_many :tests_profiles
    has_many :class_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles

I must query tests belonging to particular ClassProfile. My present helper function is like this:

def get_tests(class_profile)
        return Test.joins(:tests_profiles).where(tests_profiles: {class_profile_id: class_profile.id})

In my erb file, I am looping through the result like this:

<% tests = get_tests(class_profile) %>
    <% tests.each do |test| %>
        <%= test.name %>
    <% end %>

But the problem here is I am getting all the tests names and not the only ones associated with that particular ClassProfile. How can I correct it so that it functions that way I want it to?

Body:
You can use has_many through here:

class Test
    has_many :tests_profiles
    has_many :class_profiles, through: :tests_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles
    has_many :tests, through: :tests_profiles

and use class_profile.tests.each do in the view


问:
Reordering Chart Data Series
How does one reorder series used to create a chart in Excel?

For example, I go to the chart, right click > Select Data. In the left column I see series 1, series 2, to series n.

Say, I want to move series 3 after series 4, can it be done from chart view? I don't want to move the data cells in the worksheet.

I'm using Excel 2011 (mac OS X).

答:
Right-click any series on the chart. In the "Format Data Series" dialog, there is a "Series Order" tab, in which you can move series up and down. I find this much easier than fiddling with the last argument of the series formula.

This is in Excel 2003 in Windows. There is a similar dialog in Excel 2011 for Mac:

Title: Reordering Chart Data Series


问:
How can i improve this guessing algorithm?
I am trying to do a program that guess the word the user think, but right now the program is based only on elimination. Does anyone have an idea on how to make it better?

Here is a brief explanation on how it works now:

I have a list of words stored in "palavras.txt", these words are then transformed into a regular list.

First question is: "How much letters do your word have?". Based on that the program proceed to eliminate all the others words who do not have the same amount of letters. After that it creates a list that contains all the letters organized by the number of times they appear in the given position.

Then we have the second question: "Is the letter "x" the first letter of your word?". If the response is "not" it deletes all the words that contains that letter in that position, then goes to the second letter most used in that position and so on and so on. If yes it deletes all the words that doesn't contain that letter in that specific position and goes to the next letter of the word. And so on until the word is finished.

It works all the times, but sometimes it takes quite a lot of times. Is there a better way do it? AI? Machine learning maybe?

The code is not important since i'm just searching for ideas, but if anyone is curious here is how i did it:

```<code>import os
from unicodedata import normalize
import random
import string

# Define a função que retira os acentos das palavras
def remover_pont(txt):
    import string
    return txt.translate(str.maketrans('', '', string.punctuation))

def remover_acentos(txt):
    return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')

# Retorna uma lista com as letras mais usadas naquela posição, em ordem
def letramusada(lista, pletra):
    pletraordem = []
    pletraordem2 = []
    pl = []

    for n in lista:
        try:
            pl.append(n[pletra - 1])
        except:
            pass

    dict = {}
    for k in pl:
        if k in dict:
            dict[k] += 1
        else:
            dict[k] = 1
    pletraordem2 = (sorted(dict.items(), key=lambda t: t[1], reverse=True))

    for c in pletraordem2:
        pletraordem.append(c[0])

    return pletraordem

# Lê o "banco de dados" que contém as palavras e as armazena na variável "palavras", sem acentos
file = open('palavras.txt')
palavras = file.read().split("\n")

# Armazena a quantidade de letras que a palavra pensada tem
nletras = int(input('Digite o número de letras da palavra (considerando hífen, caso haja) que você pensou, com máximo de 8: '))

# Declara listas que serão usadas em seguida
npalavras = []
palavras2 = []
palavras3 = []
# Armazena todas as palavras que contém a quantidade de letras escolhida anteriormente em uma nova lista chamada "nletras", desconsiderando pontos

for n in palavras:
    if nletras == len(n):
        npalavras.append(remover_acentos(n).lower())

c = 0
n = 0

for k in range(1, nletras + 1):
    ordem = letramusada(npalavras, k)
    cond = 0
    try:
        while cond == 0:
            if  len(npalavras) < 20 and c == 0:
                print("\nHmmm, estou chegando perto!\n")
                c += 1
            if len(npalavras) < 3:
                break
            for c in ordem:
                if c != 0:
                    r = str(input("A {} letra da sua palavra é a letra \"{}\"? [S/N] ".format(k, c))).lower()
                    r = r[0]
                    if r == "s":
                        for n in npalavras:
                            if n[k-1] == c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        ordem.clear()
                        cond += 1
                        break
                    else:
                        for n in npalavras:
                            if n[k-1] != c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        r = 0
                        pass
    except:
        n = 1
        print("\nDesculpe, não achei nenhuma palavra :(")

escolha = random.choice(npalavras)

if n != 0:
    print("\nA palavra que você pensou é: \"{}\"".format(escolha))
</code>```

答: you could store the words that have already been used, like say The first user used the word 'carro', then you could add that to a file, and after a few letters the program could check the list for already said words see if the word matches the description given i.e.: "has a c as first letter", and ask the next user if "carro" is their word, you could improve this further by adding a counter to each word, so that words that are more used appear on top of words that are less used.</p>

Body:
I am trying to do a program that guess the word the user think, but right now the program is based only on elimination. Does anyone have an idea on how to make it better?

Here is a brief explanation on how it works now:

I have a list of words stored in "palavras.txt", these words are then transformed into a regular list.

First question is: "How much letters do your word have?". Based on that the program proceed to eliminate all the others words who do not have the same amount of letters. After that it creates a list that contains all the letters organized by the number of times they appear in the given position.

Then we have the second question: "Is the letter "x" the first letter of your word?". If the response is "not" it deletes all the words that contains that letter in that position, then goes to the second letter most used in that position and so on and so on. If yes it deletes all the words that doesn't contain that letter in that specific position and goes to the next letter of the word. And so on until the word is finished.

It works all the times, but sometimes it takes quite a lot of times. Is there a better way do it? AI? Machine learning maybe?

The code is not important since i'm just searching for ideas, but if anyone is curious here is how i did it:

import os
from unicodedata import normalize
import random
import string

# Define a função que retira os acentos das palavras
def remover_pont(txt):
    import string
    return txt.translate(str.maketrans('', '', string.punctuation))

def remover_acentos(txt):
    return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')

# Retorna uma lista com as letras mais usadas naquela posição, em ordem
def letramusada(lista, pletra):
    pletraordem = []
    pletraordem2 = []
    pl = []

    for n in lista:
        try:
            pl.append(n[pletra - 1])
        except:
            pass

    dict = {}
    for k in pl:
        if k in dict:
            dict[k] += 1
        else:
            dict[k] = 1
    pletraordem2 = (sorted(dict.items(), key=lambda t: t[1], reverse=True))

    for c in pletraordem2:
        pletraordem.append(c[0])

    return pletraordem

# Lê o "banco de dados" que contém as palavras e as armazena na variável "palavras", sem acentos
file = open('palavras.txt')
palavras = file.read().split("\n")

# Armazena a quantidade de letras que a palavra pensada tem
nletras = int(input('Digite o número de letras da palavra (considerando hífen, caso haja) que você pensou, com máximo de 8: '))

# Declara listas que serão usadas em seguida
npalavras = []
palavras2 = []
palavras3 = []
# Armazena todas as palavras que contém a quantidade de letras escolhida anteriormente em uma nova lista chamada "nletras", desconsiderando pontos

for n in palavras:
    if nletras == len(n):
        npalavras.append(remover_acentos(n).lower())

c = 0
n = 0

for k in range(1, nletras + 1):
    ordem = letramusada(npalavras, k)
    cond = 0
    try:
        while cond == 0:
            if  len(npalavras) < 20 and c == 0:
                print("\nHmmm, estou chegando perto!\n")
                c += 1
            if len(npalavras) < 3:
                break
            for c in ordem:
                if c != 0:
                    r = str(input("A {} letra da sua palavra é a letra \"{}\"? [S/N] ".format(k, c))).lower()
                    r = r[0]
                    if r == "s":
                        for n in npalavras:
                            if n[k-1] == c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        ordem.clear()
                        cond += 1
                        break
                    else:
                        for n in npalavras:
                            if n[k-1] != c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        r = 0
                        pass
    except:
        n = 1
        print("\nDesculpe, não achei nenhuma palavra :(")

escolha = random.choice(npalavras)

if n != 0:
    print("\nA palavra que você pensou é: \"{}\"".format(escolha))


问:
ASP.Net Core authenticate with AAD and B2C
We have a web api written in ASP.Net Core 2.2 and we want to authenticate users against either an AAD or a B2C. This means we have some endpoints that can be accessed only by AAD users, others by B2C users and some by both.

In Startup.cs we have

```<code>services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
</code>```

Individually these work, but when we try to add the configuration for both at the same time, neither works.

I have also tried

```<code>services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   .AddAzureADBearer(options => Configuration.Bind("AzureAd", options))
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
</code>```

But neither seems to work. How do we get this going?

答:
I too faced similar problem and achieved by custom policy. Below is the Authentication code.

```<code>public static void AddAuthorization(this IServiceCollection services, IConfigurationRoot configuration)
    {
        services.AddAuthentication()
            .AddJwtBearer("AAD", options =>
            {
                options.MetadataAddress = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"] +
                                          "/v2.0/.well-known/openid-configuration";
                options.Authority = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"];
                options.Audience = configuration["AzureAd:ClientId"];
                options.TokenValidationParameters =
                    new TokenValidationParameters
                    {
                        ValidIssuer = $"https://sts.windows.net/{configuration["AzureAd:TenantId"]}/",
                    };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context => Task.CompletedTask,
                    OnChallenge = context => Task.CompletedTask,
                    OnAuthenticationFailed = (context) =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return Task.CompletedTask;
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("Validated: " + context.SecurityToken);
                        return Task.CompletedTask;
                    }
                };
            })
            .AddJwtBearer("B2C", options =>
        {
            options.Authority = configuration["AzureAdB2C:Instance"] + configuration["AzureAdB2C:Domain"] + "/" + configuration["AzureAdB2C:SignUpSignInPolicyId"] + "/v2.0";
            options.Audience = configuration["AzureAdB2C:ClientId"];

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context => Task.CompletedTask,
                OnChallenge = context => Task.CompletedTask,
                OnAuthenticationFailed = (context) =>
                {
                    Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    Console.WriteLine("Validated: " + context.SecurityToken);
                    return Task.CompletedTask;
                }
            };
        });
        services
            .AddAuthorization(options =>
            {
                options.AddPolicy("AADUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("AAD")
                    .Build());

                options.AddPolicy("B2CUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("B2C")
                    .Build());
            });
    }
</code>```

In the startup.cs add below code in ConfigureServices

```<code>services.AddAuthorization(Configuration);
</code>```

Now in your controller you can decorate like this based on AD or B2CAD

```<code>[Authorize(Policy = "B2CUsers")] // For B2C authentication
[Authorize(Policy = "AADUsers")] // For AAD authentication
</code>```

Body:
We have a web api written in ASP.Net Core 2.2 and we want to authenticate users against either an AAD or a B2C. This means we have some endpoints that can be accessed only by AAD users, others by B2C users and some by both.

In Startup.cs we have

services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

Individually these work, but when we try to add the configuration for both at the same time, neither works.

I have also tried

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   .AddAzureADBearer(options => Configuration.Bind("AzureAd", options))
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

But neither seems to work. How do we get this going?

Body:
I too faced similar problem and achieved by custom policy. Below is the Authentication code.

public static void AddAuthorization(this IServiceCollection services, IConfigurationRoot configuration)
    {
        services.AddAuthentication()
            .AddJwtBearer("AAD", options =>
            {
                options.MetadataAddress = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"] +
                                          "/v2.0/.well-known/openid-configuration";
                options.Authority = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"];
                options.Audience = configuration["AzureAd:ClientId"];
                options.TokenValidationParameters =
                    new TokenValidationParameters
                    {
                        ValidIssuer = $"https://sts.windows.net/{configuration["AzureAd:TenantId"]}/",
                    };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context => Task.CompletedTask,
                    OnChallenge = context => Task.CompletedTask,
                    OnAuthenticationFailed = (context) =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return Task.CompletedTask;
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("Validated: " + context.SecurityToken);
                        return Task.CompletedTask;
                    }
                };
            })
            .AddJwtBearer("B2C", options =>
        {
            options.Authority = configuration["AzureAdB2C:Instance"] + configuration["AzureAdB2C:Domain"] + "/" + configuration["AzureAdB2C:SignUpSignInPolicyId"] + "/v2.0";
            options.Audience = configuration["AzureAdB2C:ClientId"];

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context => Task.CompletedTask,
                OnChallenge = context => Task.CompletedTask,
                OnAuthenticationFailed = (context) =>
                {
                    Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    Console.WriteLine("Validated: " + context.SecurityToken);
                    return Task.CompletedTask;
                }
            };
        });
        services
            .AddAuthorization(options =>
            {
                options.AddPolicy("AADUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("AAD")
                    .Build());

                options.AddPolicy("B2CUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("B2C")
                    .Build());
            });
    }

In the startup.cs add below code in ConfigureServices

services.AddAuthorization(Configuration);

Now in your controller you can decorate like this based on AD or B2CAD

[Authorize(Policy = "B2CUsers")] // For B2C authentication
[Authorize(Policy = "AADUsers")] // For AAD authentication


问:
Output on a newline
Write a statement that prints the following on a single output line. End with a newline.
3 2 1 Go!
Note: Whitespace (blank spaces / blank lines) matters; make sure your whitespace exactly matches the expected output.

java homework

```<code>public class OutputExample {
   public static void main(String [] args) {

      System.out.print(321);
      System.out.print(\n + "Go");
      System.out.print("!");

      return;
   }
}
</code>```

Output is nearly correct; but whitespace differs. See highlights below.
Special character legend

Your output

  321Go!

  Expected output

  3 2 1 Go!

答:
The problem is that you are trying to print an Integer when you write

System.out.print(321);

Solution:

System.out.print("3 2 1 ");

System.out.print("Go!");

Good luck!

Title: Output on a newline

Body:
Write a statement that prints the following on a single output line. End with a newline.
3 2 1 Go!
Note: Whitespace (blank spaces / blank lines) matters; make sure your whitespace exactly matches the expected output.

java homework

public class OutputExample {
   public static void main(String [] args) {

      System.out.print(321);
      System.out.print(\n + "Go");
      System.out.print("!");

      return;
   }
}

Output is nearly correct; but whitespace differs. See highlights below.
Special character legend

Your output

  321Go!

  Expected output

  3 2 1 Go!


答:
We can use sub to strip off the substring

```<code>sub(":.*", "","30APR2019:00:00:00")
#"30APR2019"
</code>```

Or with substring

```<code>substr("30APR2019:00:00:00", 1, 9)
</code>```

Or using strptime

```<code>format( strptime("30APR2019:00:00:00", format = "%d%b%Y:%T"), "%d%b%Y")
#[1] "30Apr2019"
</code>```

Or another option with anydate from anytime

```<code>library(anytime)
anydate("30APR2019:00:00:00")
#[1] "2019-04-30"
</code>```

Or with lubridate and format

```<code>library(lubridate)
format(dmy_hms("30APR2019:00:00:00"), "%d%b%Y")
#[1] "30Apr2019"
</code>```

and wrap with format if needed

Title: Convert factor ddmmyyyy:ss:mm:hh to ddmmyyyy format in R

Body: I have factor of date format 30APR2019:00:00:00, how can I convert it to date format ddmmyy in R?

Body:
We can use sub to strip off the substring

sub(":.*", "","30APR2019:00:00:00")
#"30APR2019"

Or with substring

substr("30APR2019:00:00:00", 1, 9)

Or using strptime

format( strptime("30APR2019:00:00:00", format = "%d%b%Y:%T"), "%d%b%Y")
#[1] "30Apr2019"

Or another option with anydate from anytime

library(anytime)
anydate("30APR2019:00:00:00")
#[1] "2019-04-30"

Or with lubridate and format

library(lubridate)
format(dmy_hms("30APR2019:00:00:00"), "%d%b%Y")
#[1] "30Apr2019"

and wrap with format if needed


问:
LUIS Usage Status
In Azure Portal, I have created Web App Bot using Basic Bot template which includes LUIS creation automatically.

LUIS has Free2 - Web/Container comes with 10,000 transactions* free per month (https://azure.microsoft.com/en-in/pricing/details/cognitive-services/language-understanding-intelligent-services/).

a. How to I see my usage of the 10,000 transactions?
b. In my Azure Cost & Billing, I do not see the LUIS except the Bot Service, App Service and App Service Plan.

Thanks.

答:
In the Azure Portal, under the list of resources there should be a Cognitive Services resource for luis, usually it will have the -luis suffix. Under the overview tab of this resource you will be able see your current usage:

In terms of viewing your LUIS costs, these can be accessed from under the Cost & Billing > Cost anaylsis section:

Title: LUIS Usage Status


问:
OpenGL 3.2 in Delphi 2009 using FastMM 4.97 problem with UBOs in FullDebugMode
I'm sitting with an OpenGL 3.2 application in Delphi 2009. When using FastMM 4.97 with FullDebugMode defined the UBOs does not get their data properly. With FullDebugMode undefined everything works like a charm.

Example:
Setting the viewport dimensions pointing to two private integer fields, FWidth and FHeight, in our render frame class.

```<code>glBufferSubData(GL_UNIFORM_BUFFER, VUniform.Offset, VUniform.Size, @FWidth);
</code>```

I've been pulling my hair over this issue for a few days now and I really don't know how to proceed. I'm not expecting full OpenGL support here but hopefully someone can come with some suggestion based on known differences between running in FullDebugMode and not.

Project settings:

```<code>[Compiling]
Optimization    False
Stack frames    True
Use debug .dcus True
[Linking]
Debug info      True
Map file        Detailed
</code>```

OS is Windows 7 64 bit.

Edit:
Found it!
It had nothing at all to do with OpenGL. Elsewhere in our codebase a function returned a PAnsiChar using Result := @AnsiString(Object.Name)[1]; This worked most of the time running normally since the memory was only released but unchanged. In FullDebugMode the data was overwritten with $80 sequence when freed.

答:
You are probably looking at memory that has been freed prematurely (by your own application).

Normally, you'd still be able to access the old values until they are overwritten by a new allocation + writes. This could very well allow your application to run properly, even though you are accessing stale (freed) parts of memory.

However, in FullDebugMode, deallocated memory is filled with a byte $80 sequence. You can easily check for this if you know the exact call to glBufferSubData that breaks, simply take a look at the memory at that point.

Body:
I'm sitting with an OpenGL 3.2 application in Delphi 2009. When using FastMM 4.97 with FullDebugMode defined the UBOs does not get their data properly. With FullDebugMode undefined everything works like a charm.

Example:
Setting the viewport dimensions pointing to two private integer fields, FWidth and FHeight, in our render frame class.

glBufferSubData(GL_UNIFORM_BUFFER, VUniform.Offset, VUniform.Size, @FWidth);

I've been pulling my hair over this issue for a few days now and I really don't know how to proceed. I'm not expecting full OpenGL support here but hopefully someone can come with some suggestion based on known differences between running in FullDebugMode and not.

Project settings:

[Compiling]
Optimization    False
Stack frames    True
Use debug .dcus True
[Linking]
Debug info      True
Map file        Detailed

OS is Windows 7 64 bit.

Edit:
Found it!
It had nothing at all to do with OpenGL. Elsewhere in our codebase a function returned a PAnsiChar using Result := @AnsiString(Object.Name)[1]; This worked most of the time running normally since the memory was only released but unchanged. In FullDebugMode the data was overwritten with $80 sequence when freed.