问:
RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 13: ERROR Places API
I am getting the following exception while trying out google places API to get likelihood places for Current Place in android.

```<code>Process: me.nabeelkottol.linkedinplaces, PID: 2995
 com.google.android.gms.tasks.RuntimeExecutionException:
 com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.tasks.zzn.getResult(Unknown Source)
 at
 me.nabeelkottol.linkedinplaces.MainActivity$1.onComplete(MainActivity.java:71)
 at com.google.android.gms.tasks.zzf.run(Unknown Source)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source)
 at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source)
 at com.google.android.gms.location.places.zzm.zzao(Unknown Source)
 at com.google.android.gms.location.places.internal.zzx.onTransact(Unknown Source)
 at android.os.Binder.execTransact(Binder.java:453)
</code>```

this is my code:

```<code>try {
      Task<PlaceLikelihoodBufferResponse> placeResult = mPlaceDetectionClient.getCurrentPlace(null);
      placeResult.addOnCompleteListener(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
        @Override public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {

          PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
          for (PlaceLikelihood placeLikelihood : likelyPlaces) {
            Log.i(TAG,
                String.format("Place '%s' has likelihood: %g", placeLikelihood.getPlace().getName(),
                    placeLikelihood.getLikelihood()));
          }
          likelyPlaces.release();

        }
      });
    } catch (SecurityException e) {
      e.printStackTrace();
    }
</code>```

Here the line PlaceLikelihoodBufferResponse likelyPlaces = task.getResult(); is giving me the error.

I have created an API key for the android app by giving the package name and SHA-1 key for debug from Google API console. And enabled Google Places API for android in the libraries section. still its giving the same error. Dont know what is wrong with the implementation. Please help me.

There is an issue reported in github regarding this.

This is my app/build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "me.nabeelkottol.linkedinplaces"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    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.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-places:11.6.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

This is my AndroidManifest.xml.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.nabeelkottol.linkedinplaces">

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.INTERNET"/>

  <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="My API Key here"/>

    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>

        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>

</manifest>
</code>```

答:
I had the same issue, I was able to resolve it by enabling Google places Api from Google console and adding places api key. As soon as you enable the Places api, it will automatically ask you to add api key, just follow the instructions.

Then add the API key in your manifest file.

```<code><application
    ...

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY" />

</application>
</code>```

Also, your emulator should have latest Google Play Services installed. Else use real Android device for testing.

Body:
I am getting the following exception while trying out google places API to get likelihood places for Current Place in android.

Process: me.nabeelkottol.linkedinplaces, PID: 2995
 com.google.android.gms.tasks.RuntimeExecutionException:
 com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.tasks.zzn.getResult(Unknown Source)
 at
 me.nabeelkottol.linkedinplaces.MainActivity$1.onComplete(MainActivity.java:71)
 at com.google.android.gms.tasks.zzf.run(Unknown Source)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source)
 at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source)
 at com.google.android.gms.location.places.zzm.zzao(Unknown Source)
 at com.google.android.gms.location.places.internal.zzx.onTransact(Unknown Source)
 at android.os.Binder.execTransact(Binder.java:453)

this is my code:

try {
      Task<PlaceLikelihoodBufferResponse> placeResult = mPlaceDetectionClient.getCurrentPlace(null);
      placeResult.addOnCompleteListener(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
        @Override public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {

          PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
          for (PlaceLikelihood placeLikelihood : likelyPlaces) {
            Log.i(TAG,
                String.format("Place '%s' has likelihood: %g", placeLikelihood.getPlace().getName(),
                    placeLikelihood.getLikelihood()));
          }
          likelyPlaces.release();

        }
      });
    } catch (SecurityException e) {
      e.printStackTrace();
    }

Here the line PlaceLikelihoodBufferResponse likelyPlaces = task.getResult(); is giving me the error.

I have created an API key for the android app by giving the package name and SHA-1 key for debug from Google API console. And enabled Google Places API for android in the libraries section. still its giving the same error. Dont know what is wrong with the implementation. Please help me.

There is an issue reported in github regarding this.

This is my app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "me.nabeelkottol.linkedinplaces"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    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.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-places:11.6.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

This is my AndroidManifest.xml.

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="me.nabeelkottol.linkedinplaces">

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.INTERNET"/>

  <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="My API Key here"/>

    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>

        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>

</manifest>

Body:
I had the same issue, I was able to resolve it by enabling Google places Api from Google console and adding places api key. As soon as you enable the Places api, it will automatically ask you to add api key, just follow the instructions.

Then add the API key in your manifest file.

<application
    ...

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY" />

</application>

Also, your emulator should have latest Google Play Services installed. Else use real Android device for testing.


来源: stackexchange

问:
How to get the last quarter
Here below is my code to get the last complete quarter:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, _ := time.Parse(layout, str)

    endDate := now.AddDate(0, 0, 0-now.Day())
    startDate := endDate.AddDate(0, -3, 0) // startDate is wrong: 2017-07-31
    // the following statement is needed to fix startDate
    if endDate.Month()-startDate.Month() == 3 {
        startDate = startDate.AddDate(0, 0, 1) // now startDate is correct: 2017-08-01
    }

    fmt.Printf("Start date: %v\n", startDate.Format("2006-01-02"))
    fmt.Printf("End date: %v\n", endDate.Format("2006-01-02"))
}
</code>```

playground

Is there a better way to get the correct start date?

For instance, the last startDate = startDate.AddDate(0, 0, 1) statement has to be omitted if I want to get the last semester:

```<code>endDate := now.AddDate(0, 0, 0-now.Day())
startDate := endDate.AddDate(0, -6, 0) // startDate is correct: 2017-05-01
</code>```

Why is there this difference?

答:
Package time

```<code>import "time"
</code>```

func Date

```<code>func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
</code>```

Date returns the Time corresponding to

```<code>yyyy-mm-dd hh:mm:ss + nsec nanoseconds
</code>```

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their
  usual ranges and will be normalized during the conversion. For
  example, October 32 converts to November 1.

For example, using normalization to get the last complete period (for example, quarter or semester):

```<code>package main

import (
    "fmt"
    "time"
)

func lastPeriod(t time.Time, period time.Month) (start, end time.Time) {
    y, m, _ := t.Date()
    loc := t.Location()
    start = time.Date(y, m-period, 1, 0, 0, 0, 0, loc)
    end = time.Date(y, m, 1, 0, 0, 0, -1, loc)
    return start, end
}

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, err := time.Parse(layout, str)
    if err != nil {
        fmt.Println(err)
        return
    }
    const (
        quarter  = 3
        semester = 6
    )
    fmt.Println("Quarter:")
    start, end := lastPeriod(now, quarter)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
    fmt.Println("Semester:")
    start, end = lastPeriod(now, semester)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
}
</code>```

Playground: https://play.golang.org/p/0t4exjVgr-

Output:

