问:
Handle Change of FormControl React
Hey so I have a text box/FormControl that's supposed to update a field in a json in this.state. I was wondering if there was a better way to do onChange?

```<code><FormControl
  type='text'
  placeholder='enter'
  defaultValue={this.state.form.name}
  onChange={this.handleChange.bind(this, 'name')}
/>
</FormGroup>
</code>```

`

```<code>handleChange(change, event) {
    var toChange = this.state.form;
    toChange[change] = event.target.value;
    this.setState({form: toChange});
  }
</code>```

答:
If your function is relatively simple you can simplify further,

```<code>onChange = { (event) => { this.myValue = event.target.value } }
</code>```

or if you're passing up the props hierarchy, e.g.

```<code>onChange = { (event) => { this.props.onMyFunc(event.target.value) } }
</code>```

Title: Handle Change of FormControl React

Body:
Hey so I have a text box/FormControl that's supposed to update a field in a json in this.state. I was wondering if there was a better way to do onChange?

<FormControl
  type='text'
  placeholder='enter'
  defaultValue={this.state.form.name}
  onChange={this.handleChange.bind(this, 'name')}
/>
</FormGroup>

`

handleChange(change, event) {
    var toChange = this.state.form;
    toChange[change] = event.target.value;
    this.setState({form: toChange});
  }

Body:
If your function is relatively simple you can simplify further,

onChange = { (event) => { this.myValue = event.target.value } }

or if you're passing up the props hierarchy, e.g.

onChange = { (event) => { this.props.onMyFunc(event.target.value) } }


来源: stackexchange

问:
How to use values of a column in a dataframe?
I have a data like this;

```<code>t1<-structure(list(`12/2018` = structure(list(Date = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("12/31/2018",
"3/11/2011"), class = "factor"), X. = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "-", class = "factor"),
    Value = c(0.2, 0, 0.1, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Date",
"X.", "Value"), row.names = c(NA, 13L), class = "data.frame"),
    `3/2011` = structure(list(Date = structure(c(2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("12/31/2018",
    "3/11/2011"), class = "factor"), X. = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "-", class = "factor"),
        Value = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Date",
    "X.", "Value"), row.names = 14:26, class = "data.frame")), .Names = c("12/2018",
"3/2011"))
</code>```

And I want to create a dataframe by considering date column for both 2 objects in the list like below;

```<code>df<-data.frame("Day" = , "Month" = , "Year" = )
</code>```

答:
To collapse the list into a dataframe, you could use rbind():

t2 <- rbind(t1$`12/2018`,t1$`3/2011`)

EDIT:
In the comments, OP mentioned that they want to do this for arbitrary columns.

For this, use do.call(). You may also want to remove the row names:

```<code>t2 <- do.call(t1,rbind)
rownames(t2) <- c()
</code>```

There are other questions on Stack Overflow which explain how to split columns, so I linked one in the comments.

ContentLicense: CC BY-SA 4.0

Body:
I have a data like this;

t1<-structure(list(`12/2018` = structure(list(Date = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("12/31/2018",
"3/11/2011"), class = "factor"), X. = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "-", class = "factor"),
    Value = c(0.2, 0, 0.1, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Date",
"X.", "Value"), row.names = c(NA, 13L), class = "data.frame"),
    `3/2011` = structure(list(Date = structure(c(2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("12/31/2018",
    "3/11/2011"), class = "factor"), X. = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "-", class = "factor"),
        Value = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Date",
    "X.", "Value"), row.names = 14:26, class = "data.frame")), .Names = c("12/2018",
"3/2011"))

And I want to create a dataframe by considering date column for both 2 objects in the list like below;

df<-data.frame("Day" = , "Month" = , "Year" = )

Body:
To collapse the list into a dataframe, you could use rbind():

t2 <- rbind(t1$`12/2018`,t1$`3/2011`)

EDIT:
In the comments, OP mentioned that they want to do this for arbitrary columns.

For this, use do.call(). You may also want to remove the row names:

t2 <- do.call(t1,rbind)
rownames(t2) <- c()

There are other questions on Stack Overflow which explain how to split columns, so I linked one in the comments.


问:
CommandManager.InvalidateRequerySuggested does not cause a requery on CanExecute in MVVM-Light
I am using MVVM-Light RelayCommand

```<code>private ICommand myRevertCmd;
public ICommand Revert
    {
        get
        {
            if (myRevertCmd == null)
            {
                myRevertCmd = new RelayCommand(RevertExecute, CanRevertExecute);
            }

            return myRevertCmd;
        }
    }

    private void RevertExecute()
    {
        searchType = SearchType.Revert;
        SearchStart();
    }

    private bool CanRevertExecute()
    {
        return isRevertEnabled;
    }
</code>```

I have some code that changes the value of isRevertEnabled but the linked button does not change. After some searching I found that you can use to force the re-evaluation of the button states

```<code>// force the GUI to re-evaluate the state of the buttons
CommandManager.InvalidateRequerySuggested();
</code>```

But this doesn't work. Does any one have any suggestions?

答: I guess you can call "Revert.RaiseCanExecuteChanged()" method at "isRevertEnabled" INPC (or dependency property) set method. This will force the "CanRevertExecute" predicate.

ContentLicense: CC BY-SA 3.0

Body:
I am using MVVM-Light RelayCommand

private ICommand myRevertCmd;
public ICommand Revert
    {
        get
        {
            if (myRevertCmd == null)
            {
                myRevertCmd = new RelayCommand(RevertExecute, CanRevertExecute);
            }

            return myRevertCmd;
        }
    }

    private void RevertExecute()
    {
        searchType = SearchType.Revert;
        SearchStart();
    }

    private bool CanRevertExecute()
    {
        return isRevertEnabled;
    }

I have some code that changes the value of isRevertEnabled but the linked button does not change. After some searching I found that you can use to force the re-evaluation of the button states

// force the GUI to re-evaluate the state of the buttons
CommandManager.InvalidateRequerySuggested();

But this doesn't work. Does any one have any suggestions?


问:
Creating new app with laravel/installer shows just file structure not website
I just decide to start learning Laravel. By following Getting Started most easy solution for me seems to be to start using laravel installer.

So what I did was installed installer globally and then simply created new project via laravel new laravelapi.

After cli prepare it I edited .env file with my database info and changed APP_URL to http://localhost/laravelapi/ (I'm using XAMPP and laravelapi is name of my project). Unfortunately when I opened browser on that URL I just see the files, not a rendered website.

Funny thing is that when i open http://localhost/laravelapi/server.php site load correctly (it's just some trivial laravel default page)

I was wondering if htaccess works correctly I tried to check if my apache has mod_rewrite as one of his loaded module but it was there.

I am really new in it and I obviously missed something important, but I fight here with it for couple hours without any result. Does anyone face this issue before? If so what was the solution?

答:
I got the same issue were two reasons behind the error.
one is not a proper .htaccess file placed in the root directory.
other php version is not compatible with your laravel current version (low PHP version).


问:
Firestore Cloud Functions, which is better Multiple Functions or One Big Function?
My Question is, would it be better to combine Functions that use the same .document & .onUpdate into one big function or have them seperated into small modules of functions?

For example i have two functions that both listen to onUpdate on Users:

```<code>export const firstUserFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ role: string }>change.after.data();
   const oldValue = <{ role: string }>change.before.data();
   if ((oldValue.role === '1' && newValue.role === '2')) {
       // do something
   }
})
export const secondUserFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ template: string }>change.after.data();
   if (newValue.template === 'x') {
       // do something
   }
})
</code>```

If we look at the pricing, then it would make sense to make combined functions like this:

```<code>export const combinedFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ role: string, template: string }>change.after.data();
   const oldValue = <{ role: string }>change.before.data();

   if ((oldValue.role === '1' && newValue.role === '2')) {
       // do something
   }

   if (newValue.template === 'x') {
       // do something
   }
})
</code>```

instead of small ones, but are there any disadvantages of having bigger ones?

If its better to combine them, what would you consider the limit?

答:
It will depend on the specific case. For example, if both the functions would always be called, than it would make sense for you to combine them, since they will be run always together and one function would work.

However, in case both functions will not be run always, it would make sense to have them split, since they will run depending on the situation. In your case, for example, if always the functions firstUserFunction and secondUserFunction will run at the same time, makes sense to combine, so you can save money and processing.

Let me know if the information helped you!

Body:
My Question is, would it be better to combine Functions that use the same .document & .onUpdate into one big function or have them seperated into small modules of functions?

For example i have two functions that both listen to onUpdate on Users:

export const firstUserFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ role: string }>change.after.data();
   const oldValue = <{ role: string }>change.before.data();
   if ((oldValue.role === '1' && newValue.role === '2')) {
       // do something
   }
})
export const secondUserFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ template: string }>change.after.data();
   if (newValue.template === 'x') {
       // do something
   }
})

If we look at the pricing, then it would make sense to make combined functions like this:

export const combinedFunction = functions.firestore
   .document('users/{userId}')
   .onUpdate((change, context) => {
   const newValue = <{ role: string, template: string }>change.after.data();
   const oldValue = <{ role: string }>change.before.data();

   if ((oldValue.role === '1' && newValue.role === '2')) {
       // do something
   }

   if (newValue.template === 'x') {
       // do something
   }
})

