问:
PHP associative array merge with unique values
I have an array which looks like this

```<code>$array=Array ( [0] => Array ( [Country] => United Arab Emirates [users] => 2 )
        [1] => Array ( [Country] => Albania [users] => 1 )
        [2] => Array ( [Country] => Armenia [users] => 4 )
        [3] => Array ( [Country] => Argentina [users] => 12 )
        [4] => Array ( [Country] => United Arab Emirates [users] => 3 )
        [5] => Array ( [Country] => Austria [users] => 1 )
        [6] => Array ( [Country] => Austria [users] => 8 )
        [7] => Array ( [Country] => Austria [users] => 1 ) )
</code>```

I want to add second value if 1st value are same.
i have tried array_unique($array) but not able to add second value if first values are same.

So the output i expected is

```<code>Array ( [0] => Array ( [Country] => United Arab Emirates [users] => 5 )
        [1] => Array ( [Country] => Albania [users] => 1 )
        [2] => Array ( [Country] => Armenia [users] => 4 )
        [3] => Array ( [Country] => Argentina [users] => 12 )
        [4] => Array ( [Country] => Austria [users] => 10 ))
</code>```

I tried as below but not able to solve

```<code>$array=array_unique($array)
and
        foreach ($array as $unique){
            if( in_array( $unique['Country'] ,$array) )
            {
                print_r ($unique['Country']);
            }
        }
</code>```

Can you help me out?

答:
you can make unique using this method

```<code>array_unique($associativeArray,SORT_REGULAR);
</code>```

Define an associative array $associativeArray with name and age keys.

```<code> $associativeArray[] = array("name" => "pankaj Singh","no"=>4);
 $associativeArray[] = array("name" => "pankaj Singh","no"=>24);
</code>```

Body:
I have an array which looks like this

$array=Array ( [0] => Array ( [Country] => United Arab Emirates [users] => 2 )
        [1] => Array ( [Country] => Albania [users] => 1 )
        [2] => Array ( [Country] => Armenia [users] => 4 )
        [3] => Array ( [Country] => Argentina [users] => 12 )
        [4] => Array ( [Country] => United Arab Emirates [users] => 3 )
        [5] => Array ( [Country] => Austria [users] => 1 )
        [6] => Array ( [Country] => Austria [users] => 8 )
        [7] => Array ( [Country] => Austria [users] => 1 ) )

I want to add second value if 1st value are same.
i have tried array_unique($array) but not able to add second value if first values are same.

So the output i expected is

Array ( [0] => Array ( [Country] => United Arab Emirates [users] => 5 )
        [1] => Array ( [Country] => Albania [users] => 1 )
        [2] => Array ( [Country] => Armenia [users] => 4 )
        [3] => Array ( [Country] => Argentina [users] => 12 )
        [4] => Array ( [Country] => Austria [users] => 10 ))

I tried as below but not able to solve

$array=array_unique($array)
and
        foreach ($array as $unique){
            if( in_array( $unique['Country'] ,$array) )
            {
                print_r ($unique['Country']);
            }
        }

Can you help me out?

Body:
you can make unique using this method

array_unique($associativeArray,SORT_REGULAR);

Define an associative array $associativeArray with name and age keys.

 $associativeArray[] = array("name" => "pankaj Singh","no"=>4);
 $associativeArray[] = array("name" => "pankaj Singh","no"=>24);


来源: stackexchange

问:
How to have maven resolve a dependency of a dependency which was created by a non-default profile for some classifier?
Given a library which has different dependencies depending on a profile, say for example

```<code>    <profile>
        <id>default</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <envClassifier>cuda-10.1</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.1.0</version>
            </dependency>
        </dependencies>
    </profile>
    <profile>
        <id>cuda-10.0</id>
        <properties>
            <envClassifier>cuda-10.0</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.0.0</version>
            </dependency>
        </dependencies>
    </profile>
</code>```

I am creating artefacts with different classifiers, say for example

```<code>library-1.0.0-cuda-10.0
</code>```

and

```<code>library-1.0.0-cuda-10.1
</code>```

(here cuda-10.0 and cuda-10.1 are the classifiers for the artefact library-1.0.0).

If another project references this library, say for example as

```<code>    <dependency>
        <groupId>net.finmath</groupId>
        <artifactId>library</artifactId>
        <version>1.0.0</version>
        <classifier>cuda-10.0</classifier>
    </dependency>
</code>```

then the correct artefact is pulled (here library-1.0.0-cuda-10.0.jar) but the dependency tree (via mvn dependency:tree) shows the wrong dependencies of the dependency. In this example it shows jcuda-10.1.0 and not juda-10.0.0.

This issue is due to an artefact having a single pom.xml for all classifiers (and the default profile kicks in).

Question 1: Can you have dedicated pom.xml in the repositories for different classifiers, to reflect the correct dependencies?

Apparently the issue cannot be resolved by setting a profile (-P parameter) on the outer project, because profile selectors are not passed to the poms of the dependencies. It looks as if profiles do not walk down the dependency tree.

Question 2: Is there a way to pass a profile selector to a pom of a dependency to select the right dependencies of the dependency?

I found two options to resolve the problem, but I am not very happy with them.

The first one would be to not have a default profile with a dependency in the pom of the library. In that case the user of the library (here library-1.0.0) has to specify the correct classifier and the correct downstream dependencies. This appears to be cumbersome. Also note that in this case the build of the library would fail without specification of the profile.

It is possible to use the profile to alter the name (or version) of the artefact. Since each version or artefact comes with its own pom, this allows to specify profile specific dependencies to be resolved.

However, I believe there should be a better solution, because otherwise it looks as if the specification of dependencies in profiles makes no sense for artefacts which are libraries, that is, which are themselves dependencies of another projects.

Question 3: What is the Maven way to resolve this issue?

PS: The question arose in this project: http://finmath.net/finmath-lib-cuda-extensions/

答:
I found a lightweight solution for the problem.

You may activate a profile though a property.

Properties may not be passed from a pom to the poms of it's dependencies, but a property which is set on the command line acts on both poms.

Hence, instead of using a profile on the command line, use a property and activate the corresponding profiles in your project's pom and the library's pom.

So in the above example, the (outer) project (which references the library) has a profile

```<code>    <profile>
        <id>cudaversion</id>
        <activation>
            <property>
                <name>cuda.version</name>
            </property>
        </activation>
        <properties>
            <finmath-cuda.classifier>cuda-${cuda.version}</finmath-cuda.classifier>
        </properties>
    </profile>
</code>```

which sets the classifier of its dependency, that is this project has a dependency to library-1.0.0

```<code>    <dependency>
        <groupId>net.finmath</groupId>
        <artifactId>library</artifactId>
        <version>1.0.0</version>
        <classifier>${finmath-cuda.classifier}</classifier>
    </dependency>
</code>```

And the pom of library-1.0.0 has a profile which is activated by the same property as in

```<code>    <profile>
        <id>cuda-10.0</id>
        <activation>
            <property>
                <name>cuda.version</name>
                <value>10.0</value>
            </property>
        </activation>
        <properties>
            <envClassifier>cuda-10.0</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.0.0</version>
            </dependency>
        </dependencies>
    </profile>
</code>```

The outer project is then build with mvn -Dcuda.version=10.0 to activate both profiles.

ContentLicense: CC BY-SA 4.0

Body:
Given a library which has different dependencies depending on a profile, say for example

    <profile>
        <id>default</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <envClassifier>cuda-10.1</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.1.0</version>
            </dependency>
        </dependencies>
    </profile>
    <profile>
        <id>cuda-10.0</id>
        <properties>
            <envClassifier>cuda-10.0</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.0.0</version>
            </dependency>
        </dependencies>
    </profile>

I am creating artefacts with different classifiers, say for example

library-1.0.0-cuda-10.0

and

library-1.0.0-cuda-10.1

(here cuda-10.0 and cuda-10.1 are the classifiers for the artefact library-1.0.0).

If another project references this library, say for example as

    <dependency>
        <groupId>net.finmath</groupId>
        <artifactId>library</artifactId>
        <version>1.0.0</version>
        <classifier>cuda-10.0</classifier>
    </dependency>

then the correct artefact is pulled (here library-1.0.0-cuda-10.0.jar) but the dependency tree (via mvn dependency:tree) shows the wrong dependencies of the dependency. In this example it shows jcuda-10.1.0 and not juda-10.0.0.

