问:
Flutter List View through Future Provider Value
I am trying to call the output of a Future Provider of type Future> into a List View builder. I think I am very near as I am able to render the final List View itself, however, prior that, an error appears and is quickly replaced by the List View after completing the Future. I believe there may be something wrong with my implementation there.

Here's what I've got so far (these are derivatives of my actual code, there's too many going on there that aren't necessary, I tried to simplify it):

```<code>class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;

    Future<List<Widget>> getList() async{
        List _result = await db....
        _result.forEach((_item){
            addToList(_item);
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return FutureBuilder(
            initialData: <Widget>[],
            future: TempProvider().getList(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.none &&
                    snapshot.hasData == true) {
                    return ListView.builder(
                        itemCount: futureProvider.length,
                        itemBuilder: (BuildContext context, int index) {
                            return futureProvider[index];
                        },
                    );
                } else {
                    return Text('ALAWS');
                }
          },
        );
    }
}
</code>```

So basically, the output of my Future will be a list of widgets that will populate a List View that I am trying to build. Though I am able to render the list view in the end, the error below appears in between:

```<code>The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was
FutureBuilder<List<Widget>>
</code>```

Hoping someone can help with this one or at least give a better example.

Thank you so much!

答:
Not sure but, this is happening because your widget might be building twice and at first futureProvider is null and in second time it has some value.

Workaround:

Replace this:

```<code>futureProvider.length
</code>```

With this:

```<code>futureProvider?.length ?? 0
</code>```

What the above code does?

futureProvider?.length: if futureProvider is null don't access it's length.

Now the value returned will be null.

?? 0: if the value returned is null then return 0;

You need to think over following things and edit your code.

At first place futureProvider should not be null.

Why are you not using snaphot.data when you are using FutureBuilder.

Body:
I am trying to call the output of a Future Provider of type Future> into a List View builder. I think I am very near as I am able to render the final List View itself, however, prior that, an error appears and is quickly replaced by the List View after completing the Future. I believe there may be something wrong with my implementation there.

Here's what I've got so far (these are derivatives of my actual code, there's too many going on there that aren't necessary, I tried to simplify it):

class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;

    Future<List<Widget>> getList() async{
        List _result = await db....
        _result.forEach((_item){
            addToList(_item);
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return FutureBuilder(
            initialData: <Widget>[],
            future: TempProvider().getList(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.none &&
                    snapshot.hasData == true) {
                    return ListView.builder(
                        itemCount: futureProvider.length,
                        itemBuilder: (BuildContext context, int index) {
                            return futureProvider[index];
                        },
                    );
                } else {
                    return Text('ALAWS');
                }
          },
        );
    }
}

So basically, the output of my Future will be a list of widgets that will populate a List View that I am trying to build. Though I am able to render the list view in the end, the error below appears in between:

The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was
FutureBuilder<List<Widget>>

Hoping someone can help with this one or at least give a better example.

Thank you so much!

Body:
Not sure but, this is happening because your widget might be building twice and at first futureProvider is null and in second time it has some value.

Workaround:

Replace this:

futureProvider.length

With this:

futureProvider?.length ?? 0

What the above code does?

futureProvider?.length: if futureProvider is null don't access it's length.

Now the value returned will be null.

?? 0: if the value returned is null then return 0;

You need to think over following things and edit your code.

At first place futureProvider should not be null.

Why are you not using snaphot.data when you are using FutureBuilder.


来源: stackexchange

问:
angular 8 how to disable button of child component that use multiple times in parent component
I have a child component that can be used multiple times in parent component with different action.now How can i disable button that exist in child component when i click on button in parent component.

My child component that can be used multiple times:

import {Component} from 'angular2/core';

```<code>@Component({
    selector: 'my-product',
    template: `<button [disabled]="isDisableButton">select</button>`
})

export class MyCardComponent {
  @Input() isDisableButton = false;
}
</code>```

my parent component html :

```<code><div>
   <p>Product Type 1<p>
  <my-product [isDisableButton]="isDisableType1Button"></my-product>
   <button (click)="onType1()">select type 1</button>
</div>

<div>
    <p>Product  Type 2<p>
  <my-product [isDisableButton]="isDisableType2Button"></my-product>
   <button (click)="onType2()">select type 1</button>
</div>
</code>```

my parent component ts :

```<code>      @Component({
      selector: 'my-parentComponent',
      templateUrl: '..'
    })
    export class PopupDirective {

        isDisableType1Button : boolean;
        isDisableType2Button: boolean;

     onType2(){
        this.isDisableType1Button = true;
        this.isDisableType2Button = false;
         }

    onType1(){
       this.isDisableType2Button = true;
       this.isDisableType1Button = false;
      }

  }
</code>```

this solution is not work correctly

答:
you can do this with component output events, you can read about in the docs.

Below a very clean example to keep it concise:

```<code><button (click)="b.disabled = true">trigger component</button>
<button #b>react on trigger</button>
</code>```

The trigger button (acting as your parent component) has a standard output for the click event. The (inline) event handler is taken a template reference (#b) to directly manipulate the disabled state.

If you translate this to your example, you should implement an output with the EventEmitter.

ContentLicense: CC BY-SA 4.0

Body:
I have a child component that can be used multiple times in parent component with different action.now How can i disable button that exist in child component when i click on button in parent component.

My child component that can be used multiple times:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-product',
    template: `<button [disabled]="isDisableButton">select</button>`
})

export class MyCardComponent {
  @Input() isDisableButton = false;
}

my parent component html :

Product Type 1

  <my-product [isDisableButton]="isDisableType1Button"></my-product>
   <button (click)="onType1()">select type 1</button>

Product  Type 2

  <my-product [isDisableButton]="isDisableType2Button"></my-product>
   <button (click)="onType2()">select type 1</button>

my parent component ts :

      @Component({
      selector: 'my-parentComponent',
      templateUrl: '..'
    })
    export class PopupDirective {

        isDisableType1Button : boolean;
        isDisableType2Button: boolean;

     onType2(){
        this.isDisableType1Button = true;
        this.isDisableType2Button = false;
         }

    onType1(){
       this.isDisableType2Button = true;
       this.isDisableType1Button = false;
      }

  }

this solution is not work correctly

Body:
you can do this with component output events, you can read about in the docs.

Below a very clean example to keep it concise:

<button (click)="b.disabled = true">trigger component</button>
<button #b>react on trigger</button>