instead of small ones, but are there any disadvantages of having bigger ones?

If its better to combine them, what would you consider the limit?


问:
Use fixture only one time in a parametrized function
I want to read a multiline string from a serial port and then compare it line by line with a reference .txt file.
The compare function itself uses a second .txt file, where I define what operation should be done with each line (e.g. 1:1 diff or compare a value with a tolerance) - my ids file.

For this line by line thing, I parametrized my test_function with a line parameter. So I can assert each line. The problem now is, that each time my fixture is called again, and it cost some time to read out the serial port.

Is there a smoother way than my current workaround?

```<code>#test_class.py
import pytest
import serial

buffered_port_readback = []

@pytest.mark.basic
@pytest.mark.parametrize("line", range(8))
def test_portname_command(fix_port_readback, fix_port_reference, fix_port_ids, line):
    if (line == 0):
        get_port_readback(fix_port_readback)
    port_compare(fix_port_reference[line], fix_port_ids[line], buffered_port_readback[line])
</code>```

```<code>#conftest.py
import pytest
import serial
import os
import datetime
import socket
import subprocess
import sys

@pytest.fixture(scope="function")
def fix_port_readback(request, fix_port_command, fix_port, line):
    if(line == 0):
        fix_port.reset_input_buffer()
        fix_port.write(fix_port_command)
        readback = fix_port.read_until(b'usb>')
        readback_decode = readback.decode("utf-8")
        readback_lines = readback_decode.split("\n")

        new_readback_lines = []
        for entry in readback_lines:
            mod_entry = entry.replace('\r', '')
            new_readback_lines.append(mod_entry)

        return new_readback_lines
</code>```

As you can see my current workaround is to read the port only in the first loop by making sure line == 0 and save that in a buffer. I think that's not the best way.

答:
The simplest would probably be to increase the scope of your fixtures, the granularity is a bit limited (class, module, package and session) but if it works....

A related alternative is to have your function fixture depend on a larger "cache" fixture and inspect the request, that way it can check the properties of the requester and either create a new value or get one from the cache.

Finally, the "big hammer" is to dynamically generate fixture result by plugging into pytest_fixture_setup or pytest_generate_tests, something like that, and then do whatever you want on the fly.

Body:
I want to read a multiline string from a serial port and then compare it line by line with a reference .txt file.
The compare function itself uses a second .txt file, where I define what operation should be done with each line (e.g. 1:1 diff or compare a value with a tolerance) - my ids file.

For this line by line thing, I parametrized my test_function with a line parameter. So I can assert each line. The problem now is, that each time my fixture is called again, and it cost some time to read out the serial port.

Is there a smoother way than my current workaround?

#test_class.py
import pytest
import serial

buffered_port_readback = []

@pytest.mark.basic
@pytest.mark.parametrize("line", range(8))
def test_portname_command(fix_port_readback, fix_port_reference, fix_port_ids, line):
    if (line == 0):
        get_port_readback(fix_port_readback)
    port_compare(fix_port_reference[line], fix_port_ids[line], buffered_port_readback[line])

#conftest.py
import pytest
import serial
import os
import datetime
import socket
import subprocess
import sys

@pytest.fixture(scope="function")
def fix_port_readback(request, fix_port_command, fix_port, line):
    if(line == 0):
        fix_port.reset_input_buffer()
        fix_port.write(fix_port_command)
        readback = fix_port.read_until(b'usb>')
        readback_decode = readback.decode("utf-8")
        readback_lines = readback_decode.split("\n")

        new_readback_lines = []
        for entry in readback_lines:
            mod_entry = entry.replace('\r', '')
            new_readback_lines.append(mod_entry)

        return new_readback_lines

As you can see my current workaround is to read the port only in the first loop by making sure line == 0 and save that in a buffer. I think that's not the best way.


问:
I am trying to add specific handlers and alertStyles to my alerts, but I am using a global alert which doesn't have a handler
Is there any separate global function to add a different style and a different handler for alerts?
My function from AppDelegate looks like this:

```<code>static func showAlertView(vc : UIViewController, titleString : String , messageString: String) ->()
 {
   let alertView = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)

   let alertAction = UIAlertAction(title: "ok", style: .cancel) { (alert) in
      vc.dismiss(animated: true, completion: nil)
   }
     alertView.addAction(alertAction)
     vc.present(alertView, animated: true, completion: nil)
 }
</code>```

答:
You just need to add more parameters to your function. In the code below I've added the following: controllerStyle for UIAlertController, actionStyle for UIAlertAction and action for UIAlertAction handler.

```<code>static func showAlertView(vc : UIViewController, titleString : String , messageString: String, controllerStyle: UIAlertController.Style = .alert, actionStyle: UIAlertAction.Style = .cancel, action:  @escaping () -> () = {}) {
    let alertView = UIAlertController(title: titleString, message: messageString, preferredStyle: controllerStyle)
    let alertAction = UIAlertAction(title: "ok", style: .cancel) { (alert) in
        if action == {} {
            vc.dismiss(animated: true, completion: nil)
        } else {
            action()
        }
    }
    alertView.addAction(alertAction)
    vc.present(alertView, animated: true, completion: nil)
}
</code>```

Body:
Is there any separate global function to add a different style and a different handler for alerts?
My function from AppDelegate looks like this:

static func showAlertView(vc : UIViewController, titleString : String , messageString: String) ->()
 {
   let alertView = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)

   let alertAction = UIAlertAction(title: "ok", style: .cancel) { (alert) in
      vc.dismiss(animated: true, completion: nil)
   }
     alertView.addAction(alertAction)
     vc.present(alertView, animated: true, completion: nil)
 }

Body:
You just need to add more parameters to your function. In the code below I've added the following: controllerStyle for UIAlertController, actionStyle for UIAlertAction and action for UIAlertAction handler.

static func showAlertView(vc : UIViewController, titleString : String , messageString: String, controllerStyle: UIAlertController.Style = .alert, actionStyle: UIAlertAction.Style = .cancel, action:  @escaping () -> () = {}) {
    let alertView = UIAlertController(title: titleString, message: messageString, preferredStyle: controllerStyle)
    let alertAction = UIAlertAction(title: "ok", style: .cancel) { (alert) in
        if action == {} {
            vc.dismiss(animated: true, completion: nil)
        } else {
            action()
        }
    }
    alertView.addAction(alertAction)
    vc.present(alertView, animated: true, completion: nil)
}


问:
Seeking Core Data model design advice
I have the following modeling problem in Core Data. A Student can take Lessons.
A Lesson has the following fields:

```title
date
grade
type```

A Lesson can be one of three types:

lessontype1:

```subtype11 subtype12 subtype13
```

lessontype2:

```
subtype21 subtype22 subtype23 subtype24
```

lessontype3:

``` subtype31 subtype32 subtype33 subtype34 subtype35
```

How do I set the lesson.type to any of these three types of Lessons? Is there a better way to model this scenario?

答:
The details of your model depend on details of the data you are modeling.

If the types are just markers that have no logic or behavior associated with them, then the simplest model would be:

```<code>Student{
    lessons<-->>Lesson.student
}

Lesson{
    title:string
    date:date
    grade:number
    type:string
    subtype:string
    student<<-->Student.lessons
}
</code>```

If the lessons have some kind of behavior associated with each type, then you could create subentities for each type of lesson.

```<code>Lesson{
    title:string
    date:date
    grade:number
    student<<-->Student.lessons
}

TypeOne:Lesson{

}

TypeOneSubOne:TypeOne{

}

// ...etc
</code>```

Since all the Lesson subentities inherit from  Lesson, they can inherit the relationship as well. All the different subentities can be in the Student.lesson relationship.

If the types of lessons have behaviors associated with them, you can break them out into separate entities as well.

```<code>Lesson{
    title:string
    date:date
    grade:number
    type<<-->Type.lessons
    student<<-->Student.lessons
}

Type{
    lessons<-->>Lesson.type
}

TypeOne:Type{

}

TypeOneSubOne:TypeOne{

}
</code>```

A Core Data model is intended to simulate real-world objects, events or conditions and the relationships between them. The first step in designing a model is to understand those real-world things and the relationships between them.

Title: Seeking Core Data model design advice

Body:
I have the following modeling problem in Core Data. A Student can take Lessons.
A Lesson has the following fields:

title
date
grade
type

A Lesson can be one of three types:

lessontype1:

subtype11 subtype12 subtype13

lessontype2:

subtype21 subtype22 subtype23 subtype24

lessontype3:

 subtype31 subtype32 subtype33 subtype34 subtype35

How do I set the lesson.type to any of these three types of Lessons? Is there a better way to model this scenario?

Body:
The details of your model depend on details of the data you are modeling.

If the types are just markers that have no logic or behavior associated with them, then the simplest model would be:

Student{
    lessons<-->>Lesson.student
}

Lesson{
    title:string
    date:date
    grade:number
    type:string
    subtype:string
    student<<-->Student.lessons
}

If the lessons have some kind of behavior associated with each type, then you could create subentities for each type of lesson.

Lesson{
    title:string
    date:date
    grade:number
    student<<-->Student.lessons
}

TypeOne:Lesson{

}

TypeOneSubOne:TypeOne{

}

// ...etc

Since all the Lesson subentities inherit from  Lesson, they can inherit the relationship as well. All the different subentities can be in the Student.lesson relationship.