This issue is due to an artefact having a single pom.xml for all classifiers (and the default profile kicks in).

Question 1: Can you have dedicated pom.xml in the repositories for different classifiers, to reflect the correct dependencies?

Apparently the issue cannot be resolved by setting a profile (-P parameter) on the outer project, because profile selectors are not passed to the poms of the dependencies. It looks as if profiles do not walk down the dependency tree.

Question 2: Is there a way to pass a profile selector to a pom of a dependency to select the right dependencies of the dependency?

I found two options to resolve the problem, but I am not very happy with them.

The first one would be to not have a default profile with a dependency in the pom of the library. In that case the user of the library (here library-1.0.0) has to specify the correct classifier and the correct downstream dependencies. This appears to be cumbersome. Also note that in this case the build of the library would fail without specification of the profile.

It is possible to use the profile to alter the name (or version) of the artefact. Since each version or artefact comes with its own pom, this allows to specify profile specific dependencies to be resolved.

However, I believe there should be a better solution, because otherwise it looks as if the specification of dependencies in profiles makes no sense for artefacts which are libraries, that is, which are themselves dependencies of another projects.

Question 3: What is the Maven way to resolve this issue?

PS: The question arose in this project: http://finmath.net/finmath-lib-cuda-extensions/

Body:
I found a lightweight solution for the problem.

You may activate a profile though a property.

Properties may not be passed from a pom to the poms of it's dependencies, but a property which is set on the command line acts on both poms.

Hence, instead of using a profile on the command line, use a property and activate the corresponding profiles in your project's pom and the library's pom.

So in the above example, the (outer) project (which references the library) has a profile

    <profile>
        <id>cudaversion</id>
        <activation>
            <property>
                <name>cuda.version</name>
            </property>
        </activation>
        <properties>
            <finmath-cuda.classifier>cuda-${cuda.version}</finmath-cuda.classifier>
        </properties>
    </profile>

which sets the classifier of its dependency, that is this project has a dependency to library-1.0.0

    <dependency>
        <groupId>net.finmath</groupId>
        <artifactId>library</artifactId>
        <version>1.0.0</version>
        <classifier>${finmath-cuda.classifier}</classifier>
    </dependency>

And the pom of library-1.0.0 has a profile which is activated by the same property as in

    <profile>
        <id>cuda-10.0</id>
        <activation>
            <property>
                <name>cuda.version</name>
                <value>10.0</value>
            </property>
        </activation>
        <properties>
            <envClassifier>cuda-10.0</envClassifier>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.jcuda</groupId>
                <artifactId>jcuda</artifactId>
                <version>10.0.0</version>
            </dependency>
        </dependencies>
    </profile>

The outer project is then build with mvn -Dcuda.version=10.0 to activate both profiles.


问:
Calculating display coordinates for the horizon given the camera position and forward, up and right unit vectors
I've written a simple roller coaster simulator in Scratch using 3d catmull-rom splines to create the track layout. Rotation minimizing frames are calculated so that surface normals flow smoothly throughout the spline. The camera path is pre-calculated with a look-at rotation matrix for each position (using unit normals for the direction of travel, the surface normal of the track and the cross product of the two. This all works fine and can be viewed here.

I'd like to add a simple background where anything above the horizon is blue for sky and anything below is green for land but am hitting a complete mental block on how to calculate this. I suspect I should consider the horizon as a simple 3D plane with surface normal of (0,1,0), rotate that using the look-at matrix and then create the visible horizon coordinates from the result but need some help in how to do this.

Any suggestions would be very welcome!

答: I achieved it by rotating the position of the horizon (0,0,0) relative to the camera and the plane's normal using the look-at matrix. It was then just a case of projecting a distant point on the horizon onto the screen.</p>


问:
Template reference variables: assigning ngForm and ngModel
I am learning Angular on Pluralsight and I have a question regarding a course I am taking currently.

I am confused on the reasoning behind template reference variables when they are assigned a value. For example, if you put #name in an <input> tag, I understand name can now reference the input tag and it's associated value. The question I have is regarding decalrations such as #name="ngModel"

Looking over the Angular documentation, I found this:

You need a template reference variable to access the input box's Angular control from within the template. Here you created a variable called name and gave it the value "ngModel".

I also found this helpful answer to guide me on the right track.

But I am still a bit unclear as to what value assigning the template reference variable ngModel adds.

Part of the form I am currently writing:

```<code><form #form="ngForm" (ngSubmit)="onSubmit(form)">

        <div class="form-group">
            <label for="name">Name</label>
            <input id="name" name="name" class="form-control" [(ngModel)]="userSettings.name"
                    required #nameField="ngModel"
                    (blur)="onBlur(nameField)"
                    [class.field-error]="form.submitted && nameField.invalid">
            <div [hidden]="!form.submitted || nameField.valid"
                class="alert alert-danger">
                Enter a name
            </div>
        </div>
</code>```

Part of the Typescript file:

```<code>@Component({
  selector: 'app-user-settings-form',
  templateUrl: './user-settings-form.component.html',
  styleUrls: ['./user-settings-form.component.css']
})
export class UserSettingsFormComponent implements OnInit {

  originalUserSettings: UserSettings = {
    name: null,
    emailOffers: null,
    interfaceStyle: null,
    subscriptionType: null,
    notes: null
  };

  userSettings: UserSettings = { ...this.originalUserSettings };

  constructor() { }

  ngOnInit(): void {

  }
</code>```

What is the difference between just using #nameField vs using #nameField="ngModel" as well as #form vs #form="ngForm"?

答:
I am not sure which documentation did you have a look at but you can have a look here => https://angular.io/guide/template-syntax#input-and-output-properties

The short answer is that normally you would declare template variables without assigning a name to them => #variable <= and this will give you access to the html element and its value. In some rare cases as is in the case with the ngForm and ngModel which are called directives, they will give you for example the ability to track the value and validity of every control in the form => ngForm.

Body:
I am learning Angular on Pluralsight and I have a question regarding a course I am taking currently.

I am confused on the reasoning behind template reference variables when they are assigned a value. For example, if you put #name in an <input> tag, I understand name can now reference the input tag and it's associated value. The question I have is regarding decalrations such as #name="ngModel"

Looking over the Angular documentation, I found this:

You need a template reference variable to access the input box's Angular control from within the template. Here you created a variable called name and gave it the value "ngModel".

I also found this helpful answer to guide me on the right track.

But I am still a bit unclear as to what value assigning the template reference variable ngModel adds.

Part of the form I am currently writing:

<form #form="ngForm" (ngSubmit)="onSubmit(form)">

            Name
            <input id="name" name="name" class="form-control" [(ngModel)]="userSettings.name"
                    required #nameField="ngModel"
                    (blur)="onBlur(nameField)"
                    [class.field-error]="form.submitted && nameField.invalid">

                Enter a name

Part of the Typescript file:

@Component({
  selector: 'app-user-settings-form',
  templateUrl: './user-settings-form.component.html',
  styleUrls: ['./user-settings-form.component.css']
})
export class UserSettingsFormComponent implements OnInit {

  originalUserSettings: UserSettings = {
    name: null,
    emailOffers: null,
    interfaceStyle: null,
    subscriptionType: null,
    notes: null
  };

  userSettings: UserSettings = { ...this.originalUserSettings };

  constructor() { }