```<code>Quarter:
Base date:  2017-11-30
Start date: 2017-08-01
End date:   2017-10-31
Semester:
Base date:  2017-11-30
Start date: 2017-05-01
End date:   2017-10-31
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get the last quarter

Body:
Here below is my code to get the last complete quarter:

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, _ := time.Parse(layout, str)

    endDate := now.AddDate(0, 0, 0-now.Day())
    startDate := endDate.AddDate(0, -3, 0) // startDate is wrong: 2017-07-31
    // the following statement is needed to fix startDate
    if endDate.Month()-startDate.Month() == 3 {
        startDate = startDate.AddDate(0, 0, 1) // now startDate is correct: 2017-08-01
    }

    fmt.Printf("Start date: %v\n", startDate.Format("2006-01-02"))
    fmt.Printf("End date: %v\n", endDate.Format("2006-01-02"))
}

playground

Is there a better way to get the correct start date?

For instance, the last startDate = startDate.AddDate(0, 0, 1) statement has to be omitted if I want to get the last semester:

endDate := now.AddDate(0, 0, 0-now.Day())
startDate := endDate.AddDate(0, -6, 0) // startDate is correct: 2017-05-01

Why is there this difference?

Body:
Package time

import "time"

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their
  usual ranges and will be normalized during the conversion. For
  example, October 32 converts to November 1.

For example, using normalization to get the last complete period (for example, quarter or semester):

package main

import (
    "fmt"
    "time"
)

func lastPeriod(t time.Time, period time.Month) (start, end time.Time) {
    y, m, _ := t.Date()
    loc := t.Location()
    start = time.Date(y, m-period, 1, 0, 0, 0, 0, loc)
    end = time.Date(y, m, 1, 0, 0, 0, -1, loc)
    return start, end
}

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, err := time.Parse(layout, str)
    if err != nil {
        fmt.Println(err)
        return
    }
    const (
        quarter  = 3
        semester = 6
    )
    fmt.Println("Quarter:")
    start, end := lastPeriod(now, quarter)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
    fmt.Println("Semester:")
    start, end = lastPeriod(now, semester)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
}

Playground: https://play.golang.org/p/0t4exjVgr-

Output:

Quarter:
Base date:  2017-11-30
Start date: 2017-08-01
End date:   2017-10-31
Semester:
Base date:  2017-11-30
Start date: 2017-05-01
End date:   2017-10-31


问:
How do I read a file line by line while modifying lines as needed?
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

```<code>while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}
</code>```

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

```<code>use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}
</code>```

答:
I tend to do it as supposed in this answer (see sub precommit_hook):

First, read in the whole file into an array:

```<code>open my $handle,'<:utf8',$name
    or croak "Error reading file contents of $name\n";
my @content = <$handle>;
close $handle or croak "unable to close";
</code>```

Then, process each line of the array and write it out to the file:

```<code># now, write it, ignoring the comment lines
open my $handle, '>:utf8', $name
or croak "Opening $name for writing failed\n";
flock $handle, LOCK_EX;

foreach my $line(@content){
  # TODO: modify the line here
  print {$handle} $line . "\n";
}

close $handle or croak "unable to close";
</code>```

The downside of this is that the whole file gets re-written and if you exit too soon (e.g. during debugging), the file is messed up.

ContentLicense: CC BY-SA 2.5

Body:
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}

Body:
I tend to do it as supposed in this answer (see sub precommit_hook):

First, read in the whole file into an array:

open my $handle,'<:utf8',$name
    or croak "Error reading file contents of $name\n";
my @content = <$handle>;
close $handle or croak "unable to close";

Then, process each line of the array and write it out to the file:

# now, write it, ignoring the comment lines
open my $handle, '>:utf8', $name
or croak "Opening $name for writing failed\n";
flock $handle, LOCK_EX;

foreach my $line(@content){
  # TODO: modify the line here
  print {$handle} $line . "\n";
}

close $handle or croak "unable to close";

The downside of this is that the whole file gets re-written and if you exit too soon (e.g. during debugging), the file is messed up.


问:
How to mix Vue components with HTML outside the template
Think about a wordpress blog, or a standard CMS with some content. I use a wysiwyg editor (CKEditor) to write my contents and save them to db.

I want to use some Vue components inside this HTML, and so I add a wrapper div to my theme. HTML pages are wrapped by

```<code><div id="#my-custom-app">
...html from server
</div>
</code>```

Basically I want to add for example

```<code><my-app-image-compare></my-app-image-compare>
</code>```

using CKEditor inside my HTML, then I will create an app mounted on #my-custom-app div. I will insert the app at the end of the html body.

Vue.app file doesn't have a template, the template is basically my HTML page written with CKEditor, but every component is loaded and defined by the app and every component has a template.

How can I do? Is there a way to have a main Vue app file without a defined template?

答:
Option 1:

First create a vue container on a basic template. This template will then load a component which gets your data from the sever and displays it, so:

```<code>// This is your main vue instance container
<div id="#my-custom-app">
  <dynamic-html v-if="myHtmlFromServer" template="myHtmlFromServer"></dynamic-html>
</div>
</code>```

Within this main component, you need to hook up created event and populate myHtmlFromServer with your HTML content from the editor.

```<code>import DynamicHtml from './myComponents/DynamicHtml'
new Vue({
  el: '#my-custom-app',
  data () {
    return {
      myHtmlFromServer: ''
    }
  },
  components: {
    DynamicHtml
  }
  created () {
    // this.myHtmlFromServer = this.getDataFromServer()
  }
})
</code>```

The <dynamic-html> component, would have props: ['template'] and on the created event would assign this.$options.template = this.template.

This option will set the HTML template of that component and allow Vue to render it as normal (meaning you can then do {{someVal}} in your CKEditor.

Option 2:

Another option is if you're using a server side language like PHP, then you could just put that html on the page i.e echo $myHtmlContent and as long as that content contains
 you Vue instance will mount. PHP will add the HTML to the page before the JS processes the page so it'll just work.

Body:
Think about a wordpress blog, or a standard CMS with some content. I use a wysiwyg editor (CKEditor) to write my contents and save them to db.

I want to use some Vue components inside this HTML, and so I add a wrapper div to my theme. HTML pages are wrapped by

...html from server

Basically I want to add for example

<my-app-image-compare></my-app-image-compare>

using CKEditor inside my HTML, then I will create an app mounted on #my-custom-app div. I will insert the app at the end of the html body.

Vue.app file doesn't have a template, the template is basically my HTML page written with CKEditor, but every component is loaded and defined by the app and every component has a template.

How can I do? Is there a way to have a main Vue app file without a defined template?

Body:
Option 1:

First create a vue container on a basic template. This template will then load a component which gets your data from the sever and displays it, so:

// This is your main vue instance container
<div id="#my-custom-app">
  <dynamic-html v-if="myHtmlFromServer" template="myHtmlFromServer"></dynamic-html>
</div>

Within this main component, you need to hook up created event and populate myHtmlFromServer with your HTML content from the editor.

import DynamicHtml from './myComponents/DynamicHtml'
new Vue({
  el: '#my-custom-app',
  data () {
    return {
      myHtmlFromServer: ''
    }
  },
  components: {
    DynamicHtml
  }
  created () {
    // this.myHtmlFromServer = this.getDataFromServer()
  }
})

The <dynamic-html> component, would have props: ['template'] and on the created event would assign this.$options.template = this.template.

This option will set the HTML template of that component and allow Vue to render it as normal (meaning you can then do {{someVal}} in your CKEditor.

Option 2:

Another option is if you're using a server side language like PHP, then you could just put that html on the page i.e echo $myHtmlContent and as long as that content contains <div id="#my-custom-app"> you Vue instance will mount. PHP will add the HTML to the page before the JS processes the page so it'll just work.


问:
Concatenating Series using the addition (+) operator?
So this is more of a question than a problem i have.

I wanted to .append() some pandas series' together and without thinking i just did total=series1+series2+series3.

The length of each series is 2199902,171175, and 178989 respectively and sum(pd.isnull(i) for i in total) = 2214596

P.S all 3 series' had no null values to start with, is it something to do with merging 3 series' of different lengths which creates missing values? Even if that is the case why aer 2,214,596 null values created?

答:
If you're trying to append series, you're doing it wrong. The + operator calls .add which ends up adding each corresponding elements in the series. If your series are not aligned, this results in a lot of NaNs being generated.

If you're looking to append these together into one long series, you can use pd.concat:

```<code>pd.concat([s1, s2, s3], ignore_index=True)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

If you're going to use append, you can do this in a loop, or with reduce:

```<code>s = s1

for i in [s2, s3]:
    s = s.append(i, ignore_index=True)

s
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

```<code>from functools import reduce

reduce(lambda x, y: x.append(y, ignore_index=True), [s1, s2, s3])

0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

Both solutions generalise to multiple series quite nicely, but they are slow in comparison to pd.concat or np.concatenate.

ContentLicense: CC BY-SA 4.0

Body:
If you're trying to append series, you're doing it wrong. The + operator calls .add which ends up adding each corresponding elements in the series. If your series are not aligned, this results in a lot of NaNs being generated.

If you're looking to append these together into one long series, you can use pd.concat:

pd.concat([s1, s2, s3], ignore_index=True)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64

If you're going to use append, you can do this in a loop, or with reduce:

s = s1

for i in [s2, s3]:
    s = s.append(i, ignore_index=True)

s
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64

from functools import reduce