The trigger button (acting as your parent component) has a standard output for the click event. The (inline) event handler is taken a template reference (#b) to directly manipulate the disabled state.

If you translate this to your example, you should implement an output with the EventEmitter.


问:
Geo Service wfs : How call by range?
I'm using the API WFS from the French Government to get geographical data. This API use OGC. (https://geoservices.ign.fr/documentation/donnees-ressources-wfs.html)

"IRIS2000" is an acronym which stood for "Islands Grouped for Statistical Information" and which referred to the target size of 2,000 inhabitants per elementary mesh. It is the basic building block for the dissemination of infra-municipal data.

I would like to get all Iris2000 data, but the API deliver 1000 objects maximum by request.
They are 49404 differents Iris2000 and I don't find the range parameter.

Could you help me please ?

答:
WFS is a public international standard, check the specification at http://docs.opengeospatial.org/is/09-025r2/09-025r2.html.

I believe you are looking for paged request support, that is, the startIndex and count parameters: http://docs.opengeospatial.org/is/09-025r2/09-025r2.html#50

Title: Geo Service wfs : How call by range?


问:
Any disadvantages or security issues for having website and databases on separate servers?
We're about to dive into Odoo (OpenERP). We're planning on using Amazon EC2 for the actual installation, and put the postgreSQL database server on Amazon RDS. (like this guide http://toolkt.com/site/install-openerp-server-and-postgresql-on-separate-servers/ )

If the RDS is only allowed to talk to the EC2 server, does this mitigate any security issues compared to a regular Odoo installation (where database and front facing webserver are on the same machine)? Is this an advisable setup?

答:
In short, Nither any Disadvantage nor any security issues.

In Detail Odoo with AWS EC2,

We "SnippetBucket.com" Team had implemeneted already RDS and better know odoo security.

RDS is bit very expensive.

RDS make private instead of public in AWS
make complete secured.

As well AWS Security helps to make extra protection with inbound and outbound ports. Totally Safe.

Note: AWS "RDS Aurora-Postgresql" is 4X faster than official postgresql. AWS RDS support specific versions by AWS.

ContentLicense: CC BY-SA 3.0


问:
How to use zookeeper.net library in a .net core application
The zookeeper.net is a library to work with zookeeper in a .net framework application, I can use it to connect the zookeeper to a .net core application, I can still install the zookeeper.net library, but when I run the code that connect zookeeper, I just got the following exception.

FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

the code I wrote is :

```<code> using (ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
        {
            var stat = zk.Exists("/root", true);
</code>```

Is there a way that I can fix this? or I just can not use this library in .net core?

答: the zookeeper.net is build for .net framework. Currenlty we can not use it in a .net core application. But we can use the zookeeperNetEx to work with zookeeper.</p>

Body:
The zookeeper.net is a library to work with zookeeper in a .net framework application, I can use it to connect the zookeeper to a .net core application, I can still install the zookeeper.net library, but when I run the code that connect zookeeper, I just got the following exception.

FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.

the code I wrote is :

 using (ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
        {
            var stat = zk.Exists("/root", true);

Is there a way that I can fix this? or I just can not use this library in .net core?


问:
Convert an array which contains strings into key value pairs
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

```<code>let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
</code>```

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

答:
Slight change to your code, use reduce instead of map.

let myString = "101-2000-10-102-2000-15";
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = strArray.reduce((acc, curr) => {
  const [a, b, c] = curr.split("-");
  return Object.assign(acc, { [a]: [b, c] });
}, {});
console.log(compartmentMap);```

Body:
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}


问:
Goto the class a method belong in Visual Studio
In Visual Studio, suppose already jump to a method in a very huge C++ class in a header file, how to know which class the method belong to? Now the method is scroll up until the class shows up, but sometimes you miss the class and get into another class's body.</p>

答: At the top of the code panel in visual studio, it shows the details like currently which project you are accessing and at which class you are in and which method you are looking into. Refer the below image,


问:
How to get dynamic shell variable with Ansible playbook and jinja2 templates
I need to call a shell script that will return the private ip of an ec2 in an Ansible task.
Once I get the IP in a variable private_ip_var I want to inject that variable in a jinja2 template to generate a config file.

Here's what I'm thinking:

```<code>- hosts: all
    vars:
    inline_variable: 'hello again'
    tasks:
    - name: Gets the IP of the ec2 instance
    command: get_ec2_private_ip.sh   <----- shell script to dynamically get the ip of ec2
    register: private_ip_var`  <------ saving shell return value to this var

    tasks:
    - name: Inject that private_ip_var into the jinja template
        template:
        src: src=config.cfg.j2
        dest: config.cfg
</code>```

config.cfg.j2

```<code>blah blah
The ip of the ec2 is: {{ private_ip_var }}  <------------ THIS IS WHAT I WANT TO ACHIEVE
Variable given as inline - {{ inline_variable }}  <------------- DONT CARE ABOUT THIS VAR
</code>```

output - config.cfg

```<code>------
blah blah
The ip of the ec2 is: 10-251-50-12  <----------------- THIS IS WHAT I WANT
Variable given as inline - hello again <---------------- DONT CARE ABOUT THIS VAR
</code>```

I don't care about inline_variable above; I only care about private_ip_var; how can I achieve this with Ansible so that i can generate that config file from a jinja2 template?

答:
To get AWS EC2 information, you will need to install the following on your (Linux) host:

boto3

botocore

Python >= 2.6

Then use the module ec2_instance_info. Here is an example:

```<code>ec2_instance_info:
instance_ids:
  - i-23456789
</code>```

Then you can filter on ip address information. You will most likely be interested in the following parameters:

primary (true / false)

Indicates whether this IPv4 address is the primary private IP address of the network interface.

For more examples, check out: https://docs.ansible.com/ansible/latest/modules/ec2_instance_info_module.html#examples

Body:
I need to call a shell script that will return the private ip of an ec2 in an Ansible task.
Once I get the IP in a variable private_ip_var I want to inject that variable in a jinja2 template to generate a config file.

Here's what I'm thinking:

- hosts: all
    vars:
    inline_variable: 'hello again'
    tasks:
    - name: Gets the IP of the ec2 instance
    command: get_ec2_private_ip.sh   <----- shell script to dynamically get the ip of ec2
    register: private_ip_var`  <------ saving shell return value to this var

    tasks:
    - name: Inject that private_ip_var into the jinja template
        template:
        src: src=config.cfg.j2
        dest: config.cfg

config.cfg.j2

blah blah
The ip of the ec2 is: {{ private_ip_var }}  <------------ THIS IS WHAT I WANT TO ACHIEVE
Variable given as inline - {{ inline_variable }}  <------------- DONT CARE ABOUT THIS VAR

output - config.cfg

------
blah blah
The ip of the ec2 is: 10-251-50-12  <----------------- THIS IS WHAT I WANT
Variable given as inline - hello again <---------------- DONT CARE ABOUT THIS VAR

I don't care about inline_variable above; I only care about private_ip_var; how can I achieve this with Ansible so that i can generate that config file from a jinja2 template?

Body:
To get AWS EC2 information, you will need to install the following on your (Linux) host:

boto3

botocore

Python >= 2.6

Then use the module ec2_instance_info. Here is an example:

ec2_instance_info:
instance_ids:
  - i-23456789

Then you can filter on ip address information. You will most likely be interested in the following parameters:

primary (true / false)

Indicates whether this IPv4 address is the primary private IP address of the network interface.

For more examples, check out: https://docs.ansible.com/ansible/latest/modules/ec2_instance_info_module.html#examples


问:
Making an animating main menu
What would be the best way to make a main menu for a game? I would prefer it to be UIButtons. More specifically, what would be the best way of animating the buttons? For example, an animation on the view load of the buttons going in, then the buttons going out when a menu option is selected and then new buttons (the submenu) animated back in. I have never done any animating before so I would like to know the best way. Thanks</p>

答:
This type of animation is very easy using UIKit:

```<code>[UIView animateWithDuration:0.5 animations:^{
    button1.frame = <new frame>;
    button2.frame = <new frame>;
}];
</code>```

This will animate the frame from the current frame, to the specified frame over the given duration (0.5 seconds). If the current frame is offscreen and the new frame is the final position you want then the buttons will move to their correct position over 0.5 seconds.

The following properties of UIView are animatable in this fashion:

frame

bounds

center

transform

alpha

backgroundColor

contentStretch

The Animations section of the View Programming Guide has more info.

Title: Making an animating main menu

Body:
This type of animation is very easy using UIKit:

[UIView animateWithDuration:0.5 animations:^{
    button1.frame = <new frame>;
    button2.frame = <new frame>;
}];

This will animate the frame from the current frame, to the specified frame over the given duration (0.5 seconds). If the current frame is offscreen and the new frame is the final position you want then the buttons will move to their correct position over 0.5 seconds.

The following properties of UIView are animatable in this fashion:

frame

bounds

center

transform

alpha

backgroundColor

contentStretch

The Animations section of the View Programming Guide has more info.


问:
Python - How do I do conditional counting of rows based on various columns?
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

```<code>A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4
</code>```

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

答:
Here's how I would do this. Use df.loc to filter down to the desired Types and then groupby and count :)

```<code>import pandas as pd
from io import StringIO

# Getting a df in the right form
s = """Sample | Type | Date | Strike
A | F | 1 Jun 2020 |
A | C | 1 Jun 2020 | 5
A | P | 1 Jun 2020 | 2.5
A | F | 1 Dec 2020 |
A | P | 1 Dec 2020 | 3
A | P | 1 Dec 2020 | 3.5
A | P | 1 Dec 2020 | 4
B | F | 1 Jun 2020 |
B | C | 1 Jun 2020 | 2.5
B | C | 1 Jun 2020 | 3
B | C | 1 Jun 2020 | 4
B | F | 1 Dec 2020 |
B | C | 1 Dec 2020 | 2
B | C | 1 Dec 2020 | 4
B | P | 1 Dec 2020 | 2
B | P | 1 Dec 2020 | 4"""
df = pd.DataFrame(pd.read_csv(StringIO(s), sep='|'))
df.columns = [i.strip() for i in df.columns]
for col in ['Sample', 'Type', 'Date']:
    df[col] = df[col].str.strip()

# Meat and bones of this operation
new_df = df.loc[(df['Type'] == 'C') | (df['Type'] == 'P')].groupby(['Sample', 'Date'])['Strike'].count().reset_index()

# Reformat to desired output
new_df['Type'] = 'F'
new_df = new_df[df.columns].rename(columns={'Strike': 'Count'}).sort_values(by=['Sample', 'Date'], ascending=[True, False])
print(new_df)
</code>```

Output:

```<code>  Sample Type        Date  Count
1      A    F  1 Jun 2020      2
0      A    F  1 Dec 2020      3
3      B    F  1 Jun 2020      3
2      B    F  1 Dec 2020      4
</code>```

Body:
I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.

I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.

Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike

      A      | F | 1 Jun 2020 |

      A | C | 1 Jun 2020 | 5

      A | P | 1 Jun 2020 | 2.5

      A | F | 1 Dec 2020 |

      A | P | 1 Dec 2020 | 3

      A | P | 1 Dec 2020 | 3.5

      A | P | 1 Dec 2020 | 4

      B | F | 1 Jun 2020 |

      B | C | 1 Jun 2020 | 2.5

      B | C | 1 Jun 2020 | 3

      B | C | 1 Jun 2020 | 4

      B | F | 1 Dec 2020 |

      B | C | 1 Dec 2020 | 2

      B | C | 1 Dec 2020 | 4

      B | P | 1 Dec 2020 | 2

      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:

Sample | Type | Date | Count

=======================

A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4

In Excel I would have used the CountIfs-function:

IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")

Please help (apologies for the poor table formatting).

Body:
Here's how I would do this. Use df.loc to filter down to the desired Types and then groupby and count :)

import pandas as pd
from io import StringIO

# Getting a df in the right form
s = """Sample | Type | Date | Strike
A | F | 1 Jun 2020 |
A | C | 1 Jun 2020 | 5
A | P | 1 Jun 2020 | 2.5
A | F | 1 Dec 2020 |
A | P | 1 Dec 2020 | 3
A | P | 1 Dec 2020 | 3.5
A | P | 1 Dec 2020 | 4
B | F | 1 Jun 2020 |
B | C | 1 Jun 2020 | 2.5
B | C | 1 Jun 2020 | 3
B | C | 1 Jun 2020 | 4
B | F | 1 Dec 2020 |
B | C | 1 Dec 2020 | 2
B | C | 1 Dec 2020 | 4
B | P | 1 Dec 2020 | 2
B | P | 1 Dec 2020 | 4"""
df = pd.DataFrame(pd.read_csv(StringIO(s), sep='|'))
df.columns = [i.strip() for i in df.columns]
for col in ['Sample', 'Type', 'Date']:
    df[col] = df[col].str.strip()

# Meat and bones of this operation
new_df = df.loc[(df['Type'] == 'C') | (df['Type'] == 'P')].groupby(['Sample', 'Date'])['Strike'].count().reset_index()

# Reformat to desired output
new_df['Type'] = 'F'
new_df = new_df[df.columns].rename(columns={'Strike': 'Count'}).sort_values(by=['Sample', 'Date'], ascending=[True, False])
print(new_df)

Output:

  Sample Type        Date  Count
1      A    F  1 Jun 2020      2
0      A    F  1 Dec 2020      3
3      B    F  1 Jun 2020      3
2      B    F  1 Dec 2020      4


问:
We hosted a website in AWS Kubernetes Service. niginx-ingress-path issue
We hosted a website in AWS Kubernetes Service. We are having following issue.

issue1.css not working
issue2:Redirection also not working

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: myapp1-alerts-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/rewrite-target: "/"

spec:
  tls:
  - hosts:
    - dev-api.myapp1.solutions
    secretName: myapp1-alerts-tls
  rules:
  - host: dev-api.myapp1.solutions
    http:
      paths:
      - path: /alerts
        backend:
          serviceName: myapp1-alerts
          servicePort: 80
</code>```

enter image description here

答:
Take a look at the official documentation. There you will find an example below:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: http-svc
          servicePort: 80
        path: /something(/|$)(.*)
  | kubectl create -f -
</code>```

In this ingress definition, any characters captured by (.*) will be
  assigned to the placeholder $2, which is then used as a parameter in
  the rewrite-target annotation.

For example, the ingress definition above will result in the following
  rewrites:

rewrite.bar.com/something rewrites to rewrite.bar.com/

rewrite.bar.com/something/ rewrites to rewrite.bar.com/

rewrite.bar.com/something/new rewrites to rewrite.bar.com/new

Adjust your config accordingly and please let me know if that helped.

Body:
We hosted a website in AWS Kubernetes Service. We are having following issue.

issue1.css not working
issue2:Redirection also not working

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: myapp1-alerts-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/rewrite-target: "/"

spec:
  tls:
  - hosts:
    - dev-api.myapp1.solutions
    secretName: myapp1-alerts-tls
  rules:
  - host: dev-api.myapp1.solutions
    http:
      paths:
      - path: /alerts
        backend:
          serviceName: myapp1-alerts
          servicePort: 80

enter image description here

Body:
Take a look at the official documentation. There you will find an example below:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: http-svc
          servicePort: 80
        path: /something(/|$)(.*)
  | kubectl create -f -

In this ingress definition, any characters captured by (.*) will be
  assigned to the placeholder $2, which is then used as a parameter in
  the rewrite-target annotation.

For example, the ingress definition above will result in the following
  rewrites:

rewrite.bar.com/something rewrites to rewrite.bar.com/

rewrite.bar.com/something/ rewrites to rewrite.bar.com/

rewrite.bar.com/something/new rewrites to rewrite.bar.com/new

Adjust your config accordingly and please let me know if that helped.


问:
java.lang.NoSuchMethodException for onCreate
I see crashes in the Google Play crash log that is really stumping me.

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3086)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3229)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1926)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:6981)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1445)
Caused by: androidx.fragment.app.Fragment$InstantiationException:
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:462)
  at androidx.fragment.app.FragmentContainer.instantiate (FragmentContainer.java:50)
  at androidx.fragment.app.FragmentState.instantiate (FragmentState.java:80)
  at androidx.fragment.app.FragmentManagerImpl.restoreAllState (FragmentManager.java:3109)
  at androidx.fragment.app.FragmentController.restoreAllState (FragmentController.java:158)
  at androidx.fragment.app.FragmentActivity.onCreate (FragmentActivity.java:344)
  at androidx.appcompat.app.AppCompatActivity.onCreate (AppCompatActivity.java:85)
  at com.autotask.jbarra.kotlinmvvm.MainActivity.onCreate (MainActivity.kt:102)
  at android.app.Activity.performCreate (Activity.java:7326)
  at android.app.Activity.performCreate (Activity.java:7317)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1271)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3066)

Caused by: java.lang.NoSuchMethodException:
  at java.lang.Class.getConstructor0 (Class.java:2328)
  at java.lang.Class.getConstructor (Class.java:1725)
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:443)
</code>```

the thing is, line 102 of Main activity is nothing special

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState) //This is line 102
</code>```

What could cause this?  Why is oncreate throwing no such method?  It's happening on a few user's devices and I haven't been able to reproduce it.

答:
My Activity had a FragmentPagerAdapter that was using the deperecated constructor.
I changed

```<code>class MyPagerAdapter(
        fragmentManager: FragmentManager,
        private val myActivity: MyActivity
    ) : FragmentPagerAdapter(fragmentManager) // DEPRECATED
</code>```

to

```<code>class MyPagerAdapter(
        fragmentManager: FragmentManager,
        private val myActivity: MyActivity
    ) : FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
</code>```

Seem to have fixed the problem

Body:
I see crashes in the Google Play crash log that is really stumping me.

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3086)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3229)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:78)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1926)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:6981)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1445)
Caused by: androidx.fragment.app.Fragment$InstantiationException:
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:462)
  at androidx.fragment.app.FragmentContainer.instantiate (FragmentContainer.java:50)
  at androidx.fragment.app.FragmentState.instantiate (FragmentState.java:80)
  at androidx.fragment.app.FragmentManagerImpl.restoreAllState (FragmentManager.java:3109)
  at androidx.fragment.app.FragmentController.restoreAllState (FragmentController.java:158)
  at androidx.fragment.app.FragmentActivity.onCreate (FragmentActivity.java:344)
  at androidx.appcompat.app.AppCompatActivity.onCreate (AppCompatActivity.java:85)
  at com.autotask.jbarra.kotlinmvvm.MainActivity.onCreate (MainActivity.kt:102)
  at android.app.Activity.performCreate (Activity.java:7326)
  at android.app.Activity.performCreate (Activity.java:7317)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1271)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3066)

Caused by: java.lang.NoSuchMethodException:
  at java.lang.Class.getConstructor0 (Class.java:2328)
  at java.lang.Class.getConstructor (Class.java:1725)
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:443)

the thing is, line 102 of Main activity is nothing special

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState) //This is line 102

What could cause this?  Why is oncreate throwing no such method?  It's happening on a few user's devices and I haven't been able to reproduce it.

Body:
My Activity had a FragmentPagerAdapter that was using the deperecated constructor.
I changed

class MyPagerAdapter(
        fragmentManager: FragmentManager,
        private val myActivity: MyActivity
    ) : FragmentPagerAdapter(fragmentManager) // DEPRECATED

to

class MyPagerAdapter(
        fragmentManager: FragmentManager,
        private val myActivity: MyActivity
    ) : FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

Seem to have fixed the problem


问:
Move showModalBottomSheet to the top
Is there a way to move showModalBottomSheet 75pixels to the top so it doesnt block my bottom menu? I tried to give my Container padding but it doesn't work.

答:
I edited bottom_sheet.dart file and added -75.0 in this part of the code

```<code>      @override
  Offset getPositionForChild(Size size, Size childSize) {
    return Offset(0.0, size.height - childSize.height * progress - 75.0);
  }
</code>```

That did the trick, however, the animation still starts from the bottom. Not sure If I like it or not.

Title: Move showModalBottomSheet to the top

Body:
I edited bottom_sheet.dart file and added -75.0 in this part of the code

      @override
  Offset getPositionForChild(Size size, Size childSize) {
    return Offset(0.0, size.height - childSize.height * progress - 75.0);
  }

That did the trick, however, the animation still starts from the bottom. Not sure If I like it or not.


问:
unable to get jsonEncode in magento2
Magento has its own json encode and decode functions:

```<code>Mage::helper('core')->jsonEncode($array);
</code>```

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

答:
You can use the below code</p>

```<code>public function __construct(\Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
    \Magento\Framework\Json\Decoder $jsonDecoder,
    \Magento\Framework\Json\Encoder $jsonEncoder,
    \CP\Coreoverride\Serialize\Serializer\Json $serializer
)
{
    $this->resultJsonFactory = $resultJsonFactory;
    $this->_jsonDecoder = $jsonDecoder;
    $this->_jsonEncoder = $jsonEncoder;
    $this->_serializer = $serializer;
    parent::__construct($context);
}

public function decodeData($data) {
  $dataArray = $this->_jsonDecoder->decode($data);
  $result = $this->_serializer->unserialize($dataArray);
  return $result;
}

public function encodeData($data) {
    $dataArray = $this->_jsonEncoder->encode($data);
    $result = $this->_serializer->unserialize($dataArray);
    return $result;
}
</code>```

Title: unable to get jsonEncode in magento2

Body:
Magento has its own json encode and decode functions:

Mage::helper('core')->jsonEncode($array);

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

Body:
You can use the below code

public function __construct(\Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
    \Magento\Framework\Json\Decoder $jsonDecoder,
    \Magento\Framework\Json\Encoder $jsonEncoder,
    \CP\Coreoverride\Serialize\Serializer\Json $serializer
)
{
    $this->resultJsonFactory = $resultJsonFactory;
    $this->_jsonDecoder = $jsonDecoder;
    $this->_jsonEncoder = $jsonEncoder;
    $this->_serializer = $serializer;
    parent::__construct($context);
}

public function decodeData($data) {
  $dataArray = $this->_jsonDecoder->decode($data);
  $result = $this->_serializer->unserialize($dataArray);
  return $result;
}

public function encodeData($data) {
    $dataArray = $this->_jsonEncoder->encode($data);
    $result = $this->_serializer->unserialize($dataArray);
    return $result;
}


问:
Why C Macro gets truncated?
I am passing a C Macro to a function which receives it as char *. Without any reason the last character from macro gets truncated. I doubt some memory leak, but could not find where.

```<code>#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"
....
char file[_D_NAME_MAX + 1] = {'\0'};
....
funMove(file, FROM, TO);
....
....
int funMove(char *file, char *from, char *to) {
//here the to value is one character less (/some/local/path/to) slash got truncated
}
</code>```

答:
There's nothing wrong with the code you've shown us since the following works fine:

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

#define _D_NAME_MAX 50

#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"

char file[_D_NAME_MAX + 1] = {'\0'};

int funMove(char *file, char *from, char *to) {
    printf ("[%s] [%s] [%s]\n", file, from, to);
    return 0;
}

int main (void) {
    strcpy (file, "fspec");
    int x = funMove(file, FROM, TO);
    printf ("[%d]\n", x);
    return 0;
}
</code>```

It outputs:

```<code>[fspec] [/some/local/path/from/] [/some/local/path/to/]
[0]
</code>```

as expected, so there must be a problem elsewhere if you're seeing to truncated.

Title: Why C Macro gets truncated?

Body:
I am passing a C Macro to a function which receives it as char *. Without any reason the last character from macro gets truncated. I doubt some memory leak, but could not find where.

#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"
....
char file[_D_NAME_MAX + 1] = {'\0'};
....
funMove(file, FROM, TO);
....
....
int funMove(char *file, char *from, char *to) {
//here the to value is one character less (/some/local/path/to) slash got truncated
}

Body:
There's nothing wrong with the code you've shown us since the following works fine:

#include <stdio.h>
#include <string.h>

#define _D_NAME_MAX 50

#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"

char file[_D_NAME_MAX + 1] = {'\0'};

int funMove(char *file, char *from, char *to) {
    printf ("[%s] [%s] [%s]\n", file, from, to);
    return 0;
}

int main (void) {
    strcpy (file, "fspec");
    int x = funMove(file, FROM, TO);
    printf ("[%d]\n", x);
    return 0;
}

It outputs:

[fspec] [/some/local/path/from/] [/some/local/path/to/]
[0]

as expected, so there must be a problem elsewhere if you're seeing to truncated.


问:
How to detect and use the row number of a table in postgreSQL, using Python?
I'm trying to find a way to use the row number of a table in postgreSQL, using Python.
So in a for loop, when the table row number is 22, do something.

Let me show you an easy example:

```<code>conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b FROM table")
rows = cur.fetchall()

for data in rows:
    if data.row_number == 22:`    #if the table row number is 22...
        do something
</code>```

obviously the expression "data.row_number" does not exist and produces an error...

Somebody could help me?

Thanks

答:
You could try with the ROW_NUMBER() function, for example:

```<code>conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b, ROW_NUMBER () OVER (ORDER BY a) FROM table")
rows = cur.fetchall()

for data in rows:
    if data[2] == 22:    #if the table row number is 22...
        # do something
</code>```

Body:
I'm trying to find a way to use the row number of a table in postgreSQL, using Python.
So in a for loop, when the table row number is 22, do something.

Let me show you an easy example:

conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b FROM table")
rows = cur.fetchall()

for data in rows:
    if data.row_number == 22:`    #if the table row number is 22...
        do something

obviously the expression "data.row_number" does not exist and produces an error...

Somebody could help me?

Thanks

Body:
You could try with the ROW_NUMBER() function, for example:

conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
cur = conn.cursor()

cur.execute("SELECT a, b, ROW_NUMBER () OVER (ORDER BY a) FROM table")
rows = cur.fetchall()

for data in rows:
    if data[2] == 22:    #if the table row number is 22...
        # do something


问:
Send real-time data from networked C program to a browser client to plot
I am faced with an architectural problem to which I cannot seem to find a suitable solution so far.
I have a Linux box which is just a machine connected to the network with an Ethernet cable, running Linux. It is sampling values from an ADC(analog to digital converter) at about 3000 samples/sec. At each sample, it actually samples all 8 channels of the ADC. So, I have 3000*8 DOUBLE type values every second.

My problem is the following: stream this data in real time to a client running a web application and plot it there with some Javascript framework. The program on the Linux box has to be in C. I try to avoid interop like the one available with .NET Core to avoid the complexity.

What I have done so far?

I have implemented a web-server in C running as a child process along with the parent process which samples ADC values. (actually the parent does not need to sample, I did it as a demo before I incorporated it in this program). The server can serve a GET request to which it only know to respond with JSON-formatted values of all 8 channels like in the screenshot below. Here is the request I am making from my computer:

Note that I only want this to work on the local network.

Now, what I think is that I could have some JS framework which receives the data from this Linux box by calling 192.168.1.95:8080 continuously in an Ajax GET request, and plotting all 8 channels simultaneously. Is that viable? How bad is this design? Can this crash the browser? Note that, each request like the one in screenshot takes ~260 bytes as sending, and response (JSON) is ~130 bytes (about 50% of exchanged data is HTTP headers).

The way I feel is that if I continue like this, I will be wasting 99% of the data the Linux box samples only getting a very small amount of data in the client web application. Note that, I have not done the web app yet. So, I do not know how it actually performs. Although, I can tell you that the server on the Linux box is quite fast. Plus, it works locally only.

A much better solution would be if I could get a socket work in the browser. Then, this would be much faster (I think).

Can you suggest a better way to do this? I would also accept a solution which can be used outside of the local network as well. I am looking for a scalable solution. For the client app, I intend to use ASP.NET Core.

Thinks I have thought of: Web Sockets (using a library for C?)? Would this be faster?

Anything you can give me would be highly appreciated.

In terms of code, here is the code:

https://github.com/giorgi3092/ECG_HW_SW_DE1_SoC/blob/master/adc_example/web_server/web_server2.c

答:
For your use case, WebSocket is definitely more scalable than doing HTTP polling.

If you want to improve overall system performance, you could use a more compact and efficient data serialization format, for example like MessagePack, it is available in wide array of programming languages (for your case, JavaScript and C).

In more extreme case where existing serialization formats didn't work too well, then you might want to directly encode double[] into uint8_t[] (C) at your server and push to browser, and then use TypedArray (JavaScript) in browser to access values encoded by the server.

On the other hand, I think C# (.NET Core) could work as good as C in this case.


问:
How to restrict user from accessing a particular action of a controller?
```<code> def filters = {
   loginCheck(controller:'*', action:'*') {
        before = {
           if(!session.user && !session.merchants)
           {
               redirect(action:'login')
               return false
            }
        }}
</code>```

That was my filter for login security. And below is interceptor in action for restricting user from search action. But both are not working. Can any one tell what the mistake is?

```<code>def beforeInterceptor = [action:this.&checkUser,Only:'search']

    def scaffold = true
    def checkUser()
    {
        if (session.user)
        {
            redirect(action:"search")
        }
        if(session.merchants)
        {
        redirect(action:"toIndex")
        flash.message="You are not valid user for this action"
        return false
        }
    }
</code>```

答:
There's a really nice shorthand that you can apply directly to actions (if you're not using filters):

```<code>@Secured(['ROLE_USER'])
def search = {

}
</code>```

You can give every user ROLE_USER and simply require that role.

Body:
 def filters = {
   loginCheck(controller:'*', action:'*') {
        before = {
           if(!session.user && !session.merchants)
           {
               redirect(action:'login')
               return false
            }
        }}

That was my filter for login security. And below is interceptor in action for restricting user from search action. But both are not working. Can any one tell what the mistake is?

def beforeInterceptor = [action:this.&checkUser,Only:'search']

    def scaffold = true
    def checkUser()
    {
        if (session.user)
        {
            redirect(action:"search")
        }
        if(session.merchants)
        {
        redirect(action:"toIndex")
        flash.message="You are not valid user for this action"
        return false
        }
    }

Body:
There's a really nice shorthand that you can apply directly to actions (if you're not using filters):

@Secured(['ROLE_USER'])
def search = {

}

You can give every user ROLE_USER and simply require that role.


问:
Java's Optional Forces Itself or else I get an error
Why do I get an error if I don't use Optional (the IDE suggested I use Optional) as oppose to just using DemographicEntity demoEntity?</p>

```<code>@Test
public void testFindDemographicsById() {
    DemographicEntity demoEntity = demoRepo.findById(1l); /////Gives Error
}

@Test
public void testFindDemographicsById() {
    /////forced to use Optional
    Optional<DemographicEntity> demoEntity = demoRepo.findById(1l); /////No Error
}
</code>```

答:
Your findById returns an Optional. Use .get() in order to get the actual value

```<code>DemographicEntity demoEntity = demoRepo.findById(1l).get();
</code>```

Body:
Why do I get an error if I don't use Optional (the IDE suggested I use Optional) as oppose to just using DemographicEntity demoEntity?

@Test
public void testFindDemographicsById() {
    DemographicEntity demoEntity = demoRepo.findById(1l); /////Gives Error
}

@Test
public void testFindDemographicsById() {
    /////forced to use Optional
    Optional<DemographicEntity> demoEntity = demoRepo.findById(1l); /////No Error
}

Body:
Your findById returns an Optional. Use .get() in order to get the actual value

DemographicEntity demoEntity = demoRepo.findById(1l).get();


问:
How do I capture QR Code data in specific area of AVCaptureVideoPreviewLayer using Swift?
I am creating an iPad app and one of it's features is scanning QR codes.  I have the QR scanning part working, but the issue I have is that the iPad screen is very large and I will be scanning small QR codes of of a sheet of paper with many QR codes visible at once.  I want to designate a smaller area of the display to be the only area that can actually capture a QR code so it is easier for the user to scan the specific QR code they want.

I currently have made a temporary UIView with red borders that is centered on the page as an example of where I will want the user to scan the QR codes.  It looks like this:

I have looked all over to find an answer to how I can target a specific region of the AVCaptureVideoPreviewLayer to collect the QR code data, and what I have found is suggestions to use "rectOfInterest" with AVCaptureMetadataOutput.  I have attempted to do that, but when I set rectOfInterest to the same coordinates and size as those I use for my UIView that shows up correctly, I can no longer scan/recognize any QR codes.  Can someone please tell me why the scannable area does not match the location of the UIView that is seen and how can I get the rectOfInterest to be within the red borders I have added to the screen?

Here is the code for the scan function I am currently using:

```<code>func startScan() {
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    var error:NSError?
    let input: AnyObject! = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: &error)

    if (error != nil) {
        // If any error occurs, simply log the description of it and don't continue any more.
        println("\(error?.localizedDescription)")
        return
    }

    // Initialize the captureSession object.
    captureSession = AVCaptureSession()
    // Set the input device on the capture session.
    captureSession?.addInput(input as! AVCaptureInput)

    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    let captureMetadataOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadataOutput)

    // calculate a centered square rectangle with red border
    let size = 300
    let screenWidth = self.view.frame.size.width
    let xPos = (CGFloat(screenWidth) / CGFloat(2)) - (CGFloat(size) / CGFloat(2))
    let scanRect = CGRect(x: Int(xPos), y: 150, width: size, height: size)

    // create UIView that will server as a red square to indicate where to place QRCode for scanning
    scanAreaView = UIView()
    scanAreaView?.layer.borderColor = UIColor.redColor().CGColor
    scanAreaView?.layer.borderWidth = 4
    scanAreaView?.frame = scanRect

    // Set delegate and use the default dispatch queue to execute the call back
    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    captureMetadataOutput.rectOfInterest = scanRect

    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = view.layer.bounds
    view.layer.addSublayer(videoPreviewLayer)

    // Start video capture.
    captureSession?.startRunning()

    // Initialize QR Code Frame to highlight the QR code
    qrCodeFrameView = UIView()
    qrCodeFrameView?.layer.borderColor = UIColor.greenColor().CGColor
    qrCodeFrameView?.layer.borderWidth = 2
    view.addSubview(qrCodeFrameView!)
    view.bringSubviewToFront(qrCodeFrameView!)

    // Add a button that will be used to close out of the scan view
    videoBtn.setTitle("Close", forState: .Normal)
    videoBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    videoBtn.backgroundColor = UIColor.grayColor()
    videoBtn.layer.cornerRadius = 5.0;
    videoBtn.frame = CGRectMake(10, 30, 70, 45)
    videoBtn.addTarget(self, action: "pressClose:", forControlEvents: .TouchUpInside)
    view.addSubview(videoBtn)

    view.addSubview(scanAreaView!)

}
</code>```

Update
The reason I do not think this is a duplicate is because the other post referenced is in Objective-C and my code is in Swift.  For those of us that are new to iOS it is not as easy to translate the two.  Also, the referenced post's answer does not show the actual update made in the code that resolved his issue.  He left a good explanation about having to use the metadataOutputRectOfInterestForRect method to convert the rectangle coordinates, but I still cannot seem to get this method to work, as it is unclear to me how this should work without an example.

答:
```<code>let metadataOutput = AVCaptureMetadataOutput()
metadataOutput.rectOfInterest = convertRectOfInterest(rect: scanRect)
</code>```

After reviewing other source(https://www.jianshu.com/p/8bb3d8cb224e),
the convertRectOfInterest function has a slight mistake, the return field should be:

```<code>return CGRect(x: newY, y: newX, width: newHeight, height: newWidth)
</code>```

where x and y, Width and Height input should be interchanged to get it working.

Body:
I am creating an iPad app and one of it's features is scanning QR codes.  I have the QR scanning part working, but the issue I have is that the iPad screen is very large and I will be scanning small QR codes of of a sheet of paper with many QR codes visible at once.  I want to designate a smaller area of the display to be the only area that can actually capture a QR code so it is easier for the user to scan the specific QR code they want.

I currently have made a temporary UIView with red borders that is centered on the page as an example of where I will want the user to scan the QR codes.  It looks like this:

I have looked all over to find an answer to how I can target a specific region of the AVCaptureVideoPreviewLayer to collect the QR code data, and what I have found is suggestions to use "rectOfInterest" with AVCaptureMetadataOutput.  I have attempted to do that, but when I set rectOfInterest to the same coordinates and size as those I use for my UIView that shows up correctly, I can no longer scan/recognize any QR codes.  Can someone please tell me why the scannable area does not match the location of the UIView that is seen and how can I get the rectOfInterest to be within the red borders I have added to the screen?

Here is the code for the scan function I am currently using:

func startScan() {
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    var error:NSError?
    let input: AnyObject! = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: &error)

    if (error != nil) {
        // If any error occurs, simply log the description of it and don't continue any more.
        println("\(error?.localizedDescription)")
        return
    }

    // Initialize the captureSession object.
    captureSession = AVCaptureSession()
    // Set the input device on the capture session.
    captureSession?.addInput(input as! AVCaptureInput)

    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    let captureMetadataOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadataOutput)

    // calculate a centered square rectangle with red border
    let size = 300
    let screenWidth = self.view.frame.size.width
    let xPos = (CGFloat(screenWidth) / CGFloat(2)) - (CGFloat(size) / CGFloat(2))
    let scanRect = CGRect(x: Int(xPos), y: 150, width: size, height: size)

    // create UIView that will server as a red square to indicate where to place QRCode for scanning
    scanAreaView = UIView()
    scanAreaView?.layer.borderColor = UIColor.redColor().CGColor
    scanAreaView?.layer.borderWidth = 4
    scanAreaView?.frame = scanRect

    // Set delegate and use the default dispatch queue to execute the call back
    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    captureMetadataOutput.rectOfInterest = scanRect

    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = view.layer.bounds
    view.layer.addSublayer(videoPreviewLayer)

    // Start video capture.
    captureSession?.startRunning()

    // Initialize QR Code Frame to highlight the QR code
    qrCodeFrameView = UIView()
    qrCodeFrameView?.layer.borderColor = UIColor.greenColor().CGColor
    qrCodeFrameView?.layer.borderWidth = 2
    view.addSubview(qrCodeFrameView!)
    view.bringSubviewToFront(qrCodeFrameView!)

    // Add a button that will be used to close out of the scan view
    videoBtn.setTitle("Close", forState: .Normal)
    videoBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    videoBtn.backgroundColor = UIColor.grayColor()
    videoBtn.layer.cornerRadius = 5.0;
    videoBtn.frame = CGRectMake(10, 30, 70, 45)
    videoBtn.addTarget(self, action: "pressClose:", forControlEvents: .TouchUpInside)
    view.addSubview(videoBtn)

    view.addSubview(scanAreaView!)

}

Update
The reason I do not think this is a duplicate is because the other post referenced is in Objective-C and my code is in Swift.  For those of us that are new to iOS it is not as easy to translate the two.  Also, the referenced post's answer does not show the actual update made in the code that resolved his issue.  He left a good explanation about having to use the metadataOutputRectOfInterestForRect method to convert the rectangle coordinates, but I still cannot seem to get this method to work, as it is unclear to me how this should work without an example.

Body:
let metadataOutput = AVCaptureMetadataOutput()
metadataOutput.rectOfInterest = convertRectOfInterest(rect: scanRect)

After reviewing other source(https://www.jianshu.com/p/8bb3d8cb224e),
the convertRectOfInterest function has a slight mistake, the return field should be:

return CGRect(x: newY, y: newX, width: newHeight, height: newWidth)

where x and y, Width and Height input should be interchanged to get it working.


答: You can hover your cursor over the function declaration and a tooltip should show you the name of the class that this method belongs to. Alternatively there is a dropdown menu in the main toolbar that shows the name of the class:

Title: Goto the class a method belong in Visual Studio

Body: In Visual Studio, suppose already jump to a method in a very huge C++ class in a header file, how to know which class the method belong to? Now the method is scroll up until the class shows up, but sometimes you miss the class and get into another class's body.


问:
Select the IDs using group by condition
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

```<code>ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0
</code>```

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

```<code>select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID
</code>```

答:
Demo on db<>fiddle

You can achieve it in this simple way

```<code>;WITH cte_TempTable AS(
 Select DISTINCT Id, Des1, Des2, Des3
 from MySampleTable
)
SELECT Id
FROM cte_TempTable
GROUP BY Id
HAVING COUNT(Id) = 1
</code>```

Output

Title: Select the IDs using group by condition

Body:
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID

Body:
Demo on db<>fiddle

You can achieve it in this simple way

;WITH cte_TempTable AS(
 Select DISTINCT Id, Des1, Des2, Des3
 from MySampleTable
)
SELECT Id
FROM cte_TempTable
GROUP BY Id
HAVING COUNT(Id) = 1

Output


答:
simple solution is using the enumerate:

```<code>for row_number, data in enumerate(rows, 1):
    if row_number == 22:
</code>```

Title: How to detect and use the row number of a table in postgreSQL, using Python?

Body:
simple solution is using the enumerate:

for row_number, data in enumerate(rows, 1):
    if row_number == 22:


问:
Flutter app not running showing only "Waiting for another flutter command to release the startup lock"
When I hit run button for Flutter app then IDE Intellij IDEA shows a message on console "Waiting for another flutter command to release the startup lock..."

Nothing happens after message.

答:
In my case, following command in Terminal or cmd helped (as suggested by Günter):

```<code>killall -9 dart
</code>```

On Windows (as suggested by upupming):

```<code>taskkill /F /IM dart.exe
</code>```

or remove this file

```<code><YOUR FLUTTER FOLDER>/bin/cache/lockfile
</code>```

This releases the occupied lock and makes you able to run other commands.

Body:
In my case, following command in Terminal or cmd helped (as suggested by Günter):

killall -9 dart

On Windows (as suggested by upupming):

taskkill /F /IM dart.exe

or remove this file

<YOUR FLUTTER FOLDER>/bin/cache/lockfile

This releases the occupied lock and makes you able to run other commands.


问:
Merge two object based on id property in JavaScript
Original array getting from response:

```<code>result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
]
</code>```

I want result which is mentioned below. Please do the needful. Thanks in advance

```<code>newResult = [
    {
        id: 1,
        newArr: [{
            a: "one",
            b: "two",
            c: "three",
            d: "four",
        }, {
            a: "five",
            b: "six",
            c: "seven",
            d: "eight",
        }]
    }
]
</code>```

答:
```<code>const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el =>
{delete el.id; return el})}));
console.log(transformed);
</code>```

result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 3,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 2,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 2,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 3,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
];
const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el => {delete el.id; return el})}));
console.log(transformed);```

Body:
Original array getting from response:

result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
]

I want result which is mentioned below. Please do the needful. Thanks in advance

newResult = [
    {
        id: 1,
        newArr: [{
            a: "one",
            b: "two",
            c: "three",
            d: "four",
        }, {
            a: "five",
            b: "six",
            c: "seven",
            d: "eight",
        }]
    }
]

Body:
const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el =>
{delete el.id; return el})}));
console.log(transformed);

result = [
    {
        id: 1,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 1,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 3,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 2,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    },
        {
        id: 2,
        a: "one",
        b: "two",
        c: "three",
        d: "four",
    },
    {
        id: 3,
        a: "five",
        b: "six",
        c: "seven",
        d: "eight",
    }
];
const obj = {};
result.forEach(t => obj[t.id] ? obj[t.id].push(t) : (obj[t.id] = [t]));
const transformed = Object.keys(obj).map(t => ({id: t, newArr: obj[t].map(el => {delete el.id; return el})}));
console.log(transformed);


问:
PHP7 Undefined class constant triggering php7:notice
I have been renaming some constants in our code and when releasing to production I get regulary in the apache log the following message :

```<code>[Sun Feb 16 19:56:29.437393 2020] [php7:notice] [pid 15948] [client 10.0.1.10:24984] Undefined class constant 'SUBMIT_STA_', referer: https://xxxx.yyyy.com/runtest/QuestionDisplayer
</code>```

Nothing after, nothing before. There are many things I don't understand :

How can an undefined class constant trigger a notice rather than a fatal error ?

Why don't I get any more information about where in the code the error appears (like script and line number) as for other errors?
Obviously, when I look into my code I don't find any instance of SUBMIT_STA_, I find some SUBMIT_STA_XX or SUBMIT_STA_YY but no SUBMIT_STA with nothing after.

答: OK, sorry I solved it. I finally found where I was using this unexisting constant. The reason for which it triggers this unusual message is because it was inside a try / catch(Throwable $e) handler, in such case no error is displayed on screen and Apache logs a [php7:notice] message. I have been able to reproduce this behavior.</p>

Body:
I have been renaming some constants in our code and when releasing to production I get regulary in the apache log the following message :

[Sun Feb 16 19:56:29.437393 2020] [php7:notice] [pid 15948] [client 10.0.1.10:24984] Undefined class constant 'SUBMIT_STA_', referer: https://xxxx.yyyy.com/runtest/QuestionDisplayer

Nothing after, nothing before. There are many things I don't understand :

How can an undefined class constant trigger a notice rather than a fatal error ?

Why don't I get any more information about where in the code the error appears (like script and line number) as for other errors?
Obviously, when I look into my code I don't find any instance of SUBMIT_STA_, I find some SUBMIT_STA_XX or SUBMIT_STA_YY but no SUBMIT_STA with nothing after.


问:
Debugging Drupal's White Screen of Death?
I have a Drupal installation that previously worked perfectly on my localhost. However, now, after a formatted my computer, it just shows a blank screen (completely white).

So my question is, how can I see where things are going wrong, if I can't even log into the sever?

The only errors I can find are (taken from the Apache Error Logs):

```<code>[Tue May 17 05:05:04 2011] [notice] Parent: child process exited with status 255 -- Restarting.
[Tue May 17 05:05:04 2011] [notice] Digest: generating secret for digest authentication ...
[Tue May 17 05:05:04 2011] [notice] Digest: done
[Tue May 17 05:05:07 2011] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 configured -- resuming normal operations
[Tue May 17 05:05:07 2011] [notice] Server built: Dec 10 2008 00:10:06
[Tue May 17 05:05:07 2011] [notice] Parent: Created child process 6992
</code>```

There are no errors in Watchdog...

I am using Xamp 1.7.1 (PHP 5.2) and Drupal 6.

I just also need to mention that once I try and load the site on my local machine, apache also crashes! I added this:

```<code>error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
</code>```

And it still just shows the screen of death? Where can I actually see errors?

I also found this in apache access.log:

```<code>127.0.0.1 - - [17/May/2011:05:22:14 +0200] "GET /greekmerchant/src/ HTTP/1.1" 200 3
127.0.0.1 - - [17/May/2011:05:25:45 +0200] "GET /greekmerchant/src/update.php HTTP/1.1" 302 -
127.0.0.1 - - [17/May/2011:05:25:46 +0200] "GET /greekmerchant/src/update.php?op=info HTTP/1.1" 200 -
</code>```

... after trying to access update.php. It also just goes to a white screen.

I have this in my sql config file:

```<code>[mysqld]
port= 3306
socket= "C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
skip-locking
key_buffer = 16M
max_allowed_packet = 128M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error="mysql_error.log"
</code>```

And...

```<code>[mysqldump]
quick
max_allowed_packet = 128M
</code>```

Also, my PHP memory is set to 1024MB.

Anyone got any idea why this is just dying? Is it really a memory problem? What else can I do to get errors shown to me? I still see nothing even after enabling error logging.

Update:

The website runs on my local machine if I delete the files folder. So, for some reason, when it has to access files in the files folder, it runs out of memory. Why? Or better yet, what could be causing this excessive use of memory?

答:
There is a whole page in the Drupal handbooks dedicated to debugging the "White Screen of Death". In a nutshell, enable error reporting by adding the following at the top of your index.php file:

```<code>error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
</code>```

...and check the logs, which you've already started to do. Those two steps tend to pinpoint the problem, most of the time. If that doesn't point you towards a solution, continue down the handbook page, for lots more tips.

If I had to take a wild guess, I would say your case is probably an out-of-memory error.

Body:
I have a Drupal installation that previously worked perfectly on my localhost. However, now, after a formatted my computer, it just shows a blank screen (completely white).

So my question is, how can I see where things are going wrong, if I can't even log into the sever?

The only errors I can find are (taken from the Apache Error Logs):

[Tue May 17 05:05:04 2011] [notice] Parent: child process exited with status 255 -- Restarting.
[Tue May 17 05:05:04 2011] [notice] Digest: generating secret for digest authentication ...
[Tue May 17 05:05:04 2011] [notice] Digest: done
[Tue May 17 05:05:07 2011] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 configured -- resuming normal operations
[Tue May 17 05:05:07 2011] [notice] Server built: Dec 10 2008 00:10:06
[Tue May 17 05:05:07 2011] [notice] Parent: Created child process 6992

There are no errors in Watchdog...

I am using Xamp 1.7.1 (PHP 5.2) and Drupal 6.

I just also need to mention that once I try and load the site on my local machine, apache also crashes! I added this:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And it still just shows the screen of death? Where can I actually see errors?

I also found this in apache access.log:

127.0.0.1 - - [17/May/2011:05:22:14 +0200] "GET /greekmerchant/src/ HTTP/1.1" 200 3
127.0.0.1 - - [17/May/2011:05:25:45 +0200] "GET /greekmerchant/src/update.php HTTP/1.1" 302 -
127.0.0.1 - - [17/May/2011:05:25:46 +0200] "GET /greekmerchant/src/update.php?op=info HTTP/1.1" 200 -

... after trying to access update.php. It also just goes to a white screen.

I have this in my sql config file:

[mysqld]
port= 3306
socket= "C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
skip-locking
key_buffer = 16M
max_allowed_packet = 128M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error="mysql_error.log"

And...

[mysqldump]
quick
max_allowed_packet = 128M

Also, my PHP memory is set to 1024MB.

Anyone got any idea why this is just dying? Is it really a memory problem? What else can I do to get errors shown to me? I still see nothing even after enabling error logging.

Update:

The website runs on my local machine if I delete the files folder. So, for some reason, when it has to access files in the files folder, it runs out of memory. Why? Or better yet, what could be causing this excessive use of memory?

Body:
There is a whole page in the Drupal handbooks dedicated to debugging the "White Screen of Death". In a nutshell, enable error reporting by adding the following at the top of your index.php file:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

...and check the logs, which you've already started to do. Those two steps tend to pinpoint the problem, most of the time. If that doesn't point you towards a solution, continue down the handbook page, for lots more tips.

If I had to take a wild guess, I would say your case is probably an out-of-memory error.


问:
imap_open() works locally but not on server
The issue is i'm trying to get the last email from my email using php, and it works fine locally. But then I uploaded the script to the client's server, and I don't get a response. When I check the logs, I get this:

```<code>[12-Feb-2020 08:43:21 location] PHP Warning:  imap_open(): Couldn't open stream {<mail>:143/imap}INBOX in /path/triggerCall.php on line 2
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_headers() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 7
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_num_msg() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 14
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_header() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 16
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_fetchbody() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 20
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_close() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 40
</code>```

This is the code:

```<code>$inbox = imap_open('{<mail>:143/imap}', '<username>', '<password>');