  ngOnInit(): void {

  }

What is the difference between just using #nameField vs using #nameField="ngModel" as well as #form vs #form="ngForm"?


问:
How to release Alicloud by a scheduled date automatically
I would like to use Terraform to organize Alicloud ECS which support to automatically release resources for post-paid clients.
Question is how to make use of this feature in Terraform to set a automatic scheduled date to release Alicloud ECS?
I didn't find a clue on tutorial of Website.

Many thanks.

答:
https://www.terraform.io/docs/providers/alicloud/r/instance.html#auto_release_time

Probably, 8 months ago this feature was not available.

There is an additional solution. alicloud_instance resource support provisioning block and aliyun CLI. You can try something like this:

```<code>resource "alicloud_instance" "test" {
  image_id = ""
  instance_type = ""
  security_groups = []

  provisioner "local-exec" {
    command = "aliyun ModifyInstanceAutoReleaseTime --InstanceId ${self.id} --AutoReleaseTime $release_date"
    environment {
      release_date = timeadd(timestamp(), "5h")
    }
  }
}
</code>```

Remember to add any authorization method to the command in the provisioner.
https://github.com/aliyun/aliyun-cli

Body:
https://www.terraform.io/docs/providers/alicloud/r/instance.html#auto_release_time

Probably, 8 months ago this feature was not available.

There is an additional solution. alicloud_instance resource support provisioning block and aliyun CLI. You can try something like this:

resource "alicloud_instance" "test" {
  image_id = ""
  instance_type = ""
  security_groups = []

  provisioner "local-exec" {
    command = "aliyun ModifyInstanceAutoReleaseTime --InstanceId ${self.id} --AutoReleaseTime $release_date"
    environment {
      release_date = timeadd(timestamp(), "5h")
    }
  }
}

Remember to add any authorization method to the command in the provisioner.
https://github.com/aliyun/aliyun-cli


问:
Move TextField containing widget to view-able area when keyboard pop up regardless of another widget in the bottom
What am trying to achieve is move my TextField to view-able area when keyboard pop up, also I want a widget(Text widget) that is aligned bottom center to remain in there and get hidden by keyboard.

My Code:

```<code>     @override
   Widget build(BuildContext context) {
     //databaseHelper.initializeDatabase();
    return Scaffold(
    resizeToAvoidBottomPadding: false,
    appBar: AppBar(
      title: Text('BOM'),
    ),
    body: Builder(builder: (BuildContext context) {
      return Container(
          child: Stack(children: <Widget>[
            //SingleChildScrollView widget tried here, result was a failure

        Container(
          margin: EdgeInsets.only(bottom: 100.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 50.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selection = '5-co';
                          });
                        },
                        child: Container(
                          width: 130.0,
                          padding: EdgeInsets.all(15.0),
                          decoration: BoxDecoration(
                              color: selection == '5-co'
                                  ? Colors.green
                                  : Colors.black45,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0))),
                          child: Center(
                              child: Text(
                            'COMPONENTS',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold),
                          )),
                        ),
                      ),
                      Container(
                        width: 30.0,
                      ),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selection = '5-nl';
                          });
                        },
                        child: Container(
                          width: 130.0,
                          padding: EdgeInsets.all(15.0),
                          decoration: BoxDecoration(
                              color: selection == '5-nl'
                                  ? Colors.blue
                                  : Colors.black45,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0))),
                          child: Center(
                              child: Text(
                            'REXIN',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold),
                          )),
                        ),
                      )
                    ],
                  ),
                ),
                // SizedBox(height: 50,),

                Padding(
                  padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                  child: TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      labelText: 'Enter article:',
                      hintText: 'eg: 3290-BR',
                      prefixIcon: Icon(Icons.local_offer),
                      suffixIcon: IconButton(
                          icon: Icon(Icons.search),
                          onPressed: () {
                            //if (value.length >= 4) {
                            navigateToList(controller.text, selection);
                            //  } else
                            //   Scaffold.of(context).showSnackBar(SnackBar(
                            //    content:
                            //
                          }),
                      /*enabledBorder:
              OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Colors.green)),*/
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0)),
                    ),
                    onSubmitted: (value) {
                      //if (value.length >= 4) {
                      navigateToList(value, selection);
                      //  } else
                      //   Scaffold.of(context).showSnackBar(SnackBar(
                      //    content:
                      //     Text('Oops, please give me more details !')));
                    },
                  ),
                ),
              ]),
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(' P  A  N  D  U',
                  style: TextStyle(
                      color: Colors.green,
                      fontSize: 30.0,
                      fontWeight: FontWeight.bold)),
            ))
      ]));
    }));
}
</code>```

Currently my TextField containing widget is in a container under stack widget and is aligned to center by column widget attribs.

WHAT I TRIED:
I referred some questions in here and tried  SingleChildScrollView widget under my stack, and result was my container under the  SingleChildScrollView widget loses its column axis attribs and get aligned to top of body.

What I didn't tried to solve my issue is with animations to move widget up. I will go for it if there isn't any other method, cause I gotta learn about those widgets which is still in que. ;')

答:
I made SingleChildScrollView widget under my stack for all my widgets except the bottom wText widget, which I don't want to see when keyboard pops up. And then I just hide my Text widget using flutter's Visibility widget when keyboard comes in screen. This completely solved my problem (I used keyboard_visibility: ^0.5.5 library to get keyboard info, that tells when to hide or show my Text widget in the bottom ).

For reference my unsorted whole code:

```<code>   bool _visible = true;

    @override
   void initState() {
   super.initState();
   KeyboardVisibilityNotification().addNewListener(
  onChange: (bool keyvisible) {
    //print('keyboard $visible');
    setState(() {
      _visible = !keyvisible;
    });
  },
);
}

  @override
 Widget build(BuildContext context) {
//databaseHelper.initializeDatabase();
return Scaffold(
    //resizeToAvoidBottomPadding: false,
    appBar: AppBar(
      title: Text('BOM'),
    ),
    body: Builder(builder: (BuildContext context) {
      return Center(
          child: Stack(children: <Widget>[
        SingleChildScrollView(
          padding: EdgeInsets.all(8.0),
          //margin: EdgeInsets.only(bottom: 100.0),
          child: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 200.0,
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 50.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              selection = '5-co';
                            });
                          },
                          child: Container(
                            width: 130.0,
                            padding: EdgeInsets.all(15.0),
                            decoration: BoxDecoration(
                                color: selection == '5-co'
                                    ? Colors.green
                                    : Colors.black45,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0))),
                            child: Center(
                                child: Text(
                              'COMPONENTS',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13.0,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                        ),
                        Container(
                          width: 30.0,
                        ),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              selection = '5-nl';
                            });
                          },
                          child: Container(
                            width: 130.0,
                            padding: EdgeInsets.all(15.0),
                            decoration: BoxDecoration(
                                color: selection == '5-nl'
                                    ? Colors.blue
                                    : Colors.black45,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0))),
                            child: Center(
                                child: Text(
                              'REXIN',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13.0,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                        )
                      ],
                    ),
                  ),
                  // SizedBox(height: 50,),

                  Padding(
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    child: TextField(
                      textInputAction: TextInputAction.search,
                      controller: controller,
                      decoration: InputDecoration(
                        labelText: 'Enter article:',
                        hintText: 'eg: 3290-BR',
                        prefixIcon: Icon(Icons.local_offer),
                        suffixIcon: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: () {
                              //if (value.length >= 4) {
                              navigateToList(controller.text, selection);
                              //  } else
                              //   Scaffold.of(context).showSnackBar(SnackBar(
                              //    content:
                              //
                            }),
                        /*enabledBorder:
                OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Colors.green)),*/
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0)),
                      ),
                      onSubmitted: (value) {
                        //if (value.length >= 4) {
                        navigateToList(value, selection);
                        //  } else
                        //   Scaffold.of(context).showSnackBar(SnackBar(
                        //    content:
                        //     Text('Oops, please give me more details !')));
                      },
                    ),
                  ),
                ]),
          ),
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Visibility(
                visible: _visible,
                child: RichText(
                    text: TextSpan(children: <TextSpan>[
                  TextSpan(
                      text: ' P  A  N  D  U',
                      style: TextStyle(
                          color: Colors.green,
                          fontSize: 30.0,
                          fontWeight: FontWeight.bold)),
                      TextSpan(text: '\t v', style: TextStyle(color: Colors.white70, fontSize: 10.0, fontWeight: FontWeight.bold)),
                      TextSpan(text: '0.02.05', style: TextStyle(color: Colors.white70, fontSize: 11.0, fontStyle: FontStyle.italic))
                ])),
              ),
            ))
      ]));
    }));
 }
</code>```

Body:
What am trying to achieve is move my TextField to view-able area when keyboard pop up, also I want a widget(Text widget) that is aligned bottom center to remain in there and get hidden by keyboard.

My Code:

     @override
   Widget build(BuildContext context) {
     //databaseHelper.initializeDatabase();
    return Scaffold(
    resizeToAvoidBottomPadding: false,
    appBar: AppBar(
      title: Text('BOM'),
    ),
    body: Builder(builder: (BuildContext context) {
      return Container(
          child: Stack(children: <Widget>[
            //SingleChildScrollView widget tried here, result was a failure

        Container(
          margin: EdgeInsets.only(bottom: 100.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 50.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selection = '5-co';
                          });
                        },
                        child: Container(
                          width: 130.0,
                          padding: EdgeInsets.all(15.0),
                          decoration: BoxDecoration(
                              color: selection == '5-co'
                                  ? Colors.green
                                  : Colors.black45,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0))),
                          child: Center(
                              child: Text(
                            'COMPONENTS',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold),
                          )),
                        ),
                      ),
                      Container(
                        width: 30.0,
                      ),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selection = '5-nl';
                          });
                        },
                        child: Container(
                          width: 130.0,
                          padding: EdgeInsets.all(15.0),
                          decoration: BoxDecoration(
                              color: selection == '5-nl'
                                  ? Colors.blue
                                  : Colors.black45,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0))),
                          child: Center(
                              child: Text(
                            'REXIN',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.0,
                                fontWeight: FontWeight.bold),
                          )),
                        ),
                      )
                    ],
                  ),
                ),
                // SizedBox(height: 50,),

                Padding(
                  padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                  child: TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      labelText: 'Enter article:',
                      hintText: 'eg: 3290-BR',
                      prefixIcon: Icon(Icons.local_offer),
                      suffixIcon: IconButton(
                          icon: Icon(Icons.search),
                          onPressed: () {
                            //if (value.length >= 4) {
                            navigateToList(controller.text, selection);
                            //  } else
                            //   Scaffold.of(context).showSnackBar(SnackBar(
                            //    content:
                            //
                          }),
                      /*enabledBorder:
              OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Colors.green)),*/
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0)),
                    ),
                    onSubmitted: (value) {
                      //if (value.length >= 4) {
                      navigateToList(value, selection);
                      //  } else
                      //   Scaffold.of(context).showSnackBar(SnackBar(
                      //    content:
                      //     Text('Oops, please give me more details !')));
                    },
                  ),
                ),
              ]),
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(' P  A  N  D  U',
                  style: TextStyle(
                      color: Colors.green,
                      fontSize: 30.0,
                      fontWeight: FontWeight.bold)),
            ))
      ]));
    }));
}

Currently my TextField containing widget is in a container under stack widget and is aligned to center by column widget attribs.

WHAT I TRIED:
I referred some questions in here and tried  SingleChildScrollView widget under my stack, and result was my container under the  SingleChildScrollView widget loses its column axis attribs and get aligned to top of body.

What I didn't tried to solve my issue is with animations to move widget up. I will go for it if there isn't any other method, cause I gotta learn about those widgets which is still in que. ;')

Body:
I made SingleChildScrollView widget under my stack for all my widgets except the bottom wText widget, which I don't want to see when keyboard pops up. And then I just hide my Text widget using flutter's Visibility widget when keyboard comes in screen. This completely solved my problem (I used keyboard_visibility: ^0.5.5 library to get keyboard info, that tells when to hide or show my Text widget in the bottom ).

For reference my unsorted whole code:

   bool _visible = true;

    @override
   void initState() {
   super.initState();
   KeyboardVisibilityNotification().addNewListener(
  onChange: (bool keyvisible) {
    //print('keyboard $visible');
    setState(() {
      _visible = !keyvisible;
    });
  },
);
}

  @override
 Widget build(BuildContext context) {
//databaseHelper.initializeDatabase();
return Scaffold(
    //resizeToAvoidBottomPadding: false,
    appBar: AppBar(
      title: Text('BOM'),
    ),
    body: Builder(builder: (BuildContext context) {
      return Center(
          child: Stack(children: <Widget>[
        SingleChildScrollView(
          padding: EdgeInsets.all(8.0),
          //margin: EdgeInsets.only(bottom: 100.0),
          child: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 200.0,
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 50.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              selection = '5-co';
                            });
                          },
                          child: Container(
                            width: 130.0,
                            padding: EdgeInsets.all(15.0),
                            decoration: BoxDecoration(
                                color: selection == '5-co'
                                    ? Colors.green
                                    : Colors.black45,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0))),
                            child: Center(
                                child: Text(
                              'COMPONENTS',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13.0,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                        ),
                        Container(
                          width: 30.0,
                        ),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              selection = '5-nl';
                            });
                          },
                          child: Container(
                            width: 130.0,
                            padding: EdgeInsets.all(15.0),
                            decoration: BoxDecoration(
                                color: selection == '5-nl'
                                    ? Colors.blue
                                    : Colors.black45,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5.0))),
                            child: Center(
                                child: Text(
                              'REXIN',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13.0,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                        )
                      ],
                    ),
                  ),
                  // SizedBox(height: 50,),

                  Padding(
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    child: TextField(
                      textInputAction: TextInputAction.search,
                      controller: controller,
                      decoration: InputDecoration(
                        labelText: 'Enter article:',
                        hintText: 'eg: 3290-BR',
                        prefixIcon: Icon(Icons.local_offer),
                        suffixIcon: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: () {
                              //if (value.length >= 4) {
                              navigateToList(controller.text, selection);
                              //  } else
                              //   Scaffold.of(context).showSnackBar(SnackBar(
                              //    content:
                              //
                            }),
                        /*enabledBorder:
                OutlineInputBorder(borderRadius: BorderRadius.circular(8.0), borderSide: BorderSide(color: Colors.green)),*/
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0)),
                      ),
                      onSubmitted: (value) {
                        //if (value.length >= 4) {
                        navigateToList(value, selection);
                        //  } else
                        //   Scaffold.of(context).showSnackBar(SnackBar(
                        //    content:
                        //     Text('Oops, please give me more details !')));
                      },
                    ),
                  ),
                ]),
          ),
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Visibility(
                visible: _visible,
                child: RichText(
                    text: TextSpan(children: <TextSpan>[
                  TextSpan(
                      text: ' P  A  N  D  U',
                      style: TextStyle(
                          color: Colors.green,
                          fontSize: 30.0,
                          fontWeight: FontWeight.bold)),
                      TextSpan(text: '\t v', style: TextStyle(color: Colors.white70, fontSize: 10.0, fontWeight: FontWeight.bold)),
                      TextSpan(text: '0.02.05', style: TextStyle(color: Colors.white70, fontSize: 11.0, fontStyle: FontStyle.italic))
                ])),
              ),
            ))
      ]));
    }));
 }


问:
Extract 'name' from array of objects on init method
I have the below code:

```<code>add_action('manage_recipe_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $test = Recipe::init($post_id);
            var_dump($test);
            break;
    }
}, 10, 3);
</code>```

Which gives me an output of this array of objects:

How can I extract all the authors 'names' only into an echo?

答:
First of all, access the authors property of the Recipe object. You're going to need an accessible method, as it's private. This is going to give you an array of Profile objects. Cycle that array and use an accessible method to get the name property, as it's private. Then do whatever you want with that information.

It should look something like this:

```<code>$recipe  = Recipe::init($post_id);
$authors = $recipe->getAuthors(); // This needs to be a method of the Recipe class.
foreach($authors as $author) {
    echo $author->getName(); // This needs to be a method of the Profile class.
    echo "\n";
}
</code>```

Format accordingly.

Body:
I have the below code:

add_action('manage_recipe_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $test = Recipe::init($post_id);
            var_dump($test);
            break;
    }
}, 10, 3);

Which gives me an output of this array of objects:

How can I extract all the authors 'names' only into an echo?

Body:
First of all, access the authors property of the Recipe object. You're going to need an accessible method, as it's private. This is going to give you an array of Profile objects. Cycle that array and use an accessible method to get the name property, as it's private. Then do whatever you want with that information.

It should look something like this:

$recipe  = Recipe::init($post_id);
$authors = $recipe->getAuthors(); // This needs to be a method of the Recipe class.
foreach($authors as $author) {
    echo $author->getName(); // This needs to be a method of the Profile class.
    echo "\n";
}

Format accordingly.


问:
Android Development - starting activity from service
I've got a bit of code which is listening for a message on a socket, and parsing data from the socket into an email to be sent.  I'm able to create the intent, and set the FLAG_ACTIVITY_NEW_TASK flag on it, but yet, when i call
startActivity(Intent.createChooser(intent, "Email"));

I get an AndoridRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

What confuses me on this is that I have explicitly called
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Am I missing something obvious here?