reduce(lambda x, y: x.append(y, ignore_index=True), [s1, s2, s3])

0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64

Both solutions generalise to multiple series quite nicely, but they are slow in comparison to pd.concat or np.concatenate.


问:
Cakephp 3 Sorting of another model is not working
I have two models Provides & Expenses
Problem: I have list of users with column Expenses.type_of_document, Expenses.change_to,Expenses.date, Provider.rut, Provider.nickname. Each & Every column has sorting but on Provider.rut and Provider.nickname sorting is not working.

ExpensesTable.php:

```<code>public function initialize(array $config)
{
    parent::initialize($config);

    $this->addBehavior('Timestamp');
    $this->table('expenses');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsToMany('Events', [
        'foreignKey' => 'expense_id',
        'targetForeignKey' => 'event_id',
        'joinTable' => 'events_expenses'
    ]);
    $this->belongsToMany('Providers', [
        'foreignKey' => 'expense_id',
        'targetForeignKey' => 'provider_id',
        'joinTable' => 'expenses_providers'
    ]);
    $this->hasMany('ExpensesProviders', [
        'foreignKey' => 'expense_id'
    ]);
}
</code>```

ProviderTable.php

```<code>public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('providers');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->hasMany('Products', [
        'foreignKey' => 'provider_id'
    ]);
}
</code>```

ExpensesProvidersTable.php

```<code>public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('expenses_providers');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsTo('Providers', [
        'foreignKey' => 'provider_id'
    ]);
    $this->belongsTo('Expenses', [
        'foreignKey' => 'expense_id'
    ]);
}
</code>```

ExpensesController.php

```<code>public function index(){
    $this->paginate=[‘contain’ => [‘Providers’],‘sortWhitelist’ => [‘Expenses.type_of_document’,‘Expenses.charge_to’,‘Expenses.date_of_issue’,‘Providers.rut’,‘Providers.nickname’,]];$expenses = $this->paginate($this->Expenses->find()->contain([‘Events’, ‘Providers’]));$this->set(compact(‘expenses’, ‘opt’));$this->set(’_serialize’, [‘expenses’]);}
</code>```

index.ctp

```<code>            <th class="left"><?= $this->Paginator->sort('Expenses.type_of_document', 'Tipo') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.charge_to', 'Cargo') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.date_of_issue', 'Fecha') ?></th>
            <th class="left"><?= $this->Paginator->sort('Providers.rut', 'Rut') ?></th>
            <th class="left"><?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.document_number', 'N° Dcto.') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.details', 'Detalle') ?></th>
            <th class="right"><?= $this->Paginator->sort('Expenses.amount_total', 'Total') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.payment_status', 'Estado') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.way_to_pay', 'Forma') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.created', 'Ingreso') ?></th>
            <th class="left"><?= $this->Paginator->sort('Expenses.paid_by', 'Pagado por') ?></th>
            <!--<th class="left"><?= $this->Paginator->sort('AccountingMonths.date', 'Mes') ?></th>
            <th scope="col"><?= $this->Paginator->sort('payment_date', 'Fecha de pago') ?></th>
            <th scope="col"><?= $this->Paginator->sort('accounting_statement', 'Estado de cuenta') ?></th>-->
            <th class="actions center"><?= __('Acciones') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($expenses as $expense): ?>
        <tr>
            <td class="left"><?= $expense->type_of_document ?></td>
            <td class="left"><?= (strcmp($expense->charge_to, 'evento') == 0 and !empty($expense->events))? $expense->events[0]->code : $expense->charge_to ?></td>
            <td class="left"><?= $this->Utils->chileanTimeZone($expense->date_of_issue, 'DDMMYYYY', 'UTC') ?></td>
            <td class="left"><?= h(!empty($expense->providers)? $expense->providers[0]->rut : '') ?></td>
            <td class="left"><?= h(!empty($expense->providers)? $expense->providers[0]->nickname : '') ?></td>
            <td class="left"><?= h($expense->document_number) ?></td>
            <td class="left"><?= h($expense->detail) ?></td>
            <td class="right"><?= "$ ".$this->Number->format($expense->amount_total, ['locale' => 'es_CL']) ?></td>
            <td class="left"><?= h($expense->payment_status) ?></td>
            <td class="left"><?= h($expense->way_to_pay) ?></td>
            <td class="left"><?= $this->Utils->chileanTimeZone($expense->created, 'DDMMYYYY', 'UTC') ?></td>
            <td class="left"><?= h($expense->paid_by) ?></td>
            <td class="actions center">
                <?= $this->Html->link(__('View'), ['action' => 'view', $expense->id]) ?>
                <?= $this->Html->link(__('Edit'), ['action' => 'edit', $expense->id]) ?>
                <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $expense->id], ['confirm' => __('Estás segur@ de eliminar # {0}?', $expense->document_number)]) ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<?= $this->element('pagination') ?>
</code>```

It does not work to order

```<code><?= $this->Paginator->sort('Providers.rut', 'Rut') ?> <?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?>
</code>```

Let me know any solution you have.

ERROR SQL

```<code>SELECT Expenses.id AS `Expenses__id`, Expenses.document_number AS `Expenses__document_number`, Expenses.charge_to AS `Expenses__charge_to`, Expenses.type_of_document AS `Expenses__type_of_document`, Expenses.date_of_issue AS `Expenses__date_of_issue`, Expenses.accounting_month_date AS `Expenses__accounting_month_date`, Expenses.detail AS `Expenses__detail`, Expenses.amount_total AS `Expenses__amount_total`, Expenses.payment_status AS `Expenses__payment_status`, Expenses.way_to_pay AS `Expenses__way_to_pay`, Expenses.payment_date AS `Expenses__payment_date`, Expenses.accounting_statement AS `Expenses__accounting_statement`, Expenses.paid_by AS `Expenses__paid_by`, Expenses.created AS `Expenses__created`, Expenses.modified AS `Expenses__modified`, Expenses.rut AS `Expenses__rut`, Expenses.provider_name AS `Expenses__provider_name` FROM expenses Expenses ORDER BY Providers.nickname asc LIMIT 20 OFFSET 0
</code>```

URL: http://localhost/pweventos/expenses?url=expenses&sort=Providers.nickname&direction=asc

答:
ExpensesController.php

```<code>    function index(){
    $this->paginate = [
                'contain' => ['Providers'],
                'sortWhitelist' => [
                    'Expenses.type_of_document',
                    'Expenses.charge_to',
                    'Expenses.date_of_issue',
                    'Providers.rut',
                    'Providers.nickname',
    ]
    ];
    }
</code>```

index.ctp

```<code> <thead>
            <tr>
 <th scope="col"><?= $this->Paginator->sort('Expenses.type_of_document', 'Tipo') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Expenses.charge_to', 'Cargo') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Expenses.date_of_issue', 'Fecha') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Providers.rut', 'Rut') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?></th>
<th scope="actions center"><?= __('Acciones') ?></th>
            </tr>
        </thead>
</code>```

Body:
I have two models Provides & Expenses
Problem: I have list of users with column Expenses.type_of_document, Expenses.change_to,Expenses.date, Provider.rut, Provider.nickname. Each & Every column has sorting but on Provider.rut and Provider.nickname sorting is not working.

ExpensesTable.php:

public function initialize(array $config)
{
    parent::initialize($config);

    $this->addBehavior('Timestamp');
    $this->table('expenses');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsToMany('Events', [
        'foreignKey' => 'expense_id',
        'targetForeignKey' => 'event_id',
        'joinTable' => 'events_expenses'
    ]);
    $this->belongsToMany('Providers', [
        'foreignKey' => 'expense_id',
        'targetForeignKey' => 'provider_id',
        'joinTable' => 'expenses_providers'
    ]);
    $this->hasMany('ExpensesProviders', [
        'foreignKey' => 'expense_id'
    ]);
}

ProviderTable.php

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('providers');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->hasMany('Products', [
        'foreignKey' => 'provider_id'
    ]);
}

ExpensesProvidersTable.php

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('expenses_providers');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsTo('Providers', [
        'foreignKey' => 'provider_id'
    ]);
    $this->belongsTo('Expenses', [
        'foreignKey' => 'expense_id'
    ]);
}