If the types of lessons have behaviors associated with them, you can break them out into separate entities as well.

Lesson{
    title:string
    date:date
    grade:number
    type<<-->Type.lessons
    student<<-->Student.lessons
}

Type{
    lessons<-->>Lesson.type
}

TypeOne:Type{

}

TypeOneSubOne:TypeOne{

}

A Core Data model is intended to simulate real-world objects, events or conditions and the relationships between them. The first step in designing a model is to understand those real-world things and the relationships between them.


问:
How To Parse Response of Multiple Types of Single Key
How To Parse Response of Multiple Types?

Key is like (suppose student_list is a key of list types when student_list is empty then it makes as a string like student_list=""), How to manage this types of response using Retrofit? I am using MVVM Model with retrofit.

My Response:

when I get Data into the List

```<code>{
    "status": 200,
    "data": [
        {
            "prod_month_total": 2989.61,
            "product": "GAS"
        },
        {
            "prod_month_total": 39566.22,
            "product": "OIL"
        },
        {
            "prod_month_total": 83912.55,
            "product": "OTHER"
        }
    ]
}
</code>```

when List is Empty Then Response:

```<code>{"status":404,"data":"No result found"}
</code>```

I am getting this Error:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 23 path $.data

答:
first create the right model calss use this site http://www.jsonschema2pojo.org

than use

```<code>`if( reponce.isSucessful){

if(responce.status==200){
   //code here
  }
else{
 // find the error
}
 }else
 {
//
 }`
</code>```

Body:
How To Parse Response of Multiple Types?

Key is like (suppose student_list is a key of list types when student_list is empty then it makes as a string like student_list=""), How to manage this types of response using Retrofit? I am using MVVM Model with retrofit.

My Response:

when I get Data into the List

{
    "status": 200,
    "data": [
        {
            "prod_month_total": 2989.61,
            "product": "GAS"
        },
        {
            "prod_month_total": 39566.22,
            "product": "OIL"
        },
        {
            "prod_month_total": 83912.55,
            "product": "OTHER"
        }
    ]
}

when List is Empty Then Response:

{"status":404,"data":"No result found"}

I am getting this Error:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 23 path $.data

Body:
first create the right model calss use this site http://www.jsonschema2pojo.org

than use

`if( reponce.isSucessful){

if(responce.status==200){
   //code here
  }
else{
 // find the error
}
 }else
 {
//
 }`


问:
Flutter - Overlay card widget on a container
In flutter, is it possible to place a part of a card on another container? In CSS, we would set margin-top to a negative value or use translate property. In flutter as we cannot set negative values to margin-top, is there an alternative to that?

答:
Here is running example with overlay:

```<code>class _MyHomePageState extends State<MyHomePage> {
     double _width = 0.0;
     double _height = 0.0;

     @override
     Widget build(BuildContext context) {
      _width = MediaQuery.of(context).size.width;
      _height = MediaQuery.of(context).size.height;
      return Scaffold(
       backgroundColor: Colors.white,
       body: Stack(
        children: <Widget>[
          // The containers in the background and scrollable
         getScrollableBody(),

         // This container will work as Overlay
         getOverlayWidget()
        ],
      ),
   );
 }

 Widget getOverlayWidget() {
   return new Container(
     alignment: Alignment.bottomCenter,
     child: new Container(
      height: 100.0,
      width: _width,
      color: Colors.cyan.withOpacity(0.4),
     ),
   );
 }
 Widget getScrollableBody() {
  return SingleChildScrollView(
    child: new Column(
      children: <Widget>[
        new Container(
         height: _height * .65,
         color: Colors.yellow,
       ),
       new Container(
         height: _height * .65,
         color: Colors.brown,
       ),
       new Container(
        margin: EdgeInsets.only(bottom: 100.0),
        height: _height * .65,
        color: Colors.orange,
       ),
     ],
   ),
  );
 }
}
</code>```

Here is Result of code:
Scrollable Body under customised Bottom Bar

Body:
Here is running example with overlay:

class _MyHomePageState extends State<MyHomePage> {
     double _width = 0.0;
     double _height = 0.0;

     @override
     Widget build(BuildContext context) {
      _width = MediaQuery.of(context).size.width;
      _height = MediaQuery.of(context).size.height;
      return Scaffold(
       backgroundColor: Colors.white,
       body: Stack(
        children: <Widget>[
          // The containers in the background and scrollable
         getScrollableBody(),

         // This container will work as Overlay
         getOverlayWidget()
        ],
      ),
   );
 }

 Widget getOverlayWidget() {
   return new Container(
     alignment: Alignment.bottomCenter,
     child: new Container(
      height: 100.0,
      width: _width,
      color: Colors.cyan.withOpacity(0.4),
     ),
   );
 }
 Widget getScrollableBody() {
  return SingleChildScrollView(
    child: new Column(
      children: <Widget>[
        new Container(
         height: _height * .65,
         color: Colors.yellow,
       ),
       new Container(
         height: _height * .65,
         color: Colors.brown,
       ),
       new Container(
        margin: EdgeInsets.only(bottom: 100.0),
        height: _height * .65,
        color: Colors.orange,
       ),
     ],
   ),
  );
 }
}

Here is Result of code:
Scrollable Body under customised Bottom Bar


问:
How do I get the direct URL from an indirect URL? Python webscraping
I'm attempting to scrape URLs based on google searches. However, the URL I am scraping has an arrow in it and seems to be a Google redirect page:

'uk.linkedin.com › pauljgarner'

What I want is the direct link:

https://www.linkedin.com/in/pauljgarner/?originalSubdomain=uk

Here is my code. I am unsure of how to modify it to get the direct link. I would greatly appreciate your help.

```<code>from selenium import webdriver
driver = webdriver.Chrome('/Users/yu/Downloads/chromedriver')
driver.get('https:www.google.com')

##inputting google search##
search_query = driver.find_element_by_name('q')
search_query.send_keys(parameters.search_query)
search_query.send_keys(Keys.RETURN)

linkedin_urls = driver.find_elements_by_xpath(".//div[@class='TbwUpd NJjxre']")
linkedin_urls = [url.text for url in linkedin_urls]

for linkedin_url in linkedin_urls:
    driver.get(linkedin_url)
    ##getting an error on this line (likely because the url is a redirect)

linkedin_url
</code>```

I've seen a few posts about transforming the redirect link into a direct link via the use of add-ons (Grease Monkey), but haven't figured how to use them. Would prefer an answer that I could modify the code with (if possible). Thanks

答:
After finding the appropriate elements, why don't you use get_attribute() to find the href link.
You could just use
if you just want the first URL:

```<code>linkedin_urls=driver.find_elements_by_xpath('//*[@id="rso"]/div[1]/div/div/a')
linkedin_urls=[url.get_attribute('href') for url in linkedin_urls]
</code>```

if you want all the URLS:

```<code>linkedin_urls=driver.find_elements_by_xpath('//*[@id="rso"]/div/div/div/a')
linkedin_urls=[url.get_attribute('href') for url in linkedin_urls]
</code>```

get_attribute() in Python

Body:
I'm attempting to scrape URLs based on google searches. However, the URL I am scraping has an arrow in it and seems to be a Google redirect page:

'uk.linkedin.com › pauljgarner'

What I want is the direct link:

https://www.linkedin.com/in/pauljgarner/?originalSubdomain=uk

Here is my code. I am unsure of how to modify it to get the direct link. I would greatly appreciate your help.

from selenium import webdriver
driver = webdriver.Chrome('/Users/yu/Downloads/chromedriver')
driver.get('https:www.google.com')

##inputting google search##
search_query = driver.find_element_by_name('q')
search_query.send_keys(parameters.search_query)
search_query.send_keys(Keys.RETURN)

linkedin_urls = driver.find_elements_by_xpath(".//div[@class='TbwUpd NJjxre']")
linkedin_urls = [url.text for url in linkedin_urls]

for linkedin_url in linkedin_urls:
    driver.get(linkedin_url)
    ##getting an error on this line (likely because the url is a redirect)

linkedin_url

I've seen a few posts about transforming the redirect link into a direct link via the use of add-ons (Grease Monkey), but haven't figured how to use them. Would prefer an answer that I could modify the code with (if possible). Thanks

Body:
After finding the appropriate elements, why don't you use get_attribute() to find the href link.
You could just use
if you just want the first URL:

linkedin_urls=driver.find_elements_by_xpath('//*[@id="rso"]/div[1]/div/div/a')
linkedin_urls=[url.get_attribute('href') for url in linkedin_urls]

if you want all the URLS:

linkedin_urls=driver.find_elements_by_xpath('//*[@id="rso"]/div/div/div/a')
linkedin_urls=[url.get_attribute('href') for url in linkedin_urls]

get_attribute() in Python


问:
Laravel Queues Not adding Jobs in Database
I have enabled Laravel Queues but the Jobs is not adding inside mine database:

here is the steps what i have follow:

```<code>php artisan queue:table

php artisan migrate
</code>```

in .env file i have changed QUEUE_CONNECTION=database

In mine controller:

```<code>    CreateCoinImage::dispatch()
                ->delay(now()->addMinutes(1));
</code>```

Do anyone know why the Queues is not working

答:
When you want to use queue:table, make sure your .env file has register the queue driver to database