$headers = imap_headers($inbox);

$last = imap_num_msg($inbox);

$header = imap_header($inbox, $last);

$body = imap_fetchbody($inbox, $last,1);
</code>```

I have tried:

```<code>{<mail>:993/imap/novalidate-cert}INBOX
{<mail>:995/pop3/tls}INBOX
{<mail>:995/pop3/ssl}INBOX
{<mail>:993/imap/ssl}INBOX
{<mail>:110/pop3}INBOX
{<mail>:993/imap/tls/novalidate-cert}INBOX
{<mail>:143}INBOX
</code>```

But none of those approaches work. Any ideas?

答:
Try this

$inbox = imap_open('{mail.gmail.com/ssl/novalidate-cert}INBOX', 'email', 'password');

Body:
The issue is i'm trying to get the last email from my email using php, and it works fine locally. But then I uploaded the script to the client's server, and I don't get a response. When I check the logs, I get this:

[12-Feb-2020 08:43:21 location] PHP Warning:  imap_open(): Couldn't open stream {<mail>:143/imap}INBOX in /path/triggerCall.php on line 2
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_headers() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 7
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_num_msg() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 14
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_header() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 16
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_fetchbody() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 20
[12-Feb-2020 08:43:21 location] PHP Warning:  imap_close() expects parameter 1 to be resource, boolean given in /path/triggerCall.php on line 40

This is the code:

$inbox = imap_open('{<mail>:143/imap}', '<username>', '<password>');

$headers = imap_headers($inbox);

$last = imap_num_msg($inbox);

$header = imap_header($inbox, $last);

$body = imap_fetchbody($inbox, $last,1);

I have tried:

{<mail>:993/imap/novalidate-cert}INBOX
{<mail>:995/pop3/tls}INBOX
{<mail>:995/pop3/ssl}INBOX
{<mail>:993/imap/ssl}INBOX
{<mail>:110/pop3}INBOX
{<mail>:993/imap/tls/novalidate-cert}INBOX
{<mail>:143}INBOX

But none of those approaches work. Any ideas?


问:
invalid_grant trying to get oAuth token from google
I keep getting an invalid_grant error on trying to get an OAuth token from Google to connect to their contacts API. All the information is correct and I have triple-checked this so I'm kind of stumped.

Does anyone know what may be causing this issue? I have tried setting up a different client ID for it but I get the same result. I have tried connecting many different ways including trying the force authentication, but still the same result.

答: If you're testing this out in postman / insomnia and are just trying to get it working, hint: the server auth code (code parameter) is only good once. Meaning if you stuff up any of the other parameters in the request and get back a 400, you'll need to use a new server auth code or you'll just get another 400.  </p>


问:
How to set 'hardwareBackPress' to another Stack

```<code>//TermsPage.tsx
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
componentWillUnmount() {
    BackHandler.addEventListener('hardwareBackPress',()=>{
      this.props.navigation.dispatch(resetAction)
      return true
    })
  }