```<code>protected void doEmail(DataInputStream in)  throws IOException {
  String id = in.readUTF();
  createEmail(id);
}

protected void createEmail(String rawEmailString) {
  // need to get to, subject, body and path from string
  String[] stringArray = rawEmailString.split("~");
  Intent intent = prepareEmail(stringArray[0], stringArray[1], stringArray[2], stringArray[3]);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(Intent.createChooser(intent, "Email"));
}

public Intent prepareEmail(String to, String subject, String body, String pathToAttachment){
  Intent intent = new Intent(Intent.ACTION_SEND);
  intent.putExtra(Intent.EXTRA_EMAIL, to);
  intent.putExtra(Intent.EXTRA_TEXT, body);
  intent.putExtra(Intent.EXTRA_SUBJECT, subject);
  intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathToAttachment));
  intent.setType("*/*");

  return intent;
}
</code>```

答:
The Intent you get back from createChooser() may not have your flag. Try adding it to the result of createChooser().

Note that:

Having a service pop up an activity is very unusual and should be able to be disabled by the user, as it can be very intrusive.

Having a service pop up a chooser is lousy UX. Do you honestly think your users are going to have any idea what is going on when this "Email" chooser dialog appears out of nowhere?

ContentLicense: CC BY-SA 3.0

Body:
I've got a bit of code which is listening for a message on a socket, and parsing data from the socket into an email to be sent.  I'm able to create the intent, and set the FLAG_ACTIVITY_NEW_TASK flag on it, but yet, when i call
startActivity(Intent.createChooser(intent, "Email"));

I get an AndoridRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

What confuses me on this is that I have explicitly called
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Am I missing something obvious here?

protected void doEmail(DataInputStream in)  throws IOException {
  String id = in.readUTF();
  createEmail(id);
}

protected void createEmail(String rawEmailString) {
  // need to get to, subject, body and path from string
  String[] stringArray = rawEmailString.split("~");
  Intent intent = prepareEmail(stringArray[0], stringArray[1], stringArray[2], stringArray[3]);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(Intent.createChooser(intent, "Email"));
}

public Intent prepareEmail(String to, String subject, String body, String pathToAttachment){
  Intent intent = new Intent(Intent.ACTION_SEND);
  intent.putExtra(Intent.EXTRA_EMAIL, to);
  intent.putExtra(Intent.EXTRA_TEXT, body);
  intent.putExtra(Intent.EXTRA_SUBJECT, subject);
  intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathToAttachment));
  intent.setType("*/*");

  return intent;
}


问:
Parsing string fragments in ANTLR4
I have a grammar which expresses instructions for creating data structures including text, which are nested inside other instructions expressing under what circumstances the data structures should be created.  It is processed using a visitor rather than a listener.  Sometimes, the text can be very long and for formatting, splitting it across lines will make it easier to read.

For example:

```<code>store(martin-luther-king,
      "The ultimate measure of a man is not where he stands in moments of comfort"
      " and convenience, but where he stands at times of challenge and controversy.")
</code>```

is easier to read than

```<code>   store(martin-luther-king,"The ultimate measure of a man is not
where he stands in moments of comfort and convenience, but where he
stands at times of challenge and controversy.")
</code>```

This style of splitting strings is familiar to Python coders. To accomplish this, my grammar contains:

```<code>quotedString : STRING+ ;
STRING : DOUBLEQUOTE (~["\\\r\n] | ('\\' .))+ DOUBLEQUOTE ;
WS : [ \t\r\n] -> skip;
fragment DOUBLEQUOTE : '"' ;
</code>```

and generally works well.

While parsing a grammar which inadvertently contained something like:

```<code>"I did not" "" "speak out"
</code>```

where a quotedString rule was expected, lexing/parsing failed with a java.lang.ClassCastException reporting "DocGenLexer cannot be cast to org.antlr.v4.runtime.Parser".  I believe it would be more appropriate for this to fail with the exception that reports "no viable alternative".

My code (after in-lining a method, for the sake of brevity) looks like:

```<code>    String docGen = "store(martin-luther-king,\"I did not\" \"\" \"speak out\")";
    DocGenLexer lexer = new DocGenLexer(CharStreams.fromString(docGen));
    lexer.removeErrorListeners();
    lexer.addErrorListener(DocGenErrorListener.INSTANCE);

    TokenStream tokenStream = new CommonTokenStream(lexer);

    DocGenParser parser = new DocGenParser(tokenStream);
    parser.removeErrorListeners();
    parser.addErrorListener(DocGenErrorListener.INSTANCE);

    ParseTree parseTree = parser.docGen();
</code>```

I would like to correct this, and I originally assumed this represents a deficiency of my grammar (rather than a bug in ANTLR4), but have discovered the problem is in the error listener class.

Code for error listener :

```<code>public class DocGenErrorListener extends BaseErrorListener {

    public static final DocGenErrorListener INSTANCE = new DocGenErrorListener();

    @Override
    public void syntaxError(Recognizer<?, ?> recognizer,
                            Object offendingSymbol,
                            int line, int charPositionInLine,
                            String msg,
                            RecognitionException e) throws ParseCancellationException {
        // the following line is the origin of the problem
        List<String> stack = ((Parser) recognizer).getRuleInvocationStack();
        Collections.reverse(stack);
        throw new DocGenParseException(
        String.format("rule stack: %s\nline %d:%d at %s: %s",
                stack, line, charPositionInLine, offendingSymbol, msg));
    }
}
</code>```

Should I conclude that I need a different error listener classes for errors generated by the lexer and parser?

答:
I see the problem. Your grammar does not allow for empty strings.

```<code>"I did not" "" "speak out"
</code>```

contains a string saying "I did not", and empty string, and a string saying "speak out", you should change the lexer rule to say:

```<code>STRING : DOUBLEQUOTE (~["\\\r\n] | ('\\' .))* DOUBLEQUOTE ;
</code>```

Title: Parsing string fragments in ANTLR4

Body:
I have a grammar which expresses instructions for creating data structures including text, which are nested inside other instructions expressing under what circumstances the data structures should be created.  It is processed using a visitor rather than a listener.  Sometimes, the text can be very long and for formatting, splitting it across lines will make it easier to read.

For example:

store(martin-luther-king,
      "The ultimate measure of a man is not where he stands in moments of comfort"
      " and convenience, but where he stands at times of challenge and controversy.")