QUEUE_DRIVER=database

Body:
I have enabled Laravel Queues but the Jobs is not adding inside mine database:

here is the steps what i have follow:

php artisan queue:table

php artisan migrate

in .env file i have changed QUEUE_CONNECTION=database

In mine controller:

    CreateCoinImage::dispatch()
                ->delay(now()->addMinutes(1));

Do anyone know why the Queues is not working


问:
Initializing a 2D array of pointer of type double through double pointer with structure
I am doing something like following;

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}
</code>```

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

答:
You have not allocated memory to your comm variable.

Also count is uninitialized.

Body:
I am doing something like following;

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?


问:
Feather js disable some methods typescript
How can i disable some methods (get, remove) in feather js.

I using mongodb.

I want disable all methods only allow (post, patch)

答:
The way to enforce this is with a before hook.

You can use the disallow hook from feathers-hooks-common as one (good) way.

https://feathers-plus.github.io/v1/feathers-hooks-common/#disallow

```<code>const { disallow } = require('feathers-hooks-common');
...
app.use('myservice', ...);
const service = app.service('myservice');
service.hooks({
  // only allow create(post) and patch
  before: {
    get: disallow(),
    find: disallow(),
    remove: disallow(),
    update: disallow()
  }
});
</code>```

Body:
The way to enforce this is with a before hook.

You can use the disallow hook from feathers-hooks-common as one (good) way.

https://feathers-plus.github.io/v1/feathers-hooks-common/#disallow

const { disallow } = require('feathers-hooks-common');
...
app.use('myservice', ...);
const service = app.service('myservice');
service.hooks({
  // only allow create(post) and patch
  before: {
    get: disallow(),
    find: disallow(),
    remove: disallow(),
    update: disallow()
  }
});


问:
Vue centralize scroll- and resize-events (avoiding repetition in components)
I have a Vue-structure like this:

```<code>App
 |--{ data: { scrollInfo {...} } }
 |
 |--Component1
 |      |--{ data: { sidebarWidth: 500 }
 |
 |--Component2
 |      |--{ data: { overlayItemWidth: 389 }
 |
 |--Component3
 ...
 ...
</code>```

In each of my components, I have elements that has variables that should change on scroll and resize (such as sidebarWidth or overlayItemWidth ). I found this post here that shows this way of adding a listener for scroll and resize.

I've added it to the main instance, like so:

```<code>data: {
  scrollInfo: {
    scrollFromTop: 0,
    viewportHeight: 0,
    viewportWidth: 0,
    pageHeight: 0
  }
},
created() {
  window.addEventListener( 'scroll', this.calculateScroll );
  window.addEventListener( 'resize', this.calculateViewport );
  window.addEventListener( 'resize', this.calculatePageScrollSpecs );
  this.calculateViewport();
  this.calculateScroll();
  this.calculatePageScrollSpecs();
},
destroyed() {
  window.removeEventListener( 'scroll', this.calculateScroll );
  window.removeEventListener( 'resize', this.calculateViewport );
  window.removeEventListener( 'resize', this.calculatePageScrollSpecs );
}
</code>```

I wont show the contents of the methods (calculateScroll, calculateViewport, ... ), since it's not relevant to this question.

Now... In my components I have variables that should change and reevaluate on scroll and on resize as well. But every time I have such a variable, then I currently add those same listeners in created and destroyed, and then add the same event-listeners to the given component, and then do the calculations from a new method in there. It seems long and clumbsy.

Are there a way that I can get around having those window.AddEventListeners in each component, but only have those in my root instance?

... I was thinking, if I had an array of 'things-that-need-to-be-recalculated-on-scroll-or-resize' in my main instance, but I'm not sure if it would get cluttered, since the variables for the components then actually wouldn't be kept in the component, but instead be referenced with this.$root.sidebarWidth. And this would also make my main instance massive.

Any suggestions?

答:
Glad you found a solution for yourself, but for future visitors who may want a little more comfortable/general solution: I had the same problem some months ago and put a Vue mixin on npm that does exactly this — handling global data once-per-lifetime, not once per mounted component.

It's called Reactivator and this is how you'd create a global handler for window.resize with it:

```<code>// viewport-width.js

export default {
  // Reactivator uses `getInitialState` to fetch the
  // initial value before any listener was attached.
  getInitialState() {
    return window.innerWidth
  },

  // Reactivator calls `listen` when the first component using
  // it is created and executes the returned cleanup callback
  // when it's the last component using it is destroyed.
  listen(set) {
    const resizeHandler = () => set(window.innerWidth)

    window.addEventListener('resize', resizeHandler)

    return () => window.removeEventListener('resize', resizeHandler)
  }
}

// component.js

import reactivator from 'vue-reactivator'
import viewportWidth from './viewport-width.js'

export default {
  mixins: [
    // `viewportWidth` will now be a reactive property in this component!
    reactivator({ viewportWidth })
  ]
}
</code>```

That said, watching viewport size is such a common case that I have put it (and other useful things like scroll position or mouse position) in an extra package of common Reactivator implementations. You can find it on npm as vue-browser-state.

Body:
I have a Vue-structure like this:

App
 |--{ data: { scrollInfo {...} } }
 |
 |--Component1
 |      |--{ data: { sidebarWidth: 500 }
 |
 |--Component2
 |      |--{ data: { overlayItemWidth: 389 }
 |
 |--Component3
 ...
 ...

In each of my components, I have elements that has variables that should change on scroll and resize (such as sidebarWidth or overlayItemWidth ). I found this post here that shows this way of adding a listener for scroll and resize.

I've added it to the main instance, like so:

data: {
  scrollInfo: {
    scrollFromTop: 0,
    viewportHeight: 0,
    viewportWidth: 0,
    pageHeight: 0
  }
},
created() {
  window.addEventListener( 'scroll', this.calculateScroll );
  window.addEventListener( 'resize', this.calculateViewport );
  window.addEventListener( 'resize', this.calculatePageScrollSpecs );
  this.calculateViewport();
  this.calculateScroll();
  this.calculatePageScrollSpecs();
},
destroyed() {
  window.removeEventListener( 'scroll', this.calculateScroll );
  window.removeEventListener( 'resize', this.calculateViewport );
  window.removeEventListener( 'resize', this.calculatePageScrollSpecs );
}

I wont show the contents of the methods (calculateScroll, calculateViewport, ... ), since it's not relevant to this question.

Now... In my components I have variables that should change and reevaluate on scroll and on resize as well. But every time I have such a variable, then I currently add those same listeners in created and destroyed, and then add the same event-listeners to the given component, and then do the calculations from a new method in there. It seems long and clumbsy.

Are there a way that I can get around having those window.AddEventListeners in each component, but only have those in my root instance?

... I was thinking, if I had an array of 'things-that-need-to-be-recalculated-on-scroll-or-resize' in my main instance, but I'm not sure if it would get cluttered, since the variables for the components then actually wouldn't be kept in the component, but instead be referenced with this.$root.sidebarWidth. And this would also make my main instance massive.

Any suggestions?

Body:
Glad you found a solution for yourself, but for future visitors who may want a little more comfortable/general solution: I had the same problem some months ago and put a Vue mixin on npm that does exactly this — handling global data once-per-lifetime, not once per mounted component.

It's called Reactivator and this is how you'd create a global handler for window.resize with it:

// viewport-width.js

export default {
  // Reactivator uses `getInitialState` to fetch the
  // initial value before any listener was attached.
  getInitialState() {
    return window.innerWidth
  },

  // Reactivator calls `listen` when the first component using
  // it is created and executes the returned cleanup callback
  // when it's the last component using it is destroyed.
  listen(set) {
    const resizeHandler = () => set(window.innerWidth)

    window.addEventListener('resize', resizeHandler)

    return () => window.removeEventListener('resize', resizeHandler)
  }
}

// component.js

import reactivator from 'vue-reactivator'
import viewportWidth from './viewport-width.js'

export default {
  mixins: [
    // `viewportWidth` will now be a reactive property in this component!
    reactivator({ viewportWidth })
  ]
}

That said, watching viewport size is such a common case that I have put it (and other useful things like scroll position or mouse position) in an extra package of common Reactivator implementations. You can find it on npm as vue-browser-state.


问:
IMAP folder/messages synchronization strategy?
I'm about to add IMAP email integration to one of our web applications (ASP.NET / SQL Server). I'm already using a commercial library which exposes the most important IMAP functionality: get folder list, get message headers, get mime message etc.)

Getting email data "live" from the IMAP server works very well. But here comes the difficult task: I have to keep the email/folders caching SQL database synchronized to the IMAP server (I have to show data applying different criteria).

Our database schema essentially contains a "Folders" and an "Emails" table. The "Emails" table contains primarily header information like "FromAddress", "FromName", "IsRead", "IsAnswered", "IsForwarded", "HasAttachments" etc. (without the email content or attachments).

I have to consider two major scenarios:

Getting all messages the first time (or after a user re-organized the folders)

Getting new/recent messages

What would be a good synchronization strategy for keeping the mail server and database server up-to-date, considering that performance is a major design criterion (I can't just query/compare thousands of messages every time I connect, in order to find out if the user moved or deleted some old emails).

Thanks!

答:
From your library's feature list:

Better UniqueId Support:  We've added
  even more options for requesting a
  message's unique id. You can now
  return the UniqueId in a message's
  DataTable for return trips to the IMAP
  server.

And:

Retrieve only New Messages

Search Flagged Messages

Mark/Unmark Messages as Read

It looks to me as though your library has all the support you need to keep your SQL server synchronized.  You can programmatically mark messages as read, and the library supports retrieval of only new messages.  That takes care of your second item.

Your strategy will depend partly on how your solution works.  If I read your question correclty, your users manage their email on the IMAP server, and your SQL Server is "subscribed" to the IMAP server, from a syncronization perspective.

If this is correct, then synchronization is effectively a background task.  My approach would be to synchronize using an event model on a user-by-user basis.  If possible, "notify" the synchronization program when there is activity (new/deleted emails) for a user.  Add a synchronization "job" to a background process that batches synch jobs together.  A notification model will ensure that the synch program only works on users that need a synch.

Small new/deleted email synch jobs go to one "processor" and larger jobs like total resynch and folder reorganization go to another.  Really big resynch jobs may have to be split up in order to keep overall throughput high.  The "small job" and "big job" processors could be two different services, or possibly two different threads depending on performance and design considerations.

OwnerDisplayName: splattne

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: splattne

OwnerDisplayName: Dave


问:
Explanation of p-value in ols_step_forward_p function of olsrr package
Consider the following example:-(taken from the e.g. of R documentation)

```<code>model <- lm(y ~ ., data = surgical)
ols_step_forward_p(model)
</code>```

The documentation says that it will be employing the Forward Stepwise method to select the final model. If I am not wrong, doesn't this forward selection is based on observing the p values of the following test statistic:-

where we are considering a model with K predictors all total. RSS denotes the residual sum of squares and the subscript p and K denote the RSS of a model with p and K predictors respectively.

If I do not give the command penter in ols_step_forward_p function what default p-value is chosen?

答:
ols_step_forward_p has documentation here (also via ?olsrr::ols_step_forward_p if you have the package installed)

The second entry ("S3 method for default") says

ols_step_forward_p(model, penter = 0.3,
    progress = FALSE, details = FALSE, ...)

(emphasis added).

This means that the default value of penter is 0.3.

To see in more detail what's going on, you can look at the code for olsrr::ols_step_forward_p.default. Here's the relevant code export::

```<code>for (i in seq_len(len_p)) {
            predictors <- c(preds, all_pred[i])
            m <- lm(paste(response, "~", paste(predictors, collapse = " + ")),
                l)
            m_sum <- Anova(m)
            pvals[i] <- m_sum$`Pr(>F)`[ppos]
        }
</code>```

So you can see that the p-value is based on the F-test from car::Anova. See ?car::Anova.lm for more details ...

Body:
Consider the following example:-(taken from the e.g. of R documentation)

model <- lm(y ~ ., data = surgical)
ols_step_forward_p(model)

The documentation says that it will be employing the Forward Stepwise method to select the final model. If I am not wrong, doesn't this forward selection is based on observing the p values of the following test statistic:-

where we are considering a model with K predictors all total. RSS denotes the residual sum of squares and the subscript p and K denote the RSS of a model with p and K predictors respectively.

If I do not give the command penter in ols_step_forward_p function what default p-value is chosen?

Body:
ols_step_forward_p has documentation here (also via ?olsrr::ols_step_forward_p if you have the package installed)

The second entry ("S3 method for default") says

ols_step_forward_p(model, penter = 0.3,
    progress = FALSE, details = FALSE, ...)

(emphasis added).

This means that the default value of penter is 0.3.

To see in more detail what's going on, you can look at the code for olsrr::ols_step_forward_p.default. Here's the relevant code export::

for (i in seq_len(len_p)) {
            predictors <- c(preds, all_pred[i])
            m <- lm(paste(response, "~", paste(predictors, collapse = " + ")),
                l)
            m_sum <- Anova(m)
            pvals[i] <- m_sum$`Pr(>F)`[ppos]
        }

So you can see that the p-value is based on the F-test from car::Anova. See ?car::Anova.lm for more details ...


问:
Installation nginx-ingress for Kubernetes Cluster On Premise with CentOS7
I don't sure which installation section is relevant for Cluster On-Premise with CentOS7
in below link
https://kubernetes.github.io/ingress-nginx/deploy/

I tried to install via helm chart, but the service created with type=LoadBalance although the cluster is not on cloud

my questions is:

Helm is the only option to install Nginx not for could (or maybe bare-metal is correct in my case)?

In case of the helm which parameters should be overridden when the helm is installed (service.type etc ...)?

thanks

答:
If you want to use Type=LoadBalancer then I recommend installing METALLB.

MetalLB is a load-balancer implementation for bare metal Kubernetes clusters, using standard routing protocols.

Why?

Kubernetes does not offer an implementation of network load-balancers (Services of type LoadBalancer) for bare metal clusters. The implementations of Network LB that Kubernetes does ship with are all glue code that calls out to various IaaS platforms (GCP, AWS, Azure…). If you’re not running on a supported IaaS platform (GCP, AWS, Azure…), LoadBalancers will remain in the “pending” state indefinitely when created.

Bare metal cluster operators are left with two lesser tools to bring user traffic into their clusters, “NodePort” and “externalIPs” services. Both of these options have significant downsides for production use, which makes bare metal clusters second class citizens in the Kubernetes ecosystem.

MetalLB aims to redress this imbalance by offering a Network LB implementation that integrates with standard network equipment, so that external services on bare metal clusters also “just work” as much as possible.

Instalation guide is here


问:
node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9)
shared.module.ts

```<code>import { animate, state, style, transition, trigger } from '@angular/animations';
import { ToastrModule } from 'ngx-toastr';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
    declarations: [HeaderComponent, SidebarComponent],
    imports: [
        CommonModule,
        RouterModule,
        FormsModule,
        NgxDatatableModule,
        ToastrModule.forRoot() // ToastrModule added
    ],
    exports: [
        HeaderComponent,
        SidebarComponent,
        FormsModule,
        NgxDatatableModule,
        ToastrModule,
    ],
    providers: []
})
</code>```

this is my shared module
i have installed
npm install ngx-toastr --save

npm install @angular/animations --save

But it gives me an error

ERROR in node_modules/@angular/animations/browser/browser.d.ts(135,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/@angular/animations/browser/browser.d.ts(301,9): error TS1086: An accessor cannot be declared in an ambient context.

    node_modules/ngx-toastr/portal/portal.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast.component.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.

Please suggest for this

package.json file

```<code>{
  "name": "mop",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@fortawesome/fontawesome-free": "^5.12.1",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "@swimlane/ngx-datatable": "^16.0.3",
    "angular-font-awesome": "^3.1.2",
    "bootstrap": "^4.4.1",
    "font-awesome": "^4.7.0",
    "line-awesome": "^1.3.0",
    "ng2-bootstrap": "^1.6.3",
    "ngx-cookie-service": "^2.3.0",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.4.0",
    "save": "^2.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.23",
    "@angular/cli": "~8.3.23",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}