</code>```

How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator

答:
I solve this problem with function pop().
In the page, where I want to go another stack I added

```<code>const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
</code>```

```<code>handleBackButtonClick() {
    this.props.navigation.dispatch(resetAction);
    return true;
  }
</code>```

And in another pages

```<code>handleBackButtonClick() {
    // @ts-ignore
    this.props.navigation.pop();
    return true;
  }
``` And voila
```

Body:
//TermsPage.tsx
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
componentWillUnmount() {
    BackHandler.addEventListener('hardwareBackPress',()=>{
      this.props.navigation.dispatch(resetAction)
      return true
    })
  }

How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator

Body:
I solve this problem with function pop().
In the page, where I want to go another stack I added

const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});

handleBackButtonClick() {
    this.props.navigation.dispatch(resetAction);
    return true;
  }

And in another pages

handleBackButtonClick() {
    // @ts-ignore
    this.props.navigation.pop();
    return true;
  }
``` And voila


问:
Rails 4: image_tag not working for images in emails
Here is the code I have:

<%= image_tag "/assets/logos/#{@company_name.downcase}_logo.jpg" %>

When the email is sent, and I view the email in my email client, the image is not showing up. It appears like a broken image

Anyone else run into this issue?

Here is my development.rb

```<code>MyApp::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  config.action_controller.asset_host = 'localhost:3000'
  config.action_mailer.asset_host = 'http://localhost:3000'