ExpensesController.php

public function index(){
    $this->paginate=[‘contain’ => [‘Providers’],‘sortWhitelist’ => [‘Expenses.type_of_document’,‘Expenses.charge_to’,‘Expenses.date_of_issue’,‘Providers.rut’,‘Providers.nickname’,]];$expenses = $this->paginate($this->Expenses->find()->contain([‘Events’, ‘Providers’]));$this->set(compact(‘expenses’, ‘opt’));$this->set(’_serialize’, [‘expenses’]);}

index.ctp

            <?= $this->Paginator->sort('Expenses.type_of_document', 'Tipo') ?>
            <?= $this->Paginator->sort('Expenses.charge_to', 'Cargo') ?>
            <?= $this->Paginator->sort('Expenses.date_of_issue', 'Fecha') ?>
            <?= $this->Paginator->sort('Providers.rut', 'Rut') ?>
            <?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?>
            <?= $this->Paginator->sort('Expenses.document_number', 'N° Dcto.') ?>
            <?= $this->Paginator->sort('Expenses.details', 'Detalle') ?>
            <?= $this->Paginator->sort('Expenses.amount_total', 'Total') ?>
            <?= $this->Paginator->sort('Expenses.payment_status', 'Estado') ?>
            <?= $this->Paginator->sort('Expenses.way_to_pay', 'Forma') ?>
            <?= $this->Paginator->sort('Expenses.created', 'Ingreso') ?>
            <?= $this->Paginator->sort('Expenses.paid_by', 'Pagado por') ?>

            <?= __('Acciones') ?>

        <?php foreach ($expenses as $expense): ?>

            <?= $expense->type_of_document ?>
            <?= (strcmp($expense->charge_to, 'evento') == 0 and !empty($expense->events))? $expense->events[0]->code : $expense->charge_to ?>
            <?= $this->Utils->chileanTimeZone($expense->date_of_issue, 'DDMMYYYY', 'UTC') ?>
            <?= h(!empty($expense->providers)? $expense->providers[0]->rut : '') ?>
            <?= h(!empty($expense->providers)? $expense->providers[0]->nickname : '') ?>
            <?= h($expense->document_number) ?>
            <?= h($expense->detail) ?>
            <?= "$ ".$this->Number->format($expense->amount_total, ['locale' => 'es_CL']) ?>
            <?= h($expense->payment_status) ?>
            <?= h($expense->way_to_pay) ?>
            <?= $this->Utils->chileanTimeZone($expense->created, 'DDMMYYYY', 'UTC') ?>
            <?= h($expense->paid_by) ?>

                <?= $this->Html->link(__('View'), ['action' => 'view', $expense->id]) ?>
                <?= $this->Html->link(__('Edit'), ['action' => 'edit', $expense->id]) ?>
                <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $expense->id], ['confirm' => __('Estás segur@ de eliminar # {0}?', $expense->document_number)]) ?>

        <?php endforeach; ?>

<?= $this->element('pagination') ?>

It does not work to order

<?= $this->Paginator->sort('Providers.rut', 'Rut') ?> <?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?>

Let me know any solution you have.

ERROR SQL

SELECT Expenses.id AS `Expenses__id`, Expenses.document_number AS `Expenses__document_number`, Expenses.charge_to AS `Expenses__charge_to`, Expenses.type_of_document AS `Expenses__type_of_document`, Expenses.date_of_issue AS `Expenses__date_of_issue`, Expenses.accounting_month_date AS `Expenses__accounting_month_date`, Expenses.detail AS `Expenses__detail`, Expenses.amount_total AS `Expenses__amount_total`, Expenses.payment_status AS `Expenses__payment_status`, Expenses.way_to_pay AS `Expenses__way_to_pay`, Expenses.payment_date AS `Expenses__payment_date`, Expenses.accounting_statement AS `Expenses__accounting_statement`, Expenses.paid_by AS `Expenses__paid_by`, Expenses.created AS `Expenses__created`, Expenses.modified AS `Expenses__modified`, Expenses.rut AS `Expenses__rut`, Expenses.provider_name AS `Expenses__provider_name` FROM expenses Expenses ORDER BY Providers.nickname asc LIMIT 20 OFFSET 0

URL: http://localhost/pweventos/expenses?url=expenses&sort=Providers.nickname&direction=asc

Body:
ExpensesController.php

    function index(){
    $this->paginate = [
                'contain' => ['Providers'],
                'sortWhitelist' => [
                    'Expenses.type_of_document',
                    'Expenses.charge_to',
                    'Expenses.date_of_issue',
                    'Providers.rut',
                    'Providers.nickname',
    ]
    ];
    }

index.ctp

 <thead>
            <tr>
 <th scope="col"><?= $this->Paginator->sort('Expenses.type_of_document', 'Tipo') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Expenses.charge_to', 'Cargo') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Expenses.date_of_issue', 'Fecha') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Providers.rut', 'Rut') ?></th>
                <th scope="col"><?= $this->Paginator->sort('Providers.nickname', 'Proveedor') ?></th>
<th scope="actions center"><?= __('Acciones') ?></th>
            </tr>
        </thead>


问:
Unable to use = operator in a "If" statement
Why can't I use = operator over here. Anyway to solve this problem ?

```<code> If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If
</code>```

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'

答:
Assuming that PictureBox1.Image references the same Image object as My.Resources.pic001, then you could use:</p>

```<code>If Object.ReferenceEquals(PictureBox1.Image, My.Resources.pic001) Then
</code>```

Body:
Why can't I use = operator over here. Anyway to solve this problem ?

 If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'

Body:
Assuming that PictureBox1.Image references the same Image object as My.Resources.pic001, then you could use:

If Object.ReferenceEquals(PictureBox1.Image, My.Resources.pic001) Then


问:
How to Resize image in Swift?
I am making an app for iOS, using Swift and Parse.com

I am trying to let the user select a picture from an image picker and then resize the selected image to 200x200 pixels before uploading to my backend.

Parse.com have a tutorial for an Instagram copy app called "AnyPic" which gives this code for resizing images, but it is in Objective-C....

```<code>// Resize the image to be square (what is shown in the preview)
UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit
        bounds:CGSizeMake(560.0f, 560.0f)
        interpolationQuality:kCGInterpolationHigh];
// Create a thumbnail and add a corner radius for use in table views
UIImage *thumbnailImage = [anImage thumbnailImage:86.0f
        transparentBorder:0.0f
        cornerRadius:10.0f
        interpolationQuality:kCGInterpolationDefault];
</code>```

How would I create a 200x200px version of the selected picture (to then upload) in Swift?

And, what is the thumbnailImage function doing?

答:
For Swift 4 I would just make an extension on UIImage with referencing to self.</p>

```<code>import UIKit
extension UIImage {
  func resizeImage(targetSize: CGSize) -> UIImage {
    let size = self.size
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height
    let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    self.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
  }
}
</code>```

Title: How to Resize image in Swift?

Body:
I am making an app for iOS, using Swift and Parse.com

I am trying to let the user select a picture from an image picker and then resize the selected image to 200x200 pixels before uploading to my backend.

Parse.com have a tutorial for an Instagram copy app called "AnyPic" which gives this code for resizing images, but it is in Objective-C....

// Resize the image to be square (what is shown in the preview)
UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit
        bounds:CGSizeMake(560.0f, 560.0f)
        interpolationQuality:kCGInterpolationHigh];
// Create a thumbnail and add a corner radius for use in table views
UIImage *thumbnailImage = [anImage thumbnailImage:86.0f
        transparentBorder:0.0f
        cornerRadius:10.0f
        interpolationQuality:kCGInterpolationDefault];

How would I create a 200x200px version of the selected picture (to then upload) in Swift?

And, what is the thumbnailImage function doing?

Body:
For Swift 4 I would just make an extension on UIImage with referencing to self.

import UIKit
extension UIImage {
  func resizeImage(targetSize: CGSize) -> UIImage {
    let size = self.size
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height
    let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    self.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
  }
}


问:
Does apache / php blocks a single file to be processed from the same client concurrently?
I have everything setup and running with KalturaCE & Drupak and the server (Ubuntu 8.02+Apache2+PHP5+MySql) is working fine.
The issue here I am having is unclassified.