</code>```

答: I had the same issue. I've solve it by changing the toastr version in the package.json. I've used this "ngx-toastr": "^10.0.4", instead of this "ngx-toastr": "^12.0.0". And then npm i.</p>

Body:
shared.module.ts

import { animate, state, style, transition, trigger } from '@angular/animations';
import { ToastrModule } from 'ngx-toastr';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
    declarations: [HeaderComponent, SidebarComponent],
    imports: [
        CommonModule,
        RouterModule,
        FormsModule,
        NgxDatatableModule,
        ToastrModule.forRoot() // ToastrModule added
    ],
    exports: [
        HeaderComponent,
        SidebarComponent,
        FormsModule,
        NgxDatatableModule,
        ToastrModule,
    ],
    providers: []
})

this is my shared module
i have installed
npm install ngx-toastr --save

npm install @angular/animations --save

But it gives me an error

ERROR in node_modules/@angular/animations/browser/browser.d.ts(135,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/@angular/animations/browser/browser.d.ts(301,9): error TS1086: An accessor cannot be declared in an ambient context.

    node_modules/ngx-toastr/portal/portal.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast.component.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.

Please suggest for this

package.json file

{
  "name": "mop",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@fortawesome/fontawesome-free": "^5.12.1",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "@swimlane/ngx-datatable": "^16.0.3",
    "angular-font-awesome": "^3.1.2",
    "bootstrap": "^4.4.1",
    "font-awesome": "^4.7.0",
    "line-awesome": "^1.3.0",
    "ng2-bootstrap": "^1.6.3",
    "ngx-cookie-service": "^2.3.0",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.4.0",
    "save": "^2.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.23",
    "@angular/cli": "~8.3.23",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}


问:
setState removes an items from an array using filter but removed item stays in state as an empty string
In the state of the component I have an array of todo items received from MongoDB via axios. The list in array is rendered using map method into an unsorted list ( is just an icon in this case):

```<code><ul>
  {this.state.items.map(e => (
    <li key={e._id}>
      {e.name}
      <i onClick={() => this.removeItem(e._id)}
      ></i>
    </li>
  ))}
