问:
Disable dropdown option after selecting (even for new visitors)
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

```<code><form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">
                                                <div class="cc-m-form-loading"></div>

                                                <div class="cc-m-form-view-sortable">
                                                    <div class="cc-m-form-view-element cc-m-form-select" data-action="element" required>
                                                        <label for="ma6b8be54cf86a6410">
    <div>Kies welke held jouw team is!</div>
    </label>
                                                        <div class="cc-m-form-view-input-wrapper">
                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select></div></div>
<input type="submit" value="Naar betalen" data-action="formButton">
</code>```

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

```<code><?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>
</code>```

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

答:
First, whenever an option is selected, save it in server. While drawing the list box value, consider the already selected (From Storage) and disable the option.

Check,

```<code><option value="Mega Mindy" disabled>Mega Mindy</option>
</code>```

<select>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="Mega Mindy" disabled>Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="The Hulk">The Hulk</option>
<option value="Hit Girl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select>
```

Body:
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

<form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">

Kies welke held jouw team is!

                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select>

<input type="submit" value="Naar betalen" data-action="formButton">

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

<?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

Body:
First, whenever an option is selected, save it in server. While drawing the list box value, consider the already selected (From Storage) and disable the option.

Check,

<option value="Mega Mindy" disabled>Mega Mindy</option>

<div>
<select>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="Mega Mindy" disabled>Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="The Hulk">The Hulk</option>
<option value="Hit Girl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select></div>


来源: stackexchange

问:
Listen to changes of dependency property
Is there any way to listen to changes of a DependencyProperty? I want to be notified and perform some actions when the value changes but I cannot use binding. It is a DependencyProperty of another class.

答:
If it's a DependencyProperty of a separate class, the easiest way is to bind a value to it, and listen to changes on that value.

If the DP is one you're implementing in your own class, then you can register a PropertyChangedCallback when you create the DependencyProperty.  You can use this to listen to changes of the property.

If you're working with a subclass, you can use OverrideMetadata to add your own PropertyChangedCallback to the DP that will get called instead of any original one.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Cordova / Ionic build android Gradle error: Minimum supported Gradle version is 2.14.1. Current version is 2.13
This is a solution to the above error that I want to document.  I found other similar posts, but none described how this error can be associated with Cordova or Ionic.

If you are not careful, there can be a mismatch between the version of Gradle that Android Studio uses and the version of Gradle that Cordova / cordova-android specifies in its auto-generated application code.  As you know, running

```<code>$ cordova platform add android
</code>```

(or $ ionic platform add android, if you are building an Ionic app) creates  the native application code at the-project/platforms/android.

Inside that folder, the file: /the-project/platforms/android/cordova/lib/builders/GradleBuilder.js exports a variable as shown below:

```<code>var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-x.y-all.zip';
</code>```

Where x and y depened on which version of Cordova / cordova-android are being used to build the native application code.

When you run

```<code>$ cordova build android
</code>```

The version of Gradle specified in the distributionUrl var is the version used for the build.

Now here comes the tricky part.  When you import the project into Android Studio, you will most likely get a message strongly recommending that you upgrade Gradle to a newer version, as shown below:

If you do this, Android Studio will download a new version of Gradle and store it locally and configure the project to use the newly download local Gradle distribution, which is the radio option below the selected “Use default grade wrapper”, which I ended up deselecting because this will cause errors.

This will cause problems because Android Studio and Cordova will now be attempting to build the application with different versions of Gradle and you will get build errors within Android Studio and also with

```<code>$ cordova build android
</code>```

in the command line.  The solution with Cordova apps is to always keep the Android Studio project set to "Use default gradle wrapper" and ignore the tempting messages to upgrade.  If you do want to use a newer version of Gradle, you can always change the distributionUrl var in the file mentioned above (however Cordova strongly discourages modifying code within the platforms folder since it is easily overwritten).  At the time of writing this, I cannot tell is there is a way to set the Gradle version at the

```<code>$ cordova platform add android
</code>```

step, which is when you would want to do it so you are never directly modifiying code inside of the-project/platforms

答:
For follow error:

Minimum supported Gradle version is 4.1. Current version is 3.3. If
  using t he gradle wrapper, try editing the distributionUrl in
  E:\ionic\MyIonicProject\gr adle\wrapper\gradle-wrapper.properties to
  gradle-4.1-all.zip for gradle 4.1

This command worked for me:

```<code>ionic cordova platform update android
</code>```

Body:
This is a solution to the above error that I want to document.  I found other similar posts, but none described how this error can be associated with Cordova or Ionic.

If you are not careful, there can be a mismatch between the version of Gradle that Android Studio uses and the version of Gradle that Cordova / cordova-android specifies in its auto-generated application code.  As you know, running

$ cordova platform add android

(or $ ionic platform add android, if you are building an Ionic app) creates  the native application code at the-project/platforms/android.

Inside that folder, the file: /the-project/platforms/android/cordova/lib/builders/GradleBuilder.js exports a variable as shown below:

var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-x.y-all.zip';

Where x and y depened on which version of Cordova / cordova-android are being used to build the native application code.

When you run

$ cordova build android

The version of Gradle specified in the distributionUrl var is the version used for the build.

Now here comes the tricky part.  When you import the project into Android Studio, you will most likely get a message strongly recommending that you upgrade Gradle to a newer version, as shown below:

If you do this, Android Studio will download a new version of Gradle and store it locally and configure the project to use the newly download local Gradle distribution, which is the radio option below the selected “Use default grade wrapper”, which I ended up deselecting because this will cause errors.

This will cause problems because Android Studio and Cordova will now be attempting to build the application with different versions of Gradle and you will get build errors within Android Studio and also with

$ cordova build android

in the command line.  The solution with Cordova apps is to always keep the Android Studio project set to "Use default gradle wrapper" and ignore the tempting messages to upgrade.  If you do want to use a newer version of Gradle, you can always change the distributionUrl var in the file mentioned above (however Cordova strongly discourages modifying code within the platforms folder since it is easily overwritten).  At the time of writing this, I cannot tell is there is a way to set the Gradle version at the

$ cordova platform add android

step, which is when you would want to do it so you are never directly modifiying code inside of the-project/platforms

Body:
For follow error:

Minimum supported Gradle version is 4.1. Current version is 3.3. If
  using t he gradle wrapper, try editing the distributionUrl in
  E:\ionic\MyIonicProject\gr adle\wrapper\gradle-wrapper.properties to
  gradle-4.1-all.zip for gradle 4.1

This command worked for me:

ionic cordova platform update android


问:
Could not resolve com.android.support:appcompat-v7:26.0.1
Newly I Installed Android studio 3.0.1, and attempt to run a simple "Hello World" project in first Common step of Gradle Project sync I faced with This Error and it faild :
Could not resolve com.android.support:appcompat-v7:26.0.1.
It seem its also common error that's cause of Maven And should be resolve with adding code below in the build.gradle project file as it said in https://developer.android.com/topic/libraries/support-library/setup.html

```<code>allprojects {
repositories {
        jcenter()
        maven {
           url "https://maven.google.com"
        }
    }
}
</code>```

Here's my top level build.gradle file:

```<code>buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
   repositories {
        google()
        jcenter()
        maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And here's my app/build.gradle file:

```<code>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.renayati.myapplication2"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary= true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.1'
    implementation 'com.android.support:design:26.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-vector-drawable:26.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
}
</code>```

I also

1.removed gradle from my project root folder and rebuild the project again, but it didn't work...

2.commented these 3 lines below, but still the same error message.

```<code>    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
</code>```

didn't work...

I searched more but I just catch same answers. Is anyone here to help me?

答: put buildToolsVersion "26.0.1" below compileSdkVersion in gradle build. and download the 26.0.1 repository

Body:
Newly I Installed Android studio 3.0.1, and attempt to run a simple "Hello World" project in first Common step of Gradle Project sync I faced with This Error and it faild :
Could not resolve com.android.support:appcompat-v7:26.0.1.
It seem its also common error that's cause of Maven And should be resolve with adding code below in the build.gradle project file as it said in https://developer.android.com/topic/libraries/support-library/setup.html

allprojects {
repositories {
        jcenter()
        maven {
           url "https://maven.google.com"
        }
    }
}

Here's my top level build.gradle file:

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
   repositories {
        google()
        jcenter()
        maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And here's my app/build.gradle file:

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.renayati.myapplication2"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary= true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.1'
    implementation 'com.android.support:design:26.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-vector-drawable:26.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
}

I also

1.removed gradle from my project root folder and rebuild the project again, but it didn't work...

2.commented these 3 lines below, but still the same error message.

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'

didn't work...

I searched more but I just catch same answers. Is anyone here to help me?


问:
Python 3.6.2 not running loops over a single value
In my code I have implemented a loop where the lower and upper bounds are variable, and it can happen that lower and upper bound are the same. In this case, Python skips the loop.

```<code>for i in range(low_, high_):
    print(i)
</code>```

Is there a way to fix this in the definition of the loop?

答:
yes, when low == high, the loop does not enter.

Loops run from start to the inclusion of (end - 1); it is therefore entirely normal behavior

In the case where low == high, you must test to print the low. (credits to @Michael_heath for catching a mistake in the comments)

```<code>for i in range(low_, high_):
    print(i)
if low_ == high_:
    print(low_)
</code>```

Body:
In my code I have implemented a loop where the lower and upper bounds are variable, and it can happen that lower and upper bound are the same. In this case, Python skips the loop.

for i in range(low_, high_):
    print(i)

Is there a way to fix this in the definition of the loop?

Body:
yes, when low == high, the loop does not enter.

Loops run from start to the inclusion of (end - 1); it is therefore entirely normal behavior

In the case where low == high, you must test to print the low. (credits to @Michael_heath for catching a mistake in the comments)

for i in range(low_, high_):
    print(i)
if low_ == high_:
    print(low_)


问:
Salforce login session issue
Please help me for login session issue for Android SDk
Hi,

I have an Android app in which we have to login using Salesforce, we have used https://github.com/forcedotcom/SalesforceMobileSDK-Android SDK (Native) .
Below are the session expired scenario:
1. After successful login on https://ABC.force.com from mobile app.
2. I am able to see this link https://ABC.force.com /customers/one/one.app in android native WebView
3. But after 24 hours I am again seeing login screen.

How can I preserve session until user manually logout from my app.
Please suggest.

答:
use the below link of salseforce sdk  to get new acces token
https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm&type=014:20</p>

Title: Salforce login session issue


问:
Input as number in JavaScript prompt
Can we customize a prompt box in JavaScript so it takes time as input?</p>

```<code>var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");
</code>```

答:
It's not possible to enforce data formats in a vanilla prompt as e.g. in a HTML5 input field.

You could achieve that by using a library like alertifyjs, which allows you to customize prompts.

Title: Input as number in JavaScript prompt

Body:
Can we customize a prompt box in JavaScript so it takes time as input?

var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");


问:
Permitting user agent (chrome) CORS requests programmatically
I need to get some data from external API, from other domain.
I use test app, runned on localhost and I get error:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I try to get access to: https://api.coinmarketcap.com/v1/ticker/ by get method

I did a lot of search and:

I know that I can ask that API by using node.js, CURL, and also by running my frontend code in jest tests

By using chrome extension - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en also everything works correctly

But unfortunatelly by simply AJAX request on my page load I can't reach that API and get an error.

And my prediction is that user agent (chrome) somehow block my request.
I can't use chrome extension because I want also access my website from my mobile phone which can't get that desktop extension.

For now my solution is "proxy", node.js server which can access that API and flow looks like:

FE

-- ASK BE -->

BE

-- ASK API -->

-- RESPONSE TO BE -->

BE

-- RESPONSE TO FE -->

FE SHOWS EVERYTHING

FE - Frontend, BE - Backend (node.js proxy), API - external API

But I want to avoid unnecessary code on the BE. Maybe there is some solution?
Like some magical header which will tell chrome to let me pass to external domain without any additional extension?

答:
Well you can do that one clean way as described here - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Set the header value

Access-Control-Allow-Origin: *

with your response to the first page load from server.


问:
Hadoop installation on windows
After extracting hadoop in my C drive I tried to execute the hadoop version command and getting below error. JAVA_HOME is set correctly in my environment variable. Can anybody help on that error ?

```<code>C:\>hadoop version

The system cannot find the path specified.
Error: JAVA_HOME is incorrectly set.
Please update C:\hadoop-2.5.1\conf\hadoop-env.cmd '-Xmx512m' is not recognized as an internal or external command, ooperable program or batch file.
</code>```

答:
I have also faced similar issue, following steps solved error for me.

Download & Install Java in c:/java/

(make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path )

Download Hadoop binary distribution.

Set Environment Variables:

```<code>JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"
</code>```

Here is a GitHub link, which has winutils of some versions of Hadoop.

(if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link)

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link

And Finally set JAVA_HOME path in hadoop-env.cmd file

Probably it will solve 'JAVA_HOME is incorrectly set.' error

Hope this helps.

Title: Hadoop installation on windows

Body:
After extracting hadoop in my C drive I tried to execute the hadoop version command and getting below error. JAVA_HOME is set correctly in my environment variable. Can anybody help on that error ?

C:\>hadoop version

The system cannot find the path specified.
Error: JAVA_HOME is incorrectly set.
Please update C:\hadoop-2.5.1\conf\hadoop-env.cmd '-Xmx512m' is not recognized as an internal or external command, ooperable program or batch file.

Body:
I have also faced similar issue, following steps solved error for me.

Download & Install Java in c:/java/

(make sure the path is this way, if java is installed in program
  files, then hadoop-env.cmd will not recognize java path )

Download Hadoop binary distribution.

Set Environment Variables:

JAVA_HOME = "c:/Java"
HADOOP_HOME="<your hadoop home>"
Path= "JAVA_HOME/bin"
Path = "HADOOP_HOME/bin"

Here is a GitHub link, which has winutils of some versions of Hadoop.

(if the version you are using is not in the list, the follow the
  conventional method for setting up Hadoop on windows - link)

If you found your version, then copy paste all content of folder into path: /bin/

Set all the .xml configuration files - Link

And Finally set JAVA_HOME path in hadoop-env.cmd file

Probably it will solve 'JAVA_HOME is incorrectly set.' error

Hope this helps.


问:
React: Closing Modal in Child Component from Parent
I have a modal in a child component that handles a delete function in the parent component. The child is holding the state of the modal (open or closed) as this seems the most logical place for it.

Parent

```<code> removeItem() {
   console.log('clicked');
  };

 ...

 <DeleteButton deleterecord={()=>this.removeItem(data.row._original._id)}/>
</code>```

Child

```<code>close() {
  this.setState({ showModal: false })
};

open() {
  this.setState({ showModal: true })
};

render() {

 return(
  <div>
    <Button
    bsStyle="primary"
    bsSize="small"
    onClick={this.open.bind(this)}
  >
    Delete
  </Button>

  <Modal
    show={this.state.showModal}
    onHide={this.close.bind(this)}
    bsSize="small"
    >
   ...
</code>```

How should I close the modal from the parent after the removeItem code has run.

答:
You could use a ref to call the child close function?

Parent

```<code>    removeItem() {
       console.log('clicked');
       this.child.close();
    }

   render() {
      return (
         <div>
            <ChildWithModal ref={(ref) => { this.child = ref; }} />
         </div>
      );
   }
</code>```

Child

```<code>...

close() {
   this.setState({ showModal: false })
};
</code>```

Body:
I have a modal in a child component that handles a delete function in the parent component. The child is holding the state of the modal (open or closed) as this seems the most logical place for it.

Parent

 removeItem() {
   console.log('clicked');
  };

 ...

 <DeleteButton deleterecord={()=>this.removeItem(data.row._original._id)}/>

Child

close() {
  this.setState({ showModal: false })
};

open() {
  this.setState({ showModal: true })
};

render() {

 return(

    <Button
    bsStyle="primary"
    bsSize="small"
    onClick={this.open.bind(this)}
  >
    Delete
  </Button>

  <Modal
    show={this.state.showModal}
    onHide={this.close.bind(this)}
    bsSize="small"
    >
   ...

How should I close the modal from the parent after the removeItem code has run.

Body:
You could use a ref to call the child close function?

Parent

    removeItem() {
       console.log('clicked');
       this.child.close();
    }

   render() {
      return (
         <div>
            <ChildWithModal ref={(ref) => { this.child = ref; }} />
         </div>
      );
   }

Child

...

close() {
   this.setState({ showModal: false })
};


问:
How to override CSS :hover?
I have this HTML code:

```<code><ul>
    <li>Line 1</li>
    <li class="disabled">Line 2</li>
</ul>
</code>```

And the corresponding CSS is:

```<code>ul li:hover {
    color: red;
}
</code>```

This allows for both lis to be hovered over and have their color changed. But if I want one of them to be disabled, I’d use the following:

```<code>.disabled {
    color: grey;
}
</code>```

But the other CSS code’s hover pseudo-class still has effect. Is there any way I can override this?

答:
You can just do following in the css to discard any color for disabled elements while we hover on it.

```<code>ul li:hover:not(:disabled) {
        color: red;
    }
</code>```

This will cause the color red to be applied only when list is not disabled.

Title: How to override CSS :hover?

Body:
I have this HTML code:

Line 1

Line 2

And the corresponding CSS is:

ul li:hover {
    color: red;
}

This allows for both lis to be hovered over and have their color changed. But if I want one of them to be disabled, I’d use the following:

.disabled {
    color: grey;
}

But the other CSS code’s hover pseudo-class still has effect. Is there any way I can override this?

Body:
You can just do following in the css to discard any color for disabled elements while we hover on it.

ul li:hover:not(:disabled) {
        color: red;
    }

This will cause the color red to be applied only when list is not disabled.


问:
All button click functions point to the last id (except last button points to undefined) instead of pointing to its own id

I want to add a delete button that will delete that specific created "event" when it is clicked ("event" is what the user creates in the app).

Problem: if there are 10 events (id 1-10), clicking on buttons 1-9 will use the id of 10 (the last event number).  However, if I click the 10th event delete button it will give undefined.

Using Postman I can see that the route works and is deleting correctly. However, when I click any button (but the last), the id always points to the number of the last id and deletes that one.  Further, the last button gives (console.logs) "undefined".

I've found a few similar issues, but they all seem to be a slightly different problem (using a for loop least notably).  I'd greatly appreciate any help in understanding what I'm doing wrong.

```<code>$(document).ready(function () {

$(document).on("click", ".individualEventButton", handleEventDelete);

$.get("/api/events/", (data) => {
    if (data) {
        const displayData = data;

        displayData.forEach((object) => {
            const eventId = object.id;
            const eventsSection = $("<div>");
            eventsSection.addClass("event");

            $(".individualEventButton").data('id', eventId); //adds data-id to each individual button

            console.log(eventId);

            eventsSection.append("<h2>" + object.title);
            eventsSection.append("<h3>" + object.date);
            eventsSection.append("<p>" + object.description);
            $("#eventsDisplay").append(eventsSection);

            const individualEventButton = $("<button/>", {
                text: "DELETE",
            });

            eventsSection.append(individualEventButton);
            individualEventButton.addClass("individualEventButton");
        });
    } else {
        console.log("ERROR GETTING DATA");
    }
});

function handleEventDelete() {
    const id = $(this).data("id");
   //shows the last created event id if any button is clicked but the last (which shows undefined
    console.log("Show Id: " + id);

    //debugger;
    // Send the DELETE request.
    $.ajax("/api/events/" + id, {
        type: "DELETE"
    }).then(
        function () {
            console.log("deleted id ", id);
            // Reload the page to get the updated list
            location.reload();
        }
    );
}

$("#goToAddEventsPageButton").on("click", ((event) => {
    event.preventDefault();
    window.location.replace('/userDashboard');
}));
});
</code>```

答:
You add id to the $(".individualEventButton"), which means all the buttons with that class, so all your buttons will have the last id except the last one, because the last one was added after your last $(".individualEventButton").data('id', eventId) call.

Just delete this line:

```<code>$(".individualEventButton").data('id', eventId);
</code>```

Change it and put it after / before addClass like this:

```<code>individualEventButton.addClass("individualEventButton");
individualEventButton.data('id', eventId);
</code>```

It's not about where you put it but the fundamental difference between individualEventButton.data('id', eventId); and $(".individualEventButton").data('id', eventId);. First adds id to the specific element, while the other adds id to all elements with specified class.

Body:
I want to add a delete button that will delete that specific created "event" when it is clicked ("event" is what the user creates in the app).

Problem: if there are 10 events (id 1-10), clicking on buttons 1-9 will use the id of 10 (the last event number).  However, if I click the 10th event delete button it will give undefined.

Using Postman I can see that the route works and is deleting correctly. However, when I click any button (but the last), the id always points to the number of the last id and deletes that one.  Further, the last button gives (console.logs) "undefined".

I've found a few similar issues, but they all seem to be a slightly different problem (using a for loop least notably).  I'd greatly appreciate any help in understanding what I'm doing wrong.

$(document).ready(function () {

$(document).on("click", ".individualEventButton", handleEventDelete);

$.get("/api/events/", (data) => {
    if (data) {
        const displayData = data;

        displayData.forEach((object) => {
            const eventId = object.id;
            const eventsSection = $("
");
            eventsSection.addClass("event");

            $(".individualEventButton").data('id', eventId); //adds data-id to each individual button

            console.log(eventId);

            eventsSection.append("
" + object.title);
            eventsSection.append("
" + object.date);
            eventsSection.append("
" + object.description);
            $("#eventsDisplay").append(eventsSection);

            const individualEventButton = $("<button/>", {
                text: "DELETE",
            });

            eventsSection.append(individualEventButton);
            individualEventButton.addClass("individualEventButton");
        });
    } else {
        console.log("ERROR GETTING DATA");
    }
});

function handleEventDelete() {
    const id = $(this).data("id");
   //shows the last created event id if any button is clicked but the last (which shows undefined
    console.log("Show Id: " + id);

    //debugger;
    // Send the DELETE request.
    $.ajax("/api/events/" + id, {
        type: "DELETE"
    }).then(
        function () {
            console.log("deleted id ", id);
            // Reload the page to get the updated list
            location.reload();
        }
    );
}

$("#goToAddEventsPageButton").on("click", ((event) => {
    event.preventDefault();
    window.location.replace('/userDashboard');
}));
});

Body:
You add id to the $(".individualEventButton"), which means all the buttons with that class, so all your buttons will have the last id except the last one, because the last one was added after your last $(".individualEventButton").data('id', eventId) call.

Just delete this line:

$(".individualEventButton").data('id', eventId);

Change it and put it after / before addClass like this:

individualEventButton.addClass("individualEventButton");
individualEventButton.data('id', eventId);

It's not about where you put it but the fundamental difference between individualEventButton.data('id', eventId); and $(".individualEventButton").data('id', eventId);. First adds id to the specific element, while the other adds id to all elements with specified class.


问:
How to animate a control roll out in Inno Setup
I want to animate a control roll out in my installer.

You can see this video.

答:
You can use a timer to animate a control.

[Code]

function SetTimer(hWnd: longword; nIDEvent, uElapse: LongWord; lpTimerFunc: LongWord):
  LongWord; external 'SetTimer@user32.dll stdcall';
function KillTimer(hWnd, nIDEvent: LongWord): LongWord;
  external 'KillTimer@User32.dll stdcall';

var
  MainPanelAnimated: Boolean;
  AnimationTimer: LongWord;

procedure AnimationTimerProc(
  H: LongWord; Msg: LongWord; IdEvent: LongWord; Time: LongWord);
var
  L: Integer;
begin
  L := WizardForm.MainPanel.Left + ScaleX(5);
  if L > 0 then
  begin
    L := 0;
    KillTimer(0, AnimationTimer);
  end;
  WizardForm.MainPanel.Left := L;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  if WizardForm.OuterNotebook.ActivePage = WizardForm.InnerPage then
  begin
    if not MainPanelAnimated then
    begin
      AnimationTimer := SetTimer(0, 0, 5, CreateCallback(@AnimationTimerProc));
      WizardForm.MainPanel.Left := -WizardForm.MainPanel.Width;
      MainPanelAnimated := True;
    end;
  end;
end;
```

For CreateCallback function, you need Inno Setup 6. If you are stuck with Inno Setup 5, you can use WrapCallback function from InnoTools InnoCallback library.

(the animation is actually more smooth than the image shows)

For right-to-left animation, see Inno Setup - Animate a control roll out from right in a determinate page.

Body:
You can use a timer to animate a control.

[Code]

function SetTimer(hWnd: longword; nIDEvent, uElapse: LongWord; lpTimerFunc: LongWord):
  LongWord; external 'SetTimer@user32.dll stdcall';
function KillTimer(hWnd, nIDEvent: LongWord): LongWord;
  external 'KillTimer@User32.dll stdcall';

var
  MainPanelAnimated: Boolean;
  AnimationTimer: LongWord;

procedure AnimationTimerProc(
  H: LongWord; Msg: LongWord; IdEvent: LongWord; Time: LongWord);
var
  L: Integer;
begin
  L := WizardForm.MainPanel.Left + ScaleX(5);
  if L > 0 then
  begin
    L := 0;
    KillTimer(0, AnimationTimer);
  end;
  WizardForm.MainPanel.Left := L;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  if WizardForm.OuterNotebook.ActivePage = WizardForm.InnerPage then
  begin
    if not MainPanelAnimated then
    begin
      AnimationTimer := SetTimer(0, 0, 5, CreateCallback(@AnimationTimerProc));
      WizardForm.MainPanel.Left := -WizardForm.MainPanel.Width;
      MainPanelAnimated := True;
    end;
  end;
end;

For CreateCallback function, you need Inno Setup 6. If you are stuck with Inno Setup 5, you can use WrapCallback function from InnoTools InnoCallback library.

(the animation is actually more smooth than the image shows)

For right-to-left animation, see Inno Setup - Animate a control roll out from right in a determinate page.


问:
Spark/Java serializable issue - org.apache.spark.SparkException: Task not serializable
I am having an issue with the following bits of code when writing an application for Spark using Java:

```<code>public class BatchLayerDefaultJob implements Serializable {

private static Function <BatchLayerProcessor, Future> batchFunction = new Function<BatchLayerProcessor, Future>() {
    @Override
    public Future call(BatchLayerProcessor s) {
        return executor.submit(s);
    }
};
public void applicationRunner(BatchParameters batchParameters) {

 SparkConf sparkConf = new SparkConf().setAppName("Platform Engine - Batch Job");
 sparkConf.set("spark.driver.allowMultipleContexts", "true");
 sparkConf.set("spark.cores.max", "1");
 JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
 List<BatchLayerProcessor> batchListforRDD = new ArrayList<BatchLayerProcessor>();

// populate List here.... Then attempt to process below

JavaRDD<BatchLayerProcessor> distData = sparkContext.parallelize(batchListforRDD, batchListforRDD.size());
JavaRDD<Future> result = distData.map(batchFunction);
result.collect(); // <-- Produces an object not serializable exception here
</code>```

So I have tried a number of things to no avail including extracting the batchFunction as a separate class outside of the influence of the main class and I have also attempted to use mapPartitions instead of map. I am more or less out of ideas. Any help is appreciated.

Stack trace below:

```<code>17/11/30 17:11:28 INFO DAGScheduler: Job 0 failed: collect at
BatchLayerDefaultJob.java:122, took 23.406561 s
Exception in thread "Thread-8" org.apache.spark.SparkException: Job aborted due to stage failure: Failed to serialize task 0, not attempting to retry it. Exception during serialization:
java.io.NotSerializableException: xxxx.BatchLayerProcessor
Serialization stack:
- object not serializable (class: xxxx.BatchLayerProcessor, value: xxxx.BatchLayerProcessor@3e745097)
- element of array (index: 0)
- array (class [Ljava.lang.Object;, size 1)
- field (class: scala.collection.mutable.WrappedArray$ofRef, name: array, type: class [Ljava.lang.Object;)
- object (class scala.collection.mutable.WrappedArray$ofRef, WrappedArray(xxxx.BatchLayerProcessor@3e745097))
- writeObject data (class: org.apache.spark.rdd.ParallelCollectionPartition)
- object (class org.apache.spark.rdd.ParallelCollectionPartition, org.apache.spark.rdd.ParallelCollectionPartition@691)
- field (class: org.apache.spark.scheduler.ResultTask, name: partition, type: interface org.apache.spark.Partition)
- object (class org.apache.spark.scheduler.ResultTask, ResultTask(0, 0))
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1499)
</code>```

Cheers.

EDIT::Added BatchLayerProcessor as requested - Slightly truncated:

```<code>public class BatchLayerProcessor implements Runnable, Serializable {
private int interval, backMinutes;
private String scoreVal, batchjobid;
private static CountDownLatch countDownLatch;
 public void run() {
    /* Get a reference to the ApplicationContextReader, a singleton*/
    ApplicationContextReader applicationContextReaderCopy = ApplicationContextReader.getInstance();

    synchronized (BatchLayerProcessor.class) /* Protect singleton member variable from multithreaded access. */ {
        if (applicationContextReader == null) /* If local reference is null...*/
            applicationContextReader = applicationContextReaderCopy; /* ...set it to the singleton */
    }

    if (getxScoreVal().equals("")) {
        applicationContextReader.getScoreService().calculateScores(applicationContextReader.getFunctions(), getInterval(), getBackMinutes(), getScoreVal(), true, getTimeInterval(), getIncludes(), getExcludes());
    }
    else {
        applicationContextReader.getScoreService().calculateScores(applicationContextReader.getFunctions(), getInterval(), getBackMinutes(), getScoreVal(), true, getTimeInterval(), getIncludes(), getExcludes());
    }

    countDownLatch.countDown();
}
</code>```

答: Decided to change BatchLayerProcessor so that it is not runnable and instead rely on Spark to do the work for me there. </p>

Body:
I am having an issue with the following bits of code when writing an application for Spark using Java:

public class BatchLayerDefaultJob implements Serializable {

private static Function <BatchLayerProcessor, Future> batchFunction = new Function<BatchLayerProcessor, Future>() {
    @Override
    public Future call(BatchLayerProcessor s) {
        return executor.submit(s);
    }
};
public void applicationRunner(BatchParameters batchParameters) {

 SparkConf sparkConf = new SparkConf().setAppName("Platform Engine - Batch Job");
 sparkConf.set("spark.driver.allowMultipleContexts", "true");
 sparkConf.set("spark.cores.max", "1");
 JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
 List<BatchLayerProcessor> batchListforRDD = new ArrayList<BatchLayerProcessor>();

// populate List here.... Then attempt to process below

JavaRDD<BatchLayerProcessor> distData = sparkContext.parallelize(batchListforRDD, batchListforRDD.size());
JavaRDD<Future> result = distData.map(batchFunction);
result.collect(); // <-- Produces an object not serializable exception here

So I have tried a number of things to no avail including extracting the batchFunction as a separate class outside of the influence of the main class and I have also attempted to use mapPartitions instead of map. I am more or less out of ideas. Any help is appreciated.

Stack trace below:

17/11/30 17:11:28 INFO DAGScheduler: Job 0 failed: collect at
BatchLayerDefaultJob.java:122, took 23.406561 s
Exception in thread "Thread-8" org.apache.spark.SparkException: Job aborted due to stage failure: Failed to serialize task 0, not attempting to retry it. Exception during serialization:
java.io.NotSerializableException: xxxx.BatchLayerProcessor
Serialization stack:
- object not serializable (class: xxxx.BatchLayerProcessor, value: xxxx.BatchLayerProcessor@3e745097)
- element of array (index: 0)
- array (class [Ljava.lang.Object;, size 1)
- field (class: scala.collection.mutable.WrappedArray$ofRef, name: array, type: class [Ljava.lang.Object;)
- object (class scala.collection.mutable.WrappedArray$ofRef, WrappedArray(xxxx.BatchLayerProcessor@3e745097))
- writeObject data (class: org.apache.spark.rdd.ParallelCollectionPartition)
- object (class org.apache.spark.rdd.ParallelCollectionPartition, org.apache.spark.rdd.ParallelCollectionPartition@691)
- field (class: org.apache.spark.scheduler.ResultTask, name: partition, type: interface org.apache.spark.Partition)
- object (class org.apache.spark.scheduler.ResultTask, ResultTask(0, 0))
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1499)

Cheers.

EDIT::Added BatchLayerProcessor as requested - Slightly truncated:

public class BatchLayerProcessor implements Runnable, Serializable {
private int interval, backMinutes;
private String scoreVal, batchjobid;
private static CountDownLatch countDownLatch;
 public void run() {
    /* Get a reference to the ApplicationContextReader, a singleton*/
    ApplicationContextReader applicationContextReaderCopy = ApplicationContextReader.getInstance();

    synchronized (BatchLayerProcessor.class) /* Protect singleton member variable from multithreaded access. */ {
        if (applicationContextReader == null) /* If local reference is null...*/
            applicationContextReader = applicationContextReaderCopy; /* ...set it to the singleton */
    }

    if (getxScoreVal().equals("")) {
        applicationContextReader.getScoreService().calculateScores(applicationContextReader.getFunctions(), getInterval(), getBackMinutes(), getScoreVal(), true, getTimeInterval(), getIncludes(), getExcludes());
    }
    else {
        applicationContextReader.getScoreService().calculateScores(applicationContextReader.getFunctions(), getInterval(), getBackMinutes(), getScoreVal(), true, getTimeInterval(), getIncludes(), getExcludes());
    }

    countDownLatch.countDown();
}


问:
HTML in language files
I made custom validation errors for an extension. Now I want to add an HTML link to an error message. tried to put HTML in language files (locallang.xlf) but it doesn't work.

Is there a way around this ?

答:
You can use CDATA to encapsulate the HTML:

```<code><target><![CDATA[Here is <a href="https://...">useful info</a>]]></target>
</code>```

You should consider generating the link URI from the outside and pass it as argument. Your translation could then look like this:

```<code><target><![CDATA[Here is <a href="%s">useful info</a>]]></target>
</code>```

In a Fluid template you would then do this:

```<code><f:translate key="translation-id" arguments="{0: '{f:uri.typolink(...)}'}"/>
</code>```

This would have the advantage that you can freely customize the link e.g. via TypoScript constants/setup.

Title: HTML in language files

Body:
You can use CDATA to encapsulate the HTML:

<target><![CDATA[Here is <a href="https://...">useful info</a>]]></target>

You should consider generating the link URI from the outside and pass it as argument. Your translation could then look like this:

<target><![CDATA[Here is <a href="%s">useful info</a>]]></target>

In a Fluid template you would then do this:

<f:translate key="translation-id" arguments="{0: '{f:uri.typolink(...)}'}"/>

This would have the advantage that you can freely customize the link e.g. via TypoScript constants/setup.


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答: Object Role Modeling (not to be confused with Object Relational Mapping) is the closest thing I know of to normalization for objects.  It doesn't have as mathematical a foundation as normalization, but it's a start.</p>

OwnerDisplayName: meade

ContentLicense: CC BY-SA 2.5

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: Bill the Lizard


问:
Jackson Vs. Gson
After searching through some existing libraries for JSON, I have finally ended up with these two:

Jackson

Google GSon

I am a bit partial towards GSON, but word on the net is that GSon suffers from a certain celestial performance issue (as of Sept 2009).

I am continuing my comparison; in the meantime, I'm looking for help to make up my mind.

答: Gson 1.6 now includes a low-level streaming API and a new parser which is actually faster than Jackson.</p>

Title: Jackson Vs. Gson


问:
How to attach function to the Observer while using Observable in Angular?
I know how to emit a value to the observer and subscribe to them using observable, as shown here

```<code>var observable = new Observable(observer => {
      observer.next(1);
      observer.next(2);
      observer.next(3);
    }).subscribe((success) => {
      console.log(success);
    })
</code>```

but if I want to do the same thing with the function, ie. I have something like this, then how can I achieve it

```<code> var observable = new Observable(observer => {
      observer.next(function () {
        setTimeout(() => {
          1
        }, 1000)
      })
      observer.next(function () {
        setTimeout(() => {
          2
        }, 1000)
      })
      observer.next(function () {
        setTimeout(() => {
          3
        }, 1000)
      })
    }).subscribe((success) => {
      console.log(success);
    })
</code>```

is it possible, all I have to do is call a series of async functions, how can I do it

UPDATE

i want to call a series of asnc fuctions in a sequence, ie. the second should be called only after the completion of the first functions operation and so on and so forth

答:
You can do something like this. This is just the fundamental here. You can call your async instead of emitting static values.</p>

```<code>var ParentObservable = new Observable();

ParentObservable.subscribe((res) => {
  //res is your response from async calls
  //Call asyncCall again from here
})

function asyncCall(){
  this.http.get("your URL").map((res)=> res.json()).subscribe((res)=>{
      ParentObservable.next(res);
  })
}
</code>```

Body:
I know how to emit a value to the observer and subscribe to them using observable, as shown here

var observable = new Observable(observer => {
      observer.next(1);
      observer.next(2);
      observer.next(3);
    }).subscribe((success) => {
      console.log(success);
    })

but if I want to do the same thing with the function, ie. I have something like this, then how can I achieve it

 var observable = new Observable(observer => {
      observer.next(function () {
        setTimeout(() => {
          1
        }, 1000)
      })
      observer.next(function () {
        setTimeout(() => {
          2
        }, 1000)
      })
      observer.next(function () {
        setTimeout(() => {
          3
        }, 1000)
      })
    }).subscribe((success) => {
      console.log(success);
    })

is it possible, all I have to do is call a series of async functions, how can I do it

UPDATE

i want to call a series of asnc fuctions in a sequence, ie. the second should be called only after the completion of the first functions operation and so on and so forth

Body:
You can do something like this. This is just the fundamental here. You can call your async instead of emitting static values.

var ParentObservable = new Observable();

ParentObservable.subscribe((res) => {
  //res is your response from async calls
  //Call asyncCall again from here
})

function asyncCall(){
  this.http.get("your URL").map((res)=> res.json()).subscribe((res)=>{
      ParentObservable.next(res);
  })
}


问:
Need the entire chain of Child of a particular parent record in SQL server
We want to get the total TREE structure (Down chain) of a particular record based on the ID from SQL Server.

This is my data table structure:

```<code>-----------------------------------------------------------------
CHILD_CODE      PARENT_CODE      CHILD_RANK      PARENT_RANK
-----------------------------------------------------------------
1               Null                  1          Null
2               1                     2          1
3               1                     2          1
4               1                     2          1
5               2                     3          2
6               2                     3          2
7               3                     3          2
8               5                     4          3
</code>```

Here I need to have the entire child tree for a parent. Means if I give 2 as parent input it will give me all the child below it as a tree till the end.
example... 1

input > PARENT_CODE = 2

output >

```<code>----------------------------------------------
PARENT_CODE     CHILD_CODE      CHILD_RANK
----------------------------------------------
2               5               3
2               6               3
2               8               4
----------------------------------------------
</code>```

Here we have used the CET like

```<code>; WITH rekurs AS (
   SELECT child_code, child_rank
   FROM   tbl
   WHERE  parent_code = 2
   UNION ALL
   SELECT ch.child_code, ch.child_rank
   FROM   tbl ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT 2 AS PARENT_CODE, child_code, child_rank
FROM  CTE
</code>```

We have already added this CTE in out program but here we are working on a large number of records and we are facing some problem. In this CTE we are passing a single parent_code for which we are getting all the child of that particular code.

Here we want to get all the child of 30,000 parent_code, which is taking so much times while we are passing the parent_code to CTE one by one in a for loop from C# program. Is there any  way to resolve this issue?

答:
You can use the following code

Suppose your table name is data then:

```<code>declare @input int =2
;with report as(
   select ChildCode,ParentCode,ChildRank,ParentRank
   from data
   where ParentCode = @input
   union all
   select d.ChildCode,d.ParentCode,d.ChildRank,d.ParentRank
   from data d
   inner join report r on d.ParentCode = r.ChildCode
 )

 select * from report
</code>```

Here a working demo

Result

```<code>ChildCode   ParentCode  ChildRank   ParentRank
5   2   3   2
6   2   3   2
8   5   4   3
</code>```

Edit based on the comments below

Explanation

you can create a user defined table type

create type ParentInputs as table(ParentCode int)

You pass the table type parameter to the query

Query

```<code>;with report as(
   select ChildCode,d.ParentCode,ChildRank,ParentRank
   from @data d
   inner join @input p on d.ParentCode = p.ParentCode
   union all
   select d.ChildCode,d.ParentCode,d.ChildRank,d.ParentRank
   from @data d
   inner join report r on d.ParentCode = r.ChildCode
 )
 select * from report order by ParentCode
</code>```

For the sake of the demo, I created a parameter table instead of the table type, kindly find the working demo

Result for ParentCode (2,3)

```<code>ChildCode   ParentCode  ChildRank   ParentRank
5   2   3   2
6   2   3   2
7   3   3   2
8   5   4   3
</code>```

Hope this will help you

Body:
We want to get the total TREE structure (Down chain) of a particular record based on the ID from SQL Server.

This is my data table structure:

-----------------------------------------------------------------
CHILD_CODE      PARENT_CODE      CHILD_RANK      PARENT_RANK
-----------------------------------------------------------------
1               Null                  1          Null
2               1                     2          1
3               1                     2          1
4               1                     2          1
5               2                     3          2
6               2                     3          2
7               3                     3          2
8               5                     4          3

Here I need to have the entire child tree for a parent. Means if I give 2 as parent input it will give me all the child below it as a tree till the end.
example... 1

input > PARENT_CODE = 2

output >

----------------------------------------------
PARENT_CODE     CHILD_CODE      CHILD_RANK
----------------------------------------------
2               5               3
2               6               3
2               8               4
----------------------------------------------

Here we have used the CET like

; WITH rekurs AS (
   SELECT child_code, child_rank
   FROM   tbl
   WHERE  parent_code = 2
   UNION ALL
   SELECT ch.child_code, ch.child_rank
   FROM   tbl ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT 2 AS PARENT_CODE, child_code, child_rank
FROM  CTE

We have already added this CTE in out program but here we are working on a large number of records and we are facing some problem. In this CTE we are passing a single parent_code for which we are getting all the child of that particular code.

Here we want to get all the child of 30,000 parent_code, which is taking so much times while we are passing the parent_code to CTE one by one in a for loop from C# program. Is there any  way to resolve this issue?

Body:
You can use the following code

Suppose your table name is data then:

declare @input int =2
;with report as(
   select ChildCode,ParentCode,ChildRank,ParentRank
   from data
   where ParentCode = @input
   union all
   select d.ChildCode,d.ParentCode,d.ChildRank,d.ParentRank
   from data d
   inner join report r on d.ParentCode = r.ChildCode
 )

 select * from report

Here a working demo

Result

ChildCode   ParentCode  ChildRank   ParentRank
5   2   3   2
6   2   3   2
8   5   4   3

Edit based on the comments below

Explanation

you can create a user defined table type

create type ParentInputs as table(ParentCode int)

You pass the table type parameter to the query

Query

;with report as(
   select ChildCode,d.ParentCode,ChildRank,ParentRank
   from @data d
   inner join @input p on d.ParentCode = p.ParentCode
   union all
   select d.ChildCode,d.ParentCode,d.ChildRank,d.ParentRank
   from @data d
   inner join report r on d.ParentCode = r.ChildCode
 )
 select * from report order by ParentCode

For the sake of the demo, I created a parameter table instead of the table type, kindly find the working demo

Result for ParentCode (2,3)

ChildCode   ParentCode  ChildRank   ParentRank
5   2   3   2
6   2   3   2
7   3   3   2
8   5   4   3

Hope this will help you


问:
Laravel 5 make routing with unique parameter
I am currently using a route with a parameter nameto query the profile of a user in my application.

So for example: /members/johnwill show the profile of John.

You see the problem here, if there are 2 John's then it's gonna be a problem.

I know I could do something like this /members/idsince id is unique but I want the url to look pretty with the user's name and not a random number.

So my question is if there is a way to use the id to make it unique but to display the name in url?

my route:

```<code>Route::get('/members/{name}', 'UserController@usersProfile');
</code>```

My usersProfile method:

```<code>/**
 * Returns a users profile.
 *
 * @param string $name
 *
 * @return \Illuminate\Http\Response
 */
public function usersProfile($name)
{
    $profile = $this->userService->getProfile($name);

    if ($profile == null) {
        return redirect('members')->with('status', 'Whoops, looks like that member does not exist (yet).');
    }

    return view('members/profile', ['profile' => $profile]);
}
</code>```

答:
you can use some package for slug your model name :

https://github.com/spatie/laravel-sluggable

https://github.com/cviebrock/eloquent-sluggable

these packages automatically doing that for you.

if you have same name this will happen:

```<code>http://example.com/post/my-dinner-with-andre-francois
http://example.com/post/my-dinner-with-andre-francois-1
http://example.com/post/my-dinner-with-andre-francois-2
</code>```

just in production i have some issue with scopes...
when you apply global scope on model , it may create duplicate slug for that ... you can fix that by add this to your model :

```<code>public function scopeFindSimilarSlugs(Builder $query, Model $model, $attribute, $config, $slug)
    {
        $separator = $config['separator'];

        return $query->withoutGlobalScopes()->where(function (Builder $q) use ($attribute, $slug, $separator) {
            $q->where($attribute, '=', $slug)
                ->orWhere($attribute, 'LIKE', $slug . $separator . '%');
        });
    }
</code>```

Body:
I am currently using a route with a parameter nameto query the profile of a user in my application.

So for example: /members/johnwill show the profile of John.

You see the problem here, if there are 2 John's then it's gonna be a problem.

I know I could do something like this /members/idsince id is unique but I want the url to look pretty with the user's name and not a random number.

So my question is if there is a way to use the id to make it unique but to display the name in url?

my route:

Route::get('/members/{name}', 'UserController@usersProfile');

My usersProfile method:

/**
 * Returns a users profile.
 *
 * @param string $name
 *
 * @return \Illuminate\Http\Response
 */
public function usersProfile($name)
{
    $profile = $this->userService->getProfile($name);

    if ($profile == null) {
        return redirect('members')->with('status', 'Whoops, looks like that member does not exist (yet).');
    }

    return view('members/profile', ['profile' => $profile]);
}

Body:
you can use some package for slug your model name :

https://github.com/spatie/laravel-sluggable

https://github.com/cviebrock/eloquent-sluggable

these packages automatically doing that for you.

if you have same name this will happen:

http://example.com/post/my-dinner-with-andre-francois
http://example.com/post/my-dinner-with-andre-francois-1
http://example.com/post/my-dinner-with-andre-francois-2

just in production i have some issue with scopes...
when you apply global scope on model , it may create duplicate slug for that ... you can fix that by add this to your model :

public function scopeFindSimilarSlugs(Builder $query, Model $model, $attribute, $config, $slug)
    {
        $separator = $config['separator'];

        return $query->withoutGlobalScopes()->where(function (Builder $q) use ($attribute, $slug, $separator) {
            $q->where($attribute, '=', $slug)
                ->orWhere($attribute, 'LIKE', $slug . $separator . '%');
        });
    }


问:
openstreetmap nominatim slash in housenumber
I'm trying to form a get request to nominatim for geocoding. The problem is that in my country (Russia) we have a lot of houses with / in their numbers.

Example:

```<code>https://www.openstreetmap.org/way/52433785
</code>```

I have tried different ways of escaping / from url encoding, but with no luck.

```<code> http://nominatim.openstreetmap.org/search?q=40/49, улица Ляпидевского, Москва&format=xml&polygon=1&addressdetails=1
 http://nominatim.openstreetmap.org/search?q=40\/49, улица Ляпидевского, Москва&format=xml&polygon=1&addressdetails=1
 http://nominatim.openstreetmap.org/search?q=40%2F49%2C%20%D1%83%D0%BB%D0%B8%D1%86%D0%B0%20%D0%9B%D1%8F%D0%BF%D0%B8%D0%B4%D0%B5%D0%B2%D1%81%D0%BA%D0%BE%D0%B3%D0%BE%2C%20%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&format=xml&polygon=1&addressdetails=1
</code>```

All of the above mentioned request return only street, not house number.

So, I'm stuck.

答:
Searching for 40/49, улица Лавочкина, Москва at https://nominatim.openstreetmap.org returns the correct object and leads to this URL:

```<code>https://nominatim.openstreetmap.org/search.php?q=40%2F49%2C+%D1%83%D0%BB%D0%B8%D1%86%D0%B0+%D0%9B%D0%B0%D0%B2%D0%BE%D1%87%D0%BA%D0%B8%D0%BD%D0%B0%2C+%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&format=xml&polygon=1&addressdetails=1
</code>```

Requesting XML format works, too:

```<code>https://nominatim.openstreetmap.org/search.php?q=40%2F49%2C+%D1%83%D0%BB%D0%B8%D1%86%D0%B0+%D0%9B%D0%B0%D0%B2%D0%BE%D1%87%D0%BA%D0%B8%D0%BD%D0%B0%2C+%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&polygon_geojson=1
</code>```

Body:
I'm trying to form a get request to nominatim for geocoding. The problem is that in my country (Russia) we have a lot of houses with / in their numbers.

Example:

https://www.openstreetmap.org/way/52433785

I have tried different ways of escaping / from url encoding, but with no luck.

 http://nominatim.openstreetmap.org/search?q=40/49, улица Ляпидевского, Москва&format=xml&polygon=1&addressdetails=1
 http://nominatim.openstreetmap.org/search?q=40\/49, улица Ляпидевского, Москва&format=xml&polygon=1&addressdetails=1
 http://nominatim.openstreetmap.org/search?q=40%2F49%2C%20%D1%83%D0%BB%D0%B8%D1%86%D0%B0%20%D0%9B%D1%8F%D0%BF%D0%B8%D0%B4%D0%B5%D0%B2%D1%81%D0%BA%D0%BE%D0%B3%D0%BE%2C%20%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&format=xml&polygon=1&addressdetails=1

All of the above mentioned request return only street, not house number.

So, I'm stuck.

Body:
Searching for 40/49, улица Лавочкина, Москва at https://nominatim.openstreetmap.org returns the correct object and leads to this URL:

https://nominatim.openstreetmap.org/search.php?q=40%2F49%2C+%D1%83%D0%BB%D0%B8%D1%86%D0%B0+%D0%9B%D0%B0%D0%B2%D0%BE%D1%87%D0%BA%D0%B8%D0%BD%D0%B0%2C+%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&format=xml&polygon=1&addressdetails=1

Requesting XML format works, too:

https://nominatim.openstreetmap.org/search.php?q=40%2F49%2C+%D1%83%D0%BB%D0%B8%D1%86%D0%B0+%D0%9B%D0%B0%D0%B2%D0%BE%D1%87%D0%BA%D0%B8%D0%BD%D0%B0%2C+%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0&polygon_geojson=1


问:
How can I insert multiple rows into database in Laravel?
Here is my code:

```<code>$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
</code>```

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

答: You should create a new voucher within the for-loop. Currently, as you said, you are inserting the same object into the database five times

Body:
Here is my code:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?


问:
PHP Regex replace all instances of a character in similar strings
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

```<code>Data_*: " ... "
</code>```

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

```<code>Data_83: "He said, "Yes!" to the question"
</code>```

to become this...

```<code>Data_83: "He said, Yes! to the question"
</code>```

I am familiar with PHP and would like to use this. I know how to do something like...

```<code><?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);
</code>```

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

```<code><?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}
</code>```

答:
You may use preg_replace_callback with a regex like

```<code>'~^(\h*Data_\d{2,}:\h*")(.*)"~m'
</code>```

Note that you may make it safer if you specify an optional , at the end of the line: '~^(\h*Data_\d{2,}:\h*")(.*)",?\h*$~m' but you might need to introduce another capturing group then (around ,?\h*, and then append $m[3] in the preg_replace_callback callback function).

Details

^ - start of the line (m is a multiline modifier)

(\h*Data_\d{2,}:\h*") - Group 1  ($m[1]):

\h* - 0+ horizontal whitespaces

Data_ - Data_ substring

\d{2,} - 2 or more digits

: - a colon

\h* - 0+ horizontal whitespaces

" - double quote

(.*) - Group 2 ($m[2]): any 0+ chars other than line break chars, as many as possible, up to the last...

" - double quote (on a line).

The $m represents the whole match object, and you only need to remove the " inside $m[2], the second capture.

See the PHP demo:

```<code>preg_replace_callback('~^(\h*Data_\d{2,}:\h*")(.*)"~m', function($m) {
    return $m[1] . str_replace('"', '', $m[2]) . '"';
}, $content);
</code>```

Body:
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

Data_*: " ... "

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

Data_83: "He said, "Yes!" to the question"

to become this...

Data_83: "He said, Yes! to the question"

I am familiar with PHP and would like to use this. I know how to do something like...

<?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

<?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}

Body:
You may use preg_replace_callback with a regex like

'~^(\h*Data_\d{2,}:\h*")(.*)"~m'

Note that you may make it safer if you specify an optional , at the end of the line: '~^(\h*Data_\d{2,}:\h*")(.*)",?\h*$~m' but you might need to introduce another capturing group then (around ,?\h*, and then append $m[3] in the preg_replace_callback callback function).

Details

^ - start of the line (m is a multiline modifier)

(\h*Data_\d{2,}:\h*") - Group 1  ($m[1]):

\h* - 0+ horizontal whitespaces

Data_ - Data_ substring

\d{2,} - 2 or more digits

: - a colon

\h* - 0+ horizontal whitespaces

" - double quote

(.*) - Group 2 ($m[2]): any 0+ chars other than line break chars, as many as possible, up to the last...

" - double quote (on a line).

The $m represents the whole match object, and you only need to remove the " inside $m[2], the second capture.

See the PHP demo:

preg_replace_callback('~^(\h*Data_\d{2,}:\h*")(.*)"~m', function($m) {
    return $m[1] . str_replace('"', '', $m[2]) . '"';
}, $content);


问:
Select wav files from a folder whose partial names are in a text file
I have 500 wave files in a folder ABC which are named  like

```<code>F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100
</code>```

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

答:
```<code>function wavelist()

   wavefiles=dir('*.wav');   % loaded wave files
   myfolder='/home/adspr/Desktop/exps_sree/waves/selectedfiles'; %Output folder to store files

   for i=1: numel(wavefiles)  %for each wave file
      filename=wavefiles(i).name;
      [~,name,~] = fileparts(filename);  % found the name of file without extension
      a=name(end-2:end); %get the last 3 digits in the file name
      fileID = fopen('nameslist','r');

      while ~feof(fileID)
          b=fgetl(fileID); % get each line in the list file

          if strcmp(a,b) % compare
              movefile(filename,myfolder); % moved to otput folder

          end

      end
   fclose(fileID);

   end
end
</code>```

I don't think this is a simple answer, thats why I asked here. Anyway, my problem solved, thats why I posted this as an answer.

Thank you all.

Body:
I have 500 wave files in a folder ABC which are named  like

F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

Body:
function wavelist()

   wavefiles=dir('*.wav');   % loaded wave files
   myfolder='/home/adspr/Desktop/exps_sree/waves/selectedfiles'; %Output folder to store files

   for i=1: numel(wavefiles)  %for each wave file
      filename=wavefiles(i).name;
      [~,name,~] = fileparts(filename);  % found the name of file without extension
      a=name(end-2:end); %get the last 3 digits in the file name
      fileID = fopen('nameslist','r');

      while ~feof(fileID)
          b=fgetl(fileID); % get each line in the list file

          if strcmp(a,b) % compare
              movefile(filename,myfolder); % moved to otput folder

          end

      end
   fclose(fileID);

   end
end

I don't think this is a simple answer, thats why I asked here. Anyway, my problem solved, thats why I posted this as an answer.

Thank you all.


答:
You are always using the same instance of the object. Each time you save the same row with different data. here is how to fix.</p>

```<code>$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
</code>```

Title: How can I insert multiple rows into database in Laravel?

Body:
You are always using the same instance of the object. Each time you save the same row with different data. here is how to fix.

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}


问:
Android ADB devices unauthorized

Configuration:

Windows 8.1

ADB version: 1.0.32

Smartphone: Oneplus One

Problem

I installed the Samsung drivers as it is said to do. When I run the ADB devices command, it said unauthorized.

Already tried:

I've done everything that'd been said on this post: https://stackoverflow.com/a/25546300/1848376

But the problem is that I don't get a prompt on the phone to tell me I must accept the connection.

When I run the command adb shell, here is the answer:

```<code>error: device unauthorized.
This adbd's $ADB_VENDOR_KEYS is not set; try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
</code>```

I did "adb kill-server", but it didn't change anything. Why?

答:
In sequence:

```<code>    adb kill-server
</code>```

in your DEVICE SETUP, go to developer-options end disable usb-debugging

press REVOKE USB debugging authorizations, click OK

enable usb-debugging

```<code>adb start-server
</code>```

Title: Android ADB devices unauthorized

Body:
Configuration:

Windows 8.1

ADB version: 1.0.32

Smartphone: Oneplus One

Problem

I installed the Samsung drivers as it is said to do. When I run the ADB devices command, it said unauthorized.

Already tried:

I've done everything that'd been said on this post: https://stackoverflow.com/a/25546300/1848376

But the problem is that I don't get a prompt on the phone to tell me I must accept the connection.

When I run the command adb shell, here is the answer:

error: device unauthorized.
This adbd's $ADB_VENDOR_KEYS is not set; try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.

I did "adb kill-server", but it didn't change anything. Why?

Body:
In sequence:

    adb kill-server

in your DEVICE SETUP, go to developer-options end disable usb-debugging

press REVOKE USB debugging authorizations, click OK

enable usb-debugging

adb start-server


问:
Regex Optional Matches
I'm trying to match two types of strings using the preg_match function in PHP which could be the following.

'_mything_to_newthing'

'_onething'

'_mything_to_newthing_and_some_stuff'

In the third one above, I only want the "mything" and "newthing" so everything that comes after the third part is just some optional text the user could add. Ideally out of the regex would come in the cases of above;

'mything', 'newthing'

'onething'

'mything', 'newthing'

The patterns should match a-zA-Z0-9 if possible :-)

My regex is terrible, so any help would be appreciated!

Thanks in advanced.

答:
Assuming you're talking about _ deliminated text:

```<code>$regex = '/^_([a-zA-Z0-9]+)(|_to_([a-zA-Z0-9]+).*)$/';

$string = '_mything_to_newthing_and_some_stuff';
preg_match($regex, $string, $match);
$match = array(
    0 => '_mything_to_newthing_and_some_stuff',
    1 => 'mything',
    2 => '_to_newthing_and_some_stuff',
    3 => 'newthing',
);
</code>```

As far as anything farther, please provide more details and better sample text/output

Edit: You could always just use explode:

```<code>$parts = explode('_', $string);
$parts = array(
    0 => '',
    1 => 'mything',
    2 => 'to',
    3 => 'newthing',
    4 => 'and',
    5 => 'some',
    6 => 'stuff',
);
</code>```

As long as the format is consistent, it should work well...

Title: Regex Optional Matches

Body:
Assuming you're talking about _ deliminated text:

$regex = '/^_([a-zA-Z0-9]+)(|_to_([a-zA-Z0-9]+).*)$/';

$string = '_mything_to_newthing_and_some_stuff';
preg_match($regex, $string, $match);
$match = array(
    0 => '_mything_to_newthing_and_some_stuff',
    1 => 'mything',
    2 => '_to_newthing_and_some_stuff',
    3 => 'newthing',
);

As far as anything farther, please provide more details and better sample text/output

Edit: You could always just use explode:

$parts = explode('_', $string);
$parts = array(
    0 => '',
    1 => 'mything',
    2 => 'to',
    3 => 'newthing',
    4 => 'and',
    5 => 'some',
    6 => 'stuff',
);

As long as the format is consistent, it should work well...


问:
How i loop through my class object add in hashtable object
```<code>// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}
</code>```

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

答:
Use strongly typed Dictionary (using System.Collections.Generic needed):

```<code>using System.Collections.Generic;

public class Program
{
    class Friend
    {
        public string Name {get;set;}
        public int Age {get;set;}

        public Friend(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public static void Main()
    {
        // this is my class object
        Friend f1 = new Friend("Nazir", 24);
        Friend f2 = new Friend("Hamza", 24);
        Friend f3 = new Friend("Abdullah", 23);
        var myDict = new Dictionary<string, Friend>();
        // add this object in hashtable object
        myDict["13b-049-bs"] = f1;
        myDict["13b-034-bs"] = f1;
        myDict["13b-038-bs"] = f1;
        foreach (KeyValuePair<string, Friend> item in myDict)
        {
            Console.WriteLine("Key {0}\tName {1}\tAge {2}", item.Key, item.Value.Name, item.Value.Age);
        }
    }
}
</code>```

Strongly typed has the advantage that you never will put an Enemy (or some other Type inside this dict - unless it derives from Friend.

Body:
// this is my class object
Friend f1 = new Friend("Nazir",24);
Friend f2 = new Friend("Hamza", 24);
Friend f3 = new Friend("Abdullah", 23);

Hashtable myhash = new Hashtable();

// add this object in hashtable object
myhash.Add("13b-049-bs",f1);
myhash.Add("13b-034-bs", f1);
myhash.Add("13b-038-bs", f1);

foreach (Friend item in myhash)
{
    Console.WriteLine("Key {0}\tName {1}\tAge {2}",item.Name,item.Age,myhash.Keys);
}

I got this error:

An unhandled exception of type 'System.InvalidCastException' occurred in HashTableDemo.exe

Body:
Use strongly typed Dictionary (using System.Collections.Generic needed):

using System.Collections.Generic;

public class Program
{
    class Friend
    {
        public string Name {get;set;}
        public int Age {get;set;}

        public Friend(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public static void Main()
    {
        // this is my class object
        Friend f1 = new Friend("Nazir", 24);
        Friend f2 = new Friend("Hamza", 24);
        Friend f3 = new Friend("Abdullah", 23);
        var myDict = new Dictionary<string, Friend>();
        // add this object in hashtable object
        myDict["13b-049-bs"] = f1;
        myDict["13b-034-bs"] = f1;
        myDict["13b-038-bs"] = f1;
        foreach (KeyValuePair<string, Friend> item in myDict)
        {
            Console.WriteLine("Key {0}\tName {1}\tAge {2}", item.Key, item.Value.Name, item.Value.Age);
        }
    }
}

Strongly typed has the advantage that you never will put an Enemy (or some other Type inside this dict - unless it derives from Friend.


问:
Casperjs Google Login (V2) Not working
I´m using casperjs (so phantomjs in the middle) to access some google utilities but, before accessing them we should be logged in google. For V1 google authentication, we are using the following script:

```<code>var casper = require('casper').create();
url = 'https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount&flowName=GlifWebSignIn&flowEntry=ServiceLogin&nojavascript=1#identifier';
casper.start(url, function() {

  this.fillSelectors('form#gaia_loginform', {
    'input[name="Email"]': 'your@email',
  }); //Fills the email box with email
  this.click("#next");

  this.wait(500, function() { //Wait for next page to load
    this.waitForSelector("#Passwd", //Wait for password box
      function success() {
        console.log("SUCCESS...");
        this.fillSelectors('form#gaia_loginform', {
          'input[name="Passwd"]': 'yourPassw',
        }); //Fill password box with PASSWORD
        this.click("#signIn"); //Click sign in button
        this.wait(500, function() {}); //Wait for it fully sigin
        casper.thenOpen('http://utility.google.com/', function() {
            this.wait(2000, function() {
                this.capture('media/status.png', undefined, {
                    format: 'png',
                    quality: 100`enter code here`
                });
            });
        });
      },
      function fail() {
        console.log("FAIL...");
      }
    );
  });
});
casper.run();
</code>```

We have changed the way that we manipulate the form and fill the fields and It's working so far. The problem with V2 authentication is that triggering the mouse events isn't possible, that means we can't click using this.click("#next") and this.click("#signIn"). I tried doing post over the form, using different mouse events and also trying to manipulate directly the jsaction events. Nothing works.

Someone has an idea on how to solve this issue? Thank you so much!

答:
Casper use PhantomJS, and Phantom itself is unable to login in google account login. It seems to use any ES6 feature not supported in phantomjs it fails silently.

Maybe you can have more luck with beta phantomjs 2.5.
Anyway, phantomjs is deprecated in favor of chrome headless. As said by phantom maintainer Vitaly Slobodin
https://groups.google.com/forum/#!topic/phantomjs/9aI5d-LDuNE

The good news is that you can start chrome in headless mode as: /opt/google/chrome/chrome --headless --disable-gpu --repl and do whatever you want.

You can replace the --repl with --remote-debugging-port=9224 to control it in any remote code, like a program in node...
There is libraries to control it like phantomjs.
High level (like phantom): https://github.com/GoogleChrome/puppeteer
and lower levels to have more control: https://github.com/cyrus-and/chrome-remote-interface#clientdomainmethodparams-callback

Currently I had no luck with puppeteer but with chrome-remote-interface I was able to login in google account.

```<code>const CDP = require('chrome-remote-interface');
const argv = require('minimist')(process.argv.slice(2));
const file = require('fs');

// CLI Args
const url = argv.url || 'https://accounts.google.com';
const format = argv.format === 'jpeg' ? 'jpeg' : 'png';
const viewportWidth = argv.viewportWidth || 1440;
const viewportHeight = argv.viewportHeight || 900;
let delay = argv.delay || 0;
const userAgent = argv.userAgent;
const fullPage = argv.full;

// Start the Chrome Debugging Protocol
CDP(async function(client) {
  // Extract used DevTools domains.
  const {DOM, Emulation, Network, Page, Runtime} = client;

  // Enable events on domains we are interested in.
  await Page.enable();
  await DOM.enable();
  await Network.enable();

  // If user agent override was specified, pass to Network domain
  if (userAgent) {
    await Network.setUserAgentOverride({userAgent});
  }

  // Set up viewport resolution, etc.
  const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false,
  };
  await Emulation.setDeviceMetricsOverride(deviceMetrics);
  await Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});

  // Navigate to target page
  await Page.navigate({url});

  // Wait for page load event to take screenshot
  Page.loadEventFired(async () => {
    // If the `full` CLI option was passed, we need to measure the height of
    // the rendered page and use Emulation.setVisibleSize
    if (fullPage) {
      const {root: {nodeId: documentNodeId}} = await DOM.getDocument();
      const {nodeId: bodyNodeId} = await DOM.querySelector({
        selector: 'body',
        nodeId: documentNodeId,
      });
      const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});

      await Emulation.setVisibleSize({width: viewportWidth, height: height});
      // This forceViewport call ensures that content outside the viewport is
      // rendered, otherwise it shows up as grey. Possibly a bug?
      await Emulation.forceViewport({x: 0, y: 0, scale: 1});
    }

    let expr="document.querySelector('input[type=email]').value='YOUREMAIL@gmail.com';";
    expr+="document.querySelectorAll('div[role=button]')[0].click();";
    setTimeout
    let x=await Runtime.evaluate({expression: expr});
    console.log('******' + JSON.stringify(x));
    setTimeout(async function(){
    expr="document.querySelector('input[type=password]').value='YOUR_PASSWORD';";
    expr+="document.querySelectorAll('div[role=button]')[1].click()";
    x=await Runtime.evaluate({expression: expr});
    console.log('******' + JSON.stringify(x));
    x=await ( async function() {
            let expr="document.querySelector('input[type=password]')";
            return Runtime.evaluate({expression: expr});
    })()
    console.log('**' + JSON.stringify(x));
    }, 2000);
delay=5000
    setTimeout(async function() {
      const screenshot = await Page.captureScreenshot({format});
      const buffer = new Buffer(screenshot.data, 'base64');
      file.writeFile('output.png', buffer, 'base64', function(err) {
        if (err) {
          console.error(err);
        } else {
          console.log('Screenshot saved');
        }
        client.close();
      });
    }, delay);
  });
}).on('error', err => {
  console.error('Cannot connect to browser:', err);
});
</code>```

References:
https://medium.com/@dschnr/using-headless-chrome-as-an-automated-screenshot-tool-4b07dffba79a

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserwsendpoint

https://developers.google.com/web/updates/2017/04/headless-chrome

Title: Casperjs Google Login (V2) Not working

Body:
I´m using casperjs (so phantomjs in the middle) to access some google utilities but, before accessing them we should be logged in google. For V1 google authentication, we are using the following script:

var casper = require('casper').create();
url = 'https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount&flowName=GlifWebSignIn&flowEntry=ServiceLogin&nojavascript=1#identifier';
casper.start(url, function() {

  this.fillSelectors('form#gaia_loginform', {
    'input[name="Email"]': 'your@email',
  }); //Fills the email box with email
  this.click("#next");

  this.wait(500, function() { //Wait for next page to load
    this.waitForSelector("#Passwd", //Wait for password box
      function success() {
        console.log("SUCCESS...");
        this.fillSelectors('form#gaia_loginform', {
          'input[name="Passwd"]': 'yourPassw',
        }); //Fill password box with PASSWORD
        this.click("#signIn"); //Click sign in button
        this.wait(500, function() {}); //Wait for it fully sigin
        casper.thenOpen('http://utility.google.com/', function() {
            this.wait(2000, function() {
                this.capture('media/status.png', undefined, {
                    format: 'png',
                    quality: 100`enter code here`
                });
            });
        });
      },
      function fail() {
        console.log("FAIL...");
      }
    );
  });
});
casper.run();

We have changed the way that we manipulate the form and fill the fields and It's working so far. The problem with V2 authentication is that triggering the mouse events isn't possible, that means we can't click using this.click("#next") and this.click("#signIn"). I tried doing post over the form, using different mouse events and also trying to manipulate directly the jsaction events. Nothing works.

Someone has an idea on how to solve this issue? Thank you so much!

Body:
Casper use PhantomJS, and Phantom itself is unable to login in google account login. It seems to use any ES6 feature not supported in phantomjs it fails silently.

Maybe you can have more luck with beta phantomjs 2.5.
Anyway, phantomjs is deprecated in favor of chrome headless. As said by phantom maintainer Vitaly Slobodin
https://groups.google.com/forum/#!topic/phantomjs/9aI5d-LDuNE

The good news is that you can start chrome in headless mode as: /opt/google/chrome/chrome --headless --disable-gpu --repl and do whatever you want.

You can replace the --repl with --remote-debugging-port=9224 to control it in any remote code, like a program in node...
There is libraries to control it like phantomjs.
High level (like phantom): https://github.com/GoogleChrome/puppeteer
and lower levels to have more control: https://github.com/cyrus-and/chrome-remote-interface#clientdomainmethodparams-callback

Currently I had no luck with puppeteer but with chrome-remote-interface I was able to login in google account.

const CDP = require('chrome-remote-interface');
const argv = require('minimist')(process.argv.slice(2));
const file = require('fs');

// CLI Args
const url = argv.url || 'https://accounts.google.com';
const format = argv.format === 'jpeg' ? 'jpeg' : 'png';
const viewportWidth = argv.viewportWidth || 1440;
const viewportHeight = argv.viewportHeight || 900;
let delay = argv.delay || 0;
const userAgent = argv.userAgent;
const fullPage = argv.full;

// Start the Chrome Debugging Protocol
CDP(async function(client) {
  // Extract used DevTools domains.
  const {DOM, Emulation, Network, Page, Runtime} = client;

  // Enable events on domains we are interested in.
  await Page.enable();
  await DOM.enable();
  await Network.enable();

  // If user agent override was specified, pass to Network domain
  if (userAgent) {
    await Network.setUserAgentOverride({userAgent});
  }

  // Set up viewport resolution, etc.
  const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false,
  };
  await Emulation.setDeviceMetricsOverride(deviceMetrics);
  await Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});

  // Navigate to target page
  await Page.navigate({url});

  // Wait for page load event to take screenshot
  Page.loadEventFired(async () => {
    // If the `full` CLI option was passed, we need to measure the height of
    // the rendered page and use Emulation.setVisibleSize
    if (fullPage) {
      const {root: {nodeId: documentNodeId}} = await DOM.getDocument();
      const {nodeId: bodyNodeId} = await DOM.querySelector({
        selector: 'body',
        nodeId: documentNodeId,
      });
      const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});

      await Emulation.setVisibleSize({width: viewportWidth, height: height});
      // This forceViewport call ensures that content outside the viewport is
      // rendered, otherwise it shows up as grey. Possibly a bug?
      await Emulation.forceViewport({x: 0, y: 0, scale: 1});
    }

    let expr="document.querySelector('input[type=email]').value='YOUREMAIL@gmail.com';";
    expr+="document.querySelectorAll('div[role=button]')[0].click();";
    setTimeout
    let x=await Runtime.evaluate({expression: expr});
    console.log('******' + JSON.stringify(x));
    setTimeout(async function(){
    expr="document.querySelector('input[type=password]').value='YOUR_PASSWORD';";
    expr+="document.querySelectorAll('div[role=button]')[1].click()";
    x=await Runtime.evaluate({expression: expr});
    console.log('******' + JSON.stringify(x));
    x=await ( async function() {
            let expr="document.querySelector('input[type=password]')";
            return Runtime.evaluate({expression: expr});
    })()
    console.log('**' + JSON.stringify(x));
    }, 2000);
delay=5000
    setTimeout(async function() {
      const screenshot = await Page.captureScreenshot({format});
      const buffer = new Buffer(screenshot.data, 'base64');
      file.writeFile('output.png', buffer, 'base64', function(err) {
        if (err) {
          console.error(err);
        } else {
          console.log('Screenshot saved');
        }
        client.close();
      });
    }, delay);
  });
}).on('error', err => {
  console.error('Cannot connect to browser:', err);
});

References:
https://medium.com/@dschnr/using-headless-chrome-as-an-automated-screenshot-tool-4b07dffba79a

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserwsendpoint

https://developers.google.com/web/updates/2017/04/headless-chrome