When I play two videos together from my site, the second video which I played later doesn't start until the first completes its buffering. I did some HTTP watch and came to know that,
both of the entries request the file with the URL as follows,

```<code>/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxx/flavor/1/version/100000
</code>```

so the first video which I played receives a 302 redirect response to the URL as follows,

```<code>/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxxx/flavor/1/version/100000/a.flv?novar=0
</code>```

and starts buffering and playing. While the second video which I started later just wait for a response till the first video end its buffering and then the second video receives its 302 redirect and start buffering

My question is, why can't both videos buffer concurrently? and Obviously this is what I require.

Your help is highly anticipated and much welcome.

答:
I found the solution to my problem and it was surely the Marc at first place suggested but it was some problem with mysql timeout as well.

So putting session_write_close() in both the files at right places solved my problem.

For a complete overview please visit the suggested thread at http://www.kaltura.org/videos-not-playing-simultaneously-0

Body:
I have everything setup and running with KalturaCE & Drupak and the server (Ubuntu 8.02+Apache2+PHP5+MySql) is working fine.
The issue here I am having is unclassified.

When I play two videos together from my site, the second video which I played later doesn't start until the first completes its buffering. I did some HTTP watch and came to know that,
both of the entries request the file with the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxx/flavor/1/version/100000

so the first video which I played receives a 302 redirect response to the URL as follows,

/kalturace/p/1/sp/100/flvclipper/entry_id/xxxxxxx/flavor/1/version/100000/a.flv?novar=0

and starts buffering and playing. While the second video which I started later just wait for a response till the first video end its buffering and then the second video receives its 302 redirect and start buffering

My question is, why can't both videos buffer concurrently? and Obviously this is what I require.

Your help is highly anticipated and much welcome.


问:
Implement http request in interceptor angular2
I'm trying to handle 401 response from interceptor using httpClientModule. The authentication is based on JWT, with accessToken and refreshToken. If the accessToken is expired, I need to request the api to get a new one with the refreshToken. I would like to block the request when the a new token should be generated, get a new one, and then make the request with the new accessToken attached.

In this way, what is the best method to make http request from the interceptor ?

My interceptor :

```<code>@Injectable()

export class JwtService implements HttpInterceptor {

 constructor(public inj: Injector){}

 intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> {

    if ( this.shouldGenerateNewAccessToken(req.url) ){

        const auth = this.inj.get(AuthService);
        auth.getNewAccessToken().then( token => {

            if (token){

                const headers = { 'Authorization' : token };
                const clone = req.clone( { setHeaders : headers } );
                return next.handle(clone);

            } else { return next.handle(req); }

        }, error => {

             return next.handle(req);

        });
    }
    else {

        if (APP_CONFIG['accessToken']){

            const headers = { 'Authorization' : APP_CONFIG['accessToken'] };
            const clone = req.clone( { setHeaders : headers });
            return next.handle(clone);

        } else {

             return next.handle(req);

        }

    }

}

shouldGenerateNewAccessToken(url : string) : Boolean {

    let lastupdate = APP_CONFIG['accessTokenTimestamp'];
    let now = new Date().getTime();

    // Let say the token expires after 5s
    if ((now - lastupdate) > 5000 && APP_CONFIG['refreshToken'] && url != APP_CONFIG['apiEndPont']+'getaccesstoken'){
        return true;
    }
    else
        return false;
}
</code>```

Auth logic

```<code>getNewAccessToken() : Promise<any>{

    return new Promise( (resolve, reject)=>{

        this.http.post(this.api+ 'getaccesstoken', JSON.stringify({refreshToken: APP_CONFIG['refreshToken'] }), { "headers" : this.headers } ).subscribe( data  => {
            let res : any = data;
            APP_CONFIG['accessToken'] = res.accessToken;
            APP_CONFIG['accessTokenTimestamp'] = new Date().getTime();
            resolve(APP_CONFIG['accessToken']);

        }, err => {console.log('error'); reject(null); })
    });
}

getuserinfos(){

   return this.http.get(this.api+ 'getuserinfos', { "headers" : this.headers } ).subscribe( data  => {
      console.log('result getUserInfos =>', data);

  },
  ( err : HttpErrorResponse ) => {

     if ( err.error instanceof Error ) { console.log('An error occurred requete login:', err.error.message); }
     else {
         console.log('error => ', err)
    }

});
</code>```

}

I get the following error when I call getUserInfos() and the token is expired :

error => TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Is this linked to this behavior ?

More rarely, an interceptor may choose to completely handle the request itself, and compose a new event stream instead of invoking next.handle(). This is acceptable behavior, but keep in mind further interceptors will be skipped entirely. It is also rare but valid for an interceptor to return multiple responses on the event stream for a single request. Source

答:
I finally managed it with a different implementation. Here is my interceptor : </p>

```<code>@Injectable()

export class JwtService implements HttpInterceptor {

constructor(public inj: Injector){}

private fixUrl(url: string) {
    if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0)
        return url;
    else
        return APP_CONFIG['apiEndPoint'] + url;
}

intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> {

    // Clone request
    var headers = {}
    if (APP_CONFIG['accessToken']){
         headers = { 'Authorization' : APP_CONFIG['accessToken'] };
    }
    const cloneRequest = req.clone( { setHeaders : headers });

    return next.handle(cloneRequest).do(data => {

        if (data instanceof HttpResponse) {
          // Some logic
        }

    })
    .catch((res)=> {

        if (res.status === 401 || res.status === 403) {

            if (APP_CONFIG['accessToken'])
            {
                const auth = this.inj.get(AuthService);
                return auth.getUpdatedAccessToken().flatMap( token => {

                    // Clone the previous request
                    let clonedRequestRepeat = req.clone({
                        headers: req.headers.set('Authorization' ,  APP_CONFIG['accessToken'] ),
                        url: this.fixUrl(req.url)
                    });

                    // Request agin
                    return next.handle(clonedRequestRepeat).do(event => {

                        if (event instanceof HttpResponse) {
                            console.log('Repeat response of server : ', event);
                        }
                    });

                });
            }else { return Observable.throw('Not authenticated'); }

        }
        else { // Not 401
             return Observable.throw(res);
        }

    })

}

}
</code>```

<p>AuthService.ts </p>

```<code>getUpdatedAccessToken()  : Observable<any>{

 return this.http.post(this.api+ 'getaccesstoken', JSON.stringify({refreshToken: APP_CONFIG['refreshToken'] }), { "headers" : this.headers } )
            .map((response: any) => {
                if (response.code == 0){
                    APP_CONFIG['accessToken'] = response.accessToken;
                }
                return response
        })
}
</code>```

Body:
I'm trying to handle 401 response from interceptor using httpClientModule. The authentication is based on JWT, with accessToken and refreshToken. If the accessToken is expired, I need to request the api to get a new one with the refreshToken. I would like to block the request when the a new token should be generated, get a new one, and then make the request with the new accessToken attached.

In this way, what is the best method to make http request from the interceptor ?

My interceptor :

@Injectable()

export class JwtService implements HttpInterceptor {

 constructor(public inj: Injector){}

 intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> {

    if ( this.shouldGenerateNewAccessToken(req.url) ){

        const auth = this.inj.get(AuthService);
        auth.getNewAccessToken().then( token => {

            if (token){

                const headers = { 'Authorization' : token };
                const clone = req.clone( { setHeaders : headers } );
                return next.handle(clone);

            } else { return next.handle(req); }

        }, error => {

             return next.handle(req);

        });
    }
    else {

        if (APP_CONFIG['accessToken']){

            const headers = { 'Authorization' : APP_CONFIG['accessToken'] };
            const clone = req.clone( { setHeaders : headers });
            return next.handle(clone);

        } else {

             return next.handle(req);

        }

    }

}

shouldGenerateNewAccessToken(url : string) : Boolean {

    let lastupdate = APP_CONFIG['accessTokenTimestamp'];
    let now = new Date().getTime();

    // Let say the token expires after 5s
    if ((now - lastupdate) > 5000 && APP_CONFIG['refreshToken'] && url != APP_CONFIG['apiEndPont']+'getaccesstoken'){
        return true;
    }
    else
        return false;
}

Auth logic

getNewAccessToken() : Promise<any>{

    return new Promise( (resolve, reject)=>{

        this.http.post(this.api+ 'getaccesstoken', JSON.stringify({refreshToken: APP_CONFIG['refreshToken'] }), { "headers" : this.headers } ).subscribe( data  => {
            let res : any = data;
            APP_CONFIG['accessToken'] = res.accessToken;
            APP_CONFIG['accessTokenTimestamp'] = new Date().getTime();
            resolve(APP_CONFIG['accessToken']);

        }, err => {console.log('error'); reject(null); })
    });
}

getuserinfos(){

   return this.http.get(this.api+ 'getuserinfos', { "headers" : this.headers } ).subscribe( data  => {
      console.log('result getUserInfos =>', data);

  },
  ( err : HttpErrorResponse ) => {

     if ( err.error instanceof Error ) { console.log('An error occurred requete login:', err.error.message); }
     else {
         console.log('error => ', err)
    }

});

}

I get the following error when I call getUserInfos() and the token is expired :

error => TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Is this linked to this behavior ?

More rarely, an interceptor may choose to completely handle the request itself, and compose a new event stream instead of invoking next.handle(). This is acceptable behavior, but keep in mind further interceptors will be skipped entirely. It is also rare but valid for an interceptor to return multiple responses on the event stream for a single request. Source

Body:
I finally managed it with a different implementation. Here is my interceptor :

@Injectable()

export class JwtService implements HttpInterceptor {

constructor(public inj: Injector){}

private fixUrl(url: string) {
    if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0)
        return url;
    else
        return APP_CONFIG['apiEndPoint'] + url;
}

intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> {

    // Clone request
    var headers = {}
    if (APP_CONFIG['accessToken']){
         headers = { 'Authorization' : APP_CONFIG['accessToken'] };
    }
    const cloneRequest = req.clone( { setHeaders : headers });

    return next.handle(cloneRequest).do(data => {

        if (data instanceof HttpResponse) {
          // Some logic
        }

    })
    .catch((res)=> {

        if (res.status === 401 || res.status === 403) {

            if (APP_CONFIG['accessToken'])
            {
                const auth = this.inj.get(AuthService);
                return auth.getUpdatedAccessToken().flatMap( token => {

                    // Clone the previous request
                    let clonedRequestRepeat = req.clone({
                        headers: req.headers.set('Authorization' ,  APP_CONFIG['accessToken'] ),
                        url: this.fixUrl(req.url)
                    });

                    // Request agin
                    return next.handle(clonedRequestRepeat).do(event => {

                        if (event instanceof HttpResponse) {
                            console.log('Repeat response of server : ', event);
                        }
                    });

                });
            }else { return Observable.throw('Not authenticated'); }

        }
        else { // Not 401
             return Observable.throw(res);
        }

    })

}

}

AuthService.ts

getUpdatedAccessToken()  : Observable<any>{

 return this.http.post(this.api+ 'getaccesstoken', JSON.stringify({refreshToken: APP_CONFIG['refreshToken'] }), { "headers" : this.headers } )
            .map((response: any) => {
                if (response.code == 0){
                    APP_CONFIG['accessToken'] = response.accessToken;
                }
                return response
        })
}


问:
How do I include WordPress PHP tags in JSON-LD?
I want to add JSON-LD structured data to my WordPress WooCommerce site in order to increase my chances of rich snippets on search engine results pages.

I want to begin by adding it first to my products pages.

If I've included the code below in header-shop.php...

```<code>    <!-- Include Schema Markup File
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<?php include('json-ld.php'); ?><script type="application/ld+json"><?php echo json_encode($payload); ?></script>
</code>```

how do I reference PHP tags like <php the_title(); ?> within the json-ld.php file?

Is it as simple as the following?

```<code><script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "<?php the_title(); ?>",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>
</code>```

答:
You could do this in PHP to print to your page. By echoing your script in entirety will allow you to concat inline functions.</p>

```<code>echo '
<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "'. the_title() .'",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>
';
</code>```

Body:
I want to add JSON-LD structured data to my WordPress WooCommerce site in order to increase my chances of rich snippets on search engine results pages.

I want to begin by adding it first to my products pages.

If I've included the code below in header-shop.php...

<?php include('json-ld.php'); ?>

how do I reference PHP tags like <php the_title(); ?> within the json-ld.php file?

Is it as simple as the following?

Body:
You could do this in PHP to print to your page. By echoing your script in entirety will allow you to concat inline functions.

echo '
<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "'. the_title() .'",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>
';


问:
REGEX to get ID ath the end of an URL without /
I'm trying to do a GreaseMonkey script and i'm stucked on a REGEX to get the ID of an article in URL.

I have URL like https://www.blabla.com/poney-2000-poneys-dance-bla,272317

And i want to use the ID at the end after the Comma : 272317

I tried this REGEX : (,([\d]+)) to avoid taking digit in the rest of the URL and it get me ,272317 but I want it without the comma at the begining.

Do you have an idea how i can improve my REGEX ?

Thanks a lot :)

答: Try this: (?!,)([0-9]+){5}, it should be fine as long as the id is greater than 5


问:
Fallback format in rails
for my CMs i want to be able to easily add new themes, my idea was to simply add a mime type for the new theme (so application.theme1.erb  would work).

but for 99% of the themes im not going to want to change the views, well not all of them.

is there someway to have rails fall back on html if the themed view isnt present?

答:
I've just had this same problem with mobile_fu, which sets the format to :mobile for mobile requests.

It turns out that if an :action.:format.erb template isn't available, Rails will serve :action.rhtml as a replacement in any format.

I can't say whether this will work for layouts, but it certainly works for actions

Title: Fallback format in rails


问:
Laravel DB::listen get controller & method from which the query was called
As suggested in https://laravel.com/docs/5.5/database

I have

```<code>DB::listen(function(query) {
  ....
});
</code>```

to log a query from my Laravel application.

I'd also like to find out which controller or function that this query was called from. How could I achieve that? Is that possible?

答:
As long as the query is being fired during a request you should be able to use this.

```<code>DB::listen(function($query) {
     dd($this->app->request->route()->action['uses']);
});

output:  "App\Http\Controllers\SomeController@someAction"
</code>```

There is also $this->app->request->route()->action['controller']

There may be ways to use $this-app to reach the controller in none request situations.

Body:
As suggested in https://laravel.com/docs/5.5/database

I have

DB::listen(function(query) {
  ....
});

to log a query from my Laravel application.

I'd also like to find out which controller or function that this query was called from. How could I achieve that? Is that possible?

Body:
As long as the query is being fired during a request you should be able to use this.

DB::listen(function($query) {
     dd($this->app->request->route()->action['uses']);
});

output:  "App\Http\Controllers\SomeController@someAction"

There is also $this->app->request->route()->action['controller']

There may be ways to use $this-app to reach the controller in none request situations.


问:
TypeScript: Sometimes don't show the latest data when delete user
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

```<code> deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }
</code>```

service

```<code>deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }
</code>```

html

```<code><button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>
</code>```

Please advice me. Many thanks.

答:
It should be:

```<code>  async deleteUser(user: User): Promise<void>  {
    if(user){
      await this.userService.deleteUser(user);
      await this.getAllUsers();
    }
  }
</code>```

Notice that calling ngOnInit hook manually has a smell, also ngOnInit doesn't return a promise, so there would be race conditions too when deleteUser is called by other means than click event (including tests).

Body:
I'm working on chrome browser. I have a table list users, and want to CRUD on that. Try to delete user, sometimes data reload is OK, but sometimes it's not change (need to press f5, the page will show latest data)
In ts file:

 deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { //when component loading get all users and set the users[]
    this.getAllUsers();
  }

 getAllUsers() {
    this.userService.getUsers().then(user =>
        this.users = user
       );

  }

service

deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }

html

<button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>

Please advice me. Many thanks.

Body:
It should be:

  async deleteUser(user: User): Promise<void>  {
    if(user){
      await this.userService.deleteUser(user);
      await this.getAllUsers();
    }
  }