</ul>
</code>```

I then need to remove an item using onClick. I'm deleting the item using axios from DB and then filtering the item out of the array in state by the id:

```<code>removeItem = e => {
  axios
    .delete(`${process.env.REACT_APP_API_URL}/items/${e}`)
    .then(res => {
      let newItems = this.state.items;
      newItems.filter(item => item._id !== res.data._id);
      this.setState({ items: newItems });
    })
    .catch(err => console.log(err));
}
</code>```

when I click on the icon in it removes the item from the array. However the
 element of that item remains in DOM with a blanc value.
When inspecting the state I noticed that after the array item is removed the state has an empty string instead of this item (which I guess is then still rendered but without a value.

Screenshot of the inspector

After page refresh it is completely gone. It looks like setState doesn't re-renders the DOM in my case and I can't figure out why.

答:
Filter method returns a new array, to avoid side effects I would write it this way:

```<code>...
.then(res => {
   const newItems = this.state.items.filter(item => item._id !== res.data._id)

   this.setState({ items: newItems });
 })
...
</code>```

And to be sure that state is a reference to the component state at the time the change is being applied (as API request may take some time), I suggest:

```<code>...
.then(res => {
   this.setState(state => {
      return {
         items: state.items.filter(item => item._id !== res.data._id)
       }
   ))
 })
...
</code>```

I am not 100% sure that it is an issue, it would be nice to have a working snippet, but you can try it.

Body:
In the state of the component I have an array of todo items received from MongoDB via axios. The list in array is rendered using map method into an unsorted list ( is just an icon in this case):

  {this.state.items.map(e => (

      {e.name}
       this.removeItem(e._id)}
      >

  ))}

I then need to remove an item using onClick. I'm deleting the item using axios from DB and then filtering the item out of the array in state by the id:

removeItem = e => {
  axios
    .delete(`${process.env.REACT_APP_API_URL}/items/${e}`)
    .then(res => {
      let newItems = this.state.items;
      newItems.filter(item => item._id !== res.data._id);
      this.setState({ items: newItems });
    })
    .catch(err => console.log(err));
}

when I click on the icon in it removes the item from the array. However the
 element of that item remains in DOM with a blanc value.
When inspecting the state I noticed that after the array item is removed the state has an empty string instead of this item (which I guess is then still rendered but without a value.

Screenshot of the inspector

After page refresh it is completely gone. It looks like setState doesn't re-renders the DOM in my case and I can't figure out why.

Body:
Filter method returns a new array, to avoid side effects I would write it this way:

...
.then(res => {
   const newItems = this.state.items.filter(item => item._id !== res.data._id)

   this.setState({ items: newItems });
 })
...

And to be sure that state is a reference to the component state at the time the change is being applied (as API request may take some time), I suggest:

...
.then(res => {
   this.setState(state => {
      return {
         items: state.items.filter(item => item._id !== res.data._id)
       }
   ))
 })
...

I am not 100% sure that it is an issue, it would be nice to have a working snippet, but you can try it.


问:
Can i substract 2 column given some conditions pandas
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

```<code>def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)
</code>```

but this is a lot slower?

答:
You can do it for all rows then replace ones that don't fit your filter with 0:

```<code> df['X channel view time'] = df['EndTime'] - df['StartTime']
 df.loc[df['Channel'] == 1000, 'X channel view time'] = 0
</code>```

Body:
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)

but this is a lot slower?

Body:
You can do it for all rows then replace ones that don't fit your filter with 0:

 df['X channel view time'] = df['EndTime'] - df['StartTime']
 df.loc[df['Channel'] == 1000, 'X channel view time'] = 0


问:
Displaying a different cursor when the user hovers the mouse over a particular TreeNode control of a TreeView control
I require the cursor of the form to change to the cursor Cursors.Hand when the user hovers the pointer over a node with a specifically named parent node.

The issue I am having in implementing this is regarding changing the cursor back to the default one when the user moves the pointer away from the TreeNode in concern.

I have handled the NodeMouseHover event of the TreeView control (as in the code snippet in the end) to change the pointer to the alternative cursor and back to the default cursor when the pointer is moved to another node, but this does not handle the case when the user moves the pointer away from the nodes to a, say, a blank area of the TreeView control.

My initial, and only, intuition regarding the solution to this problem was to get the location and calculate the area of the TreeNodes which require the cursor to change and check if the pointer is still on one of these on the event handler of the MouseMove event of the TreeView control, but, I believe, this is not an elegant solution as there are a lot of TreeNodes that require this behavior which would require looping through a lot of them for checking, which in turn may cause the application to be, in rare scenarios, a tad non-responsive.

Thanks in advance.

PS The code snippet in question:

```<code>this.treeView.NodeMouseHover += delegate (object sender, TreeNodeMouseHoverEventArgs e)
{
   bool isNewCursorAssigned = false;
   if (e.Node.Parent != null)
   {
      if (e.Node.Parent.Text == "someTxt")
      {
         this.Cursor = Cursors.Hand;
         isNewCursorAssigned = true;
      }
   }
   if (isNewCursorAssigned == false && this.Cursor != this.DefaultCursor)
      this.Cursor = this.DefaultCursor;
};
</code>```

答:
Handle the MouseMove instead, get a Node from the current mouse location, iterate backward to get the Parent (and the parent of the parent if any) of the current Node, and change the Cursor accordingly:

private void treeView1_MouseMove(object sender, MouseEventArgs e)
{
    var node = treeView1.GetNodeAt(e.Location);

    if (node != null)
    {
        var parent = node.Parent;

        while (parent != null)
        {
            if (parent.Text == "someTxt")
            {
                if (Cursor != Cursors.Hand)
                            Cursor = Cursors.Hand;
                        return;
            }
            parent = parent.Parent;
        }
        Cursor = Cursors.Default;
    }
}
```

<p>Also handle the <code>MouseLeave</code> event to check if there's a need to <em>Default</em> the <code>Cursor</code>.</p>

<pre class="lang-cs prettyprint-override"><code>private void treeView1_MouseLeave(object sender, EventArgs e)
{
    if (Cursor != Cursors.Default)
        Cursor = Cursors.Default;
}
</code>```

Or if you prefer the Lambda way:

//In the constructor:

treeView1.MouseMove += (s, e) =>
{
    var node = treeView1.GetNodeAt(e.Location);

    if (node != null)
    {
        var parent = node.Parent;
        while (parent != null)
        {
            if (parent.Text == "someTxt")
            {
                if (Cursor != Cursors.Hand)
                    Cursor = Cursors.Hand;
                return;
            }
            parent = parent.Parent;
        }
        Cursor = Cursors.Default;
    }
};

treeView1.MouseLeave += (s, e) =>
{
    if (Cursor != Cursors.Default)
        Cursor = Cursors.Default;
};
```

Body:
I require the cursor of the form to change to the cursor Cursors.Hand when the user hovers the pointer over a node with a specifically named parent node.

The issue I am having in implementing this is regarding changing the cursor back to the default one when the user moves the pointer away from the TreeNode in concern.

I have handled the NodeMouseHover event of the TreeView control (as in the code snippet in the end) to change the pointer to the alternative cursor and back to the default cursor when the pointer is moved to another node, but this does not handle the case when the user moves the pointer away from the nodes to a, say, a blank area of the TreeView control.

My initial, and only, intuition regarding the solution to this problem was to get the location and calculate the area of the TreeNodes which require the cursor to change and check if the pointer is still on one of these on the event handler of the MouseMove event of the TreeView control, but, I believe, this is not an elegant solution as there are a lot of TreeNodes that require this behavior which would require looping through a lot of them for checking, which in turn may cause the application to be, in rare scenarios, a tad non-responsive.

Thanks in advance.

PS The code snippet in question:

this.treeView.NodeMouseHover += delegate (object sender, TreeNodeMouseHoverEventArgs e)
{
   bool isNewCursorAssigned = false;
   if (e.Node.Parent != null)
   {
      if (e.Node.Parent.Text == "someTxt")
      {
         this.Cursor = Cursors.Hand;
         isNewCursorAssigned = true;
      }
   }
   if (isNewCursorAssigned == false && this.Cursor != this.DefaultCursor)
      this.Cursor = this.DefaultCursor;
};

Body:
Handle the MouseMove instead, get a Node from the current mouse location, iterate backward to get the Parent (and the parent of the parent if any) of the current Node, and change the Cursor accordingly:

private void treeView1_MouseMove(object sender, MouseEventArgs e)
{
    var node = treeView1.GetNodeAt(e.Location);

    if (node != null)
    {
        var parent = node.Parent;

        while (parent != null)
        {
            if (parent.Text == "someTxt")
            {
                if (Cursor != Cursors.Hand)
                            Cursor = Cursors.Hand;
                        return;
            }
            parent = parent.Parent;
        }
        Cursor = Cursors.Default;
    }
}

Also handle the MouseLeave event to check if there's a need to Default the Cursor.

private void treeView1_MouseLeave(object sender, EventArgs e)
{
    if (Cursor != Cursors.Default)
        Cursor = Cursors.Default;
}

Or if you prefer the Lambda way:

//In the constructor:

treeView1.MouseMove += (s, e) =>
{
    var node = treeView1.GetNodeAt(e.Location);

    if (node != null)
    {
        var parent = node.Parent;
        while (parent != null)
        {
            if (parent.Text == "someTxt")
            {
                if (Cursor != Cursors.Hand)
                    Cursor = Cursors.Hand;
                return;
            }
            parent = parent.Parent;
        }
        Cursor = Cursors.Default;
    }
};