end
</code>```

Working code:

<%= image_tag("logos/#{@company_name.downcase}_logo.jpg") %>

答:
In contact mailer add image as an atachement

```<code>def sendCode(message,email)
 @message = "message: #{message} "
 attachments.inline['img1.png'] = File.read(Rails.root.join("public/emails", "img1.png"))
 attachments.inline['logo.png'] = File.read(Rails.root.join("public/emails", "logo.png"))
 mail(to: email, subject: 'Sample Email')
end
</code>```

And in your html.erb file you can call the attachement image like that

```<code><%= image_tag attachments['logo.png'].url, alt: 'image', class: 'photo' -%>
</code>```

it will work with you

Body:
Here is the code I have:

<%= image_tag "/assets/logos/#{@company_name.downcase}_logo.jpg" %>

When the email is sent, and I view the email in my email client, the image is not showing up. It appears like a broken image

Anyone else run into this issue?

Here is my development.rb

MyApp::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  config.action_controller.asset_host = 'localhost:3000'
  config.action_mailer.asset_host = 'http://localhost:3000'
end

Working code:

<%= image_tag("logos/#{@company_name.downcase}_logo.jpg") %>

Body:
In contact mailer add image as an atachement

def sendCode(message,email)
 @message = "message: #{message} "
 attachments.inline['img1.png'] = File.read(Rails.root.join("public/emails", "img1.png"))
 attachments.inline['logo.png'] = File.read(Rails.root.join("public/emails", "logo.png"))
 mail(to: email, subject: 'Sample Email')
end

And in your html.erb file you can call the attachement image like that

<%= image_tag attachments['logo.png'].url, alt: 'image', class: 'photo' -%>

it will work with you


问:
How do you read/write to/from and xcode plist?
I have a utility app with the flipsideview and I'm trying to use the flipsideview to enable the user to change settings that will effect the main view. I thought the easiest way to do this would be to write changes made on the flip side view to a plist but I am new to objective-c and can't seem to find any help in any forums. When I use the code I found online I keep getting a "Initializer element is not a compile-time constant". This is the code:

```<code>NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Settings.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];