Notice that calling ngOnInit hook manually has a smell, also ngOnInit doesn't return a promise, so there would be race conditions too when deleteUser is called by other means than click event (including tests).


问:
Deleting multiple elements from a list
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].

I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.

答:
You can use this logic:</p>

```<code>my_list = ['word','yes','no','nice']

c=[b for i,b in enumerate(my_list) if not i in (0,2,3)]

print c
</code>```

OwnerDisplayName: Joe Calimari

Title: Deleting multiple elements from a list

Body:
You can use this logic:

my_list = ['word','yes','no','nice']

c=[b for i,b in enumerate(my_list) if not i in (0,2,3)]

print c


问:
PHP - How to use Foreach to turn a list into a column rather than a row of items?
I have a database, and am trying to get a list using PHP with foreach, but  the list are returning like this:

RiquelmeMacielLewBrMarcuus

But it like so:

RiquelmeMaciel
 LewBr
 Marcuus

My code:

```<code><?php
        include_once("conexao.php");
        $select = "SELECT * FROM usuarios ORDER BY id";
        $query = mysqli_query($conn, $select);
        $rows = mysqli_fetch_assoc($query);
              ?>
              <?php foreach($rows as $row){
              echo '<td class="mdl-data-table__cell--non-numeric name">'.$row['nome'].'</td>';
              } ?>
</code>```

答:
You need to insert table rows to create the rows:

```<code><?php
//Incluindo a conexão com banco de dados
include_once("conexao.php");

$result_usuario = "SELECT * FROM usuarios ORDER BY id";
$resultado_usuario = mysqli_query($conn, $result_usuario);
$resultado = mysqli_fetch_assoc($resultado_usuario);

foreach($resultado_usuario as $teste){
    echo '<tr>';
    echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
    echo '<td class="mdl-data-table__cell--non-numeric"></td>';
    echo '<td class="mdl-data-table__cell--non-numeric"></td>';
    echo '</tr>';
}
</code>```

Now you just need to add in your variables for 'EMAIL' and 'SENHA'.

Body:
I have a database, and am trying to get a list using PHP with foreach, but  the list are returning like this:

RiquelmeMacielLewBrMarcuus

But it like so:

RiquelmeMaciel
 LewBr
 Marcuus

My code:

<?php
        include_once("conexao.php");
        $select = "SELECT * FROM usuarios ORDER BY id";
        $query = mysqli_query($conn, $select);
        $rows = mysqli_fetch_assoc($query);
              ?>
              <?php foreach($rows as $row){
              echo ''.$row['nome'].'	';
              } ?>

Body:
You need to insert table rows to create the rows:

<?php
//Incluindo a conexão com banco de dados
include_once("conexao.php");

$result_usuario = "SELECT * FROM usuarios ORDER BY id";
$resultado_usuario = mysqli_query($conn, $result_usuario);
$resultado = mysqli_fetch_assoc($resultado_usuario);

foreach($resultado_usuario as $teste){
    echo '<tr>';
    echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
    echo '<td class="mdl-data-table__cell--non-numeric"></td>';
    echo '<td class="mdl-data-table__cell--non-numeric"></td>';
    echo '</tr>';
}

Now you just need to add in your variables for 'EMAIL' and 'SENHA'.


问:
GNU parallel: execute one command parallel for all files in a folder
I am trying to parallelize particle simulations with different parameters to save some time. Therefore I wanted to use GNUparallel to run a bash script for the different parameters. The script reads a file and then performs the simulation eg :

$bash script <<< input file

However:-

$cd ~/parameter_files ls | parallel bash script <<< {}

does not work at all. I am a total newbie to Linux and GNUparallel, so hopefully someone can  help.

答:
You're almost right, use double quotes around the command

```<code>ls | parallel "bash script <<< {}"
</code>```

Otherwise the here string <<< would feed the input into the parallel command rather than each individual bash script commands

I find this use case to be quite unusual however, since it means that basically your script is reading the filename string. If you just want to pass the files as arguments to the script, you can use

```<code>ls | parallel bash script
</code>```

or if you want to pass the content of the files using standard input

```<code>ls | parallel "bash script < {}"
</code>```

Body:
You're almost right, use double quotes around the command

ls | parallel "bash script <<< {}"

Otherwise the here string <<< would feed the input into the parallel command rather than each individual bash script commands

I find this use case to be quite unusual however, since it means that basically your script is reading the filename string. If you just want to pass the files as arguments to the script, you can use

ls | parallel bash script

or if you want to pass the content of the files using standard input

ls | parallel "bash script < {}"


问:
Why dict not being updated in python multiprocessing?
Please check below code.

I initialized a dict and send it to a function f. I checked the address of return_dict. It is not changing inside the process. So I thought the dict should be updated

But it is not updated, so why?

```<code>from multiprocessing import Process

return_dict = dict({})
print id(return_dict)

def f(value, return_dict):
    return_dict['value'] = value
    print return_dict

p = Process(target=f, args=(100, return_dict))
p.start()
p.join()
print return_dict
</code>```

答:
Your Process() creates another process. It inherits objects as they are from your parent process when the child process is spawned, but modifications to these objects only modify the objects in child process memory and none of these changes are visible to parent.

You can overcome this by using Manager():

```<code>from multiprocessing import Process, Manager

def f(value, return_dict):
    return_dict['value'] = value
    print return_dict

d = Manager().dict()
p = Process(target=f, args=(100, d))
p.start()
p.join()
print d
</code>```

Body:
Please check below code.

I initialized a dict and send it to a function f. I checked the address of return_dict. It is not changing inside the process. So I thought the dict should be updated

But it is not updated, so why?

from multiprocessing import Process

return_dict = dict({})
print id(return_dict)

def f(value, return_dict):
    return_dict['value'] = value
    print return_dict

p = Process(target=f, args=(100, return_dict))
p.start()
p.join()
print return_dict

Body:
Your Process() creates another process. It inherits objects as they are from your parent process when the child process is spawned, but modifications to these objects only modify the objects in child process memory and none of these changes are visible to parent.

You can overcome this by using Manager():

from multiprocessing import Process, Manager

def f(value, return_dict):
    return_dict['value'] = value
    print return_dict

d = Manager().dict()
p = Process(target=f, args=(100, d))
p.start()
p.join()
print d


问:
Detecting drop into textarea with Javascript
All I need is to be able to detect when text is dropped into a Textarea.  I then take that text and do stuff with it and clear the textarea.  There may be many of these textareas and very high UI expectations, so polling is a last resort.

For IE, "onfocus" does the trick, since this event is fired after the user drops stuff into the textarea.

For Firefox, I can't find an event that works.  I've tried onmouseup and onchange.. don't know what else to try from there.  I'd hate to have to poll the textarea for content.  Help much appreciated.  Thanks.

Edit:  For clarification, "dropped" means the user selects text (usually) from the page, but it doesn't matter where, drags it, and drops it into the textarea.  This is not the same as Ctrl+V, or right click pasting (which take two different methods of detection, BTW), or (obviously) typing into the textarea.  Specifically, it is the "drop" aspect of drag and drop.  I really don't know how else to phrase it.

I feel this question was stated rather accurately.  To humor me, assume that I meant any of the other operations on a textarea that you all have chosen to share.  If I meant "pasting", don't you think I would have mentioned something about pasting in the title or content of my question?  Same goes for typing in a textarea.  But, perhaps, you all just don't know me well enough to know that I type what I mean, rather than mistakingly typing things only somewhat related to what I mean.

答:
Polling seems to be the only way to go.

When a Drag+Drop operation is started within the browser, it seems to cancel out everything else that's going on.  You can witness this by putting "onmouseover" events on something on the page, then starting a DnD operation and dragging over it.  The events will not fire.

It seems only a coincidence of how the browser internally handles "drag and drop" that it causes onfocus() to be fired for the textarea in IE and Safari.  I doubt there is much defined in the W3 specification... not that it matters, W3 is crap, and besides nobody adheres to it completely.

In my question I stated the luxury of emptying out the textarea after each use, so I feel that polling for: textarea.value.length>0 is hardly any cost and shouldn't be much of a performance concern.

But, alas, it specifically has to do with dropping content into a textarea.