treeView1.MouseLeave += (s, e) =>
{
    if (Cursor != Cursors.Default)
        Cursor = Cursors.Default;
};


问:
Get the most common values in a column according to another / Convert pandas series of series into a dictionary of list
Is there an easier way to convert a pandas series of series into a dictionary of lists ignoring the values? Instead of iterating over the series in a for loop?
I want to get the most common values in a dataframe according to a column

df = pd.DataFrame([[1,10],[1,10], [1, 11], [1,11] ,[2,20],[2,21], [3,30], [3,30], [3,31]], columns=['A', 'B'])
common_values = df.groupby(['A'])['B'].value_counts()
common_values = common_values[common_values>1]
```

<p>I want at the end to get</p>

<pre class="lang-py prettyprint-override"><code>{1: [10,11], 3: [30]}
</code>```

答:
Pandas solution is possible, but slowier, because many operiations - created DataFrame from MultiIndex and aggregate list:

```<code>d = common_values.index.to_frame(index=False).groupby('A')['B'].apply(list).to_dict()
print (d)
{1: [10, 11], 3: [30]}
</code>```

So use collections.defaultdict for better performance:

```<code>from collections import defaultdict

d = defaultdict(list)
for a, b in common_values.index:
    d[a].append(b)

d = dict(d)
print (d)
{1: [10, 11], 3: [30]
</code>```

Body:
Is there an easier way to convert a pandas series of series into a dictionary of lists ignoring the values? Instead of iterating over the series in a for loop?
I want to get the most common values in a dataframe according to a column

df = pd.DataFrame([[1,10],[1,10], [1, 11], [1,11] ,[2,20],[2,21], [3,30], [3,30], [3,31]], columns=['A', 'B'])
common_values = df.groupby(['A'])['B'].value_counts()
common_values = common_values[common_values>1]

I want at the end to get

{1: [10,11], 3: [30]}

Body:
Pandas solution is possible, but slowier, because many operiations - created DataFrame from MultiIndex and aggregate list:

d = common_values.index.to_frame(index=False).groupby('A')['B'].apply(list).to_dict()
print (d)
{1: [10, 11], 3: [30]}

So use collections.defaultdict for better performance:

from collections import defaultdict

d = defaultdict(list)
for a, b in common_values.index:
    d[a].append(b)

d = dict(d)
print (d)
{1: [10, 11], 3: [30]


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答: If you absolutely HAVE to log directly to MySQL, consider using two databases. One optimized for quick inserts, which means no keys other than possibly an auto_increment primary key. And another with keys on everything you'd be querying for, optimized for fast searches. A timed job would copy hits from the insert-only to the read-only database on a regular basis, and you end up with the best of both worlds. The only drawback is that your available statistics will only be as fresh as the previous "copy" run.</p>


答:
You were not that far. Syntax is:</p>

```<code>df.loc[df['Channel'] == 1000, 'X channel view time']=df.loc[df['Channel'] == 1000, 'EndTime']-df.loc[df['Channel'] == 1000, 'StartTime']
</code>```

Title: Can i substract 2 column given some conditions pandas

Body:
You were not that far. Syntax is:

df.loc[df['Channel'] == 1000, 'X channel view time']=df.loc[df['Channel'] == 1000, 'EndTime']-df.loc[df['Channel'] == 1000, 'StartTime']


问:
Changing each records int column value by 1 throws a duplicate error
My entity has a column Order which value must be unique. I want to create a function that increments each record's Order by 1:

```<code>MyEntities db = new MyEntities();

var entities = db.Entity.Where(e => e.Order > 10);
foreach (var entity in entities)
{
    entity.Order++;
}
db.SaveChanges();
</code>```

The problem is when saving changes. I get an error that there is a duplicate on column Order. I suspect it saves changes row by row and when it saves the first Order's change the next wasn't processed yet and has the same value. Am I right? How can I overcome this issue?

答:
If not of the suggestions in comments work for you, you could code it at SQL directly like this:

```<code>        string Cmd = "UPDATE Entity SET [Order] = [Order] + 1 WHERE [Order] > 10 ";
        db.Database.ExecuteSqlCommand(Cmd);
</code>```

Or if you want to use EF to select the dataset and construct the SQL Command from that, try something like:

```<code>            var entities = db.Entity.Where(e => e.Order > 10);
            string Cmd = string.Format("UPDATE Entity SET [Order] = [Order] + 1 WHERE [Order] in ({0})",string.Join(",", entities.Select(e => e.Order.ToString()).ToList()));
            db.Database.ExecuteSqlCommand(Cmd);
</code>```

Body:
My entity has a column Order which value must be unique. I want to create a function that increments each record's Order by 1:

MyEntities db = new MyEntities();

var entities = db.Entity.Where(e => e.Order > 10);
foreach (var entity in entities)
{
    entity.Order++;
}
db.SaveChanges();

The problem is when saving changes. I get an error that there is a duplicate on column Order. I suspect it saves changes row by row and when it saves the first Order's change the next wasn't processed yet and has the same value. Am I right? How can I overcome this issue?

Body:
If not of the suggestions in comments work for you, you could code it at SQL directly like this:

        string Cmd = "UPDATE Entity SET [Order] = [Order] + 1 WHERE [Order] > 10 ";
        db.Database.ExecuteSqlCommand(Cmd);

Or if you want to use EF to select the dataset and construct the SQL Command from that, try something like:

            var entities = db.Entity.Where(e => e.Order > 10);
            string Cmd = string.Format("UPDATE Entity SET [Order] = [Order] + 1 WHERE [Order] in ({0})",string.Join(",", entities.Select(e => e.Order.ToString()).ToList()));
            db.Database.ExecuteSqlCommand(Cmd);


问:
How to add milliseconds to a datetime object
I created a datetime object like that:

```<code>dt = datetime(2020,2, 3, 10, 0, 0)
</code>```

which gives me the following output:
2020-02-03 10:00:00

But how can I add milliseconds to that?
So that my output looks like:
2020-02-03 10:00:00:000

Thanks for your help!

答:
Use strftime() to print your datetime in whatever format you want.

The built-in Datetime only really supports six-digit microseconds using strftime(), with the format code %f:

```<code>dt = datetime(2020,2, 3, 10, 0, 0)
dt.strftime('%Y-%m-%d %H:%M:%S:%f')
# '2020-02-03 10:00:00:000000'
</code>```

You can use a string slice to cut off the latter three digits if you want (leaving only the milliseconds):

```<code>dt.strftime('%Y-%m-%d %H:%M:%S:%f')[:-3]
'2020-02-03 10:00:00:000'
</code>```

Body:
I created a datetime object like that:

dt = datetime(2020,2, 3, 10, 0, 0)

which gives me the following output:
2020-02-03 10:00:00

But how can I add milliseconds to that?
So that my output looks like:
2020-02-03 10:00:00:000

Thanks for your help!

Body:
Use strftime() to print your datetime in whatever format you want.

The built-in Datetime only really supports six-digit microseconds using strftime(), with the format code %f:

dt = datetime(2020,2, 3, 10, 0, 0)
dt.strftime('%Y-%m-%d %H:%M:%S:%f')
# '2020-02-03 10:00:00:000000'

You can use a string slice to cut off the latter three digits if you want (leaving only the milliseconds):

dt.strftime('%Y-%m-%d %H:%M:%S:%f')[:-3]
'2020-02-03 10:00:00:000'


问:
Pop-up not be displayed when receiving an achievement using Google Play Games
I have found a bunch of posts with similar issues but most are using BaseGameUtils or GoogleApiClient which I don't have.
One suggested answer was to add, Games.setViewForPopups(getApiClient(), findViewById(R.id.gps_popup)); Which I can't do unless I have GoogleApiClient.

Achievement code:

```<code>public void achieve(String achievement) {
    Games.getAchievementsClient(this, signedInAccount).unlock(achievement);
}

public void increment(String achievement, int i) {
    Games.getAchievementsClient(this, signedInAccount).increment(achievement, i);
}
</code>```

Sign In code:

```<code>@Override
protected void onCreate(Bundle _savedInstanceState) {
    ...
    signInSilently();
}

private void signInSilently() {
    GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    signInClient.silentSignIn().addOnCompleteListener(this,
            new OnCompleteListener<GoogleSignInAccount>() {
                @Override
                public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                    if (task.isSuccessful()) {
                        signedInAccount = task.getResult();
                        findViewById(R.id.achievements_btn).setVisibility(View.VISIBLE);
                    } else {
                        startSignInIntent();
                    }
                }
            });
}

private void startSignInIntent() {
    GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
            GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    Intent intent = signInClient.getSignInIntent();
    startActivityForResult(intent, RC_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            signedInAccount = result.getSignInAccount();
            findViewById(R.id.achievements_btn).setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "Signed In", Toast.LENGTH_SHORT).show();
        } else {
            String message = result.getStatus().getStatusMessage();
            if (message == null || message.isEmpty()) {
                message = "Error";
            }
            Toast.makeText(getApplicationContext(), "Sign In Failed, please check internet connection and restart the app to use achievements.", Toast.LENGTH_LONG).show();
            cancelledSignIn = true;
        }
    }
}

private void showAchievements() {
    Games.getAchievementsClient(this, signedInAccount)
            .getAchievementsIntent()
            .addOnSuccessListener(new OnSuccessListener<Intent>() {
                @Override
                public void onSuccess(Intent intent) {
                    startActivityForResult(intent, RC_ACHIEVEMENT_UI);
                }
            });
}
</code>```

Not sure what to do, this all has worked fine except the pop up never shows. I never had to use GoogleApiClient, if I do need to could you tell me why and how?
All help would be greatly appreciated!

答: If you are testing the game services and Pop-ups are not showing for achievements, the reason could be that you have not added an ICON for that achievement. I have found, Popups are only shown for the achievements with ICON</p>

Body:
I have found a bunch of posts with similar issues but most are using BaseGameUtils or GoogleApiClient which I don't have.
One suggested answer was to add, Games.setViewForPopups(getApiClient(), findViewById(R.id.gps_popup)); Which I can't do unless I have GoogleApiClient.

Achievement code:

public void achieve(String achievement) {
    Games.getAchievementsClient(this, signedInAccount).unlock(achievement);
}

public void increment(String achievement, int i) {
    Games.getAchievementsClient(this, signedInAccount).increment(achievement, i);
}

Sign In code:

@Override
protected void onCreate(Bundle _savedInstanceState) {
    ...
    signInSilently();
}

private void signInSilently() {
    GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    signInClient.silentSignIn().addOnCompleteListener(this,
            new OnCompleteListener<GoogleSignInAccount>() {
                @Override
                public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                    if (task.isSuccessful()) {
                        signedInAccount = task.getResult();
                        findViewById(R.id.achievements_btn).setVisibility(View.VISIBLE);
                    } else {
                        startSignInIntent();
                    }
                }
            });
}