[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
</code>```

Also, I am new to objective-c (making the transition from html, css, etc.) and so a description of what's going on would be much appreciated. And please don't just paste a link to the apple developer tutorials. I've been through them and can't seem to grasp it being I learn much better by doing a practical example.

Thanks ahead of time.

答: Use NSUserDefaults. That's what you're supposed to use for saving user preferences.

Body:
I have a utility app with the flipsideview and I'm trying to use the flipsideview to enable the user to change settings that will effect the main view. I thought the easiest way to do this would be to write changes made on the flip side view to a plist but I am new to objective-c and can't seem to find any help in any forums. When I use the code I found online I keep getting a "Initializer element is not a compile-time constant". This is the code:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Settings.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];

[fileManager copyItemAtPath:bundle toPath: path error:&error];
}

Also, I am new to objective-c (making the transition from html, css, etc.) and so a description of what's going on would be much appreciated. And please don't just paste a link to the apple developer tutorials. I've been through them and can't seem to grasp it being I learn much better by doing a practical example.

Thanks ahead of time.


问:
@SpringBootTest interferes with EclipseLink dynamic weaving
My company is developing a web application using Spring Boot, Spring MVC, JPA with EclipseLink and dynamic weaving.
My task is to prepare implementation of UI and integration tests spinning up the application using JUnit and @SpringBootTest and interacting with it using Selenium.

As stated at Spring Boot Testing Features,
Tests using the @SpringBootApplication annotation can make use of the @MockBean annotation to define Mockito mocks for beans within the ApplicationContext.
This is achieved by registering a BeanFactoryPostProcessor, MockitoPostProcessor, recursively scanning classes annotated with @Component or @Configuration for classes and fields annotated with @MockBean.

Unfortunately, this causes the entity classes referenced in those classes to be loaded before the LocalContainerEntityManagerFactoryBean that is supposed to scan for them is instantiated and set up with a LoadTimeWeaver, thus causing the load time weaving for those entities to be skipped.
This leads to NoSuchMethodExceptions for methods created by weaving like _persistence_propertyChange() when persistence actions are performed.

Is it possible to use @SpringBootTest with EclipseLink and dynamic weaving?
If not, what would be a good alternative to set up an integration test
for a recent Spring Boot version?

答:
We encountered the same problem in a web app built with Spring Boot 2.1.6 and EclipseLink 2.7.6.

Is it possible to use @SpringBootTest with EclipseLink and dynamic weaving? If not, what would be a good alternative to set up an integration test for a recent Spring Boot version?

The solution was to set eclipselink.weaving JPA property to false in @SpringBootTest, and to true in regular operation.

Persistence config:

```<code><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaProperties">
        <props>
            <prop key="eclipselink.weaving">${jpa.eclipselink.weaving}</prop>
        </props>
    </property>
    <!-- ... -->
</bean>
</code>```

Then in application.properties:

```<code>jpa.eclipselink.weaving=true
</code>```

And on JUnit test class:

```<code>@TestPropertySource(properties = "jpa.eclipselink.weaving=false")
</code>```

Body:
We encountered the same problem in a web app built with Spring Boot 2.1.6 and EclipseLink 2.7.6.

Is it possible to use @SpringBootTest with EclipseLink and dynamic weaving? If not, what would be a good alternative to set up an integration test for a recent Spring Boot version?

The solution was to set eclipselink.weaving JPA property to false in @SpringBootTest, and to true in regular operation.

Persistence config:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaProperties">
        <props>
            <prop key="eclipselink.weaving">${jpa.eclipselink.weaving}</prop>
        </props>
    </property>
    <!-- ... -->
</bean>

Then in application.properties:

jpa.eclipselink.weaving=true

And on JUnit test class:

@TestPropertySource(properties = "jpa.eclipselink.weaving=false")


问:
CORS preflight request not making call after the options request method
I am trying to make a CORS call from my localhost to a website. The request headers is as shown in the image . According to preflight it first makes a OPTIONS type request and then it makes the actual call() to the server. I am able to get 200 for the OPTIONS type but it is not making the real call of GET to the server

答:
The OPTIONS method will only tell you what the server allows you to do. If it fails from the browser after the OPTIONS method was a success then the Origin is probably the problem.

When you ask for the OPTIONS it will tell you which methods are allowed, but it will still check on the server if the Origin which the browser provides is allowed to perform those actions.