Down-mod away to sooth your pain.

OwnerDisplayName: sam

LastEditorDisplayName: sam


问:
How to Install mysql-server via dockerfile
Does anybody knows how to install mysql-server via dockerfile? I have written a Dockerfile, but the build ends with an error: /bin/sh: 1: /usr/bin/mysqld: not found

```<code>USER root

RUN apt-get update
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server-5.7

# Remove pre-installed database
RUN rm -rf /var/lib/mysql/*

RUN sed -i -e"s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/"/etc/mysql/my.cnf

ENV DB_USER example
ENV DB_PASSWORD example
ENV DB_NAME example
ENV VOLUME_HOME "/var/lib/mysql"

EXPOSE 3306

RUN cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf
RUN /usr/bin/mysqld  && sleep 5 && \
     mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASSWORD}'" && \
     mysql -uroot -e "GRANT ALL PRIVILEGES ON *.* TO '${DB_USER}'@'%' WITH GRANT OPTION" &&\
     mysql -uroot -e "CREATE DATABASE ${DB_NAME}" && \
     mysqladmin -uroot shutdown
</code>```

答:
For an ubuntu:16.04 base image, mysqld is found in /usr/sbin, not /usr/bin

If you can add a step RUN which mysqld before your final RUN command that will show you where the mysqld executable is found. It may vary depending on which base image/distro you're using.

You can also use RUN mysqld ... without a full path, if the file is in your $PATH

You may also need to update your RUN sed line as below, adding spaces around the quoted string:

```<code>RUN sed -i -e "s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/" /etc/mysql/my.cnf
</code>```

Otherwise, you may see the following error:

```<code>The command '/bin/sh -c sed -i -e"s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/"/etc/mysql/my.cnf' returned a non-zero code: 1
</code>```

Body:
Does anybody knows how to install mysql-server via dockerfile? I have written a Dockerfile, but the build ends with an error: /bin/sh: 1: /usr/bin/mysqld: not found

USER root

RUN apt-get update
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server-5.7

# Remove pre-installed database
RUN rm -rf /var/lib/mysql/*

RUN sed -i -e"s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/"/etc/mysql/my.cnf

ENV DB_USER example
ENV DB_PASSWORD example
ENV DB_NAME example
ENV VOLUME_HOME "/var/lib/mysql"

EXPOSE 3306

RUN cp /etc/mysql/my.cnf /usr/share/mysql/my-default.cnf
RUN /usr/bin/mysqld  && sleep 5 && \
     mysql -uroot -e "CREATE USER '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASSWORD}'" && \
     mysql -uroot -e "GRANT ALL PRIVILEGES ON *.* TO '${DB_USER}'@'%' WITH GRANT OPTION" &&\
     mysql -uroot -e "CREATE DATABASE ${DB_NAME}" && \
     mysqladmin -uroot shutdown

Body:
For an ubuntu:16.04 base image, mysqld is found in /usr/sbin, not /usr/bin

If you can add a step RUN which mysqld before your final RUN command that will show you where the mysqld executable is found. It may vary depending on which base image/distro you're using.

You can also use RUN mysqld ... without a full path, if the file is in your $PATH

You may also need to update your RUN sed line as below, adding spaces around the quoted string:

RUN sed -i -e "s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/" /etc/mysql/my.cnf

Otherwise, you may see the following error:

The command '/bin/sh -c sed -i -e"s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/"/etc/mysql/my.cnf' returned a non-zero code: 1


问:
Regular expression to search text "From TableName" using VisualStudio
I am using the below regular expression to search sql script file from VisualStudio find text in files dialogbox:

```<code>from\s+(Table123|\[Table123\])\s*
</code>```

Output:

```<code>FROM [Table123] [i]

FROM Table123 I

FROM Table123Extended t1

FROM Table123";

How can I modify my regular expression to eliminate third result

1. FROM [Table123] [i]         (correct)

2. FROM Table123 I             (correct)

3. FROM Table123Extended t1    (incorrect)

4. FROM Table123";             (correct)
</code>```

答:
You want to make sure thematch ends with a double quote or a whitespace, thus, you should replace \s* with [\s"] and use

```<code>from\s+(Table123|\[Table123\])[\s"]
</code>```

The [\s"] is a * character class* that matches any single char that is defined in the class, hete, a whitespace or a double quote.

Body:
I am using the below regular expression to search sql script file from VisualStudio find text in files dialogbox:

from\s+(Table123|\[Table123\])\s*

Output:

FROM [Table123] [i]

FROM Table123 I

FROM Table123Extended t1

FROM Table123";

How can I modify my regular expression to eliminate third result

1. FROM [Table123] [i]         (correct)

2. FROM Table123 I             (correct)

3. FROM Table123Extended t1    (incorrect)

4. FROM Table123";             (correct)

Body:
You want to make sure thematch ends with a double quote or a whitespace, thus, you should replace \s* with [\s"] and use

from\s+(Table123|\[Table123\])[\s"]

The [\s"] is a * character class* that matches any single char that is defined in the class, hete, a whitespace or a double quote.


问:
Replace substring of text matching regexp
I have text that looks like something like this:

```<code>1. Must have experience in Java 2. Team leader...
</code>```

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

```<code>s = replace(s, ". ", "</li>");
</code>```

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

答:
We want

```<code><ol>
  <li>one</li>
  <li>two<li>
</ol>
</code>```

This can be done as:

```<code>s = s.replaceAll("(?s)(\\d+\\.)\\s+(.*\\.)\\s*", "<li>$2</li></ol>");
s = s.replaceFirst("<li>", "<ol><li>");
s = s.replaceAll("(?s)</li></ol><li>", "</li>\n<li>");
</code>```

The trick is to first add

 with a spurious
 that should only remain after the last list item.

(?s) is the DOTALL notation, causing . to also match line breaks.

In case of more than one numbered list this will not do. Also it assumes one single sentence per list item.

Body:
I have text that looks like something like this:

1. Must have experience in Java 2. Team leader...

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

s = replace(s, ". ", "
");

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

Body:
We want

<ol>
  <li>one</li>
  <li>two<li>
</ol>

This can be done as:

s = s.replaceAll("(?s)(\\d+\\.)\\s+(.*\\.)\\s*", "<li>$2</li></ol>");
s = s.replaceFirst("<li>", "<ol><li>");
s = s.replaceAll("(?s)</li></ol><li>", "</li>\n<li>");

The trick is to first add </li></ol> with a spurious </ol> that should only remain after the last list item.

(?s) is the DOTALL notation, causing . to also match line breaks.

In case of more than one numbered list this will not do. Also it assumes one single sentence per list item.


问:
Why isn't the variable and its content visible in HTML
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

```<code>var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(agetest)</script>,</span> to THE SESH</h3>
</code>```

No dice

```<code>var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(age)</script>,</span> to THE SESH</h3>
</code>```

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

```<code><div id="overlay">
<div id="text">Are you over 18 years old?</div>
<div id="off"><button onclick="off(), ageinyear()">Submit</button></div>
<div id="test"><form>
    <label>
        Name
        <input id="name" name="lblname" type="text" />
    </label>
    <label>
        Age
        <input id="year" name="lblyear" type="text" />
    </label>
</form>
</div>
</code>```

答:
In the snippet below you take an input from your HTML, you can make some computation on it depending on your use case and then, you modify an HTML element.

to change

<input id="age" type="number"/>
<button onclick="change()">change</button>

```

Body:
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

    Welcome , to THE SESH

No dice

var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

    Welcome , to THE SESH

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

Are you over 18 years old?

<button onclick="off(), ageinyear()">Submit</button>

<form>

        Name
        <input id="name" name="lblname" type="text" />

        Age
        <input id="year" name="lblyear" type="text" />

</form>

Body:
In the snippet below you take an input from your HTML, you can make some computation on it depending on your use case and then, you modify an HTML element.

<h3 id="change">to change</h3>
<input id="age" type="number"/>
<button onclick="change()">change</button>

<script>
function change() {
        var age = document.getElementById("age").value;
        //make a computation
        parseInt(age) + 1
        document.getElementById("change").innerHTML = "hello" + age
    }
</script>