private void startSignInIntent() {
    GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
            GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    Intent intent = signInClient.getSignInIntent();
    startActivityForResult(intent, RC_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            signedInAccount = result.getSignInAccount();
            findViewById(R.id.achievements_btn).setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "Signed In", Toast.LENGTH_SHORT).show();
        } else {
            String message = result.getStatus().getStatusMessage();
            if (message == null || message.isEmpty()) {
                message = "Error";
            }
            Toast.makeText(getApplicationContext(), "Sign In Failed, please check internet connection and restart the app to use achievements.", Toast.LENGTH_LONG).show();
            cancelledSignIn = true;
        }
    }
}

private void showAchievements() {
    Games.getAchievementsClient(this, signedInAccount)
            .getAchievementsIntent()
            .addOnSuccessListener(new OnSuccessListener<Intent>() {
                @Override
                public void onSuccess(Intent intent) {
                    startActivityForResult(intent, RC_ACHIEVEMENT_UI);
                }
            });
}

Not sure what to do, this all has worked fine except the pop up never shows. I never had to use GoogleApiClient, if I do need to could you tell me why and how?
All help would be greatly appreciated!


问:
Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows
```<code><script>
    export default {
        name: "OutPatient",
        data(){
            return{
                out_patients: {}
            }
        },
        methods: {
                index(){
                        axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));

                },
                update(){}
        },
        created(){
                this.index();
        }

    }
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
      <a href="#"><i class="fa fa-edit blue"></i></a>
      |
      <a href="#"><i class="fa fa-trash red"></i></a>
    </td>
</tr>

</code>```

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

答:
```<code>index() {
                this.error = this.out_patients = null;
                this.loading = true;
                axios
                    .get('/data/out_patient')
                    .then(response => {
                        this.loading = false;
                        this.out_patients = response.data;
                    }).catch(error => {
                    this.loading = false;
                    this.error = error.response.data.message || error.message;
                });
            },
</code>```

this rather works for me.
thank you all for the support

Body:
    {{out_patient.id}}
    {{out_patient.first_name}}

      |

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

Body:
index() {
                this.error = this.out_patients = null;
                this.loading = true;
                axios
                    .get('/data/out_patient')
                    .then(response => {
                        this.loading = false;
                        this.out_patients = response.data;
                    }).catch(error => {
                    this.loading = false;
                    this.error = error.response.data.message || error.message;
                });
            },

this rather works for me.
thank you all for the support


问:
Javascript : Increase a Date object by a year
I'm assign a new date object to my object attribute like that :

giftObject.purshasedDate = new Date()

which give a date format :

Date Thu Feb 20 2020 13:36:37 GMT+0100 (heure normale d’Europe
  centrale)

I want to increase this date by one year, I tried :

new Date().setFullYear(giftObject.purshasedDate.getFullYear() + 1) but it give a number serial like this : 1613824899244

I do not understand what that number serial mean! it's a date or should a try some thing else ?

答:
```<code>const oldDate = new Date("Date Thu Feb 20 2020 13:36:37 GMT+0100")
const newDate = oldDate.setFullYear(oldDate.getFullYear() + 1)
const dateWithPlusOneYear = new Date(newDate)
console.log(new Date(dateWithPlusOneYear))
//Sat Feb 20 2021 13:36:37 GMT+0100 (Central European Standard Time)
</code>```


问:
External access for minikube hosted in Azure
I installed minikube in the Azure cloud on an ubuntu machine 18.04. But I do not know how to connect to it through kubectl using real IP of the virtual machine. Using i minikube on virtualbox driver (https://192.168.99.100:8443). Please tell me how to make port forwarding? Thanks. </p>

答:
I tested it and come up with some solutions.

The easiest way to make minikube accessible from your local machine can be achieved by using ssh port forwarding (but you need to remember to have ssh session open all the time and its not really what you want because it will be accessible only from your local machine).

You can run:

```<code>ssh <user>@<azure_vm_ip> -L 8443:192.168.99.100:8443
</code>```

to start port forwarding from your local host to the minikube vm.

You will also need to copy these certificate files from azure vm ~/.minikube/ directory to
you local machine:

```<code>ca.crt
client.crt
client.key
</code>```

also copy .kube/config from azure vm to you local machine and edit paths to certificate files mentioned earlier and change server IP address to localhost.

second way to make it accessible (this time allowing for external access) using ssh port forwarding is possible by doing the following:

In file /etc/ssh/sshd_config on azure vm change GatewayPorts to yes, save file and run

```<code>systemctl restart sshd
</code>```

next, ssh to your azure vm and run:

```<code>ssh -R 0.0.0.0:8443:192.168.99.100:8443 localhost
</code>```

remember about certificate files and change server IP in .kube/config file  public IP of your azure vm.

When trying to connect to minikube form you local machine may see:

```<code>$ kubectl get pods
Unable to connect to the server: x509: certificate is valid for 192.168.99.100, 10.96.0.1, 10.0.0.1, not <your_vm_ip>
</code>```

So you need to either use --insecure-skip-tls-verify flag or generate new valid certificates (or start minikube with --apiserver-ips=<public_ip> and it will generate valid certificate for you).

NOTE: remember to allow ingress traffic to your azure vm on port 8443.

If you don't want to use ssh port forwarding you can use any kind of proxy e.g nginx, that will run on azure vm and forward requests to minkube vm

Probably the best way. Running without a VM:

```<code> sudo minikube start --vm-driver=none --apiserver-ips=<public_ip>
</code>```

--apiserver-ips is needed to generate appropriate certificates.
--vm-driver=none won't create a vbox vm

Now all you need is to copy certificates to your local machine and provide appropriate server ip in .kube/confg file.

Let me know if it was helpful.

Body:
I tested it and come up with some solutions.

The easiest way to make minikube accessible from your local machine can be achieved by using ssh port forwarding (but you need to remember to have ssh session open all the time and its not really what you want because it will be accessible only from your local machine).

You can run:

ssh <user>@<azure_vm_ip> -L 8443:192.168.99.100:8443

to start port forwarding from your local host to the minikube vm.

You will also need to copy these certificate files from azure vm ~/.minikube/ directory to
you local machine:

ca.crt
client.crt
client.key

also copy .kube/config from azure vm to you local machine and edit paths to certificate files mentioned earlier and change server IP address to localhost.

second way to make it accessible (this time allowing for external access) using ssh port forwarding is possible by doing the following:

In file /etc/ssh/sshd_config on azure vm change GatewayPorts to yes, save file and run

systemctl restart sshd

next, ssh to your azure vm and run:

ssh -R 0.0.0.0:8443:192.168.99.100:8443 localhost

remember about certificate files and change server IP in .kube/config file  public IP of your azure vm.

When trying to connect to minikube form you local machine may see:

$ kubectl get pods
Unable to connect to the server: x509: certificate is valid for 192.168.99.100, 10.96.0.1, 10.0.0.1, not <your_vm_ip>

So you need to either use --insecure-skip-tls-verify flag or generate new valid certificates (or start minikube with --apiserver-ips=<public_ip> and it will generate valid certificate for you).

NOTE: remember to allow ingress traffic to your azure vm on port 8443.

If you don't want to use ssh port forwarding you can use any kind of proxy e.g nginx, that will run on azure vm and forward requests to minkube vm

Probably the best way. Running without a VM:

 sudo minikube start --vm-driver=none --apiserver-ips=<public_ip>

--apiserver-ips is needed to generate appropriate certificates.
--vm-driver=none won't create a vbox vm

Now all you need is to copy certificates to your local machine and provide appropriate server ip in .kube/confg file.

Let me know if it was helpful.