is easier to read than

   store(martin-luther-king,"The ultimate measure of a man is not
where he stands in moments of comfort and convenience, but where he
stands at times of challenge and controversy.")

This style of splitting strings is familiar to Python coders. To accomplish this, my grammar contains:

quotedString : STRING+ ;
STRING : DOUBLEQUOTE (~["\\\r\n] | ('\\' .))+ DOUBLEQUOTE ;
WS : [ \t\r\n] -> skip;
fragment DOUBLEQUOTE : '"' ;

and generally works well.

While parsing a grammar which inadvertently contained something like:

"I did not" "" "speak out"

where a quotedString rule was expected, lexing/parsing failed with a java.lang.ClassCastException reporting "DocGenLexer cannot be cast to org.antlr.v4.runtime.Parser".  I believe it would be more appropriate for this to fail with the exception that reports "no viable alternative".

My code (after in-lining a method, for the sake of brevity) looks like:

    String docGen = "store(martin-luther-king,\"I did not\" \"\" \"speak out\")";
    DocGenLexer lexer = new DocGenLexer(CharStreams.fromString(docGen));
    lexer.removeErrorListeners();
    lexer.addErrorListener(DocGenErrorListener.INSTANCE);

    TokenStream tokenStream = new CommonTokenStream(lexer);

    DocGenParser parser = new DocGenParser(tokenStream);
    parser.removeErrorListeners();
    parser.addErrorListener(DocGenErrorListener.INSTANCE);

    ParseTree parseTree = parser.docGen();

I would like to correct this, and I originally assumed this represents a deficiency of my grammar (rather than a bug in ANTLR4), but have discovered the problem is in the error listener class.

Code for error listener :

public class DocGenErrorListener extends BaseErrorListener {

    public static final DocGenErrorListener INSTANCE = new DocGenErrorListener();

    @Override
    public void syntaxError(Recognizer<?, ?> recognizer,
                            Object offendingSymbol,
                            int line, int charPositionInLine,
                            String msg,
                            RecognitionException e) throws ParseCancellationException {
        // the following line is the origin of the problem
        List<String> stack = ((Parser) recognizer).getRuleInvocationStack();
        Collections.reverse(stack);
        throw new DocGenParseException(
        String.format("rule stack: %s\nline %d:%d at %s: %s",
                stack, line, charPositionInLine, offendingSymbol, msg));
    }
}

Should I conclude that I need a different error listener classes for errors generated by the lexer and parser?

Body:
I see the problem. Your grammar does not allow for empty strings.

"I did not" "" "speak out"

contains a string saying "I did not", and empty string, and a string saying "speak out", you should change the lexer rule to say:

STRING : DOUBLEQUOTE (~["\\\r\n] | ('\\' .))* DOUBLEQUOTE ;


问:
there is a function in python i am not understanding
```<code>        link_regx = re.compile('<cite.*?>(.*?)<\/cite>')
        try:
            links_list = link_regx.findall(resp)
            for link in links_list:
                link = re.sub('<span.*>', '', link)

</code>```

<p>what is
compile() and  sub()
function use here </p>

答:
re.compile(pattern, flags=0)

Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods.

https://docs.python.org/3/library/re.html#re.compile

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

https://docs.python.org/3/library/re.html#re.sub

Body:
        link_regx = re.compile('(.*?)<\/cite>')
        try:
            links_list = link_regx.findall(resp)
            for link in links_list:
                link = re.sub('', '', link)

what is
compile() and  sub()
function use here


问:
PHP search array for a value between two numbers
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

```<code><?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>
</code>```

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

答:
Yes, you can create a range and use it as the "needle", but not using in_array.  You can create a range and compute the intersection of the numbers array. To just check for any match:

```<code>$numbers = array(1105, 2140, 3170);
$needle  = range(1000, 1500);

if (array_intersect($numbers, $needle)) {
  echo "Match found";
} else {
  echo "Match not found";
}
</code>```

Or to get the possible match(es):

```<code>$numbers = array(1105, 2140, 3170);
$needle  = range(1000, 1500);
$result  = array_intersect($numbers, $needle);
</code>```

Or you can filter out the ones not in the range:

```<code>$numbers = array(1105, 2140, 3170);
$min = 1000;
$max = 1500;
$result  = array_filter($numbers, function($v) use($min, $max) {
                                     return $v >= $min && $v <= $max;
                                 });
</code>```

You will get an empty array if there are no matches in either case.  Also, you don't state what you want if there is more than one, but you'll get an array in either case so you could use current for one or min and/or max instead:

```<code>$one = current(array_intersect($numbers, $needle));
$min = min(array_intersect($numbers, $needle));
$max = max(array_intersect($numbers, $needle));
</code>```

Body:
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

<?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

Body:
Yes, you can create a range and use it as the "needle", but not using in_array.  You can create a range and compute the intersection of the numbers array. To just check for any match:

$numbers = array(1105, 2140, 3170);
$needle  = range(1000, 1500);

if (array_intersect($numbers, $needle)) {
  echo "Match found";
} else {
  echo "Match not found";
}

Or to get the possible match(es):

$numbers = array(1105, 2140, 3170);
$needle  = range(1000, 1500);
$result  = array_intersect($numbers, $needle);

Or you can filter out the ones not in the range:

$numbers = array(1105, 2140, 3170);
$min = 1000;
$max = 1500;
$result  = array_filter($numbers, function($v) use($min, $max) {
                                     return $v >= $min && $v <= $max;
                                 });

You will get an empty array if there are no matches in either case.  Also, you don't state what you want if there is more than one, but you'll get an array in either case so you could use current for one or min and/or max instead:

$one = current(array_intersect($numbers, $needle));
$min = min(array_intersect($numbers, $needle));
$max = max(array_intersect($numbers, $needle));


问:
reading JSON element using JS
I am receiving a JSON object from a PHP get request. It looks like this:

```<code>data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

```<code>eti=data["emp_type_id"];
var myVar = eti[0];
</code>```

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

答:
data is an object that has two properties, user_id and emp_type_id.  emp_type_id is an array with one element (???), that element is an object with the properties 0 and 1.

There are two ways of reading a property from an object:

```<code>var prop = data['emp_type_id'];
var prop = data.emp_type_id;
</code>```

If you have "weird" property names then you will have to use the square-bracket technique.

so

```<code>var prop0 = data.emp_type_id[0].0;
var prop1 = data.emp_type_id[0].1;
</code>```

I'm concerned that "0" and "1" will fall under the category of "weird property names" so you might need to do

```<code>var prop0 = data.emp_type_id[0]["0"];
var prop1 = data.emp_type_id[0]["1"];
</code>```

Title: reading JSON element using JS

Body:
I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

Body:
data is an object that has two properties, user_id and emp_type_id.  emp_type_id is an array with one element (???), that element is an object with the properties 0 and 1.

There are two ways of reading a property from an object:

var prop = data['emp_type_id'];
var prop = data.emp_type_id;

If you have "weird" property names then you will have to use the square-bracket technique.

so

var prop0 = data.emp_type_id[0].0;
var prop1 = data.emp_type_id[0].1;

I'm concerned that "0" and "1" will fall under the category of "weird property names" so you might need to do

var prop0 = data.emp_type_id[0]["0"];
var prop1 = data.emp_type_id[0]["1"];


问:
Is it possible to flush a node response to the client to keep a connection alive?
I have a large data-set that a client is requesting. It requires loading and processing so I can convert it to CSV. If I try to load and convert the entire data-set at once it doesn't finish processing before the client times out. In response to this, I load my data-set and then chunk it for processing. At this point I have data ready to send to the client before the timeout.

My issue is that when I send the data, either by piping my write stream into the response, or by listening to my write stream and sending VIA response.write, it does not get sent in time. This seems to be because I'm not hitting the highWaterMark on the response writer. I need a way to either tell the connection to wait longer (res.setTimeout(2147483647); doesn't seem to do the trick), lower the highWaterMark, or to drain the response so the client consistently gets the processed data as it comes in.

This is on Node 12.x w/ Express 4.

答:
Is it possible to flush a node response to the client to keep a connection alive?
As per what jfriend00 said, corking my response before writing data, writing the data, and then uncorking it caused it to be sent to the client.

Calling this solved.


问:
How to automate the renaming of a txt file using python
I am trying to find a way to automate the renaming of a file using python.

So the text files need to be renamed everyday to include yesterday's date (T-1).

For example: FileName_20200121.txt needs to be renamed to FileName_20200120.txt.

How do I go about this?

Thanks for the help in advance.

答:
You can use os.rename(src, dst):

Rename the file or directory src to dst. If dst exists, the operation
  will fail with an OSError

The following should do the trick, assuming that all of your files end in .txt:

```<code>import os
from datetime import datetime, timedelta

directory = '/path/to/files'
filenames = [f for f in os.listdir(directory) if f.endswith('.txt')]
yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')

for file_name in filenames:
    new_file_name = file_name[:-12] + yesterday + file_name[-4:]
    os.rename(os.path.join(directory, file_name), os.path.join(directory, new_file_name))
</code>```

Body:
You can use os.rename(src, dst):

Rename the file or directory src to dst. If dst exists, the operation
  will fail with an OSError

The following should do the trick, assuming that all of your files end in .txt:

import os
from datetime import datetime, timedelta

directory = '/path/to/files'
filenames = [f for f in os.listdir(directory) if f.endswith('.txt')]
yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')

for file_name in filenames:
    new_file_name = file_name[:-12] + yesterday + file_name[-4:]
    os.rename(os.path.join(directory, file_name), os.path.join(directory, new_file_name))


问:
Update specific indices of Seq by another Seq in Scala
I have a first seq, for example:

```<code>val s: Seq[Double] = List.fill(6)(0.0)
</code>```

and a sub sequences of the indices of s:

```<code>val subInd: Seq[Int] = List(2, 4, 5)
</code>```

Now, what I want to do is update s on the positions 2, 4 and 5 by another Seq, which has the length of subInd:

```<code>val t: Seq[Double] = List(5.0, 6.0, 7.0)
</code>```

such, that:

```<code>val updateBySeq(s, subInd, t): List[Double] = List(0.0, 0.0, 5.0, 0.0, 6.0, 7.0)
</code>```

I have searched on this site and found Update multiple values in a sequence where the second answer comes close to the functionality I want to have.

However, the difference is, that the function provided would update s on the indices contained in subInd by one value. I, on the other hand, would want them to correspond to multiple, unique values in a third Seq t.

I have tried various things, like using recursion and ListBuffers, instead of Lists, to incrementally update the elements of s, but either they left s unchanged or I got an error because I violated some immutability constraint.

答:
This should work:

```<code>def updateListByIndexes[T](data: List[T])(indexes: List[Int], update: List[T]): List[T] = {
  val updateMap = (indexes lazyZip update).toMap

  data.iterator.zipWithIndex.map {
    case (elem, idx) =>
      updateMap.getOrElse(key = idx, default = elem)
  }.toList
}
</code>```

Which you can use like this:

```<code>val s = List.fill(6)(0.0)
// s: List[Double] = List(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

val subInd = List(2, 4, 5)
// subInd: List[Int] = List(2, 4, 5)

val t = List(5.0, 6.0, 7.0)
// t: List[Double] = List(5.0, 6.0, 7.0)

updateListByIndexes(s)(subInd, t)
// res: List[Double] = List(0.0, 0.0, 5.0, 0.0, 6.0, 7.0)
</code>```

Body:
I have a first seq, for example:

val s: Seq[Double] = List.fill(6)(0.0)

and a sub sequences of the indices of s:

val subInd: Seq[Int] = List(2, 4, 5)

Now, what I want to do is update s on the positions 2, 4 and 5 by another Seq, which has the length of subInd:

val t: Seq[Double] = List(5.0, 6.0, 7.0)

such, that:

val updateBySeq(s, subInd, t): List[Double] = List(0.0, 0.0, 5.0, 0.0, 6.0, 7.0)

I have searched on this site and found Update multiple values in a sequence where the second answer comes close to the functionality I want to have.

However, the difference is, that the function provided would update s on the indices contained in subInd by one value. I, on the other hand, would want them to correspond to multiple, unique values in a third Seq t.

I have tried various things, like using recursion and ListBuffers, instead of Lists, to incrementally update the elements of s, but either they left s unchanged or I got an error because I violated some immutability constraint.

Body:
This should work:

def updateListByIndexes[T](data: List[T])(indexes: List[Int], update: List[T]): List[T] = {
  val updateMap = (indexes lazyZip update).toMap

  data.iterator.zipWithIndex.map {
    case (elem, idx) =>
      updateMap.getOrElse(key = idx, default = elem)
  }.toList
}

Which you can use like this:

val s = List.fill(6)(0.0)
// s: List[Double] = List(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

val subInd = List(2, 4, 5)
// subInd: List[Int] = List(2, 4, 5)

val t = List(5.0, 6.0, 7.0)
// t: List[Double] = List(5.0, 6.0, 7.0)

updateListByIndexes(s)(subInd, t)
// res: List[Double] = List(0.0, 0.0, 5.0, 0.0, 6.0, 7.0)


问:
Powerquery : How to insert a row in a table based on conditions in other rows
I have been playing around quite a bit with powerquery to import all kinds of files and transform them in usable tables in excel. But recently I stumbled upon a problem I don't seem to find a solution for.

After some steps in my query I finally have the following result :

Column 1	Column 2

Country	France

Number of hits	10

Number of misses	5

Country	UK

Number of hits	150

Number of misses	35

Country	Japan

Number of hits	5

Country	China

Number of hits	50

Number of misses	3

```
</div>
</div>
</p>

<p>So, normally I always expected each time a line with "Country", followed by a line with "hits" followed by a line with "misses" (and lots of other lines in between that i don't need and filtered out in previous steps).</p>

<p>But it now turns out that for countries where the number of misses = 0 there is not even a row available in the input file. In my example this is the line for "Japan"</p>

<p>My idea was to find some kind of function that does this :<p>
<code>IF < Column1 of current line > ='Number of hits' AND < Column1 of next line > ='Country' THEN
insert ['Number of misses','0'] after the current line.</code></p>

<p>The end result should then look like this :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
 <tr><th>Column 1</th><th>Column 2</th></tr>
 <tr><td>Country</td><td>France</td></tr>
 <tr><td>Number of hits</td><td>10</td></tr>
 <tr><td>Number of misses</td><td>5</td></tr>
 <tr><td>Country</td><td>UK</td></tr>
 <tr><td>Number of hits</td><td>150</td></tr>
 <tr><td>Number of misses</td><td>35</td></tr>
 <tr><td>Country</td><td>Japan</td></tr>
 <tr><td>Number of hits</td><td>5</td></tr>
 <tr><td><b>Number of misses</b></td><td><b>0</b></td></tr>
  <tr><td>Country</td><td>China</td></tr>
 <tr><td>Number of hits</td><td>50</td></tr>
 <tr><td>Number of misses</td><td>3</td></tr>
 </table></code>```

All of this should happen in the (advanced) query part and not once the data is imported in a table in excel.

答:
See of this works for you. Assumes source data is a table named Table1
You can paste into powerquery in home .. advanced editor...

What it does (a) creates a table of unique descriptions from Column 1 (b) creates a table of unique Country names from Column 2 (c) creates all combinations of the two (d) merges original data back into that, and anything missing automatically becomes a null we can replace with a zero

```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

// create table of all unique descriptions
#"Removed Duplicates" = Table.Distinct(Source, {"Column 1"}),
#"Select" = Table.FromList(Table.Column(#"Removed Duplicates" ,"Column 1")),
#"Added Custom1" = Table.AddColumn(#"Select", "Custom", each 1),

// create table of all unique countries
#"Filtered Rows" = Table.SelectRows(Source, each ([Column 1] = "Country")),
#"Select2" = Table.FromList(Table.Column(#"Filtered Rows" ,"Column 2")),
#"Removed Duplicates1" = Table.Distinct(Select2),
#"Added Custom" = Table.AddColumn(#"Removed Duplicates1", "Custom", each 1),

// create all possible combinations of description x countries
#"Merged Queries" = Table.NestedJoin(#"Added Custom",{"Custom"},#"Added Custom1" ,{"Custom"},"Table3",JoinKind.FullOuter),
#"Expanded Table3" = Table.ExpandTableColumn(#"Merged Queries", "Table3", {"Column1"}, {"Column1.1"}),

// create table to compare to
#"Added Custom2" = Table.AddColumn(Source, "Fill", each if [Column 1]="Country" then [Column 2] else null),
#"Filled Down" = Table.FillDown(#"Added Custom2",{"Fill"}),

// merge compare table onto combination table. Anything missing comes up as null. Then replace nulls with 0
#"Merged Queries1" = Table.NestedJoin(#"Expanded Table3",{"Column1.1", "Column1"},#"Filled Down",{"Column 1", "Fill"},"Table4",JoinKind.LeftOuter),
#"Expanded Table4" = Table.ExpandTableColumn(#"Merged Queries1", "Table4", {"Column 2"}, {"Column 2"}),
#"Replaced Value" = Table.ReplaceValue(#"Expanded Table4",null,0,Replacer.ReplaceValue,{"Column 2"}),
#"Removed Columns" = Table.RemoveColumns(#"Replaced Value",{"Column1", "Custom"})

in  #"Removed Columns"
</code>```

Body:
I have been playing around quite a bit with powerquery to import all kinds of files and transform them in usable tables in excel. But recently I stumbled upon a problem I don't seem to find a solution for.

After some steps in my query I finally have the following result :

Column 1	Column 2

Country	France

Number of hits	10

Number of misses	5

Country	UK

Number of hits	150

Number of misses	35

Country	Japan

Number of hits	5

Country	China

Number of hits	50

Number of misses	3

So, normally I always expected each time a line with "Country", followed by a line with "hits" followed by a line with "misses" (and lots of other lines in between that i don't need and filtered out in previous steps).

But it now turns out that for countries where the number of misses = 0 there is not even a row available in the input file. In my example this is the line for "Japan"

My idea was to find some kind of function that does this :

IF < Column1 of current line > ='Number of hits' AND < Column1 of next line > ='Country' THEN
insert ['Number of misses','0'] after the current line.

The end result should then look like this :

Column 1	Column 2

Country	France

Number of hits	10

Number of misses	5

Country	UK

Number of hits	150

Number of misses	35

Country	Japan

Number of hits	5

Number of misses	0

Country	China

Number of hits	50

Number of misses	3

All of this should happen in the (advanced) query part and not once the data is imported in a table in excel.

Body:
See of this works for you. Assumes source data is a table named Table1
You can paste into powerquery in home .. advanced editor...

What it does (a) creates a table of unique descriptions from Column 1 (b) creates a table of unique Country names from Column 2 (c) creates all combinations of the two (d) merges original data back into that, and anything missing automatically becomes a null we can replace with a zero

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

// create table of all unique descriptions
#"Removed Duplicates" = Table.Distinct(Source, {"Column 1"}),
#"Select" = Table.FromList(Table.Column(#"Removed Duplicates" ,"Column 1")),
#"Added Custom1" = Table.AddColumn(#"Select", "Custom", each 1),

// create table of all unique countries
#"Filtered Rows" = Table.SelectRows(Source, each ([Column 1] = "Country")),
#"Select2" = Table.FromList(Table.Column(#"Filtered Rows" ,"Column 2")),
#"Removed Duplicates1" = Table.Distinct(Select2),
#"Added Custom" = Table.AddColumn(#"Removed Duplicates1", "Custom", each 1),

// create all possible combinations of description x countries
#"Merged Queries" = Table.NestedJoin(#"Added Custom",{"Custom"},#"Added Custom1" ,{"Custom"},"Table3",JoinKind.FullOuter),
#"Expanded Table3" = Table.ExpandTableColumn(#"Merged Queries", "Table3", {"Column1"}, {"Column1.1"}),

// create table to compare to
#"Added Custom2" = Table.AddColumn(Source, "Fill", each if [Column 1]="Country" then [Column 2] else null),
#"Filled Down" = Table.FillDown(#"Added Custom2",{"Fill"}),

// merge compare table onto combination table. Anything missing comes up as null. Then replace nulls with 0
#"Merged Queries1" = Table.NestedJoin(#"Expanded Table3",{"Column1.1", "Column1"},#"Filled Down",{"Column 1", "Fill"},"Table4",JoinKind.LeftOuter),
#"Expanded Table4" = Table.ExpandTableColumn(#"Merged Queries1", "Table4", {"Column 2"}, {"Column 2"}),
#"Replaced Value" = Table.ReplaceValue(#"Expanded Table4",null,0,Replacer.ReplaceValue,{"Column 2"}),
#"Removed Columns" = Table.RemoveColumns(#"Replaced Value",{"Column1", "Custom"})

in  #"Removed Columns"


问:
Spring use Computer name instead of supplied username for jdbc database access
Reading Pro Spring 5, an example that show Spring JDBC is using MySQL DB. I use the book source code. Here is the code

```<code>@Configuration
@PropertySource("classpath:db/jdbc2.properties")
@ComponentScan(basePackages = "com.apress.prospring5.ch6")
public class AppConfig {

    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

@Bean(destroyMethod = "close")
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            logger.error("DBCP DataSource bean cannot be created!", e);
            return null;
        }
    }
</code>```

jdbc2.properties

```<code>driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/musicdb?useSSL=true
username=prospring5
password=prospring5
</code>```

The test

```<code>public class AnnotationJdbcTest {

    private GenericApplicationContext ctx;
    private SingerDao singerDao;

    @Before
    public void setUp() {
        ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        singerDao = ctx.getBean(SingerDao.class);
        assertNotNull(singerDao);
    }

    @Test
    public void testFindAll() {
        List<Singer> singers = singerDao.findAll();
        assertTrue(singers.size() == 3);
        listSingers(singers);
        ctx.close();
    }
</code>```

My MySQL instance already have the user prospring5 and the schema created and populated

When I try to run AnnotationJdbcTest, I get this exception:

```<code>Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:612)
</code>```

As you can see the project is using my computer name 'Mehdi' instead of the one in the .properties file 'prospring5' . Why is That? and how Can I fix it?

You can yourself download the source code and run it from here: https://github.com/Apress/pro-spring-5
the project is: chapter6/spring-jdbc-annotations

EDIT:
I printed the values as suggested by @STaefi and here is the output:

```<code>com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/musicdb?useSSL=false
Mehdi
prospring5
</code>```

Code

```<code>@Bean()
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            System.out.println(driverClassName);
            dataSource.setUrl(url);
            System.out.println(url);
            dataSource.setUsername(username);
            System.out.println(username);
            dataSource.setPassword(password);
            System.out.println(password);
            return dataSource;
</code>```

First I tried setting the values at initialization and that was no good. but after I used username = "prospring5"; dataSource.setUsername(username); it worked. so what does this mean. why Spring cannot load the username like it successfully loaded the url and the password.

答: So I have fixed the problem by simply using a different String identifier in the .propreties file . I changed it to one=prospring5 and it worked. Apparently using a proprety named 'username' will be loaded with anything other than Your Computer name. I don't know if Spring provides a list of prohibited values for property names. if they don't, they certainly should consider.

Body:
Reading Pro Spring 5, an example that show Spring JDBC is using MySQL DB. I use the book source code. Here is the code

@Configuration
@PropertySource("classpath:db/jdbc2.properties")
@ComponentScan(basePackages = "com.apress.prospring5.ch6")
public class AppConfig {

    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

@Bean(destroyMethod = "close")
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            logger.error("DBCP DataSource bean cannot be created!", e);
            return null;
        }
    }

jdbc2.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/musicdb?useSSL=true
username=prospring5
password=prospring5

The test

public class AnnotationJdbcTest {

    private GenericApplicationContext ctx;
    private SingerDao singerDao;

    @Before
    public void setUp() {
        ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        singerDao = ctx.getBean(SingerDao.class);
        assertNotNull(singerDao);
    }

    @Test
    public void testFindAll() {
        List<Singer> singers = singerDao.findAll();
        assertTrue(singers.size() == 3);
        listSingers(singers);
        ctx.close();
    }

My MySQL instance already have the user prospring5 and the schema created and populated

When I try to run AnnotationJdbcTest, I get this exception:

Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:612)

As you can see the project is using my computer name 'Mehdi' instead of the one in the .properties file 'prospring5' . Why is That? and how Can I fix it?

You can yourself download the source code and run it from here: https://github.com/Apress/pro-spring-5
the project is: chapter6/spring-jdbc-annotations

EDIT:
I printed the values as suggested by @STaefi and here is the output:

com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/musicdb?useSSL=false
Mehdi
prospring5

Code

@Bean()
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            System.out.println(driverClassName);
            dataSource.setUrl(url);
            System.out.println(url);
            dataSource.setUsername(username);
            System.out.println(username);
            dataSource.setPassword(password);
            System.out.println(password);
            return dataSource;

First I tried setting the values at initialization and that was no good. but after I used username = "prospring5"; dataSource.setUsername(username); it worked. so what does this mean. why Spring cannot load the username like it successfully loaded the url and the password.


问:
Difference between InnoDB and MyISAM?

Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

```<code>$q = ("SELECT * ... );
$r = mysql_query($q);
</code>```

答:
InnoDB vs. MyISAM won't have any difference with how you code your select statements. Where it will help is allow for foreign keys, which will help you keep referential integrity in your database, and if properly setup, help ensure not creating orphan records.

See http://en.wikipedia.org/wiki/Foreign_key for more information.

Title: Difference between InnoDB and MyISAM?

Body:
Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

$q = ("SELECT * ... );
$r = mysql_query($q);


问:
Using class functions and handling data externally - PyGame
Just a small question. I have a class that does something and handles strings. I have an active class that has a button which when pressed closes the screen and deactivates the class at the same time. I would like the class to return the strings it has been handling to variables that are outside the class itself., but I am not sure how to do this.

```<code>    class InputBox:
       def __init__(self, x, y, w, h, text=''):
           #... Instructions for defining the class.
       def Otherinstructions():
           #... Other instructions
       def returnVar(): # The function to return text externally.
           return InputBox.text

     NewVar = '' # I would like the class to return the string to this variable.
</code>```

Thank you. I just want to find out the most effective way.

答:
box = InputBox(<your data>)
NewVar = box.returnVar()
```

Although you should follow the style convention where methods and variables begin with a lowercase character. For future reference, the returnVar() method is called a getter.

Body:
Just a small question. I have a class that does something and handles strings. I have an active class that has a button which when pressed closes the screen and deactivates the class at the same time. I would like the class to return the strings it has been handling to variables that are outside the class itself., but I am not sure how to do this.

    class InputBox:
       def __init__(self, x, y, w, h, text=''):
           #... Instructions for defining the class.
       def Otherinstructions():
           #... Other instructions
       def returnVar(): # The function to return text externally.
           return InputBox.text

     NewVar = '' # I would like the class to return the string to this variable.

Thank you. I just want to find out the most effective way.

Body:
box = InputBox(<your data>)
NewVar = box.returnVar()

Although you should follow the style convention where methods and variables begin with a lowercase character. For future reference, the returnVar() method is called a getter.